Search

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

Sunday, February 21, 2016

Identifying your Arduino board from code

For my IoT project I needed to write code slightly differently for specific Arduino boards. E.g. for Arduino UNO I wanted to use Serial to talk to ESP8266 and for Arduino Mega wanted to use Serial1. So basically I wanted to use Board specific #defines

#ifdef MEGA
    #define SERIAL Serial1
#elif UNO
    #define SERIAL Serial
#endif

SERIAL.println("Something")

For that I needed to get board specific #defines for each of the board options in the Arduino IDE, so that as I change the board type in the IDE, I automatically build code for that specific board.

image

That information is actually available in a file called board.txt inside your arduino install folder. For me it is G:\arduino-1.6.5\arduino-1.6.5-r5\hardware\arduino\avr\boards.txt. For each board there is a section inside that file and the relevant entries look something as follows

##############################################################

uno.name=Arduino/Genuino Uno

uno.vid.0=0x2341
uno.pid.0=0x0043
uno.vid.1=0x2341
uno.pid.1=0x0001
...
uno.build.board=AVR_UNO
uno.build.core=arduino
uno.build.variant=standard

The .board entry when prefixed by ARDUINO_ becomes the #define. I wrote a quick PowerShell routine to get all such entires. The code for it is in GitHub at https://github.com/bonggeek/Samples/blob/master/Arduino/ListBoard.ps1

$f = Get-ChildItem -Path $args[0] -Filter "boards.txt" -Recurse
foreach($file in $f)
{
    Write-Host "For file" $file.FullName
    
    foreach ($l in get-content $file.FullName) {
        if($l.Contains(".name")) {
            $b = $l.Split('=')[1];
        }

        if($l.Contains(".board")) {
            $s = [string]::Format("{0,-40}ARDUINO_{1}", $b, ($l.Split('=')[1]));
            Write-Host $s
        }

    }
}

Given the argument of root folder or Arduino install, you get the following.

PS C:\Users\abhinaba> D:\SkyDrive\bin\ListBoard.ps1 G:\arduino-1.6.5\
For file G:\arduino-1.6.5\arduino-1.6.5-r5\hardware\arduino\avr\boards.txt
Arduino Yún                            ARDUINO_AVR_YUN
Arduino/Genuino Uno                     ARDUINO_AVR_UNO
Arduino Duemilanove or Diecimila        ARDUINO_AVR_DUEMILANOVE
Arduino Nano                            ARDUINO_AVR_NANO
Arduino/Genuino Mega or Mega 2560       ARDUINO_AVR_MEGA2560
Arduino Mega ADK                        ARDUINO_AVR_ADK
Arduino Leonardo                        ARDUINO_AVR_LEONARDO
Arduino/Genuino Micro                   ARDUINO_AVR_MICRO
Arduino Esplora                         ARDUINO_AVR_ESPLORA
Arduino Mini                            ARDUINO_AVR_MINI
Arduino Ethernet                        ARDUINO_AVR_ETHERNET
Arduino Fio                             ARDUINO_AVR_FIO
Arduino BT                              ARDUINO_AVR_BT
LilyPad Arduino USB                     ARDUINO_AVR_LILYPAD_USB
LilyPad Arduino                         ARDUINO_AVR_LILYPAD
Arduino Pro or Pro Mini                 ARDUINO_AVR_PRO
Arduino NG or older                     ARDUINO_AVR_NG
Arduino Robot Control                   ARDUINO_AVR_ROBOT_CONTROL
Arduino Robot Motor                     ARDUINO_AVR_ROBOT_MOTOR
Arduino Gemma                           ARDUINO_AVR_GEMMA

So now I can use

#ifdef  ARDUINO_AVR_MEGA2560
    // Serial 1: 19 (RX) 18 (TX);
    #define SERIAL Serial1
#elif ARDUINO_AVR_NANO
    #define SERIAL Serial
#endif // ARDUINO_MEGA

Saturday, January 23, 2016

ESP8266 Wifi With Arduino Uno and Nano

