Jumat, 11 April 2014

Xathrya Sabertooth

Xathrya Sabertooth


WiringPi and Raspberry Pi

Posted: 11 Apr 2014 12:13 AM PDT

In this article, I use:

  • Raspberry Pi model B
  • Raspbian Wheezy

What is WiringPi?

WiringPi is a GPIO access library written in C for BCM2835 used in Raspberry Pi. It is designed to be familiar to people who have used the Arduinowiring” system.

Raspberry Pi has a 26-pin General Purpose Input/Output (GPIO) connector and this carries a set of signals and buses. There are 8 general purpose digital I/O pins – these can be programmed as either digital outputs or inputs. Besides input/output capability, one of these pins can be designated for PWM output too. Additionally there is a 2-wire I2C interface and a 4-wire SPI interface (with a 2nd select line, making it 5 pins in total) and the serial UART with a further 2 pins.

The Revision2 Raspberry Pi has an additional 4 GPIO lines on a separate connector which you have to solder on the board.

The I2C, SPI and UART interfaces can also be used as general purpose I/O pins when not being used in their bus modes, giving a grand total of 8 + 2 + 5 + 2 = 17 I/O pins on the P1 connector (plus 4 more on the P5 connector on a Revision 2 Pi).

WiringPi includes a command-line utility gpio which can be used to program and setup the GPIO pins. You can use this to read and write the pins and even use it to control them from shell scripts.

WiringPi is extendable and modules are provided to extend wiringPi to use analog interface devices on the Gertboard, and to use the popular MCP23x17/MCP23x08 (I2C 7 SPI) GPIO expansion chips, as well as module that will allow blocks of up to 4 74×595 shift registers to be daisy-chained together for an additional 32-bits worth of output as a single unit. (You can have several blocks of 4 74x595s if needed) One of the extension modules allows you to use an ATmega (e.g. Arduino, or the Gertboard) as more GPIO expansion too – via the Pi's serial port.

Additionally, you can easily write your own expansion modules to integrate your own peripheral devices with wiringPi as required.

WiringPi supports analog reading and writing, and while there is no native analog hardware on a Pi by default, modules are provided to support the Gertboards analog chips and other A/D and D/A devices can be implemented relatively easily.

WiringPi Installation

Before you can use WiringPi, of course you have to install it inside your Raspberry Pi. The installation is fairly simple. There are two way to get WiringPi installed to Pi: clone from git, download the source tar ball.

Before we go, it is recommended to check whether our distribution is up to date or not.

sudo apt-get update  sudo apt-get upgrade

Remember, this is optional.

Plan A

Installing using git, involving clone the source code tree from git repository. Make sure you have GIT installed. If you do not have one, you can install it by:

sudo apt-get install git-core

Then, clone the WiringPi source code tree by:

git clone git://git.drogon.net/wiringPi

To build WiringPi, do this command:

cd wiringPi  git pull origin  ./build

The second command will fetch an updated version of WiringPi source code (if any) and the third script will start building the library. The script will compile and install the library automatically. Remember to use root privilege to do this.

Plan B

If you can’t or don’t want to use git, use following step for manual download and installation:

Click on following URL: https://git.drogon.net/?p=wiringPi;a=summary

Look for the link marked as “snapshot”. Click on the top one which is the latest source code. You will download a tar.gz file with a name like “wiringPi-f18c8f7.tar.gz”. Note that the numbers and letter after “wiringPi” (f18c8f7 in this case) might be different. They are unique identifier for each release.

Extract and then build the package:

tar xfz wiringPi-f18c8f7.tar.gz  cd wiringPi-f18c8f7  ./build

Testing WiringPi

After success installation, we should check our WiringPi. WiringPi has a utility called “gpio” which is used for GPIO access. Here how we check:

gpio -v  gpio readall

Pin Numbering

Pin numbering of the BCM2835 GPIO port(s) on the Raspberry Pi has been a source of great confusion since the designs for the Pi were first published. In the early days (even beofre hardware was avalable) the default usable GPIO pins were simply referred to by number as GPIO0 through GPIO7. Additionally there were pins for other purposes, SPI, I2C and serial. This was highlighted on the original image on the Raspberry Pi Wiki site too.

Reference: Raspberry Pi GPIO Reference

wiringPi supports its own pin numbering scheme as well as the BCM_GPIO pin numbering scheme, and as of Version 2, it also supports the physical hardware pin numbers (for the P1 connector only). However, simplified wiringPi numbering is really recommended. In this way, our programs will be portable over different hardware revisions without needing any changes.

The following tables give the mapping of the Raspberry Pi GPIO Pins to the (P1) GPIO connector in relation to the pin numbers and the physical location on the connector. This is a representation of the GPIO connector as viewed looking at the board from above. The GPIO connector is to the top-right of the board with the Ethernet and USB sockets to the bottom.

P1 Header

gpio1

RPi_P1_header

P5 Header (Rev. 2 Pi only)

gpio21

RPi_P5_header

Further Read

Installing Adafruit’s Occidentalis on Raspberry Pi

Posted: 10 Apr 2014 07:18 AM PDT

Raspberry Pi, a small computer powered by ARM architecture is a very interesting board for learning embedded system. In this article we will discuss about how to install how to install Occidentalis v0.2 Rubus occidentalis.

For this article I use following:

  1. Slackware64 14.0
  2. Windows 8.1
  3. Raspberry Pi model B
  4. Official Occidentalis v0.2

You can use either Linux (in this article, Slackware) or Windows (in this article Windows 8.1). Just pick one and follow the rest of article for your choice.

About Occidentalis

Occidentalis is a embedded Linux distribution derived from Raspbian Wheezy. This distro is created and maintained by Adafruit Industries. The latest version is Occidentalis v0.2 which is derived from Raspbian Wheezy August 16 2012.

What differs occidentalis and other distro?

Occidentalis is tweaked in purpose to make DIY electronics more fun using Raspberry Pi. Yes, we have kernel modules for DS1307, AD525x, I2C digipots, HMC6352, BMP085, ADS1015, easy PWM/Servo control, and many more. It’s not very surprising as this distro is officially created for learning purpose in some Adafruit materials.

