• Arduino

    Learn about Arduino and make various interesting projects using Arduino...

    Read More
  • 555 IC

    Learn about 555 IC and make various interesting projects using 555 IC...

    Read More
  • Basic Electronics

    Learn about Basic Electronics and various electronic components and their working...

    Read More
Showing posts with label Arduino. Show all posts
Showing posts with label Arduino. Show all posts

Sending Data to Two Serial Devices at the Same Time

You want to send data to a serial device such as a serial LCD, but you are already using
the built-in serial port to communicate with your computer.

On a Mega this is not a problem, as it has four hardware serial ports; just create two
serial objects and use one for the LCD and one for the computer:

void setup() {
// initialize two serial ports on a Mega
Serial.begin(9600); // primary serial port
Serial1.begin(9600); // Mega can also use Serial1 through Serial3
}

On a standard Arduino board (such as the Uno or Duemilanove) that only has one
hardware serial port, you will need to create an emulated or “soft” serial port.
You can use the distributed SoftwareSerial library for sending data to multiple devices.


Select two available digital pins, one each for transmit and receive, and connect your
serial device to them. It is convenient to use the hardware serial port for communication
with the computer because this has a USB adapter on the board. Connect the device’s
transmit line to the receive pin and the receive line to the transmit pin.Connecting a serial device to a “soft” serial port
In your sketch, create a Software Serial object and tell it which pins you chose as your
emulated serial port.
 In this example, we’re creating an object named  serial_lcd, which
we instruct to use pins 2 and 3:
/*
* SoftwareSerialOutput sketch
* Output data to a software serial port
*/
#include <SoftwareSerial.h>
const int rxpin = 2; // pin used to receive (not used in this version)
const int txpin = 3; // pin used to send to LCD
SoftwareSerial serial_lcd(rxpin, txpin); // new serial port on pins 2 and 3
void setup()
{
Serial.begin(9600); // 9600 baud for the built-in serial port
serial_lcd.begin(9600); //initialize the software serial port also for 9600
}
int number = 0;
void loop()
{
serial_lcd.print("The number is "); // send text to the LCD
serial_lcd.println(number); // print the number on the LCD
Serial.print("The number is ");
Serial.println(number); // print the number on the PC console
delay(500); // delay half second between numbers
number++; // to the next number
}
If you are using Arduino versions prior to 1.0, download the NewSoftSerial  library  and  replace  references  to  SoftwareSerial  with  NewSoftSerial:
// NewSoftSerial version
#include <NewSoftSerial.h>
const int rxpin = 2; // pin used to receive from LCD
const int txpin = 3; // pin used to send to LCD
NewSoftSerial serial_lcd(rxpin, txpin); // new serial port on pins 2 + 3
This sketch assumes that a serial LCD has been connected to pin 3 as shown in Figure 4-6, and that a serial console is connected to the built-in port. The loop will repeatedly display the same message on each:
The number is 0
The number is 1

Receiving Serial Data in Arduino

You want to receive data on Arduino from a computer or another serial device; for
example, to have Arduino react to commands or data sent from your computer.


It’s easy to receive 8-bit values (chars and bytes), because the Serialfunctions use 8-bit values. This sketch receives a digit (single characters 0 through 9) and blinks the
LED on pin 13 at a rate proportional to the received digit value:

/*
* SerialReceive sketch
* Blink the LED at a rate proportional to the received digit value
*/
const int ledPin = 13; // pin the LED is connected to
int blinkRate=0; // blink rate stored in this variable
void setup()
{
Serial.begin(9600); // Initialize serial port to send and receive at 9600 baud
pinMode(ledPin, OUTPUT); // set this pin as output
}
void loop()
{
if ( Serial.available()) // Check to see if at least one character is available
{
char ch = Serial.read();
if( isDigit(ch) ) // is this an ascii digit between 0 and 9?
{
blinkRate = (ch - '0'); // ASCII value converted to numeric value
blinkRate = blinkRate * 100; // actual rate is 100ms times received digit
}
}
blink();
}
// blink the LED with the on and off times determined by blinkRate
void blink()
{
digitalWrite(ledPin,HIGH);
delay(blinkRate); // delay depends on blinkrate value
digitalWrite(ledPin,LOW);
delay(blinkRate);
}
Upload  the sketch and send messages using the Serial Monitor. Open the Serial Monitor
by clicking the Monitor icon and type a digit in the text box at the top
of the Serial Monitor window. Clicking the Send button will send the character typed
into the text box; if you type a digit, you should see the blink rate change