If you are trying to add Wifi connectivity to an existing Arduino project or have serious aspirations for developing a Internet of Things (IoT) solution, Arduino + ESP8266 wifi module is one  of the top choices. Especially the Nano because it is super cheap (<$3) and is very small in size. Using some sort of web-server directly on ESP8266 (e.g. via Lua) doesn't cut it due to the lack of IO pins on ESP8266. You can get a full IoT node out at under $12 with a few sensors, Arduino Nano and a ESP9266 module (excluding the power supply).

Inspite of a plethora of posts online it turned out to be very hard for me to get this to combination to work. I spent atleast 3-4 days until I actually got this right. The main problem I see is that a lot of the solutions online are actually down-right incorrect, not-recommended or for other similar boards (e.g. Arduino Mega). Also there are a few gotchas that were not commonly called out. Before I start let me get all of those out of the way

  1. Arduino Uno/Nano is very different from say Mega which can supply more current and have different number of UART. The steps to make a Uno and Nano work is different from them.
  2. Power Supply
    1. ESP8266 is powered by 3.3V and NOT 5V. So you cannot have a common power supply between Arduino and ESP8266
    2. ESP8266 draws way more current (200mA) then it can be supplied by the 3.3v pin on the Uno/Nano. Don’t even try them, I don't buy anyone who claims to have done this. Maybe they have some other high power variant of Arduino (Mega??) that can do this.
    3. So you either use a 3.3v 1A power supply to ESP8266 with common ground with the 5V powering Arduino, or you use a step down 5v to 3.3v (e.g. like here).
  3. Arduino <-> ESP8266
    1. All the ESP8266 I bought  came with the UART serial IO speed (BAUD) set to 115200. Now the problem is that Uno/Nano has only one HW serial, which is set to be used for communicating with the PC over USB with which you are debugging. You can use any other two IO pins to talk to the ESP8266 using SoftwareSerial, but it does not support that high a BAUD speed. If you try 115200 to communicate with Arduino <-> ESP8266 you will get garbage. A lot of articles online show a setup with Arduino Mega which does have two HW serial IO using which you can easily get 115200 and more. So you need to dial the ESP8266 settings to move the communication speed to a more manageable BAUD of 9600
    2. Arduino IO pins have 5V and ESP8266 accepts 3.3 v (max 3.6). I have seen people directly connect the pins but you are over driving the ESP8266. If it doesn’t burn out immediately (the cheaper ones does), it will burn out soon. I suggest you use a voltage divider using simple resistor to have Arduino transmission (TX) drive ESP8266 receive (RX)
    3. For some strange reason D2/D3 pins on Arduino Nano didn’t work for me for the communicating with ESP8266. I have no explanation for this and it happened on two separate Nano. The Arduino would just read a whole bunch of garbage character. So I had to move to the pins 8/9.
    4. In spite of whatever I did, garbage characters would still come in sometimes. So I wrote a small filter code to ignore them

 

Things you need

  1. ESP8266
  2. Arduino Nano
  3. Power supply 5v and 3.3v
  4. Resistors 1K, 2.2K, 10K
  5. FTDI USB to serial TTL adapter. Link (optional, see below)

Setting up ESP8266

imageAs mentioned above I first set the ESP8266 BAUD rate to 9600. If yours is already 9600 then nothing to be done, if not you need to make the following connection

PC (USB) <-> FTDI <-> ESP8266

Then using specific AT commands from the PC set the 9600 BAUD rate on the ESP8266. I used the following circuit. Where the connections are as follows

FTDI TX –> Via voltage divider (to move 5v to ~3.3v) to ESP8266 RX (blue wire)
FTDI RX –> Directly to ESP8266 TX (green wire). A 3.3v on Nano I/0 pin will be considered as 1.
FTDI GND to common ground (black)

ESP8266 GND to common GND (black)
ESP8266 VCC to 3.3v (red)
ESP8266 CH_PD to 3.3v via a 10K  resistor (red)

Power supply GND to common GND

PC to FTDI USB.

One that is set bring up Arduino IDE and do the following using the menu

  1. Tools –> Port –>COM{n}. For me it was COM6
  2. Then Tools –> Serial monitor