However, Adafruit is not full time linux distro maintainers, which means you can’t expect too much. Adafruit state that this distro is not for beginners or people who are new to linux.

Obtain the Materials

The Operating System images I used is Occidentalis v0.2 which can be downloaded from here. The size is about 900MB, per August 31, 2012.

Prepare the Disk (SD Card)

To boot the Raspberry Pi, an installation media and storage media is needed. All we need is a single SD card. On this article I use my 4GB SD card. The image we download on previous section will be stored on this card and later installed. Make sure you have a way to write on SD card.

Windows-based Instruction

For Windows user, you can follow this section to “burn” the image. For this purpose you need additional software for writing to SD card, such as Win32DiskImager utility.

  1. Extract the image (in this case Occidentalisv02.zip) so you will get an .img file.
  2. Insert SD card into SD card reader and check what drive letter it assigned to. For example G:\
  3. If it is not new, format it. Or at least make sure there is only one partition (FAT32 is recommended).
  4. Run the Win32DiskImager with administrator privileges.
  5. Select the image we have extracted (Occidentalis_v02.img).
  6. Select the drive letter of the SD card on our machine. Make sure you have the correct drive, or you will destroy data on that drive.
  7. Click Write and wait. The process should be not long.
  8. Exit the imager and eject the SD card

Beside Win32DiskImager, you can also use other tool such as Flashnul.

  1. Follow step 1 to step 3 for Win32DiskImager’s solution
  2. Extract Flashnul from the archive
  3. Open command prompt with elevated privilege (administrator privilege).
  4. Go to your extracted directory and run flashnul with argument “-p”. For example: flashnul -p
  5. You will get list of physical drive attached on your machine, and list of drive. Make sure the drive is correct. At time of writing this article, the SD card is detected as device number 1 with and mounted to drive G:
  6. Load the image to flashnul: flashnul 1 -L Occidentalis_v02.img
  7. If you get an access denied error, try re-plugging the SD card and make sure to close all explorer windows or folders open for the device. If still get denial, try substitute the device number with its drive letter: flashnul G: -L Occidentalis_v02.img

At this point, you have successfully written image to your SD card. And I assume you are. You can proceed to next stage.

Linux-based Instruction

Writing image on Linux is easier, in my opinion. The utility we use is “dd” which is already bundled on most distro. Make sure you know the correct device file for your SD card. In my machine I use a built in card reader and detect my SD card as /dev/sdb. It might be different on your system so better check it. For this article I use /dev/sdb to refer to SD card.

  1. Extract the image (in this case Occidentalisv02.zip) so you will get an .img file.
  2. Insert SD card into SD card reader .
  3. If it is not new, format it. Or at least make sure there is only one partition (FAT32 is recommended).
  4. Unmount the SD card if it is mounted. We need the whole SD card so if you see partition such as /dev/sdb1, etc its better you unmount them all.
  5. Write the image to SD card. Make sure you replace the input file after if= argument with correct path to .img file and “/dev/sdb” in the output file of= argument with your device. Also make sure to use whole SD drive and not their partition (i.e. not use /dev/sdb1, /dev/sdb1, etc). The command: dd bs=4M if=Occidentalis_v02.img of=/dev/sdb
  6. Run sync as root. This will ensure the write cache is flushed and safe to unmount SD card.
  7. Remove SD card from card reader.

If you hesitate to use terminal and prefer to use GUI method, here is the tutorial. Note that we

  1. Do step 1 to step 3 for previous tutorial. Make sure your directory or image file doesn’t contain any spaces.
  2. Install the ImageWriter tool from https://launchpad.net/usb-imagewriter
  3. Launch the ImageWriter tool (needs administrative privileges)
  4. Select the image file (in this case Occidentalis_v02.img) to be written to the SD card (note: because you started ImageWriter as administrator the starting point when selecting the image file is the administrator’s home folder so you need to change to your own home folder to select the image file)
  5. Select the target device to write the image to. In my case, it’s /dev/sdb
  6. Click the “Write to device” button
  7. Wait for the process to finish and then insert the SD card in the Raspberry Pi

At this point, you have successfully written image to your SD card. And I assume you are. You can proceed to next stage.

Running the Pi

You have write image and at this point your raspberry pi is ready. Now set up raspberry pi to boot: insert your SD card back to raspberry pi, put on power, plug video output (either HDMI or RCA).

To resize the SD card after installation, you can follow this article. Another way, you can use “raspi-config” utility to do it.

To log in on your Raspberry pi you can use the default login, which is:

Username: pi
Password: raspberry

Side Notes

I2C Support

I2C support is on SDA and SCL pins. To test, connect any I2C device to power, ground, SDA, and SCL. Run this command as root to detect which addresses are on the bus:

i2cdetect -y 0

SPI Support

SPI support is on the CLK/MOSI/MISO/CS0/CS1 pins. To test, connect your logic analyzer / scope to the pins and run following command to send some dummy data to the SPI port.

echo "xathrya test" > /dev/spidev0.0

You can simply read/write the /dev/spidev files to read/write from SPI.

One Wire Support

Most commonly used for DS18B20 temperature sensors. The Pi does not have ‘hardware’ 1-wire support but it can bit bang it with some success. Connect a DS18B20 with VCC to 2V, ground to ground, and Data to GPIO #4. Then connect a 4.7K resistor from Data to VCC.

Run following commands as root. Both command will be used to attach the temperature sub module.

modprobe w1-gpio  modprobe w1-therm

You can then run following command to read the temperature data from the bus:

cat /sys/bus/w1/devices/28-*/w1_slave

WiFi Support

The kernel has been patched with RTL8192cu-based patches.

Adafruit Kernel Source Code

You can get the kernel source code here.

Have fun :D

Kamis, 03 April 2014

Xathrya Sabertooth

Xathrya Sabertooth


List of Component and Device for ARM Tutorial Series

Posted: 02 Apr 2014 07:53 AM PDT

If you want to start tinkering in ARM, you may look at following list. This list is the parts you might need to follow my tutorials. You are not obligate to gather all because I always specify what materials you need in every article. However, you can see following as a reference.