Programmable LED MATRIX [ARDUINO]


This led matrix can be programmed using arduino, various patterns can be made using functions and by specifying the LED's on the array.

components-

transistors- BC547
Resistances- 470 ohm and 1K ohm
Arduino Uno
hookup wires
breadboard

Circuit Schematic-



Sketch-

int x [4] = {13,12,11,4}; //Pins of x axis in numerical order
int y [4] = {10,7,8,2}; //Pins of y axis in numerical order
void setup ()
{
 for (int a=0; a<4; a++) { //Output pins
 pinMode(x[a], OUTPUT);
 }
  for (int b=0; b<4; b++) { //Output pins
 pinMode(y[b], OUTPUT);
 }
}
void flash (int x1,int y1) { //Function to flash leds
  x1-=1; //-1 because arrays starts with 0 so the 4 is 3 and 3 is 2...
  y1-=1;
  for (int c=0; c<4;c++) {
if(c!=x_){ //This will turn off every single x led except the led you wanna flash
  digitalWrite(x[c], LOW);
}
  }
  for (int d=0; d<4;d++) {
if(d!=y_){ //This will turn off every single y led except the led you wanna flash
digitalWrite(y[d], LOW);
}
  }
  digitalWrite(x[(x1)],HIGH); 
  delay(80);
  //Flashes the x led you want to
  digitalWrite(y[(y1)],HIGH);
  delay(80);
}

void loop () {

flash(1,1);
flash(1,2);
flash(1,3);
flash(1,4);
flash(2,1);
flash(2,2);
flash(2,3);
flash(2,4);
flash(3,1);
flash(3,2);
flash(3,3);
flash(3,4);
flash(4,1);
flash(4,2);
flash(4,3);
flash(4,4);

flash(1,1);
flash(2,1);
flash(3,1);
flash(4,1);
flash(1,2);
flash(2,2);
flash(3,2);
flash(4,2);
flash(1,3);
flash(2,3);
flash(3,3);
flash(4,3);
flash(1,4);
flash(2,4);
flash(3,4);
flash(4,4);


}

Programmable LED MATRIX [ARDUINO] video DEMO
























ARDUINO: Driving DC Motors using Transistors and PWM

DC motors, which you can find in numerous devices around your home, rotate continuously when a DC voltage is applied across them. Such motors are commonly found as the driving motors in radio control (RC) cars, and as the motors that make the discs spin in your DVD player. DC motors are great because they come in a huge array of sizes and are generally very cheap. By adjusting the voltage you apply to them, you can change their rotation speed. By reversing the direction of the voltage applied to them, you can change their direction of rotation as well. This is generally done using an H-bridge,Brushed DC motors,employ stationary magnets and a spinning coil. Electricity is transferred to the coil using “brushes,” hence the reason they are called brushed DC motors. Unlike 
brushless DC motors (such as stepper motors), brushed DC motors are cheap and have easier speed control. However, brushed DC motors do not last as long because the brushes can wear out over time. These motors work through an inductive force. When current passes through the spinning coil, it generates a magnetic field that is either attracted to or repelled by the stationary magnets depending on the polarity. By using the brushes to swap the polarity each half rotation, you can generate angular momentum. The exact same configuration can be used to create a generator if you manually turn the armature. This will generate a fluctuating magnetic field that will, in turn, generate current. This is 
how hydroelectric generators work—falling water turns the shaft, and a current is produced. This capability to create current in the opposite direction is why we will use a diode to ensure that the motor cannot send current back into your circuit when it is forcibly turned.

Handling High-Current Inductive Loads

