Electronics & Arduino

Tips, tricks, circuit designs, sketch and code for electronics and Arduino

  • Blog
  • RGB LAMP
  • ACTARUS
  • ArduDome
  • Versione in Italiano

Non-blocking “breathing” led

Posted by Luca Soltoggio on May 12, 2015
Posted in: Arduino. Tagged: arduino, led, pwm. 1 Comment

Who has not happened to note that wonderful breathing led effect present on some electronic devices?
There are makers all over the world equipped with oscilloscope tried to do reverse engingering to find the algorithm and turn it into an Arduino sketch. The problem lies in the fact that most of the codes found in the network have two defects: the first is that such algorithms do not contain a function but a series of pre-calculated values ​​that do not make the effect smooth, while the second resides in the fact that often these codes are blocking, making use of delay and therefore do not permit the correct execution of the remaining code inside of the sketch.
Ispired by the Sean Voisen’s post who find the function defining the ​​PWM values to drive the LED, I made some changes and tests to make it non-blocking and to make it work in background allowing execution to other code.
The end result is the following:

The connection is obviously as for any other LEDs and the system is capable of driving even power LEDs or LED strip, through appropriate transistor or MOSFET (See: Driving a LED Strip with Arduino)

The Arduino code is the following:

/*

NonBlockingBreathingLed 0.1
by Luca Soltoggio - 2015
12 May 2015
http://www.arduinoelettronica.com/
https://arduinoelectronics.wordpress.com/
http://minibianpi.wodpress.com/

Use a exp + sin function to recreate a
non-blocking breathing led effect

Released under GPL v.2 license

*/

#include <math.h>
#define ledPin 11 
int i=0;
int breathe_delay = 15;   // delay between loops
unsigned long breathe_time = millis();
void setup()
{
}

void loop()
{
  nonBlockingBreath();  // call the nonblocking function
  // yourOtherCodeHere();
}

void nonBlockingBreath()
{
  if( (breathe_time + breathe_delay) < millis() ){
    breathe_time = millis();
    float val = (exp(sin(i/2000.0*PI*10)) - 0.36787944)*108.0; 
    // this is the math function recreating the effect
    analogWrite(ledPin, val);  // PWM
    i=i+1;
  }
}

Have fun!!! 🙂

Ultra Low Power Led Flasher (with ATtiny)

Posted by Luca Soltoggio on January 6, 2014
Posted in: Circuit schematics. Tagged: attiny, avr, led. 6 Comments

On the internet there are so many Led Flasher’s projects, some even with low current consumption, but what I needed was a flasher  to be used for geocaching, extremely small and that could last at least one year with a button battery.
I started so a little experiments with the ATtiny85 low power modes using the sketch of insidegadgets, achieving a power consumption of about 4.5uA in standby and of about 3mA during the led flash that occurs every 4 seconds and lasts for about 30ms.
In this way, the average consumption is around 25uA, which with a CR2032 button battery from about 220mAh, this means about a year of life!
After a first draft of the project, I thought it might be useful to also have a 12V version so that it can be also powered by the battery of a car.
Here you can see the circuit on the first version, namely the one powered by 3V button battery:

led_flasher_circuit

The schematic is really very simple because the real work is done by the code:

/*

Ultra Low Power Led Flasher
with AtTiny85 @ 1Mhz
by Luca Soltoggio
06/01/2014

http://www.arduinoelettronica.com

*/

#include <avr/sleep.h>
#include <avr/wdt.h>

#ifndef cbi
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif

int pinLed = 4;
volatile boolean f_wdt = 1;

void setup(){
pinMode(pinLed,OUTPUT);
setup_watchdog(8); // approximately 4 seconds sleep
}

void loop(){
if (f_wdt==1) {  // wait for timed out watchdog / flag is set when a watchdog timeout occurs
f_wdt=0;       // reset flag

digitalWrite(pinLed,HIGH);  // let led blink
delay(30);
digitalWrite(pinLed,LOW);

pinMode(pinLed,INPUT); // set all used port to intput to save power
system_sleep();
pinMode(pinLed,OUTPUT); // set all ports into state before sleep
}
}