Board

I have both learning board and development board.

For learning board I mainly focus on Nuvoton LB-NUC140.

For development board I mainly focus on DT-ARM NUC120.

Component

Buy one item of component isn’t too useful. A better idea is to buy a pack of that component, if possible.

  • Resistors:
    1. 100 ohm x 3
    2. 220 ohm x3
    3. 330 ohm x 3
    4. 10k ohm x 3
    5. 1k ohm x 3
  • Light Emitting Diode (LED): Choose 5mm LED any color. We use three LEDs at minimum.
  • Trimpot
  • Photocell
  • Pushbuttons x 2
  • Some wires, preferably breadboard jumper wires.
  • infrared LED
  • pin 0.1″ standard header x 6
  • Piezo speaker or buzzer

Some sensors we need:

  • Parallax PING))) sensor
  • TMP36 temperature sensor (or LM35 for alternative)
  • ADXL335 accelerometer breakout board
  • PNA4602 infrared sensor
  • Tilt sensor

and actuator:

  • Servo 5V, for example: Hitec HS-322HD or Vigor Hextronic

Tools

  • Standard A-B USB cable. This cable is used for connecting Arduino to computer
  • Breadboard. You can use either 400 pin or 170 pin breadboard.

Additional Gadgets

Of course this is optional.

  • Nintendo Nunchuk controller

List of Component and Device for Arduino Tutorial Series

Posted: 02 Apr 2014 07:46 AM PDT

If you want to start tinkering Arduino, you may look at following list. This list is the parts you might need to follow my tutorials. You are not obligate to gather all because I always specify what materials you need in every article. However, you can see following as a reference.

Arduino board

Normally I would use my Arduino Uno R3, unless told otherwise. You can use any Arduino board you think suitable for both your budget or your specidication.

Component

Buy one item of component isn’t too useful. A better idea is to buy a pack of that component, if possible.

  • Resistors:
    1. 100 ohm x 3
    2. 220 ohm x3
    3. 330 ohm x 3
    4. 10k ohm x 3
    5. 1k ohm x 3
  • Light Emitting Diode (LED): Choose 5mm LED any color. We use three LEDs at minimum.
  • Trimpot
  • Photocell
  • Pushbuttons x 2
  • Some wires, preferably breadboard jumper wires.
  • infrared LED
  • pin 0.1″ standard header x 6
  • Piezo speaker or buzzer

Some sensors we need:

  • Parallax PING))) sensor
  • TMP36 temperature sensor (or LM35 for alternative)
  • ADXL335 accelerometer breakout board
  • PNA4602 infrared sensor
  • Tilt sensor

and actuator:

  • Servo 5V, for example: Hitec HS-322HD or Vigor Hextronic

Tools

  • Standard A-B USB cable. This cable is used for connecting Arduino to computer
  • Breadboard. You can use either 400 pin or 170 pin breadboard.

Additional Gadgets

Of course this is optional.

  • Nintendo Nunchuk controller

Arduino Project: Arduino and LM35 Sensor

Posted: 02 Apr 2014 06:37 AM PDT

LM35 is an integrated circuit sensor that can be used to measure temperature with an electrical output proportional to the temperature in Celcius. Compared to thermistor, this component give more accurate result and generate higher voltage than thermocouples which may not require output amplifier.

LM35

The scale factor for this sensor is .01V/oC and doesn’t require any external calibration or trimming and maintains an accuracy of +/-0.4 oC at room temperature and +/-0.8 oC over range of 0oC to 100 oC. It has three leg: VCC, V-out, GND. The VCC is input voltage to supply the IC. The V-out is the pin which output the result temperature reading. The GND is ground.

LM35Detail

Objective

  • Measure surrounding temperature.
  • Display the measured temperature to serial communication

Prerequisite

  • none

Requirement

Following is all materials I use for this tutorial.

  • Arduino Uno R3
  • LM35

You can change the Arduino board to higher specification if you like.

You also need an USB A to B cable for upload our program to our Arduino.

Circuit

Here is the circuit image, created using Fritzing.

SimpleTemperatureSensor

Make sure you have the pin and leg configured properly. We will connect V-out leg to pin Analog 0 or A0. Next we can sense the temperature by read the value of this pin.

Code

Let’s see what code we use for this project and discuss it later.

const unsigned int TEMP_SENSOR_PIN = 0;   // We mean analog 0  const float SUPPLY_VOLTAGE = 5.0;         // If you use 3.3V, write it here.  const unsigned int BAUD_RATE = 9600;    const float get_temperature() {    const int sensor_voltage = analogRead(TEMP_SENSOR_PIN);    const float voltage = sensor_voltage * SUPPLY_VOLTAGE / 1024;    return (voltage * 100);  }    void setup() {    Serial.begin(BAUD_RATE);  }    void loop() {    Serial.print(get_temperature());    Serial.println(" C");    delay(1000);  }

We define the pin for reading as TEMP_PIN and assign this constant by 0. Remember that our reading will be in analog, so we will use analogRead() function instead of digitalRead() function. We use 5.0V from Arduino and write it as constant SUPPLY_VOLTAGE. If you use different voltage, write it there.

Result

Open serial communication on Arduino IDE. You will see something similar to this:

LM35SerialCommResult

Why it Works

The heart of this project is get_temperature().

const float get_temperature() {    const int sensor_voltage = analogRead(TEMP_SENSOR_PIN);    const float voltage = sensor_voltage * SUPPLY_VOLTAGE / 1024;    return (voltage * 100);  }

First, we read the output of sensor. The value range from 0 to 1023, which is a scale actually. We multiply the output with our SUPPLY_VOLTAGE, we got the exact value which has V unit. Division with 1024 is applied as the highest output is 1024 value. Because the precision is 10 mV/oC, we should convert the Volt unit to mV unit which we next multiply it by 1000. But wait, we then should divide it with 10 the scale, so we can get the shortcut: just multiply the voltage with 100. And that’s the recipe.

You can revise the code to make compact code by using magic number.