DC motors generally require more current than the Arduino’s built-in power supply can provide, and they can create harmful voltage spikes due to their inductive nature. To address this issue, you first learn how to effectively isolate a DC motor from your Arduino, and then how to power it using a secondary supply. A transistor will allow the Arduino to switch the motor on and off safely, as well
as to control the speed using the pulse-width modulation (PWM).

Before you hook up your DC motor, it’s important to understand what all
these components are doing:



■Q1 is an NPN bipolar-junction transistor (BJT) used for switching the separate 9V supply to the motor. There are two types of BJTs, NPN and PNP, which refer to the different semiconductor “doping” techniques used to create the transistor.You can simplistically think of an NPN transistor as a voltage-controlled switch that allows you to inhibit or allow current flow.
■A 1kΩ resistor is used to separate the transistor’s base pin from the control
pin of the Arduino.
■U1 is the DC motor.
■C1 is for filtering noise caused by the motor.
■D1 is a diode used to protect the power supply from reverse voltage
caused by the motor acting like an inductor.



Controlling Motor Speed with PWM

//Simple Motor Speed Control Program
const int MOTOR=9; //Motor on Digital Pin 9
void setup()
{
pinMode (MOTOR, OUTPUT);
}
void loop()
{
for (int i=0; i<256; i++)
{
analogWrite(MOTOR, i);
delay(10);
}
delay(2000);
for (int i=255; i>=0; i--)
{
analogWrite(MOTOR, i);
delay(10);
}
delay(2000);
}

XBEE Cheatsheet


    Source: www.tunnelsup.com

Atmega AT328P pin mapping


Arduino:Reading Digital Inputs with Pulldown Resistors

All digital inputs use a pullup or pulldown resistor to set the “default state” of the input pin. Imagine the circuit in Figure below without the 10kΩ resistor. In this scenario, the pin would obviously read a high value when the button is pressed.But, what happens when the button is not being pressed? In that scenario, the input pin you would be reading is essentially connected to nothing—the input pin is said to be “floating.” And because the pin is not physically connected to 0V or 5V, reading it could cause unexpected results as electrical noise on nearby pins causes its value to fluctuate between high and low. To remedy this, the pulldown resistor is installed as shown in Figure .

Now, consider what happens when the button is not pressed with the pulldown resistor in the circuit: The input pin will be connected through a 10kΩ resistor to ground. While the resistor will restrict the flow of current, there is still enough current flow to ensure that the input pin will read a low logic value. 10kΩ is a fairly common pulldown resistor value. Larger values are said to be weak pulldowns because it easier to overcome them, and smaller resistor values are said to be strong pulldowns because it is easier for more current to flow through them to ground. When the button is pressed, the input pin is directly connected to 5V through the button. 

Now, the current has two options:
■It can flow through a nearly zero resistance path to the 5V rail.
■It can flow through a high resistance path to the ground rail

Pulldown and pullup resistors are important because they ensure that the button does not create a short circuit between 5V and ground when pressed and that the input pin is never left in a floating state.

Sketch
simple LED control using push button

const int LED=9; //The LED is connected to pin 9
const int BUTTON=2; //The Button is connected to pin 2
void setup()
{
pinMode (LED, OUTPUT); //Set the LED pin as an output
pinMode (BUTTON, INPUT); //Set button as input
}
void loop()
{
if (digitalRead(BUTTON) == LOW)
{
digitalWrite(LED, LOW);
}
else
{
digitalWrite(LED, HIGH);
}
}

Arduino: Pulse-Width Modulation with analogWrite()

we can generate analog output values by using a trick called pulse-width modulation(PWM). Select pins on each Arduino can use the analogWrite()command to generate PWM signals that can emulate a pure analog signal when used with certain peripherals. These pins are marked with a ~ on the board.On the Arduino Uno, Pins 3, 5, 6, 9, 10, and 11 are PWM pins. If you’re using an Uno, you can continue to use the circuit from Figure 2-1 to test out the analogWrite()command with your LED. Presumably, if you can decrease the voltage being dropped across the resistor, the LED should glow more dimly because less current will flow. That is what you will try to accomplish using PWM via the analogWrite()command. The analogWrite()command accepts two arguments: the pin to control and the value to write to it.The PWM output is an 8-bit value. In other words, you can write values from 0 to 28-1, or 0 to 255. Try using a similar forloop structure to the one you used previously to cycle through varying brightness values .