// set system into the sleep state
// system wakes up when wtchdog is timed out
void system_sleep() {
cbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter OFF

set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here
sleep_enable();

sleep_mode();                        // System sleeps here

sleep_disable();                     // System continues execution here when watchdog timed out
sbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter ON
}

// 0=16ms, 1=32ms,2=64ms,3=128ms,4=250ms,5=500ms
// 6=1 sec,7=2 sec, 8=4 sec, 9= 8sec
void setup_watchdog(int ii) {

byte bb;
int ww;
if (ii > 9 ) ii=9;
bb=ii & 7;
if (ii > 7) bb|= (1<<5);
bb|= (1<<WDCE);
ww=bb;

MCUSR &= ~(1<<WDRF);
// start timed sequence
WDTCR |= (1<<WDCE) | (1<<WDE);
// set new watchdog timeout value
WDTCR = bb;
WDTCR |= _BV(WDIE);
}

// Watchdog Interrupt Service / is executed when watchdog timed out
ISR(WDT_vect) {
f_wdt=1;  // set global flag
}

The complete project, 3V and 12V dual-use version can be found on Fritzing posted to the following address:
http://fritzing.org/projects/ultra-low-power-led-flasher-with-attiny

See you soon!

Arduino Yún: welcome future!

Posted by Luca Soltoggio on October 25, 2013
Posted in: Arduino. Tagged: arduino, communication, domotic, ethernet, linux embedded, raspberry pi, robotics, serial, wifi. Leave a comment

The title could not be more appropriate: Arduino Yún is in fact the first of a series of products that is already revolutionizing the world of Makers.
I will not examine here the specifications (which have already been widely discussed in various blogs and which are summarized on the official website), but I would rather analyze the mode of operation of this platform, as well as highlight the possible future implications.

arduino-yun

The starting premise is that the Arduino environment has spread exponentially since its inception, becoming a de facto standard, fueling in a virtuous circle the worldwide Makers movement.
From Arduino have resulted in fact hundreds of projects, similar board and new ideas, so that now are very few technological innovations that have nothing to do with this board (just think of the advent of 3D printers).

Ad Arduino mancava però ancora una cosa, di importanza sempre più fondamentale per poter partecipare all’Internet dell Cose: la capacità di scambiare ed elaborare metadati complessi con il resto del mondo (utilizzando ad esempio il web semantico).
The Arduino, however, still lacked one crucial thing to be able to participate in the Internet of Things: the ability to exchange and process complex metadata with the rest of the world (using for example the Semantic Web).
This deficit the world of digital artisans tried to remedy, with more or less successful solutions usually based on the combination of Arduino with embedded linux systems, such as the Raspberry Pi, which are very web-oriented and prepared to data processing, but lack of physical connections with the real world (in my own small I also made a few attempts: see Ardudome).

The makers of Arduino have responded to this ever more pressing need with a truly unique product: Arduino Yún.
Its uniqueness is due to several new features:
– The ability to combine into a single board a low-power embedded linux and an Arduino Leonardo
– The onboard Wifi which lets you connect to the network and makes it possible to load the sketch wireless
– The interaction with the widest range API (Google, Youtube, Twitter, etc.).
– Linux System on board based on OpenWrt, light and powerful at the same time
– Web interface and REST APIs that allow direct communication between the web pages and Arduino
– The form factor compatible with previous Arduino board

But the feature that I think above all else is the hub of the whole operation, is the Bridge library, which is the software that allows these two worlds to communicate with each other in a simple and fast way.
At first glance, reading the various examples, it all seemed quite incomprehensible, but using and experimenting with the library , you quickly realize the enormous potential and brilliance of this product: the connection between the two souls of the Yún is via a serial communication that allows a direct exchange of data in a bidirectional communication using simple dedicated functions. Therefore it is possible for example to directly access Arduino sensors data from the Linux side, or vice versa to access directly the output of a linux command from the Arduino side.
This mode of communication simplifies everything and vastly expands the incredible potential of the old Arduino board, but also those of a “trivial” embedded linux board.