const float get_temperature() {    return (analogRead(TEMP_SENSOR_PIN) * 0.48828125);  }

Where did we get this magic number? You should figure it by yourself ;)

Sabtu, 29 Maret 2014

Xathrya Sabertooth

Xathrya Sabertooth


Arduino Project: Simple Traffic Light

Posted: 28 Mar 2014 04:44 AM PDT

Traffic lights, also known as traffic signals, traffic lamps, signal lights, stop lights, or technically as traffic control signals are signalling device positioned at road intersection, pedestrian crossings, and other locations to control competing flows of traffic.

In this project we will create a simple “traffic light”, imitating what traffic light does and program it using Arduino.

Objective

  • Three light switch each other to perform a simple traffic light.
  • Multiple digital signal output.
  • The order of light in one cycle: red – yellow – green – yellow

Prerequisite

Requirement

Following is all materials I use for this tutorial.

  • Arduino Uno R3
  • LEDs ( red x1, yellow x1, green x1 )
  • Resistor 10k ohm x3

You can change the Arduino board to higher specification if you like.

Because we want to do this as realistic as we can, we will use three different LED: one red LED, one yellow LED, one green LED.

The resistors should be 1/4 Watt resistors with resistance value of 10k ohm. You can use resistors of any band.

You also need an USB A to B cable for upload our program to our Arduino.

Circuit

Here is the circuit image, created using Fritzing.

Traffic Lamp

We use three LED at once. The first LED is red, the second LED should be yellow, and the last one is green LED. Remember which one is the positive leg and which one is negative leg (anode and cathode) for each LED. Connect attach the long leg of an LED (positive leg or anode) with resistor and then connect it to corresponding pin. Red one will use pin 12, yellow will be in 11, and green would use pin 10. Connect the short leg (negative leg or cathode) to the ground (GND).

Code

Let’s see what code we use for this project and discuss it later.

#define RED_PIN 12  #define YELLOW_PIN 11  #define GREEN_PIN 10      // timeout for each LED in second  int timeout[3] = {10, 1, 20};  int currentLED = 0;  int alternate = -1;    int enumLED[3] = { RED_PIN, YELLOW_PIN, GREEN_PIN };    void setup() {    pinMode(RED_PIN, OUTPUT);    pinMode(YELLOW_PIN, OUTPUT);    pinMode(GREEN_PIN, OUTPUT);  }    void loop() {    digitalWrite(enumLED[currentLED], LOW);    if (currentLED == 0) {      alternate = 1;    } else if (currentLED == 2) {      alternate = -1;    }    currentLED = currentLED + alternate;    digitalWrite(enumLED[currentLED], HIGH);      delay(timeout[currentLED] * 1000);  }

We define three constant here: RED_PIN, YELLOW_PIN, and GREEN_PIN for red, yellow, and green LED respectively.  However this time we only define it using macro not as constant. Then we create an array of LED as enumLED. This array will be our shortcut to switch between LED. For indexing we use currentLED variable.

The timeout array is an array which stored delay interval for each LED in seconds. This means our lights won’t turned on in same duration.

The alternate variable is used to increment the currentLED index. Remember that in one cycle, we define the LED switching as red – yellow – green – yellow.

Result

LED is turned on in following order:

  • red for 10 seconds
  • yellow for 1 second
  • green for 20 seconds
  • yellow for 1 second
  • red for 10 seconds at another cycle.

Why it Works

Our code is as simple as turned off current LED and turned on the next LED. The previous, current, and next LED are defined in an array and we use currentLED variable as an index. The alternate is used to increase or decrease the index and make our LED obey our pattern.

Jumat, 28 Maret 2014

Xathrya Sabertooth

Xathrya Sabertooth


Arduino Project: Toggle the LED with Push Button

Posted: 27 Mar 2014 06:13 PM PDT

This project is upgrade of previous project (Simple Push Button). In this project, we just need to press the push button once to turn it on or off, instead of hold it.

Objective

  • Make the LED turn on or off by pressing the push button.

Prerequisite

Requirement

Following is all materials I use for this tutorial.

  • Arduino Uno R3
  • LED
  • Push button

You can change the Arduino board to higher specification if you like. The LED I use will emit red light as it is powered by electricity.

There are some kind of push button exists. In our project, we need only push button with four legs.

You also need an USB A to B cable for upload our program to our Arduino and also for serial communication.

Circuit

Here is the circuit image, created using Fritzing.

PushButton

To build the circuit, attach the LED as shown in the figure. Attach the long leg of an LED (positif leg or anode) to pin 13. Attach the short leg (negative leg or cathode) to the ground (GND). On Arduino Uno, there is also a built in status LED which connected to pin 13. When our Arduino running successfully, both status LED and external LED will start to blink.

The push button has four legs (or four pins) as shown above. Two opposite pins connect when the button is pushed; otherwise, they are disconnected. In one side, we connect one leg to Arduino pin 7. In other side, we supply 5V electricity to one leg. The other leg is connected to a 10k ohm resistor before going to ground.

Code

Let’s see what code we use for this project and discuss it later.

const unsigned int BUTTON_PIN = 7;  const unsigned int LED_PIN = 13;    int old_button_state = LOW;  int led_state = LOW;    void setup() {    pinMode(LED_PIN, OUTPUT);    pinMode(BUTTON_PIN, INPUT);  }    void loop() {    const int CURRENT_BUTTON_STATE = digitalRead(BUTTON_PIN);      if (CURRENT_BUTTON_STATE != old_button_state &&        CURRENT_BUTTON_STATE == HIGH)    {      led_state = (led_state == LOW ? HIGH : LOW);      digitalWrite(LED_PIN, led_state);      delay(50);    }    old_button_state = CURRENT_BUTTON_STATE;  }

Notice that we define two constant here, LED_PIN which is for LED, and BUTTON_PIN for the push button. Both are defined as different purpose, the LED is output pin while the push button is input.

There is no significance change to our code from previous project. Things we can notice are the existence of two new variables: old_button_state and led_state.

Result

You should see that LED is turned on or off whenever we press the button.

Why it Works