In the serial monitor ensure you have the following set correctly. The BAUD should match the preset BAUD of your ESP8266. If you are not sure, use 115200 and type the command AT. If should return OK, if not try changing the BAUD, until you get that.

image

Then change the BAUD rate by using the following command, and you should get OK back

AT+CIOBAUD=9600

After that immediately change the BAUD rate in the serial monitor to be 9600 baud as well and issue a AT command. You should see OK. You are all set for the ESP8266.

Setting up Arduino Nano + ESP8266

This step should work for Uno as well. Essentially make the same circuit as above, but now instead of FTDI use an Arduino. I used pins 8 and 9 on Arduino for the RX and TX respectively.

image

 

Debugging and Setup WIFI

Even though I could easily run AT commands with the PC <->FTDI <-> ESP8266, I ran into various issues while doing the same programmatically in PC <->Arduino <-> ESP8266 setup. So I wrote the following very simple code to pass on commands I typed in the PC via the Arduino to the ESP8266 and reverse for outputs.

The code is at GitHub as https://github.com/bonggeek/Samples/blob/master/Arduino/SerialRepeater.ino

#include <SoftwareSerial.h>
SoftwareSerial softSerial(8, 9); // RX, TX

void setup() 
{
  uint32_t baud = 9600;
  Serial.begin(baud);
  softSerial.begin(baud);
  Serial.print("SETUP!! @");
  Serial.println(baud);
}

void loop() 
{
    while(softSerial.available() > 0) 
    {
      char a = softSerial.read();
      if(a == '\0')
        continue;
      if(a != '\r' && a != '\n' && (a < 32))
        continue;
      Serial.print(a);
    }
    
    while(Serial.available() > 0)
    {
      char a = Serial.read();
      Serial.write(a);
      softSerial.write(a);
    }
}

With this code built and uploaded to Arduino I launched the Serial monitor on my PC. After that I could type commands in my Serial Monitor and have the Arduino pass that only ESP8266 and read back the response. I can still see some junk chars coming back (in RED). All commands are in Green and could easily enumerate all Wifi in range using AT+CWLAP and even connect to my Wifi.

image

Friday, October 31, 2014

Halloween Costume with Arduino

This Halloween me and my daughter decided to add some dazzle to her fairy costume. Since we were anyway learning to code on Arduino we decided to dip our hands in wearables.

The basic idea is to build a costume that glows when someone comes close. The project was intended to teach a 9 year old to code and is hence simple enough for her to grasp. We used the following

Parts

  1. Arduino UNO board
  2. TIP120 transistor
  3. Diode 1N4004
  4. 1K Resistor
  5. HC-SR04 Ultrasonic Range Finder

Circuit

It’s best to consider the circuit as two separate pieces. One to acquire the distance of someone approaching using the HC-SR04 ultrasound range finder. The second is to actually make the LED strip glow.

The first part consists of connecting the 4 pins of the HC-SR04 as follows

image

We cannot simply drive the LED strip using an output pin of Arduino because the strip drains way more current than that can be supplied by the Arduino chip. So we use a TIP120 or TIP121 chip as shown below

image

There is a nice explanation of this whole setup at http://www.instructables.com/id/Use-Arduino-with-TIP120-transistor-to-control-moto/. The same principles hold, but instead of a fan we use a LED strip in our case.

Code

The entire code is available on GitHub at https://github.com/bonggeek/GlowDress/ (I cleaned up the code a tiny bit after my daughter wrote it). This is how it looks

#include <ultrasonicranging.h>

#define ECHO_PIN 2 // ECHO pin of HC-SR04
#define TRIG_PIN 3 // Trigger pin of HC-SR04
#define LED_OUT 5 // Drive LED (Base pin of TIP120

const int space = 125; // Distance in cm in which to trigger LED

void setup()
{
Serial.begin (9600);
pinMode(TRIG_PIN, OUTPUT); // trigger pin of US range finder
pinMode(ECHO_PIN, INPUT); // Echo pin of US range finder
pinMode(LED_OUT, OUTPUT); // base of TIP120 to drive LED

analogWrite(LED_OUT, 0);
}