SKETCH:
const int LED=9; //define LED for Pin 9
void setup()
{
pinMode (LED, OUTPUT); //Set the LED pin as an output
}
void loop()
{
for (int i=0; i<256; i++)
{
analogWrite(LED, i);
delay(10);
}
for (int i=255; i>=0; i--)
{
analogWrite(LED, i);
delay(10);
}
}

What does the LED do when you run this code? You should observe the LED fading from off to on, then from on to off. Of course, because this is all in the main loop, this pattern repeats ad infinitum. Be sure to note a few differences in this forloop. In the first loop, i++is just shorthand code to represent i=i+1. Similarly, i--is functionally equivalent to i=i–1. The first for loop fades the
LED up, and the second loop fades it down.

Pulse Width Modulation

PWM control can be used in lots of circumstances to emulate pure analog control, but it cannot always be used when you actually need an analog signal. For instance, PWM is great for driving direct current (DC) motors at variable speeds, but it does not work well for driving speakers unless you supplement it with some external circuitry. Take a moment to examine how PWM actually works.


PWM works by modulating the duty cycle of a square wave (a signal that 
switches on and off). Duty cycle refers to the percentage of time that a square 
wave is high versus low. You are probably most familiar with square waves that 
have a duty cycle of 50%—they are high half of the time, and low half of the time.

The analogWrite()command sets the duty cycle of a square wave depending
on the value you pass to it:

■Writing a value of 0 with analogWrite()indicates a square wave with a
duty cycle of 0 percent (always low).
■Writing a 255 indicates a square wave with a duty cycle of 100 percent
(always high).
■Writing a 127 indicates a square wave with a duty cycle of 50 percent
(high half of the time, low half of the time).

The graphs in Figure show that for a signal with a duty cycle of 25 percent, it is high 25 percent of the time, and low 75 percent of the time. The frequency of this square wave, in the case of the Arduino, is about 490Hz. In other words, the signal varies between high (5V) and low (0V) about 490 times every second.So, if you are not actually changing the voltage being delivered to an LED, why do you see it get dimmer as you lower the duty cycle? It is really a result of your eyes playing a trick on you! If the LED is switching on and off every 1ms (which is the case with a duty cycle of 50 percent), it appears to be operating at approximately half brightness because it is blinking faster than your eyes can perceive. Therefore, your brain actually averages out the signal and tricks you into believing that the LED is operating at half brightness.











Arduino: Working with “Bouncy” Buttons

When was the last time you had to hold a button down to keep a light on?
Probably never. It makes more sense to be able to click the button once to turn it
on and to click the button again to turn it off. This way, you do not have to hold
the button down to keep the light on. Unfortunately, this is not quite as easy as
you might first guess. You cannot just look for the value of the switch to change
from low to high; you need to worry about a phenomenon called switch bouncing.
Buttons are mechanical devices that operate as a spring-damper system. In
other words, when you push a button down, the signal you read does not just
go from low to high, it bounces up and down between those two states for a
few milliseconds before it settles.


The button is physically pressed at the 25ms mark. You would expect the
button state to be immediately read as a high logic level as the graph on the left
shows. However, the button actually bounces up and down before settling, as
the graph on the right shows.

If you know that the switch is going to do this, it is relatively straightforward
to deal with it in software. Next, you write switch-debouncing software that
looks for a button state change, waits for the bouncing to finish, and then reads
the switch state again. This program logic can be expressed as follows:

1.  Store a previous button state and a current button state (initialized
to LOW).
2.  Read the current button state.
3.  If the current button state differs from the previous button state, wait 5ms
because the button must have changed state.
4.  After 5ms, reread the button state and use that as the current button state.
5.  If the previous button state was low, and the current button state is high,
toggle the LED state.
6.  Set the previous button state to the current button state.
7.  Return to step 2