We define a global variable named led_state to store the current state of our LED. It will be LOW when the LED is on and HIGH otherwise. In loop() we check the button’s current state. When we press the button, the switches is in HIGH logic and we toggle the content of led_state.

The global variable old_button_state is used to store the old state of push button. If we don’t do this, when we press and hold the button, the state will constantly be HIGH and we’d toggle the LED’s state continuously. Because this happens so fast it seems like the LED’s constantly on. When we release the button, the LED is in a more or less arbitrary state. Therefore we use previous push button to guard the state of LED.

 

Arduino Project: Push Button

Posted: 27 Mar 2014 05:17 PM PDT

Pushbutton is one of common component found in projects. The mechanism is simple, we press push button and we got a signal, otherwise it (should) gives nothing.

Objective

  • Make the LED turn on when we press the push button.
  • Make the LED turn off when we release the push button.

Prerequisite

Requirement

Following is all materials I use for this tutorial.

  • Arduino Uno R3
  • LED
  • Push button

You can change the Arduino board to higher specification if you like. The LED I use will emit red light as it is powered by electricity.

There are some kind of push button exists. In our project, we need only push button with four legs.

You also need an USB A to B cable for upload our program to our Arduino and also for serial communication.

Circuit

Here is the circuit image, created using Fritzing.

PushButton

To build the circuit, attach the LED as shown in the figure. Attach the long leg of an LED (positif leg or anode) to pin 13. Attach the short leg (negative leg or cathode) to the ground (GND). On Arduino Uno, there is also a built in status LED which connected to pin 13. When our Arduino running successfully, both status LED and external LED will start to blink.

The push button has four legs (or four pins) as shown above. Two opposite pins connect when the button is pushed; otherwise, they are disconnected. In one side, we connect one leg to Arduino pin 7. In other side, we supply 5V electricity to one leg. The other leg is connected to a 10k ohm resistor before going to ground.

Code

Let’s see what code we use for this project and discuss it later.

const unsigned int BUTTON_PIN = 7;  const unsigned int LED_PIN = 13;    void setup() {    pinMode(LED_PIN, OUTPUT);    pinMode(BUTTON_PIN, INPUT);  }    void loop() {    const int BUTTON_STATE = digitalRead(BUTTON_PIN);      if (BUTTON_STATE == HIGH) {      digitalWrite(LED_PIN, HIGH);    } else {      digitalWrite(LED_PIN, LOW);    }  }

Notice that we define two constant here, LED_PIN which is for LED, and BUTTON_PIN for the push button. Both are defined as different purpose, the LED is output pin while the push button is input.

Our code is as simple as checking the push button state and then output the corresponding voltage to LED.

Result

You should see that LED is turned on whenever we press the push button and turned off when we don’t. To keep the LED turned on, we have to keep pressing the push button.

Why it Works

Why do we need resistor for push button?

The problem is that we expect the push button to return a default value (LOW) in case it isn't pressed. But when the button isn't pressed,it would not be directly connected to ground and would flicker because of static and interference. A little bit of current flows through the resistor,and this helps prevent random noise from changing the voltage that the input pin sees.

When the button is pressed, there will still be 5 volts at Arduino’s digital pin, but when the button isn’t pressed, it will cleanly read the connection to the ground. We call this a pull-down resistor. That is, we have to connect the Arduino’s signal pin to power through the pushbutton and connect the other pin of pushbutton to ground using a resistor.

You can also wire this circuit the opposite way, with a pullup resistor keeping the input HIGH, and going LOW when the button is pressed. If so, the behavior of the sketch will be reversed, with the LED normally on and turning off when you press the button.

Arduino Project: Software Serial Communication

Posted: 27 Mar 2014 08:04 AM PDT

In most case, our device are stand-alone application, which means we don’t involve any additional computer for operation. However, we can still make Arduino interact with our computer in such nice way. We use serial communication to achieve this.

Most possible reason for communication is debugging purpose. We analyze Arduino state for various input and condition given, by reading output shown by Arduino. The serial communication can also be used for communication of two devices.

Arduino have built-in support for serial communication on pin 0 and 1, but what if we need more serial ports? Here come SoftwareSerial Library to rescue. This library has been developed to allow serial communication to take place on the other digital pins of our Arduino board, using software to replicate the functionality of the hardwired RX and TX lines. This can be extremely helpful when the need arises to communicate with two serial enabled devices, or to talk with just one device while leaving the main serial port open for debugging purpose.

Objective

  • Use pin 10 and 11 as virtual RX and TX serial lines.
  • Echo data received from main RX serial line to virtual TX line.
  • Echo data received from virtual RX line to main TX serial line.

Prerequisite

Requirement

Following is all materials I use for this tutorial.

  • Arduino Uno R3

You can change the Arduino board to higher specification if you like.

You also need an USB A to B cable for upload our program to our Arduino and also for serial communication.

Circuit

Here is the circuit image, created using Fritzing.

SerialComm

We don’t need any extra component to do this project.

SerialComm_Diagram

Code

Let’s see what code we use for this project and discuss it later.

#include <SoftwareSerial.h>    SoftwareSerial EuSerial(10, 11);        // Bind RX and TX to pin 10 and 11    void setup() {    // Open serial communications and wait for port to open    Serial.begin(57600);    // Wait for serial port to connect. Needed for Leonardo only    while(!Serial);      Serial.println("Arduino SoftwareSerial Demo");      // Set the data rate for the SoftwareSerial port    EuSerial.begin(4800);    EuSerial.println("Hello, world?");  }    void loop() {    // Echo data from virtual RX to main TX    if (EuSerial.available())      Serial.write(EuSerial.read());    // Echo data from main RX to virtual TX    if (Serial.available())      EuSerial.write(Serial.read());  }

Here we have two serial line: Arduino serial and virtual serial by SoftwareSerial. Both have difference baud rate, the main lines have baud rate 57600 while the virtual lines have baud rate 4800.

The initialization of both lines are similar. We use begin() function to set the baud rate of both lines.

In loop(), we will echo every input we got. To do that, we should check the availability first. This is done by executing available(). To read data, Arduino use read() function. To send data to other end, Arduino provide print() and println() function. These functions are slight different where println() send extra new line character at the end of transmission.