void GlowLed()
{
// Slowly get from LED strip off to full bright (glow-in)
for (int brightness = 0; brightness < 255; brightness++)
{
analogWrite(LED_OUT, brightness);
delay(3);
}

// Slowly get from LED strip on to full off (glow-out)
for (int brightness = 255; brightness >= 0; brightness--)
{
analogWrite(LED_OUT, brightness);
delay(3);
}
}

void loop()
{
int distance = GetDistanceInCm(TRIG_PIN, ECHO_PIN);
Serial.println(distance);

if (distance <= 0 || distance > space)
{
analogWrite(LED_OUT, 0);
delay(500);
return;
}

if (distance <= space)
{
GlowLed();
}
}

Here to abstract away the intricacies of how distance is received from the ranger, I have used GetDistanceInCm. The source for this library is at  https://github.com/bonggeek/GlowDress/tree/master/UltraSonicRanging.


Once we tested out the circuit we went ahead and soldered it on a board. My daughter did receive a battle scar (a small burn from iron) but we battled on.

IMG_0565This is how it looks partially done 

IMG_0574


With my wife’s help we sewed it underneath her fairy dress. It was pretty well concealed other than the sensor sticking out a bit.


IMG_0578


Thursday, December 26, 2013

Getting Arduino Uno work on Windows 8

I keep needing to do this and I couldn’t find one place where all the instructions are placed, so capturing it here. Also the standard instructions at http://arduino.cc/en/Guide/Windows didn’t work for me.

Get the Software

  1. Get Arduino Software from http://arduino.cc/en/Main/Software. Choose the Windows (ZIP file) and unzip it to local PC. I used D:\Skydrive\bin\arduino-1.0.5

Disable Driver Signature Enforcement

Unfortunately this step does disable a security feature of the OS, but I couldn’t find a way to do this otherwise.

  1. Open an command prompt and run the command
    shutdown.exe /r /o /f /t 00
  2. System restarts with Choose an option screen
  3. Select Troubleshoot
  4. Select Advanced options
  5. Select Windows Startup Settings
  6. Click Restart and it will restart into the Advanced Boot Options Screen
  7. Press the keyboard button for the number for Disable Driver Signature Enforcement (which was 7 in my case)
  8. System will restart with driver signature enforcement disabled.

Install The Driver

Press Windows key + W and type “Devices and Printers” and open that. Connect the Arduino board over USB. You should see something called Unknown Device shown in it.

image

Run the installer "D:\Skydrive\bin\arduino-1.0.5\drivers\dpinst-amd64.exe” or locate corresponding path from your installation folder. The window above should get updated as below.

image

You can also verify by again hitting Windows Key + W and typing Device Manager and launching it. Then expand to see the following

image

Monday, April 29, 2013

Arduino Fun – Door Entry Alarm

 
Arduino UNO based door entry alarm

Physical computing and “internet of things” is a super exciting area that is unfolding right now. Even decades back one could hook up sensors and remotely get those data and process it. What is special now is that powerful micro-controllers are dirt cheap and most of us have in our pockets a really powerful computing device. Connecting everything wirelessly is also very easy now and almost every home has a wireless network.

All of these put together can create some really compelling and cool stuff where data travels from sensor over wireless networks into the cloud and finally into the cell phone we carry everywhere. I finally want to create a smart door so that I can get an notification while at work when someone knocks at our home door. Maybe I can remotely open the door. The possibilities are endless, but time is not, so lets see how far I get in some reasonable amount of time.

Arduino UNO

I unboxed the Arduino Uno Ultimate Starter Kit that I had got last week and spend some time with my daughter setting it up. The kit comes with a fantastic manual that helped me recap the basics of electronics. It contains an Arduino UNO prototyping board based on ATmega328 chip. It is a low-power 8-bit microprocessor running at max 20 MHz. To most people that seems paltry but it’s amazing what you can pull off with one of these chips.

The final assembled setup of the kit looks as follows. It comes with a nice handy plastic surface on which the Arduino (in blue) and a breadboard is stuck. It’s connected over USB to my PC.

IMG_9181

Getting everything up was easy with the instruction booklet that came. Only glitch was that Windows 8 wouldn’t let me install the drivers because they are not properly signed. So I had to follow the steps given here to disable driver verification.