For example we can very easily turn on an LED when we get an email, rather than monitor the power consumption of our house and save the data on a Google Spreadsheet document, or even build an alarm clock that according to traffic conditions retrieved from the Internet, decides whether it is early or too late to wake up.

The practical implications of this technology are really futuristic and endless, and we can imagine that this library will be the engine of the next Arduino’s revolution: Arduino Tre, which promises extreme performance compared to Arduino Yún, especially with regard to the Linux side. Will in fact have more power, an HDMI output and will be based on the Beagleboard system.

During these days I’m working on my first project which will be published as soon as completed.

Arduino Yún: welcome future!

Simple LDR switch

Posted by Luca Soltoggio on September 4, 2013
Posted in: Circuit schematics. Tagged: ldr, mosfet, sensor. Leave a comment

Hello to all,
these days I had the need for a “Dusk to Dawn” switch completely electronically (without relay) and a made with just few components.
I initially opted for a single transistor solutions, but unfortunately there were two drawbacks: the change of status was not quick but very gradual and the transistor generated a slight dropout that drastically decreased the brightness of the LED Strip.
At this point I opted for a N mosfet and in this way the change of status much better and  the dropout was just a few mV.
The final circuit is the following:

Immagine

The operation is very simple: the photoresistor (LDR) has a value of about 100kΩ in the dark and when this is illuminated the resistance decreases and the voltage divider between R1 and R2, means that the gate of Q1 goes below the threshold level (between 2V and 4V) turning off the the Led Strip. With R1 I can set sensitivity, while reversing R1 and R2, I reverse the operation (it turns on with light and turn off with the dark).
See you soon!

ArduDome: Opensource domotic with Arduino + RaspberryPI + PHP + JSON + jQuery

Posted by Luca Soltoggio on May 5, 2013
Posted in: Arduino. Tagged: arduino, domotic, ethernet, raspberry pi, serial. 10 Comments

Subtitle: Platform and browser-independent web based Arduino bidirectional remote control &amp; sensors. (Smartphone optizimized)

ardudome_interface

Here we are with the perhaps more interesting so far presented project.
I was looking on the internet for a way to control the Arduino via the web, but everything had to be estrememanete flexible, simple, adaptable to a smartphone but also had to have a two-way communication and automatic refresh. I have not found anything that had all of these combined, that’s why I decided to implement this project.
The majority of similar projects, have in my opinion incomplete features: those specific to automation usually have to download an application and therefore are not cross-platform, web-based ones either have a poor interface or require to refresh the page in order to update the state of outputs, or still have the opportunity to read sensors, but not change the outputs…
The requirement that I had in particular was that if I was changing the state of an output not remotely, but locally (via a button for example), the interface had to introduce almost in real time such modification exactly on the button of  the interface without having to refresh anything.
To do this I need to use a bit more complex web interface than the one coming from the Arduino Ethernet Shield, so I opted to use the Raspberry Pi web side (but can be used any Linux PC, or with some modifications even Windows), connected via USB (ie serial) with Arduino.
In this way I could implement some technologies, especially PHP and jQuery, which allowed me to realize everything.
The final operation is therefore very simple:
The interface shown in the photo above is a simple web page (as you can see is optimized for smartphones). Clicking on the slide we enable or disable an output (which is operated in real time), and every 5 seconds we have the automatic refresh of the outputs and of the analogic inputs also (in the above example I enabled only four outputs and one input).
The complete interface, contains the 13 outputs of the Arduino (not including the 0 and 1, which are used for serial communication), and the 6 analog inputs.
Connections and configuration is very simple: The Raspberry Pi or our PC is connected via USB to the Arduino board on which we loaded the sketch, then load up the interface and scripting on the Raspberry Pi et voila, you’re done.
IMPORTANT NOTE: In order for this to work, we need to disable the Arduino auto reset. This can be done by connecting a 10uF capacitor between RESET and GND. If this is not done the serial communication will not work properly!