Result

You need two serial lines connected to your PC. The result should be similar to Simple Serial Communication project. It is strongly recommended to use PuTTY and connect to both port recognized by your computer.

Why it Works

We have demonstrate serial communication in this project. The word serial means “one after the other”. Serial data transfer is a transmission method where data is transferred one bit at a time, one right after the other.

Information is passed back & forth between the computer and Arduino, by essentially, setting a pin high or low.

There are two condition of logic in circuit, HIGH and LOW. Some microcontrollers might define HIGH and LOW difference, but in Arduino Uno we have HIGH logic as 5V and LOW logic as 0V. If you know boolean value, yes this is boolean value with HIGH is true and LOW is false.

Arduino Project: Turn On/Off LED using Serial Communication

Posted: 27 Mar 2014 07:34 AM PDT

Objective

  • Input/Output from and to Arduino.
  • Make the LED turn on when we input certain command.
  • Make the LED turn off when we input certain command.

Prerequisite

Requirement

Following is all materials I use for this tutorial.

  • Arduino Uno R3
  • LED

You can change the Arduino board to higher specification if you like. The LED I use will emit red light as it is powered by electricity.

You also need an USB A to B cable for upload our program to our Arduino and also for serial communication.

Circuit

Here is the circuit image, created using Fritzing.

Blinking LED

To build the circuit, attach the LED as shown in the figure. Attach the long leg of an LED (positif leg or anode) to pin 13. Attach the short leg (negative leg or cathode) to the ground (GND). On Arduino Uno, there is also a built in status LED which connected to pin 13. When our Arduino running successfully, both status LED and external LED will start to blink.

We don’t need extra resistor for this project, but make sure you are using pin 13. If you do connect it to other pin, it might be destroyed. The reason is that pin 13 has an internal resistor that other pins don’t have which limit current to our LED.

ExampleCircuit_sch

Code

Let’s see what code we use for this project and discuss it later.

const unsigned int LED_PIN = 13;  const unsigned int BAUD_RATE = 9600;    char command;    void setup() {     pinMode(LED_PIN, OUTPUT);     Serial.begin(BAUD_RATE);  }    void loop() {     if (Serial.available() > 0) {        command = Serial.read();        if (command == '1') {           Serial.println("Led on");           digitalWrite(LED_PIN, HIGH);        } else if (command == '2') {           Serial.println("Led off");           digitalWrite(LED_PIN, LOW);        } else {           Serial.println("Led pattern 1");           digitalWrite(LED_PIN, HIGH);           delay(250);           digitalWrite(LED_PIN, LOW);           delay(500);           digitalWrite(LED_PIN, HIGH);           delay(250);           digitalWrite(LED_PIN, LOW);        }        Serial.print("You enter: ");        Serial.println(command);     }  }

Notice that we define two constant here, LED_PIN which is pin we use, and BAUD_RATE for the baud rate. Baud rate is the rate of character transferred every second. Notice that 1 character is 1 byte, which is also 8 bit. Both party who communicate must agree on same baud rate before transmission began. If baud rate is not equal, data can’t be transferred correctly.

Here we introduce a object called Serial. This object handles input output in serial communication. To use this object we should initialize which baud rate we use. In this case we use 9600, which is common baud rate used.

To do input, we should check the availability first. This is done by executing Serial.available(). Single character can be read by read() function. To send data to other end, Arduino provide print() and println() function. These functions are slight different where println() send extra new line character at the end of transmission.

We define three commands: ’1′, ’2′, and ’3′. If we enter 1, we turn the LED on. If we enter 2, we turn the LED off. If we enter 3, we make the LED on/off in certain pattern.

Result

Once the program is uploaded, open “Serial Monitor” window in Arduino IDE. It is our tool to do serial communication using Arduino IDE. You can open it by navigate to Tool > Serial Monitor. Another way to do it is press CTRL + SHIFT + M at once.

SerialMonitor

To give input to Arduino, type in to the text box and click on “Send” button. Now give input of number 1, 2, 3 and see the result. You should see the LED are turned on and off according to your command.

Why it Works

It similar to project Simple Serial Communication where we received some commands from serial communication. This command are then processed to determine which routine should we do.

Arduino Project: Simple Serial Communication

Posted: 27 Mar 2014 06:27 AM PDT

In most case, our device are stand-alone application, which means we don’t involve any additional computer for operation. However, we can still make Arduino interact with our computer in such nice way. We use serial communication to achieve this.

Most possible reason for communication is debugging purpose. We analyze Arduino state for various input and condition given, by reading output shown by Arduino. The serial communication can also be used for communication of two devices.

Objective

  • Input/Output from and to Arduino.
  • Doing simple math operation and output the result.
  • Echoing the user inputs.

Prerequisite

  • none

Requirement

Following is all materials I use for this tutorial.

  • Arduino Uno R3

You can change the Arduino board to higher specification if you like.

You also need an USB A to B cable for upload our program to our Arduino and also for serial communication.

Circuit

Here is the circuit image, created using Fritzing.

SerialComm

We don’t need any extra component to do this project.

SerialComm_Diagram

Code

Let’s see what code we use for this project and discuss it later.

