And now another interesting little project.
After seeing various online projects, especially based on the PIC microcontroller, I decided to make a charger for NiMH batteries driven by an ATtiny85.
Why we need a microcontroller to manage charging a battery? The answer is very simple … The most economic charger that on the market, regulate the charge based on a timer, that is if I charge a 2500mAh battery for example, they provide a charging current of 250mAh, keeping the charge for eg 14 hours (a part of the energy will be lost, so 10 hours would not be enough).
This way of charging NiMh or NiCd batteries is not very functional. It is a slow process, and does not guarantee a 100% accurate cell charge, as well as increasing the risk of overload.
“Smart” chargers however, charge batteries correctly, but besides being quite expensive, their usually charge current is not very high, leading to charging times still quite long.
So in addition to the curiosity and the desire to create something of my own, this project was born …
But lets proceed with order, starting with a video showing the finished running project:
Let us now try to understand the operating principle.
First nickel batteries require a constant current to be charged properly. So we used a transistor-based constant current source, derived from what we saw in a previous post, and so far nothing special, but how do we know when the battery is fully charged?
We need to constantly read the voltage of the battery being charged, and when there will be a maximum peak voltage followed by a sudden drop of about 20mV, the battery may be considered charged. This phenomenon (called Negative Delta V) is related to the chemistry of this type of battery, and allows to establish precisely the right moment to terminate charging.
Thus we see the circuit diagram:
The schematic is pretty simple. The darlington transistor Q1 (TIP127), through LED1 (which must be absolutely RED) and the resistance R3 from 0.3 Ω, creates a constant current flowing in the direction of the 6-cell battery (7.2V), while the Schottky diode 1N5822, serves to protect the entire circuit in the case that is lacking the input voltage with the battery connected. The voltage divider R4-R5, serves to bring to port 7 of the ATtiny (A1) the battery voltage decreased to about 1/3, in such a way that it can operate with voltages up to 15V (the analog input of the ATtiny can not exceed 5V). The transistor Q2, driven by the port 5 of the ATtiny (D0), serves as a switch to enable or disable the LED-1 and the transistor Q1.
It’s really important that LED1 is RED, and this is not a matter of aesthetics, but because the power output is given by the ratio between the voltage of the LED (the red LED is about 1.8 to 2.2 V) and resistance R3. Using a green LED, the reference voltage is raised, and consequently also the current rises (and not just a little bit).
The circuit above, can deliver about 1.5-2.5 A: you may have to do some testing with various types of red LED, or vary the resistance, which must be at least 2W. If you can not find resistance with so low values, you can use 3 or 4 1Ω resistors in parallel.
Another thing to remember, is the power dissipated by the TIP127, which can be up to 20 watt (depending on the current and the voltage difference between the input and the battery), then a heat sink need to be mounted properly. In my case was enough to use the aluminum enclosure.
Last note is the input voltage, which must not be too high otherwise you risk to burn the transistor, but must not be even too low, because otherwise the dropout induced by the various components makes too low the charging current. Can fit approximately a difference of about 5V between the input voltage and the nominal value of the battery. For example, with 6-cell a voltage of 12.2 V is recommended (maybe 12). Of course you can also charge less cells, by suitably adjusting the input voltage. For a cell, we should feed the device with a voltage of about 1.2 + 5 = 6.2 V (maybe 6 or 7).
Let us consider now the printed circuit board:
Note the two gems that were not visible in the schematic. The ICSP connector (ie the ability to update the firmware on the ATtiny – via UsbTinyISP programmer for example – and the debug connector, to be connected to a TTL converter in order to read the battery voltage during charging.
The J1 connector is a jumper that must be closed at all times, except when updating the firmware of Attiny85.
About firmware … The source code is as follows:
/* NiMh Charger 0.9 with AtTiny85 @ 1Mhz by Luca Soltoggio 10/03/2012 - 20/04/2012 Use negative deltaV to determine end of charge. Suitable for NiMh and NiCD battery pack. Default is for 6 cells 2500mAh. Need some hardware/software adjustment for changing current / cells number See http://arduinoelettronica.wordpress.com/ */ const int inputPin = A1; const int outputPin = 0; const int numReadings = 30; // number of analog read before checking battery status const int multi = 1614; // multi coefficent for obtaining millivolts from analogread long interval = 1000; // interval for pulse charging and analog read - don't change this long interval2 = 250; // pulse off interval - you can adjust power with this. Use 100 for 2-4Ah battery packs, 500 for 1-2Ah battery pack long interval2b=interval2; long previousMillis,currentMillis,currentMillis2,trickleMillis = 0; unsigned int readingtemp; unsigned int total = 0; unsigned int average,medium,maxmedium = 0; boolean executed,endcharge,trickle=false; // booleans for controlling various activities (for example "end of charge") unsigned int myarray [7]; // array for keeping last 7 readings int index,i = 0; void setup() { Serial.begin(9600); pinMode(0,OUTPUT); // Some readings for initial check for (i=0;i<10;i++) { readingtemp = analogRead(inputPin); total=total+readingtemp; } average = (((float)total / 1023.0) * (float)multi) / 10.0 + 0.5; if (average<=70) endcharge=true; // If there is no battery, end charge Serial.println(average); total=0; average=0; } void pusharray() { // push the array for (i=0;i<=5;++i) { myarray[i]=myarray[i+1]; } myarray[6]=average; } void voltread() { readingtemp = analogRead(inputPin); // read analog input total= total + readingtemp; index++; // if numReadings reached, calculate the average if (index==numReadings) { index=0; average = (((float)total / 1023.0) * (float)multi) / numReadings + 0.5; if (average<=70) endcharge=true; // stop charge if battery is detached total=0; pusharray(); // insert new average in array medium=(float)(myarray[6]+myarray[5]+myarray[4]+myarray[3]+myarray[2]+myarray[1]+myarray[0])/7.0+0.5; // calculate the average of the last 7 readings if (medium>maxmedium) maxmedium=medium; // save the value of highest medium in "maxmedium" Serial.print(medium); Serial.print(","); Serial.print(maxmedium); Serial.print(","); Serial.println(myarray[6]); if ( ((medium+1) < maxmedium) && ((millis()/60000)>=11) ) { // if battery charged (average voltage is dropped 0.02v), but not in the firsts 11 mintues if (!trickle) trickleMillis=millis(); // start trickle timer trickle=true; // enter final trickle charging mode if ((millis()/60000)<=15) endcharge=true; // if battery is charged in the firts 15 minutes, don't apply trickle charge (maybe was yet charged) } } } void loop() { currentMillis = millis(); // executed every "interval" millis if(currentMillis - previousMillis > interval) { voltread(); // call reading and check volts function digitalWrite(outputPin,LOW); // temporaly stop charging previousMillis = currentMillis; executed=false; // boolean for setting and checking if has been yet turned ON charge // in the firsts 10 minutes and in the endings 15 minutes do a trickle charge (change OFF interval) if ( ( (trickle) && (((millis()-trickleMillis)/60000)<15) ) || ((millis()/60000)<10) ) { interval2=(interval-(interval-interval2b)/5); } else if ((millis()/60000)>=10) interval2=interval2b; // after initial trickle charghe set back right time if ( (trickle) && (((millis()-trickleMillis)/60000)>=15) ) endcharge=true; // if final trickle charge end, end charge } currentMillis2 = millis(); // executed "interval2" millis after turning OFF charge if ((currentMillis2 - previousMillis > interval2) && (!executed)) { executed=true; if (!endcharge) { digitalWrite(outputPin,HIGH); // if battery is not charged, re-enable charging } } }
The code is pretty simple and self-explanatory.
I conclude with a few pictures of the finished project:
Find my project on Fritzing:
http://fritzing.org/projects/smart-nimh-battery-power-charger-with-attiny85/
Until next time!
ehbbbravoilfratellino!
Ciao, bel progettino 🙂
Come programmi l’ATtiny85? Gli carichi il bootloader di arduino? Mi consigli qualche risorsa sul web?
Grazie 🙂
Oops, mi rispondo da solo: qui sul tuo blog!
E allora ti faccio i complimenti per il blog 😀
Grazie mille!!!
Ciao e a presto
Luca
Ciao trovo il tuo progetto molto interessante dato che devo realizzare un caricabatterie serio per le Ni-Mh da 2500mAh.
In particolare dovrei caricare pacchi da 4 batterie quindi sono 4.8V mi potresti indicare le modifiche da apportare?
Vorrei inoltre sapere se hai il circuito stampato già pronto da vendere, in caso contattami in privato.
Grazie
Andrea
Ciao Andrea,
e grazie per i complimenti.
Per caricare un pacco da 4.8V, potrebbe già andare bene così, se non che rischia di surriscaldare un po’ troppo il transistor, altrimenti come indicato nell’articolo, riduci il voltaggio in ingresso a 4,8V+5V = 9,8V (va bene 10V).
Il circuito non lo vendo, ne ho fatti stampare alcuni su fritzing fab.
Puoi eventualmente seguire il ling su fritizing alla fine del mio articolo, e da li comprarlo direttamente da loro.
A presto
Hi toggio, nice charger!
Please, this 0.3ohms resistor R3 can be a carbon resistor 0.24ohms 2W? I ask this because it seems to me by your photo that you are using a different resistor. Looks like a wirewound resistor. I want to charge 6 NiMh 2200mAh battery pack.
Thanks
Hi Bernardo,
sure you can use 0.24ohms, but be carefull that power will increase, so you will have to dissipate well the TIP127!!!
Greetings
Luca
Hai mai pensato di creare una per lo zinco nichel? ZN?
Molto difficile ahcar caricabatterie intelligente per questo tipo di chimica.
Ci scusiamo per il traduttore.
Ciao!
Ho l’esigenza di caricare 3 NiMH AAA, ed ho preso spunto dal tuo progetto. Per il generatore di corrente costante ho usato un LM317, ed ho fatto alcune prove utilizzando un atmega328 per leggere la tensione ai capi della serie di batterie, ma non ho ottenuto, o meglio, non ho visto, il calo di tensione! Ho usato batterie ‘quasi’ cariche, per velocizzare il tutto, ma dopo 4 ore a 125mA (le batt. sono da 700mAh) ho solo letto valori in costante aumento tra 3.95 e 4.24volts. Il sistema di lettura è simile al tuo, faccio la media di 20 letture (una ogni 5 secondi)…. leggo i millivolts, per cui un calo di anche solo di 10 mVolts dovrei vederlo bene…. le letture di tensione sono sempre o costanti o in aumento, ed ho visto pochissime diminuzioni, nell’ordine di 1mV….
Qualche suggerimento??
Grazie per aver reso pubblico il progetto!!
Caro Ivan,
grazie a te che segui questo blog.
La risposta al tuo quesito credo sia abbastanza semplice. Il problema dovrebbe essere legato al fatto che la corrente di carica è troppo bassa… dovrebbe essere almeno la metà del valore nominale delle batterie, o anche un po’ di più, altrimenti non si genera l’effetto di abbassamento del voltaggio o si genera in maniera troppo blanda. Ti consiglio una corrente di carica di 600-700ma con una pausa di 100ms ogni secondo… Inoltre per poter funzionare correttamente le batterie devono essere completamente scariche…
A presto.
azz… 700mA… mi sa che il LM317 non è sufficente!
Farò ulteriori prove!
Grazie mille delle preziose informazioni!
Ciao Ivan,
L’integrato LM317 supporta carichi fino a 1,5A, quindi non preoccuparti…
Fa attenzione anche al dropout… Il voltaggio in ingresso deve essere almeno 6volts in più rispetto al voltaggio delle batterie…
A presto
Rispondo qua, non ho l’opzione ‘risposta’….
Penso che costruirò un caricabatterie piu ‘malleabile’, anche per serie di AA, per cui mi avvicinerei troppo a 1.5A…. gia con 125mA scalda tanto (con su un dissipatore da ram video)…. credo opterò per un LM338, identiche caratteristiche del 317 ma corrente max 5A, e un case piu grande, piu adatto ad essere dissipato efficacemente rispetto al TO220.
Grazie ancora!
Ciao Toggio,
innanzitutto grazie mille per aver reso disponibile il tuo utilissimo progetto, era da tanto tempo che cercavo un sistema per caricare “intelligentemente” le mie NiMH, in quanto quelli in commercio a basso costo caricano male e i risultati sono quindi poco soddisfacenti, senzo contare la paura di accorciare la vita delle batterie ogni volta che le mettevo sotto carica 😀
Volevo chiederti come mai hai usato un darlington PNP e non invece un NPN come un TIP122?
Non ho sotto mano TIP127, secondo te è possibile sostituire il 127 con un 122 modificando la posizione del transistor “pilota” a monte del tip e correlati aggiustamenti? (se si, dammi una dritta su come potrei procedere :P) In quanto ho qualche “122 avanzato che aspetta solo di esser usato 🙂
Nel tuo articolo specifichi inoltre che il led deve essere obbligatoriamente rosso, in quanto è necessario al corretto funzionamento del dispositivo, e che se si andasse a modificare bisognerebbe ritarare la resistenza… intendi R1 o R3? e perchè? non ho afferrato il principio
Ringrazio ancora infinitamente per l’utilissimo progetto 🙂
Ciao Claudio,
scusa se ci ho messo un po’ a rispondere, ma sono stato un po’ impegnato…
Ti ringrazio molto per i tuoi complimenti: il motivo per cui anche io ho creato questo progetto, è che anche io non avevo trovato progetti soddifacenti in rete.
Ma venendo al dunque, ho usato un PNP perchè era l’unico modo che ho trovato per usarlo come switch in parallelo ad una tensione attiva come quella di una batteria… Per usare un NPN sarebbe stato estremamente più complicato…
Non è possibile quindi sostituire il circuito usando un NPN. Puoi comunque usare (li trovi a basso costo) qualsiasi PNP darligton di adeguata potenza, purchè si leggano le specifiche e si effettuino alcuni test.
Per quanta riguarda il LED rosso il discorso è questo: la corrente di carica è data dal rapporto tra la tensione di riferimento – data dal LED – e la resistenza R3.
Se vuoi variare la corrente in uscita (in questo caso siamo tra 1,5A e 2,5A), devi modificare la resistenza R3 (più il valore è alto, più la corrente diminuisce). Potresti usare anche un LED con un dropout diverso volendo (quelli bianchi arrivano fino a 3,5V contro 1,8-2V di quelli rossi), ma aumenteresti il dropout generale del circuito diminuendone l’efficienza.
In definitiva, ogni LED, ogni transistor ed ogni resisenza sono diverse: ti consiglio di fare dei test misurando gli Ampere generati dal circuito, prima di realizzare la versione definitiva.
Spero che il tutto sia abbastanza chiaro.
A presto
Luca
Ciao Luca,
grazie ancora per aver pubblicato il tuo lavoro, mi ha dato modo di conoscere e capire meglio il funzionamento delle batterie NiMH e NiCD, infatti dopo averlo letto ho iniziato a documentarmi incuriosito dai vari sistemi di carica e dei relativi pro e contro, e più o meno tutti sembrano concordi che il sistema del dV negativo a fine carica sembra il più funzionale, anche se promuovono il fatto che una carica lenta sarebbe meglio, ma difficile da controllare…
Tralasciando le mie divagazioni e tornando al punto xD, volevo utilizzare un modello modificato del tuo schema sempre tenendo intatto il tuo codice, ma nell’intestazione del codice specifichi che necessita di aggiustamenti “hardware/software”… aggiustamenti all’hardware ok li hai puù o meno illustrati nei precedenti post, ma riguardo il software? sarebbe possibile secondo te creare un codice “universale” che vada solo a rilevare il deltaV a prescindere dalla portata e tensione del pacco batterie? (sempre restando entro la tolleranza di lettura del controllore e considerando il partitore per la lettura) cioè che legga il solito numero di misure, e che ne faccia la differenza con quelle effettuate precedentemente, e che quando intercetta un risultato negativo interrompa la carica e/o vada in modalità “mantenimento” (opzionale, basta che stacchi la carica come prima priorità)?
Grazie ancora mille per le ottime idee divulgate 😉
Penso che continuerò ad usare i caricabatteria con PIC perchè questo non mi sembra un granchè. Naturalmente di caricabatterie seri con microcontrollori AVR c’è ne sono ma questo sicuramente NO!
Caro Gigi, ovviamente non ho mai preteso di realizzare il miglior caricabatterie al mondo… Tutto quanto presente in questo sito è realizzato in maniera hobbistica e senza grandi pretese. Tutti i commenti, anche negativi, sono accettati. Certamente sarebbe più costruttivo un commento che mi indicasse i motivi del perché secondo te non è un granché e magari qualche link di progetti migliori da cui prendere spunto.
A presto
Ciao volevo chiederti i metodi di pagamento di fritzing fab e anche il costo del circuito stampato. Grazie (:
Come spiegato dettagliatamente sul sito (http://fab.fritzing.org/fritzing-fab/pricing), il prezzo è di 0,70€ per centimetro quadro + 4€ di fisso per sketch + 6€ di spedizione.
Quindi per una board di 40mmx30mm, sono 8,4+4+6=18,4€ (+ 19% di iva su 8,4+4).
Il pagamento viene invece effettauto con paypal.
A presto
ok grazie mille,molto gentile 🙂
ciao,
innazitutto bel lavoro, non sono un grande esperto ma avrei bisogno di caricare un pacco batterie ni-mh da 20 celle cioè mi servirebbero 24 v in uscita. Volevo chiederti che modifiche fare al tuo circuito per renderlo utilizzabile per i 24 v.
Grazie ancora per il progetto.
Ciao Matteo,
il circuito così com’è supporterebbe già i 24v, in quanto i due transistor utilizzati lavorano tranquillamente fino a più di 60v.
La tensione in ingresso dovrebbe essere ovviamente intorno ai 29v, o anche qualcosina in più (diciamo 30v), l’importante è dotare il TIP127 di un bel dissipatore, altrimenti rischi di bruciarlo.
Per lo stadio in ingresso del microcontroller, l’integrato LM7805 supporta fino a 35v, ma è un po’ “tirato” e rischia di surriscaldarsi. Consiglio quindi anche qui un dissipatore… Il consumo basso del micro, non doverebbe creare però grossi problemi.
Spero di esserti stato utile.
A presto
Hello,
Very interesting project, congratulations. I will try to build one, following your design. I have kind of a robot powered from eight 2100 mAh NiMH batteries. The elements that draw current are, basically, an arduino, a motor bridge and an xbee RF transmitter. The robot has a charging station. My plan is to charge batteries when the robot comes to charging station. I bought a so called “smart” NiMH charger and wanted to use it to charge the robot in the charging station, but…. I think it is so “smart” (it uses pulses as in your design) that it somehow detects that energy is drawn from the batteries (the arduino and other stuff are working non stop) and it refuses to charge. If I disconnect the arduino and all the other consuming elements, the charger does its job.
So, I hope with your design I will be able to charge the batteries, even if energy is drawn whilst charging is taking place. Do you think it will be possible?
The other question I have is in regard to pulses: are they necessary? and if so, why? is it possible to charge continually, without pulses, as one does for example with Pb batteries?
Thanks a lot in advance,
Angel Valor from Madrid
Hola Angel,
muchas gracias por los cumplidos. Ahora escribo en Inglés, porque para hablar de la electrónica es más fácil.
Ok, so i think it’s not possibile to charge the NiMh batteries when in use, because that charging metod requires batteries volts to be so precise with an accuracy of 1-2mv. If not batteries will damages, or not charge at all. That’s because the only method to know if NiMh have reached charge (during fast charge), is to detect a negative peak in battery volts. That is really different from Pb batteries. Regarding pulses, they are not necessary, but it help to full charge the battery leaving it sit for some time during charge. If u want fast charge, pulses are necessary. If u want slow charge, you don’t need pulese neither smart charge, but i think your robot need to charge quickly… So i advise you to use Lithium batteries (like the ones in cell phones, notebooks and so)… Are more powerfull, lighter, and althugh they requires more precise battery charger, they chan be charged while in use. There is a sparkfun dedicated Lipo charger shield (https://www.sparkfun.com/products/10711).
Espero que esto ayude
Hasta pronto
muchas gracias Toggio por la rapida y util respuesta.
The thing is that budget in my case is a constraint (you know, we are in economical crisis 🙂 and I would like yet to explore a way to use the NiMh batteries in the project. I forgot to mention that in the robot there is still an ip wireless camera not very efficient, as it draws 2 amperes! thats why pb batteries is neither a good choice for me. NiMh is a good choice but i have this problem with charging.
i will have into account the lipo option, but still explore a solution with nimh.
something as for example switch power to the circuit from batteries to mains when the robot enters charging station. i.e. disconnect batteries from the circuit and charge batteries. when robot leaves charging station, do the opposite. I just have to find out how to implement this (i am relatively new to this fascinating world of electronics).
thanks a lot again. Angel Valor
Great idea — I really like this! The constant-current driver is clever, too. One question: are the designations for Q1 and Q2 swapped on your PCB artwork? In other words, the schematic indicates that Q1 is the TIP127 and Q2 is BC547B. However, on the PCB, it looks like the TIP127 should be mounted at the location labeled Q2 and the BC547B should be mounted at the location labeled Q1.
You’re right… it’s just a mistake!
Thanx
Ciao,
scusa non sono un grande esperto ma mi piacerebbe usare Arduino per realizzare un sistema di accumulo per impianti fotovoltaici.
Mi potresti dare qualche indicazione ?
Grazie
Hi, I was thinking of using an enhanced P channel MOSFET instead of the PNP Darlington . It would have fractional resistance and therefore generate less heat. I would probably need to eliminate R1 but I think a pull up resistor to the source voltage. I’m not sure if the LED would be enough to cause the MOSFET to be able to switch on. What do you think?
You have to try!!! 🙂
Hey, nice one! i need assistance since i am not an electronics expert (i’m slowly learning) i need to make this one, but instead of having 6 cell i need to charge 7, that means 8.4V. What should i change on the circuit to obtain more voltage output to charge a larger pack?
Voltage must be slightly higher than the cell voltage. From .3 to .5 volts per cell. So, 1.2 v + .4 (middle value) = 1.6. 1.6 *7 = 11.2 . So some where around 11 volts to charge.
Hi, thank you very much for this post, you’ve made a great job, I was surfing the net triying to find a nice charger to build and’s not an easy stuff. This one is great. Now, it will be very complicated to convert it into a smart charger?. I mean, detect battery pack voltage and then charge according to this voltage?, I need a charger cappable to do that from 12v NiMh pack’s up to 24v. Thank’s again for this excelent post. Happy new year for all of you!!
Please tell me how do I charge 4 x AA Ni-MH batteries (4.8 V) with this charger. If needed make some modification to the circuit and let me know that.
Pingback: 80+ ARDUINO Projects List : - Electronicaa
exit status 1
‘Serial’ was not declared in this scope
This is what i get trying to buid the code …
Did you copy and paste the code? If you did, you might have missed a bracket somewhere(}). If you really want, you can comment out all the Serial calls in the program. They are there for debugging.
I did copy-paste the code, i will run another test and comment out all the serial references, and see how it goes.. Thanks !!
After research, i found this :
No Serial (UART). Yes SPI and I2C.
You may notice, on the listing of special pin functions there are no UART RX’s or TX’s. That’s because the ATtiny85 doesn’t have a built in hardware UART. If you try to compile any Arduino code with Serial.begin(9600)’s or Serial.print()’s you’ll get an error.
how much will it cost for the full project
Very nice project! Good work! Please advise on which arduino boot loader you used. Thank you.
Hello Luca,
First of all, thank you for making this circuit and putting it on the internet. I like its simplicity very much and I’d like to try my hand to modify this and make an integrated charger circuit that will be powered off USB(5v) and charge two AAA NiMH batteries (2.4V), probably hard-wired as two cells in series.
My intention is to make the charger small in form-factor, and integrate it in a small joystick-device. I have to use NiMH AAA because of space limitation in the device, and because and LiPos or LiIONs of that size have small mAh ratings, while the device has a relatively high draw, 14mA.
From your schematic I can only say that I don’t particularly like the Red LED concept, but is probably the simplest way to go.
Before I attempt this however, do you have any advice to give me? Maybe even a complete schematic for USB? 😀
Thank you,
Marko
Very good and informative.Can we use this circuit for Lithium ion 4.2V battery?.Please reply what should be change in schematic and code.