Let see principle of operation:
The Arduino sketch gets a command from serial port and actvite/deactvate output or send value back.
The command has to be 7 chars long and begin with *CMD and end with /.
Between “*CMD” and “/”, you have to put the pin number (02, 03, 04, …, A5, A6) followed by the action:
V = value (read) – get the raw value for analog input
S = status (read) – is the output status of digital pins
H = high (write) – just for digital pins
L = low (write) – just for digital pins
T = toggle (write) – just for digital pins
This sketch is designed to work with his PHP script, but it could be integrated in other prjects using the syntax above.

The PHP script communicate with web interface and Arduino for getting and setting PIN status.
If invoked without parameters it returns a JSON string with status of digital output and value of analog input.
For example:
{“02″:0,”03″:0,”04″:0,”05″:0,”06″:0,”07″:0,”08″:0,”09″:0,”10″:0,”11″:0,”12″:0,”13″:0,”14″:756,”15″:745,”16″:722,”17″:679,”18″:634,”19”:494}
If invoked with the GET method it use two parameters: “pin” (from P02 to P13) and “cmd” (0 or 1).
For example http://raspberrypi/ardudome.php?pin=P13&cmd=1, will send the following command *CMD13H/ to Arduino
putting PIN13 in HIGH status.
This script is designed to work with his web interface, but it could be integrated in other projects using the syntax above.

The web interface, based on HTML, jQuery and AJAX, will call every 5 seconds the PHP script, udpating HTML with right values got from Arduino.
If a slider would be clicked or touched, changing his value, the script will suddenly call PHP script giving
PIN to change, and VALUE to set.
As you can see is all really simply and intuitive.

Now let’s see how to install:

