From 太極
Jump to navigation Jump to search



The Arduino Uno is a microcontroller board based on the ATmega328 (datasheet). It has 14 digital input/output pins (of which 6 can be used as PWM outputs), 6 analog inputs, a 16 MHz ceramic resonator, a USB connection, a power jack, an ICSP header, and a reset button. It contains everything needed to support the microcontroller; simply connect it to a computer with a USB cable or power it with a AC-to-DC adapter or battery to get started.

This means that the Uno can execute 16 million 8 bit instructions per second.

Basic facts:

  • It has digital input/output pins and analog inputs but no analog output pins. See PWM/Analog output.
  • Each pin can only handle 40 mA of current. So there is a chance to blow the chip if you directly connect motors to it without a motor controller (That's what people invented H-bridge), not to say about changing current. See also the discussion stackexchange and arduino forums (Google: why we should not direct connect motor to arduino).


The Arduino Due is a microcontroller board based on the Atmel SAM3X8E ARM Cortex-M3 CPU (datasheet). It is the first Arduino board based on a 32-bit ARM core microcontroller. It has 54 digital input/output pins (of which 12 can be used as PWM outputs), 12 analog inputs, 4 UARTs (hardware serial ports), a 84 MHz clock, an USB OTG capable connection, 2 DAC (digital to analog), 2 TWI, a power jack, an SPI header, a JTAG header, a reset button and an erase button.

Since UNO is 8-bit and DUE is 32-bit, there is difference in terms of storage. On the Arduino Uno (and other ATMega based boards) an int stores a 16-bit (2-byte) value. This yields a range of -32,768 to 32,767 (minimum value of -2^15 and a maximum value of (2^15) - 1).

On the Arduino Due, an int stores a 32-bit (4-byte) value. This yields a range of -2,147,483,648 to 2,147,483,647 (minimum value of -2^31 and a maximum value of (2^31) - 1). See and Discussion of comparing UNO & Due.

Another interesting point is neither of them have floating point support (Beaglebone bone and Rasp Pi do have FP).

Comparison of Boards


  1. Flash memory (program space), is where the Arduino sketch is stored. Flash memory is the same technology used for thumb-drives and SD cards. It is non-volatile, so your program will still be there when the system is powered off.
  2. SRAM (static random access memory) is where the sketch creates and manipulates variables when it runs. This memory includes 3 kinds of space: static data, heap and stack.
  3. EEPROM is memory space that programmers can use to store long-term information.

Wio Terminal

Get Started with Wio Terminal

Arduino alternatives

Arduino IDE

The serial port is ttyACM0 for UNO, ttyUSB0 for Nano under my Ubuntu. To detect the serial port device, first run

ls -t /dev/tty*

Then plug in Arduino UNO and run the above command again. See

Source code in Github

Install Arduino IDE under Ubuntu

Using source code (For some reason, I cannot find ~/.arduino/preference.txt file with this approach)

sudo apt-get install arduino-core
sudo apt-get install openjdk-7-jre
# Go to to download the latest software
tar xzvf arduino-1.0.5-linux32.tgz
cd arduino-1.0.5
sudo ./arduino

The 2nd approach is (I think it is better since I can find and modify ~/.arduino/preference.txt file).

sudo apt-get update && sudo apt-get install arduino arduino-core

After Arduino IDE is installed, I can change the font (Line 11 of preference.txt file) from Monospaced DejaVu Sans Mono,plain,12 to something like

editor.font=DejaVu Sans Mono,bold,16
editor.font=Courier New,bold,16

PS. Open AbiWord to check available fonts in Ubuntu OS.

Update 6/27/2016: I download the tar ball from official website in order to get the latest version. Running <> from Arduino 1.6.9 under Ubuntu

  • sudo is not needed. Just run <>
$ '/home/brb/binary/arduino-1.6.9/' 
Adding desktop shortcut, menu item and file associations for Arduino IDE... done!
  • if we open Arduino as a regular user, we cannot write to the serial port. So we need to run sudo usermod -a -G dialout <username> to fix it. Remember to log out and log in again for this change to take effect. See
  • Not sure if this is necessary: sudo chmod a+rw /dev/ttyACM0 (It seems if I issue it, I don't need to log out & log in)

Using Arduino IDE as user instead sudo in Ubuntu

brb@brb-P45T-A:~$ ls -lt /dev | more
total 0
crw-rw-rw-  1 root tty         5,   2 Sep 15 20:07 ptmx
crw-rw-rw-  1 root tty         5,   0 Sep 15 20:06 tty
drwxr-xr-x  2 root root          3820 Sep 15 20:06 char
drwxr-xr-x  4 root root            80 Sep 15 20:06 serial
crw-rw----  1 root dialout   166,   0 Sep 15 20:06 ttyACM0
crw-rw----  1 root dialout     4,  64 Sep 15 19:51 ttyS0

sudo usermod -a -G dialout yourusename

Then log out and log in again. Type 'groups' to see if the current user belongs to dialout group.

No only we don't need to use 'sudo' to run arduino, we can also save a sketch under user's ownership.

The 2nd trick is to make the menu on the Arduino IDE to be visible. Open and edit arduino-1.0.5/arduino file, and then modify the last line so it becomes "java". What this essentially does is uses the Arduino look and feel instead of the GTK version.

Arduino Reset Button

To "reset" the Uno power it down, hold down the reset button, and, while still holding the reset button down, power it up again. This will prevent the existing sketch from running. You can then upload a new sketch.

ArduBlock - Scratch like interface for Arduino

ArduBlock is a programming environment designed to make “physical computing with Arduino as easy as drag-and-drop.” Instead of writing code, worrying about syntax, and (mis)placing semicolons, ArduBlock allows you to visually program with an snapped-together list of code blocks.

Arduino Library

For example, if we want to try the pong game which uses the vgax library, we can copy the vgax folder and paste it to arduino-1.6.5-r5/libraries folder (I am using Linux OS). The library will appear under Arduino IDE -> File -> Example when we launch the IDE next time.

Arduino Web Editor


Arduino Simulators

4 Arduino Simulators You Can Use in Your Electronics Projects

C users


Alternatives for retrieving sensor data from Arduino compatible microcontrollers into R

Programming using Scratch

Since this will involve uploading a firmware to Arduino, we now can only do programming using S4A. We can go back to use Arduino IDE for programming if we want to discard using S4A.

s4a is available as deb package.

Simple example (button & LED)

  1. Connect wires according to I use 330 Ohm resistor. The digital pin I use is 3, not 2.
  2. sudo s4a to launch S4A
  3. Follow the instruction in to try 1. LED blinking and 2. LED and button in S4A.

One problem with this idea is the arduino board needs to be connected to computer all the time.




  • Check google to see the difference between dc motor and servo. This site explains the difference among dc motor, servo motor and step motor. has an article to explain stepper motors.
  • Adafruit motor shield v2. It can be used to control DC motors, stepper motors and servos. It can drive up to 4 DC motors or 2 stepper motors.

Arduino IDE, Books, Forums


# Create a file 'Prescaler.h' under ~/sketchbook/
# ln -s /home/brb/sketchbook/Prescaler.h ~/binary/arduino-1.0.5/hardware/arduino/cores/arduino/Prescaler.h
# nano ~/sketchbook/Prescaler.h and change WProgram.h to Arduino.h.
# OK. It is the time to run sketch_05_01_prescale from Arduino IDE > sketchbook > ArduinoNextSteps.

See the post.




It is possible to send a byte of data from the Arduino to a personal computer and graph the result. This is called serial communication because the connection appears to both the Arduino and the computer as a serial port, even though it may actually use a USB cable.

  • First, download and install Processing software (currently 2.0.3)
  • Check out for wiring. Very simple. Just one potentiometer and 3 wires (one goes to gnd, 2nd one goes to 5v and the 3rd one connects to A0).
  • Check out for the idea of how to plot the analog data using Processing. It contains 2 steps: 1. Open Arduino IDE (sudo is necessary if OS is not Windows) and compile/run a code to print byte to serial using Serial.write(). 2. Open Processing (sudo is necessary if OS is not Windows) and run a code. We shall be able to see a beautiful streaming graph appearing on screen. Both codes are attached below.


int sensorPin = A0;    // analog input pin to hook the sensor to
int sensorValue = 0;  // variable to store the value coming from the sensor
void setup() {
  Serial.begin(9600); // initialize serial communications
void loop() {
  sensorValue = analogRead(sensorPin)/4; // read the value from the sensor
  Serial.write(sensorValue); // print bytes to serial


import processing.serial.*;
Serial myPort;        // The serial port
float xPos = 0;             // horizontal position of the graph
void setup () {
  size(800, 600);        // window size
  // List all the available serial ports
  String portName = Serial.list()[0];
  myPort = new Serial(this, portName, 9600);
void draw () {
  // nothing happens in draw.  It all happens in SerialEvent()
void serialEvent (Serial myPort) {
  // get the byte:
  int inByte =;
  // print it:
  float yPos = height - inByte;
  // draw the line in a pretty color:
  line(xPos, height, xPos, height - inByte);
  // at the edge of the screen, go back to the beginning:
  if (xPos >= width) {
    xPos = 0;
    // clear the screen by resetting the background:
  else {
    // increment the horizontal position for the next reading:



Data Logging

Robot based on BOE shield for Arduino

My robot is based on 'Shield for Arduino' which means I can use Arduino IDE + C code style to write my code instead of using PBASIC programming which is used in another similar robot.

Projects from each chapters

Chapter 3. Activity 2: Re-test the servos

We can use Pins 11 and 12 instead of 12 and 13. Be sure to adjust your code accordingly.

Chapter 4. Activity 2

First time we disconnect robot from the computer and let it go (forward, left turn, right turn and back ward).

Chapter 5 (Whiskers). Activity 3 or 4

See my robot is in action on

Robot whisker.jpg

Chapter 7 (Infrared headlight). Activity 4

Similar to Chapter 5 but IR detectors are used. See the robot in action on

Activity 7: Drop-off detection (Very Cool).

Robot Infrared.jpg

This site contains some more information to use infrared LED to avoid object by testing on arduino board.

Using regular IR remote controll

The Arduino code provided for this project makes the BOE Shield-Bot recognize Sony IR remote signals only! For example, the BRIGHTSTAR universal remote sold by Parallax is programmed by holding the SET-UP button down until an LED on the remote lights up, then entering the code 605. Different models of remotes may use different codes and configuration methods. Check your remote's docs! See the instruction and arduino code in IR Remote Controlled Shield-Bot.

Using ping))) with BOEShield

Information and arduino code from Parallax. I find the code by searching within See for arduino code. Some modified code here. My recorded video is available on Youtube.

Robot ping.jpg

Other robots


The astounding athletic power of quadcopters from TED.


  • v2 and v1 from makeblock.


Special Projects

    • (Windows + The key is how to send data to the serial port from PC (Windows or Linux). The serial port could be /dev/ttyS0 or /dev/ttyS1 or /dev/ttyACM0 for Linux. How To Check and Use Serial Ports Under Linux from You have to plug in an Arduino in order to get the port. See also Udoo > Minicom. The arduino code is very simple
      #include <LiquidCrystal.h>
      //Set's lcd to the Arduino's ports
      LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
      void setup() {
        lcd.begin(16, 2);
      void loop() { 
        String content = "";
        char character; 
        while(Serial.available()) {
            character =;
        if (content != "") {
          if (content == "`") {
            content = "";
          if (content == "*") {
            content = "";
        if (content == "~") {

Simple LED

GND --- wire --- 300 Ohm --- short end of LED --- long end of LED --- wire --- 5v/3.3v.

The 300 Ohm resistor can be replaced by anyone between 100 Ohm and 10K Ohm.

7 Segment LED


LCD Keypad shield

This Arduino shield includes a 16x2 HD44780 White on Blue LCD module and a 5 push button keypad for menu selection and user interface programming. The shield can be directly used by opening Arduino > Example > CrystalLCD > Autoscroll as long as we have changed the pin numbers (see comments from; changing the lcd object to the following

LiquidCrystal lcd(8, 9, 4, 5, 6, 7); // instead of lcd(12, 11, 5, 4, 3, 2);

Note that there are two versions of shield.


Control DC motors

L298P motor shield.jpg

  • 5V L298N Dual Stepper Motor Driver Controller Board Module from ebay. It includes standoff and is very large (~ 2 inch x 2 inch).
  • PC fan motor (brushless): using TIP120 transistor to control motors and high power devices.
  • Reading pc fan rpm. The pc fan can be just powered by a 9V battery. I save a copy of the code in github. PS. 9 wires and 3 crocodile clips in addition to 1 PC case fan are needed.

ArduinoDCmotor.jpg ArduinoMotorRPM.png

Bubble blaster

Using Web to read/write GPIO (it works)

Using Node/Websocket to create a Web page and control Arduino

Ethernet Shield

Test Ethernet Shield

Use sketch_12_01_dhcp from Programming Arduino Next Steps. Or

// sketch_12_01_dhcp
#include <SPI.h>
#include <Ethernet.h>

byte mac[] = { 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 };

void setup() 
  while (!Serial){};

  if (Ethernet.begin(mac)) 
    Serial.println("Could not connect to network");

void loop() 

Open Serial Monitor. Mine shows when I use ethernet 1 from PC to share the internet connection.

Control light from a browser

Blynk - mobile app

Blynk allows to create an iOs, Android app for any connected project or product based on Arduino, Raspberry, ESP8266, and other hardware.

Getting Started With Blynk: Simple DIY IoT Devices


How to Make Your Own Wi-Fi Connected Button With ESP8266


How to Detect Room Presence and Automate Smart Home Devices With ESP32

Arduino with bluetooth


It works as the instruction on Windows Vista computer. However on Ubuntu computer (I use my bluetooth dongle obtained from Udoo) I need to

  1. Make sure the arduino code has been uploaded to arduino uno via USB cable when bluetooth module is not connected to arduino. After the code has been uploaded to arduino, we can connect the bluetooth module to arduino and then power on arduino.
  2. Don't use Ubuntu default bluetooth utility. Download and install blueman (Bluetooth manager) from software center.
  3. Paired it to jy-mcu (device name is linvor) . Enter pin number 1234.
  4. Right click on 'linvor' in blueman and click setup. The default option 'serial port' is good so we can click 'forward' button. At this time, the connection should be successful. The screen also shows the device is on /dev/rfcomm0.
  5. Open Arduino IDE. The IDE does not need to have any code there. Select Tools > board > 'Arduino Uno'. For some reason Arduino IDE 1.0.5 does not find the port /dev/rfcomm0 but Arduino IDE 1.5.7 finds the port. So I use Arduino IDE 1.5.7 to test jy-mcu.
  6. Open the serial monitor and make sure the baud rate is 9600. Type H to turn on the LED and L to turn off the LED. That's it.

For Android device, it works too by following the author's instruction.

  1. Download the free Blueterm app. P.S. I found from play store that the app Bluetooth Serial Controller made by Next Prototypes works well - we can assign commands (in terms ASCII) to different buttons and we can hide buttons.
  2. Rx on jy-mcu is connected to arduino Pin 2 and Tx is connected to Pin 4. Note that I did not use shift register/resistors between Rx on jy-mcu and Android.
  3. Open Android > Bluetooth > Setting to connect jy-mcu (linvor). We need to enter pin 1234.
  4. Open Blueterm and click setting > connect > linvor. We need to enter pin 1234 once more.
  5. Test if it is working by entering 1 or 0. Look at the small LED next to pin 13.

Android Apps

Accelerometers & Gyroscopes

From Astro Pi:

  1. A gyroscope measures the orientation of an object.
  2. An accelerometer measures the speed of movement of an object.


Python and Arduino

Monitor a movement (serial port) and send an email

The arduino program is launched first. The arduino is used to send messages and python is used to read messages. So arduino program can be run without a Python program.

Monitor files and send signals to LED

Write one arduino and one python file or

See also website for mire info about Python talking to Arduino via a serial interface.

Smart remote controller

Arduino + Music

Arduino Music project running on Arduino Uno, Sparkfun Music Instrument Shield and Makey Makey. and more at this link.


Temperature sensor

Use Arduino to Avoid Frozen Plumbing This Winter

Pedometer Watch, With Temperature, Altitude and Compass using Arduino Pro Mini 3.3V

Lipo battery

Door sensor with Adafruit IO + IFTTT

Paper Signals

DIY beginner-level electronics projects with paper


DIY Smart Lock and Key With Arduino and RFID

Single-key keyboard

Magnetic field

HC-SR04 Ultrasonic Sensor

Wash-A-Lot-Bot! A DIY Hand Washing Timer

Kinetic digital clock

Kinetic digital clock takes 7-segment displays to another dimension





Clock cycles

The following code was used to measure the time spent on running 2 statements: one is delay(1000) and the other is Serial.println(). I got an output of 8 (most of time) or 4 (few times) microseconds. The code was modified from Arduino Reference, this discussion or another discussion.

Recall that nano second=10^(-9) second and micro second = 10^(-6) second. On 16 MHz Arduino boards (e.g. Duemilanove and Nano), this function has a resolution of four microseconds (i.e. the value returned is always a multiple of four).

unsigned long time;

void setup(){
void loop(){
  Serial.print("Time: ");
  time = micros();
  delay(1000);    // wait a second so as not to send massive amounts of data
                        // We can also move this line to the end of loop() function to see the difference
  Serial.println(micros() - time);

If loop is empty, it will run at 16 MHz. If toggling a PIN is only line inside loop, it will run 16x10^6/2 loops since toggling a PIN took 2 clock cycles.

On a slightly more complex example,

unsigned long time;

void setup(){
void loop(){
  Serial.print("Time: ");
  time = micros();
  int angle = 0;
  while(angle < 180)
  Serial.println(micros() - time);
  // wait a second so as not to send massive amounts of data

it took 1061804 microseconds on my Arduino UNO; that is 16*10^6/10^6 * 1061804/ instructions to execute. Here, 16*10^6 number denotes 16 MHz of the CPU and 10^6 denotes the number of micro seconds. In other words, there are billions of instructions were executed in 4 lines.

Instruction <> Cycle,4324.0.html

Calculate resistor value for LED

To figure out which resistor to use I used the formula: R = (V1 - V2) / I

where: V1 = power supply voltage, V2 = LED voltage, I = LED current (usually 20mA which is .02A).

For example, my LED is 1.7V, it takes 20mA (which is .02 A) of current and my supply is 4.5V. So the math is...

R = (4.5V - 1.7V) / .02 A = 140 ohms

Also putting LEDs in series would add voltages together while in parallel won't add voltages but draw more current. That is if we put LEDs together, we need to multiply the current that one LED draws by the total number of LEDs I was using.

If we putting resistors in series, it would add ohms. But we put resistors in parallel, it would reduce resistance.



Ah (Amp Hour)


See Chapter 3 of Programming Arduino Next Steps. On Arduino UNO, there are 2 interrupts (PIN 2 and 3). A simple sketch to test interrupts (using attachInterrupt function) is

// sketch 03_01_interrupts
int ledPin = 13;
void setup()
  pinMode(ledPin, OUTPUT);
  attachInterrupt(0, stuffHapenned, FALLING);

void loop() { }

void stuffHapenned()
  digitalWrite(ledPin, HIGH);

Note that PIN 13 has an LED (also know "L" LED since there is a label "L" next to it) connected on UNO board so we don't need to manually connect another LED. See website. The first argument 0 is the interrupt number. On an Arduino Uno, interrupt 0 is pin D2 and interrupt 1 is D3. The hardware arrangement is

D2 ---- 1 k resistor --- 5V
   |--- pushbutton   --- Gnd

PWM/Analog Output

Using a multimeter (Sparkfun)

See Chapter 1 of Programming Arduino Next Steps - Analog output. It also teaches how to use multimeter to measure analog output <Sketch_01_07_pwm>. It is noted that UNO does not have true analog output (Arduino Due has). On Arduino UNO board, the pins marked with little "~" (pins 3,5,6,9,10 and 11) can be used as analog outputs (with the analogWrite function).

See Chapter 3 of Programming Arduino Next Steps <Sketch_03_03_1kHz>.





How UART, SPI, and I2C Serial Communications Work, and Why We Still Use Them

USB Programming

Network Programming

Digital Signal Processing

Relay module shield




  • Part:
  • Example: SIK guide project 2 (use pot to control the blink rate of LED) from Sparkfun Inventor Kit.
  • On potentiometer, number 1 is 5v and number 3 is 0v although we can swap these 2 pins to get reverse effect when using the knob.
  • A copy of the SIK guide and example code are available at my github page.

Push button

See how it works at this blog and its references. The diagram below shows the connection (vertically displayed). It is seen legs are already connected in groups of two. When the push button is pressed all the 4 legs are connected. So two components can be A & B (same side) or A & D (opposite side).

  A      B
  |      |
  |--/ --|
  |      |
  C      D


A night light example (tested on Arduino Nano)

/* Night light

Connect the photoresistor one leg to pin 0, and pin to +5V
Connect a resistor (around 10k is a good value, higher
Turn on LED if it is dark and turn off LED if it is bright.


               PhotoR     10K
     +5    o---/\/\/--.--/\/\/---o GND
Anlg Pin 0 o-----------

Dgt Pin 9  o-----------o GND

int lightPin = 0;  //define an analog pin for Photo resistor
int ledPin=9;     //define a digital pin for LED
int threshold = 400; // adjust it according to your need

void setup()
    Serial.begin(9600);  //Begin serial communcation
    pinMode(lightPin, INPUT);
    pinMode( ledPin, OUTPUT );
    // can be replaced by the built-in small LED 
    // pinMode(LED_BUILTIN, OUTPUT);

void loop()
    int v = analogRead(lightPin);
    if ( v < threshold) 
      analogWrite(ledPin, 255); 
      analogWrite(ledPin, 0);
    delay(10); //short delay for faster response to light.

IR resistor

Measure RPM with an IR sensor and Arduino

IR remote

Controlling any IR device with a remote and some hacking



Evermind sensors


My Misc Collection

ProMini vs Nano.jpg



  • 123D Design from AUTODESK and an article (The ‘Pi’cture: A 3D Printed Raspberry Pi Camera You Can Build Yourself) mentioned about it.

Embedded System

Open source hardware

8 ways to get started with open source hardware


Seller, Community

The CanaKit's Sparkfun inventor's kit for Arduino (SX10173) contains lots of stuff like 1N4148 diode, P2N222AG NPN transistor (youtube, potentiometer, 5V relay, temperature sensor (TMP36GZ), 74HC595 shift register, hobby servo and photo resistor/photocell. Circ-03 (or Circ-12 on the new guide) teaches how to use P2N222AG transistor and 1N4001 Diode to spin a motor. See the SIK guide in pdf from the above link. The resistors it has included have 330 ohm, 10K. I also purchased 3.3M resistors for another application.

In the Arduino budget pack, it includes 100 ohm, 1k and 10k resistors and photocell.