const unsigned int BAUD_RATE = 9600;    int a = 5;  int b = 10;  int c = 20;    void setup() {    Serial.begin(BAUD_RATE);    Serial.println("Arduino Serial Communication Demo");      Serial.print("a = ");    Serial.println(a);      Serial.print("b = ");    Serial.println(b);      Serial.print("c = ");    Serial.println(c);      Serial.print("a + b = ");      // addition    Serial.println(a + b);      Serial.print("a * c = ");      // multiplication    Serial.println(a * c);      Serial.print("c / b = ");      // division    Serial.println(c / b);    Serial.print("b - c = ");      // subtract    Serial.println(b - c);  }    void loop() {    if (Serial.available()) {      Serial.write(Serial.read());    }  }

In the first line we declare a constant, BAUD_RATE, which has value 9600. Baud rate is the rate of character transferred every second. Notice that 1 character is equal to 1 byte or 8 bit. Both party who communicate using serial communication must agree on same baud rate before transmission began. If baud rate is not equal, data can’t be transferred correctly.

Here we introduce a object called Serial. This object handles input output in serial communication. To use this object we should initialize which baud rate we use. In this case we use 9600, which is common baud rate used.

We declare three variables for our math operation: a, b, and c with their respective value. In setup() we do some basic math operation over these three variables. The result will be presented every time we initiate serial connection.

In loop(), we will echo every input we got. To do that, we should check the availability first. This is done by executing available(). To read data, Arduino use read() function. To send data to other end, Arduino provide print() and println() function. These functions are slight different where println() send extra new line character at the end of transmission.

Result

Once the program is uploaded, open “Serial Monitor” window in Arduino IDE. It is our tool to do serial communication using Arduino IDE. You can open it by navigate to Tool > Serial Monitor. Another way to do it is press CTRL + SHIFT + M at once.

SerialMonitor

Here we will be presented with the result of our math operation.

To give input to Arduino, type in to the text box and click on “Send” button. You will see nice similar message you type. Here is the result after I type “Satria Ady Pradana”:

SerialMonitor2

Alternatively, you can use puTTY in Windows or Linux terminal in Linux. However we won’t cover this subject.

Why it Works

We have demonstrate serial communication in this project. The word serial means “one after the other”. Serial data transfer is a transmission method where data is transferred one bit at a time, one right after the other.

Information is passed back & forth between the computer and Arduino, by essentially, setting a pin high or low.

There are two condition of logic in circuit, HIGH and LOW. Some microcontrollers might define HIGH and LOW difference, but in Arduino Uno we have HIGH logic as 5V and LOW logic as 0V. If you know boolean value, yes this is boolean value with HIGH is true and LOW is false.

Rabu, 26 Maret 2014

Xathrya Sabertooth

Xathrya Sabertooth


Arduino Project: Simple Blinking LED

Posted: 25 Mar 2014 06:43 AM PDT

Blink LED, like what it should be, we make certain LED blinking. We can define “blinking” as continuous condition switching between ON and OFF condition. This is the simplest project we can do for Arduino.

Objective

  • Make LED blinking.

Prerequisite

  • Basic understanding of LED

Requirement

Following is all materials I use for this tutorial.

  • Arduino Uno R3
  • LED

You can change the Arduino board to higher specification if you like. The LED I use will emit red light as it is powered by electricity.

You also need an USB A to B cable for upload our program to our Arduino.

Circuit

Here is the circuit image, created using Fritzing.

Blinking LED

To build the circuit, attach the LED as shown in the figure. Attach the long leg of an LED (positif leg or anode) to pin 13. Attach the short leg (negative leg or cathode) to the ground (GND). On Arduino Uno, there is also a built in status LED which connected to pin 13. When our Arduino running successfully, both status LED and external LED will start to blink.

We don’t need extra resistor for this project, but make sure you are using pin 13. If you do connect it to other pin, it might be destroyed. The reason is that pin 13 has an internal resistor that other pins don’t have which limit current to our LED.

ExampleCircuit_sch

Code

Let’s see what code we use for this project and discuss it later.

const unsigned int LED_PIN = 13;  const unsigned int PAUSE = 500;    void setup() {     pinMode(LED_PIN, OUTPUT);  }    void loop() {     digitalWrite(LED_PIN, HIGH);     delay(PAUSE);     digitalWrite(LED_PIN, LOW);     delay(PAUSE);     }

Notice that we define two constant here, LED_PIN which is pin we use, and PAUSE for the delay interval which is 500 ms.

The heart of this project is pin 13. We use this pin as output pin. Therefore we initialize pin 13 as an output pin with the statement:

pinMode(LED_PIN,OUTPUT);

Next in the main loop, we turn the LED on by:

digitalWrite(LED_PIN, HIGH);

and turn it off by:

digitalWrite(LED_PIN, LOW);

And we now know that digitalWrite() function is used to output signal on a pin.

The delay() command is used to tell Arduino to do nothing for given time. In our case, we make Arduino wait for 500 miliseconds.

Result

LED is blinking.

Why it Works

There are  two condition of logic in circuit, HIGH and LOW. Some microcontrollers might define HIGH and LOW difference, but in Arduino Uno we have HIGH logic as 5V and LOW logic as 0V. If you know boolean value, yes this is boolean value with HIGH is true and LOW is false.

The LED we use is active-high LED, which means it can turn on when it is given HIGH voltage.

Selasa, 25 Maret 2014

Xathrya Sabertooth

Xathrya Sabertooth


Arduino and List of Arduino Boards

Posted: 24 Mar 2014 06:19 PM PDT

Arduino is an open source electronics prototyping platform based on flexible, easy-to-use hardware and software. It is a single board microcontroller intended for artists, designers, hobbyists, and anyone interested in creating interactive objects or environment.

A microcontroller (sometimes abbreviated as µC, uC, or MCU) is an integrated circuit contain a processor core, memory, and programmable input/output peripherals. One can program microcontroller for various purpose especially for control machinery, for example: robotics, automobile engine control systems, remote controls, toys, and other embedded systems. In short, microcontroller is similar to our brain, controlling input, process, and output of electronic device. This behavior similar to computer, however microcontroller already have memory, timer, and storage for store executable program.

A microcontroller can’t be used directly. It is a IC chip and we can’t use it immediately, which means we have to supply a minimum system to run it. That is analogically same with processor and motherboard. Fortunately, Arduino has provide all we need to utilize a microcontroller. Arduino has wrapped all the complicated things and provide us with nice programmable board without us to do extra work to create a system minimum.

The Boards

When we talk about Arduino, we are actually talking about Arduino family. There are some boards released by Arduino, designed using either Atmel AVR processor and ARM-based processor. The main differences between those boards are the:

  • Type of processor
  • Number of inputs and outputs
  • Form factor

An Arduino board is basically a single board with appropriate system and components enough to power and run a microcontroller. One Arduino product (Arduino board) might differs in some aspects when compared to another Arduino product. Arduino boards use megaAVR series of chips, specifically the ATmega8, ATmega 328, ATmega 1280, and ATmega 2560; and also ARM Cortex chips.

The boards include a 5 volt linear regulator. We can power Arduino board from power connector or from USB connector when we program it.

Most of Arduino products include 16MHz crystal oscillator (or ceramic resonator in some variants). Although some designes such as the LilyPad run at 8 MHz.

As stated before, Arduino is an open-source. Arduino exposed the schematics for all of their products, open to everyone. Anyone who interested can make their own arduino board. However, Arduino restricts that no one should use Arduino brand name for third party maker. That means, any company who create the Arduino clone cannot use Arduino name.

The Shields

Shields are printed circuit expansion boards that plug into the normally supplied Arduino pin-headers. Shields can provide motor controls, GPS, ethernet, LCD display, or any function specific to that shield. These peripherals are sold separately and can also be made by ourselves.

Programming in Arduino

Microcontroller is programmable, so does Arduino board which use microcontroller to run its awesomeness.

Arduino has official Integrated Development Environment (IDE) in use of programming for Arduino. The IDE is a cross-platform application written in Java and derived from the IDE for the Processing programming language and Wiring projects. It is designed to introduce programming to artists and other newcomers unfamiliar with software development. There are also alternative to Arduino IDE which you can see from this list.

Arduino programs are written in C or C++, however the structure is simplified. Arduino use software library called Wiring from original Wiring project which makes many common input/output operations much easier. We at minimum only need to define two function to make a runnable cyclic executive program:

  • setup(): a function run once at the start of a program that can initialize settings.
  • loop(): a function called repeatedly until the board powers off.

An example for simple source code (also called as “sketch”) which will blinks a LED on and off:

const unsigned int LED_PIN = 13;    void setup() {     pinMode (LED_PIN, OUTPUT);    // Enable pin 13 for digital output  }    void loop() {     digitalWrite(LED_PIN, HIGH);  // Turn on the LED     delay(1000);                  // Wait 1 second or 1000 miliseconds     digitalWrite(LED_PIN, LOW);   // Turn off the LED     delay(1000);                  // Wait 1 second  }

The programs compiled or created are in binary format which executable by the microcontroller. However this binary program is different with binary program in our computer. These programs use the different format, the mnemonic used by microcontroller.

The last step in programming Arduino is “upload” the program to Arduino. In common practice, uploading a program to microcontroller need external device called “programmer”. The fancy thing is, Arduino needs no external programmer. It has built component in board which allow our ordinary computer as programmer.

List of Boards

Arduino release numbers of board. This list might not be up to date. Please refer this page for more accurate Arduino product.

  1. Arduino Uno
  2. Arduino Leonardo
  3. Arduino Due
  4. Arduino Yùn
  5. Arduino Tre
  6. Arduino Micro
  7. Arduino Robot
  8. Arduino Esplora
  9. Arduino ADK
  10. Arduino Ethernet
  11. Arduino Mega 2560
  12. Arduino Mini
  13. Arduino BT (BlueTooth)
  14. LilyPad Arduino USB
  15. LilyPad Arduino Simple
  16. LilyPad Arduino SimpleSnap
  17. LilyPad Arduino
  18. Arduino Nano
  19. Arduino Pro Mini
  20. Arduino Pro
  21. Arduino Fio

For quick comparison:

Name
Processor
Operating Voltage/Input Voltage
CPU Speed
Analog In/Out
Digital IO/PWM
EEPROM [KB]
SRAM [KB]
Flash [KB]
USB
UART
UnoATmega3285 V/7-12 V16 Mhz6/014/61232Regular1
DueAT91SAM3X8E3.3 V/7-12 V84 MHz12/254/12-965122 Micro4
LeonardoATmega32u45 V/7-12 V16Mhz12/020/712.532Micro1
Mega 2560ATmega25605 V/7-12 V16Mhz16/054/1548256Regular4
Mega ADKATmega25605 V/7-12 V16Mhz16/054/1548256Regular4
MicroATmega32u45 V/7-12 V16Mhz12/020/712.532Micro1
MiniATmega3285 V/7-9 V16Mhz8/014/61232--
NanoATmega168

ATmega328
5 V/7-9 V16Mhz8/014/60.512

1
1

2
16

32
Mini-B1
EthernetATmega3285 V/7-12 V16Mhz6/014/41232Regular-
EsploraATmega32u45 V/7-12 V16Mhz--12.532Micro-
ArduinoBTATmega3285 V/2.5-12 V16Mhz6/014/61232-1
FioATmega328P3.3 V/3.7-7 V8 Mhz8/014/61232Mini1
Pro (168)ATmega1683.3 V/3.35-12 V8 Mhz6/014/60.512116-1
Pro (328)ATmega3285 V/5-12 V16Mhz6/014/61232-1
Pro MiniATmega1683.3 V/3.35-12 V

5 V/5-12 V
8 Mhz

16 MHz
6/014/60.512116-1
LilyPadATmega168V
ATmega328V
2.7-5.5 V/2.7-5.5 V8 Mhz6/014/6 0.512116--
LilyPad USBATmega32u43.3 V/3.8-5V8 Mhz4/09/412.532Micro-
LilyPad SimpleATmega3282.7-5.5 V/2.7-5.5 V8 Mhz4/09/41232--
LilyPad SimpleSnapATmega3282.7-5.5 V/2.7-5.5 V8 Mhz4/09/41232--
YùnATmega32u45 V/5 V

you should provide regulated 5V
16 MHz7/020/712.532Regular

Micro
1
TreATmega32u416 MHz6/014/7 (5 V)

12/4 (3.3 V)
12.532

We might cover some Arduino models. To get start, you can check following models:

  • Arduino Uno, basic one with a replaceable chipset.
  • Arduino Mega 2560, provides a bunch of inputs and output.
  • Arduino LilyPad, wearable as clothes.
  • Arduino Nano, very small device.

For my series of tutorials unless told otherwise, I will use Arduino Uno and sometime Arduino Mega.

Reference

  1. Arduino official site – http://arduino.cc/