1 – Download files from github (https://github.com/toggio/ardudome/)
2 – Load the sketch ArduDome.ino in your Arduino UNO board
3 – Put a 10uF capacitor between GND and RESET (this will disable autoreset feature on serial open)
4 – Connect you Arduino UNO through USB port to your RaspberryPI (or any other Linux PC) with apache and php preinstalled
5 – Put all files (except for Ardudome.ino and functions.ino) in your www directory (usually /var/www)
6 – Verify the name of your USB serial port (usually /dev/ttyACM0) and change it in ardudome.php ($serial->deviceSet(“/dev/ttyACM0”);)
7 – Give the user www-data permission for dialout (usermod -a -G dialout www-data)
8 – Verify connection (php ardudome.php)
9 – Open your web browser from smartphone or PC to http://yourraspberryip/ardudome.html

Have fun and see you at the next project!

Actarus: Open Source Arduino & Android-based High Altitude Balloon

Posted by Luca Soltoggio on April 11, 2013
Posted in: Arduino projects. Tagged: actarus, arduino, stratosphere. Leave a comment

actarus_500

In recent months I’ve been busy on a project I’m doing with some friends: launch a weather balloon into the stratosphere (over 38km of altutudine).
Although is not a new project in the world, and even in Italy (see the project Stratospera), we believe there is new compared to other similar projects.
First of all, the project is entirely open source, both for hardware than for the software: each aspect it will come out, will be published on the official website.
In secondo luogo, il “computer di bordo”, è realizzato interamente con Arduino, che si occuperà quindi della gestione della posizione, dei dati meteorologici, del datalogging, di una parte di comunicazione, e della gestione del “cut-off” di emergenza. Android si occuperà prevalentemente invece della gestione della posizione e dell’invio tramite rete cellulare dei dati in tempo reale (ovviamente quando sarà sotto copertura di rete, cioè realisticamente fino a 5-6km di altitudine).
As the tird innovation, there is in preparation, not from the first launch of course, the possibility of recovering the payload (containing all the electronic equipment), via a glider drone, which should autonomously bring everything to the point of launch…
From the point of view of the feasibility study we have finished, while now we are focusing on the Arduino software, and we are proceeding with the request of various authorizations, as well as to raise funds for various expenses …

If you want more information, you can go to our site:
http://actarusproject.wordpress.com/
Italian one:
https://actarusprojectitalia.wordpress.com/
This site is instead to raise funds on IndieGogo:
http://igg.me/at/actarus

We are also looking for people willing to contribute to the project, not only economically but also humanly to the project.
In addition, if some company wants to sponsor us with material that can be used in the project, we will be happy.
I will keep you updated!

Arduino Two: First Impressions and new features

Posted by Luca Soltoggio on November 5, 2012
Posted in: Arduino. Tagged: arduino, arm, atmel, power led, usb. Leave a comment

After months of waiting, the long-awaited Arduino Two is finally here 🙂

I have not yet had the opportunity to have it in my hands, but looking around in the network and specially in the official site, in this article i want to highlight the main news of this system compared to its predecessor Arduino UNO.
Well, what to say!
On the paper, the news are actually many and all derives from the new Atmel SAM3X8E CPU Cortex M3 with 32bits ARM architecture that replaces the old 8bits AVR:
1 – CPU Clock at 84Mhz (16Mhz compared to the previous version)
2 – 96Kb of RAM (compared to 2Kb)
3 – 512Kb of Flash (UNO had 32Kb)
4 – 12bits PWM and analog inputs (compared to 8bits)
5 – Output DAC – New for Arduino
6 – Higher number of PIN
7 – USB Host

Tis means an extremely higher processing speed, accuracy greatly improved and new possibilities thanks to the DAC and the USB host.

Performances are mainly related to the clock speed coupled with the 32bits (and of course more RAM).
With 32bit we are able to perform a 4bytes operation (8 x 4 = 32) with a single CPU clock. This means in an empirical way, that Arduino TWO might be about 20 times faster than Arduino UNO.

The most accuracy is related to the 12-bits analog inputs and PWM outputs: we have 16 times the old resolution, that means we have 4096 levels of conversion from analog to digital and vice versa compared to the 256 of the previous version. This allows a higher density of input data and a greater control on the PWM output.

The new features mainly concern the DAC pin (analog outputs, that is linear from 0 to 3.3 V) allowing for example to perform a MP3 file and hear it on the speakers connected to these outputs.

The only negative notes in my opinion (you have to be really picky though!), are the lack of an ethernet port – now essential in any application, and the fact that the TTL is 3.3V and not compatible 5V; with the wrong voltage you will fry pin or microcontroller itself. This leads to an incomplete compatibility with the existing shield or with third-party hardware.

Regarding consumption theoretically should be similar Arduino Mega although I did not find anything specific about it.

The programming instead always work through our Arduino IDE, updated to version 1.5 for the occasion, which contains additional libraries for the management of the new capabilities of the board. The programming mode is very similar to the old procedure.

Obviously, in this article we talked about a version out a few days ago and still in the testing phase. Time will tell if this card will completely replace the old Arduino, or if there will be a parallel market that will adapt depending on the final application. Surely those news lead further innovation in this field, such as to suggest that now the Arduino product may encroach further from the world of “geeks home” in the electronics professional.
Certainly a product like Arduino DUE, in terms of performance and precision is a product that is well suited for applications beyond entertainment home at a very attractive price (Arduino Store official price: Euro 39).
On the other hand, with this platform, it will be difficult to create embedded designs similar to those achieved with ATtiny85 or ATmega328 in standalone mode, but you can of course continue to use the old AVRs: as I said before, depending on the final application, you will find the best solution.

About Time will … See you next post!

Easy Level Sensor / Rain / Flooding / Touch / With single transistor – CORRECTED 03/10/2012

Posted by Luca Soltoggio on May 31, 2012
Posted in: Circuit schematics. Tagged: led, sensor, transistor. 13 Comments

Today I want to show you a project really very simple but effective that can be used for various applications.
This is a high resistance continuty sensor (current gain approximately 30000 times), based on the interesting Darlington NPN BC517, and very low cost.
The basic design published here simply allows you to turn on an LED by touching or immersing in water two metallic elements (cables, plates or whatever), but “cloning” the circuit and putting more transistors and more LEDs, we can get a gauge with 2, 3, 4 or 30 sectors.
It goes without saying nothing forbids to replace the LED with a relay in order to drive loads the most important.
But let’s see in detail the circuit:

The operation is quite trivial: by touching the two contacts of the sensor “SENS” with hands for example, the weak current flowing through the body is sufficient to excite the transistor via the resistor R1 which serves as protection if we join directly the two contacts. The BC517 is able to amplify this current approximately 30,000 times, for which a current of 10 uA, is able to slide up to 300 mA through the transistor. The resistor R2 serves to prevent accidental starting by grounding the base of the transistor, while R3 is simply the resistor to limit the current flowing through the LED.

Although simple, I believe that this project will be a starting point for other applications.
Also sometimes the simple things are the most functional and a little ‘analog electronics’ sometimes … is not bad …

Greetings and see you soon!

Update – 03/10/2012
Schema corrected: obviously one of the two leads did not go to mass but on the positive … I apologize for the mistake and thanx who rightly corrected me with his comments.

Smart NiMh battery charger based on Attiny85 (and Arduino)

Posted by Luca Soltoggio on April 20, 2012
Posted in: Arduino, Arduino projects. Tagged: arduino, attiny, fritzing, led, nimh, transistor, TTL. 45 Comments

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!

Driving a LED Strip with Arduino (also with PWM)

Posted by Luca Soltoggio on April 11, 2012
Posted in: Arduino, Circuit schematics. Tagged: arduino, led, transistor. 4 Comments

Some of my previous post that talked about LED Driver, have generated a bit of confusion in someone … So I wanted to do a bit of clarity.
In particular, in a comment, I was asked if the driver did well to drive the LED strips.
The answer is: NO WAY!
Nothing to do. We have to consider LED strips as if they were bulbs or motors at 12V: they do not require special drivers to be controlled, but we simply have to feed them with a proper voltage (usually just 12V).
This is because LED strips are not simple LED, but within them ther is a circuit of series-parallel LED equipped with suitable resistances, and are then handled as a normal 12V equipment.
In the case of single LED, which has no real operating voltage, we need instead oconstant current in order to operate.
The correct circuit for driving an LED strip with Arduino is therefore as follows:

Where VCC is obviously the Arduino output (digital or analog) and X1 represents my LED strip (or motor or any other dimmable equipment at 12V).
Q1 is a TIP120, but any NPN or darlington NPN is fine, as long as is adequate to the load power.
I hope this article could have done a little ‘clarity.
See you soon!

Posts navigation

← Older Entries
  • Recent Posts

    • Non-blocking “breathing” led
    • Ultra Low Power Led Flasher (with ATtiny)
    • Arduino Yún: welcome future!
    • Simple LDR switch
    • ArduDome: Opensource domotic with Arduino + RaspberryPI + PHP + JSON + jQuery
  • Archives

    • May 2015
    • January 2014
    • October 2013
    • September 2013
    • May 2013
    • April 2013
    • November 2012
    • May 2012
    • April 2012
    • March 2012
    • February 2012
  • Categories

    • Arduino
    • Arduino programming
    • Arduino projects
    • Circuit schematics
    • Uncategorized
  • Tag

    actarus arduino arm atmega atmega328 atmel attiny avr bootloader breadboard communication costant current domotic ethernet firmware fritzing hardware IDE ldr led linux embedded lm317 logic microbots mini pro mosfet ne555 nimh power led programmer pwm raspberry pi RGB robot robotics sensor serial sketch software standalone stratosphere transistor TTL usb wifi
  • Meta

    • Register
    • Log in
    • Entries feed
    • Comments feed
    • WordPress.com
  • Friends

    • Actarus Project
    • My Ip Address
Blog at WordPress.com.
Electronics & Arduino
Blog at WordPress.com.
Privacy & Cookies: This site uses cookies. By continuing to use this website, you agree to their use.
To find out more, including how to control cookies, see here: Cookie Policy
  • Follow Following
    • Electronics & Arduino
    • Already have a WordPress.com account? Log in now.
    • Electronics & Arduino
    • Customize
    • Follow Following
    • Sign up
    • Log in
    • Report this content
    • View site in Reader
    • Manage subscriptions
    • Collapse this bar
 

Loading Comments...