Within the program flow (listed in the preceding steps) is a series of repeating steps that need to be applied to changing variable values. Because you’ll want to repeatedly debounce the switch value, it’s useful to define the steps for debouncing as a function that can be called each time. This function will accept the previous button state as an input and outputs the current debounced button
state. The following program accomplishes the preceding steps and switches the LED state every time the button is pressed.

Sketch:
const int LED=9; //The LED is connected to pin 9
const int BUTTON=2; //The Button is connected to pin 2
boolean lastButton = LOW; //Variable containing the previous
//button state
boolean currentButton = LOW; //Variable containing the current
//button state
boolean ledOn = false; //The present state of the LED (on/off)
void setup()
{
pinMode (LED, OUTPUT); //Set the LED pin as an output
pinMode (BUTTON, INPUT); //Set button as input (not required)
}
/*
* Debouncing Function
* Pass it the previous button state,
* and get back the current debounced button state.
*/
boolean debounce(boolean last)
{
boolean current = digitalRead(BUTTON); //Read the button state
if (last != current) //if it's different…
{
delay(5); //wait 5ms
current = digitalRead(BUTTON); //read it again
return current; //return the current value
}
void loop()
{
currentButton = debounce(lastButton); //read deboucned state
if (lastButton == LOW && currentButton == HIGH) //if it was pressed...
{
ledOn = !ledOn; //toggle the LED value
}
lastButton = currentButton; //reset button value
digitalWrite(LED, ledOn); //change the LED state
}

Simple Motor Control using Arduino

We are first going to simply control the speed of a DC motor, in one direction, using a power transistor, diode, and external power supply to power the motor and a potentiometer to control the speed. Any suitable NPN power transistor designed for high current loads can replace the TIP120 transistor. However, I would highly recommend you use a power Darlington-type transistor. Make sure you choose a transistor that can handle the voltage and current your motor will draw. It may be necessary to fit a heat sink to the transistor if it is pulling more than about an amp.

The external power supply can be a set of batteries or a “wall wart”-style external DC power supply. The power source must have enough voltage and current to drive the motor. The voltage must not exceed that required by the motor. For my testing purposes I used a DC power supply that provided 5V at 500mA. This was enough for the 5V DC motor I was using. If you use a power supply with voltage higher than the motor can take, you may damage it permanently.

























Connect It Up

First, make sure your Arduino is powered off by unplugging it from the USB cable. Now, take the required parts and connect them up as in Figure. It is essential for this project that you check and double check all of your connections are as they should be before supplying power to the circuit, as failure to do so may result in damage to your components or even your Arduino.



Enter the Code

Open up your Arduino IDE and type in the code

int potPin = 0; // Analog in 0 connected to the potentiometer
int transistorPin = 9; // PWM Pin 9 connected to the base of the transistor
int potValue = 0; // value returned from the potentiometer

void setup() {
// set the transistor pin as output:
pinMode(transistorPin, OUTPUT);
}
void loop() {
// read the potentiometer, convert it to 0 - 255:
potValue = analogRead(potPin) / 4;
// use that to control the transistor:
analogWrite(transistorPin, potValue);
}

Before uploading your code, disconnect the external power supply to the motor and ensure the potentiometer is turned fully counterclockwise. Now upload the code to the Arduino. Once the code is uploaded, connect the external power supply. You can now turn the potentiometer to control the speed of the motor.

Pulsating Lamp using Arduino

In this project we will alter the brightness of the LED, and make a pulsating lamp, using the analogWrite() function.

Parts Required

Table 3-3lists the parts required for Project 7. We simply use an LED and resistor.










Connect It Up

The circuit for this project is simply a green LED connecting, via a current-limiting resistor, between ground and Digital Pin 11.



Enter the Code

Open up your Arduino IDE and type in the code .

int ledPin = 11;
float sinVal;
int ledVal;
void setup()
 {
pinMode(ledPin, OUTPUT);
}
void loop() {
for (int x=0; x<180; x++)
 {
// convert degrees to radians then obtain sin value
sinVal = (sin(x*(3.1412/180)));
ledVal = int(sinVal*255);
analogWrite(ledPin, ledVal);
delay(25);
}
}

Verify and upload. You will now see your LED pulsate on and off steadily. Instead of a simple on/off state, we are now adjusting its brightness.

LED Chase Effect using Arduino

We are now going to use a string of LEDs (10 in total) to make an LED chase effect (see Table 3-1), similar to that used
on the car KITT in the KnightriderTV series or the Cylons in Battlestar Galactica.













Connect It Up

First, make sure your Arduino is powered off by unplugging it from the USB cable. Now take your breadboard, LEDs, resistors, and wires, and connect everything up as in Figure 3-1. Check your circuit thoroughly before connecting the power back up to the Arduino.



Enter the Code
Open up your Arduino IDE and type in the code .

 LED Chase Effect

byte ledPin[] = {4, 5, 6, 7, 8, 9, 10, 11, 12, 13}; // Create array for LED pins
int ledDelay = 65; // delay between changes
int direction = 1;
int currentLED = 0;
unsigned long changeTime;
void setup() {
for (int x=0; x<10; x++)
{
// set all pins to output
pinMode(ledPin[x], OUTPUT);
}
changeTime = millis();
}
void loop() {
if ((millis() - changeTime) > ledDelay)
{
// if it has been ledDelay ms since last change
changeLED();
changeTime = millis();
}
}
void changeLED()
 {
for (int x=0; x<10; x++)
{
// turn off all LED's
digitalWrite(ledPin[x], LOW);
}
digitalWrite(ledPin[currentLED], HIGH); // turn on the current LED
currentLED += direction; // increment by the direction value
// change direction if we reach the end
if (currentLED == 9) {direction = -1;}
if (currentLED == 0) {direction = 1;}
}

If you have done everything
correctly, you should now see the LEDs appear to move along the line, then bounce back to the start.

By changing the value of ledDelay, you can make the LED ping back and forth at different speeds. Try different
values to see what happens. You have to stop the program and manually change the value of ledDelay, then upload the amended code to see any changes.











Arduino cheatsheet!!


what is Arduino ?

Arduino is an open-source electronics prototyping platform based on flexible, easy-to-use hardware and software. It's intended for artists, designers, hobbyists, and anyone interested in creating interactive objects or environments. This Google Code project is the home for the development of the Arduino platform. For more information on using Arduino, see the Arduino homepage.

The Arduino software consists of a development environment (IDE) and the core libraries. The IDE is written in Java and based on the Processing development environment. The core libraries are written in C and C++ and compiled using avr-gcc and AVR Libc. The source code for Arduino is now hosted on GitHub.

“Arduino is a single-board microcontroller designed to make the process of using electronics in
multidisciplinary projects more accessible. The hardware consists of a simple open-source hardware board designed around an 8-bit Atmel AVRmicrocontroller, though a new model has been designed around a 32-bit Atmel ARM.
The software consists of a standard programming language compiler and a boot loader that executes on the microcontroller.

 The Arduino board is made up of an Atmel AVR microprocessor, a crystal or oscillator (a crude clock that sends time pulses at a specified frequency to enable it to operate at the correct speed) and a 5V voltage regulator. (Some Arduinos may use a switching regulator, and some, like the Due, are not 5 volt). Depending on what type of Arduino you have, it may also have a USB socket to enable it to be connected to a PC or Mac to upload or retrieve data. The board exposes the microcontroller’s I/O (input/output) pins to enable you to connect those pins to other circuits or to
sensors, etc.
To program the Arduino (make it do what you want it to), you also use the Arduino IDE, which is a piece of free software that enables you to program in the language that the Arduino understands. In the case of the Arduino, the language is based on C/C++ and can even be extended through C++ libraries. The IDE enables you to write a computer program, which is a set of step-by-step instructions that you then upload to the Arduino. Your Arduino will then carry out those instructions and interact with whatever you have connected to it. In the Arduino world, programs
are known as “sketches”.