Post that the Arduino IDE connected to the board and I could easily write and deploy code (C like syntax).

image

The tool bar icons are a bit weird though (side arrow for upload and up arrow for open????).

There was no way to debug through the IDE (or at least couldn’t find one). So I setup some easy printf style debugging. Basically you write to the serial port and the IDE displays it.

image

It was after this that I got to know that there’s a Visual Studio plugin with full debugging support. However, I haven’t yet used that.

The Project

imageI decided to start out with making a simple entry alarm and see how much time it takes to get everything done. In college I built something similar, but without a microcontroller (based on 555 IC and IR photo-transistors) and it took decent amount of time to hook up all the components. Basically the idea is that across the door there will be some source of light and a sensor will be on the other side. When someone passes in between the light on the sensor will be obstructed and this will sound an alarm.

When I last did it in college I really made it robust by using pulsating (at fixed frequency) IR LED as source and IR sensors. Now for this project I relied on visible light and the photo-resistor that came with the kit.

I built the following circuit.

image

Connected a photo-resistor in series with another 10K resistor and connected the junction to the analog input pin A0 of Arduino. Essentially this acts like a voltage divider. In bright light the junction and hence A0 input reads around 1.1 V. When light is obstructed the resistance of photo-resistor changes and the junction reads 2.6 V. The analog pins read in a range of 0 (means 0 volt) and 1023 (for 5V). So this roughly comes to around 225 in light and 530 in the shade. Obviously these are relative based on the strength of the light and how dark it becomes when someone obstructs the light. To avoid taking absolute dependency on the value I created another voltage divider using a potentiometer and connected that to another analog input pin A1. So now I can change the potentiometer to control a threshold value. If the voltage of A0 is above this threshold it would mean that it’s dark enough that someone obstructed the light falling on the resistor and it’s time to sound the alarm.

The alarm consists of flashing blue and red LEDs (obviously to match police lights) and a standard siren sound played using a piezo crystal that also came with the kit.

This full assembled and deployed setup looks as follows.

IMG_9167

Update*** The picture above says photo-transistor, it should be photo-resistor

Code

The key functions are setup() which is automatically called at startup and loop() which as the name suggests is called in a loop.setup() sets up the digital pins for output to drive the flashing LEDS. In loop() I read in the values of  photo-resistor and that from the potentiometer. Based on comparison I sound the alarm

// Define the constants
const int sensorPin = 0; // Photo-resistor pin
const int controlPin = 1; // Potentiometer pin
const int buzzerPin = 9; // Buzzer pin
const int rLedPin = 10; // Red LED pin
const int bLedPin = 11; // Blue LED pin

// Always called at startup
void setup()
{
// Set the two LED pins as output
pinMode(rLedPin, OUTPUT);
pinMode(buzzerPin, OUTPUT);
}

// This loops forever
void loop()
{
int sensorVal = analogRead(sensorPin);
int controlVal = analogRead(controlPin);

if(sensorVal < controlVal)
{
// Light is below threshold so sound buzzer
playBuzzer(buzzerPin);
}

delay(100);
}

void playBuzzer(const int buzzerPin)
{
for(int i = 0; i < 3; ++i)
{
// alternate between two tones, one high and one low
// at the same time alternate the blue and red LED flashing

digitalWrite(rLedPin, HIGH); // Red LED on
tone(buzzerPin, 400); // play 400 Hz tone for 500 ms
delay(500);
digitalWrite(rLedPin, LOW); // RED LED off

digitalWrite(bLedPin, HIGH); // Blue LED on
tone(buzzerPin, 800); // play 800Hz tone for 500ms
delay(500);
digitalWrite(bLedPin, LOW); // Blue LED off
}

// Stop the buzzer
noTone(buzzerPin);
}



imageNext Steps



This system has some obvious flaws. Someone can duck below or over the light-path or even shine a flashlight on the sensor while passing through. To make this robust consider using strips of mirrors on the two side and then use a laser (preferably IR) bouncing off them so that it’s virtually impossible to get through without breaking the light



Also you can decide to use a pulsating source of light and detect the frequency on the sensor. This will just make it more harder to break.