Showing posts with label Wemos. Show all posts
Showing posts with label Wemos. Show all posts

Friday, 10 February 2017

ROBOTICS: Compiling the 7Bot Arduino code for the ESP8266 - BangBot

I wrote previously about building a desktop robot arm that I started calling the BangBot (because I bought it from bangood). I finished with a brief overview of the existing open source software solutions including some software written for similar desktop robots. 
In this post I'll investigate the specifics of the 7Bot software written for a similar looking desktop bot. 


7Bot Software:

The software comes in two components:
  • Arduino code to run the robot
  • Desktop code that passes positions to the robot and includes a simulator/visualiser. 

I'll be focussing on the embedded software that controls the arm over serial communications. You can find more info on the serial communications protocol here.

I forked the github repo of the 7Bot Arduino software which has been written specifically for the Arduino Due. This board has some special features that your run-of-the-mill Arduino has like a 12 bit DAC on 12 channels and high clock speed.

As this isn't a typical feature of low cost Arduinos I'm pretty sure I'll end up needing an external servo driver board, but until I hit a wall I'll try to get everything running off the one board.

My gut feel is that I'll want to use a board with some decent clock speed to make sure the Inverse Kinematics equations are computed quickly enough to give smooth robot motions when operating in Cartesian mode. This is because the robot needs to interpolate the path between points and calculate do the IK calculations to update joint angles at at least 15fps for smooth motion.
For this reason I'm going to try to get it compiling for an ESP8266 as the base clock speed is 80MHz and is capable of going up to 160MHz. I'll need to do some research to understand how this clock speed relates to real world computational speed and how that compares to the Due.


Embedded Device Specs:

I need to compare the ESP8266 with the Due to understand how it might handle the code designed for the 7Bot and the Due board:

ESP8266
  • IEEE 802.11 b/g/n Wi-Fi
  • 32-bit RISC CPU (80 or 160MHz)
  • 64 KB of instruction RAM, 96 KB of data RAM
  • External QSPI flash - 512 KB to 4 MB* (up to 16 MB is supported)
  • 16 GPIO pins
  • 1 10-bit ADC (analog input pins)
  • 1 UART on dedicated pins, plus a transmit-only UART can be enabled on GPIO2

Arduino Due
  • 32-bit ARM core (84 MHz)
  • 96 KB (two banks: 64KB and 32KB)
  • 512 KB all available for the user applications
  • 54 (of which 12 provide PWM output) 
  • 12 12-bit ADC (analog input pins)
  • 3 UARTs

I found that there were already some basic benchmark comparing some basic operations of the ESP and the Due on the Arduino forums:

BENCHMARK RESULTS (smaller values are better):

ESP8266 @160MHzArduino Due @84MHz
float [ms]216636
int [ms]2828


Code Changes

As I was making my changes I found that some changes were pushed to the main repo that allowed for more typical flash storage using the EEPROM library. First problem solved.

In order to get the project to compile I also needed to change the analogWriteResolution function to the analogWriteRange function available on the ESP8266. I've not yet tested this at PWMRANGE 4096.

The last issue I overcame was a compiler optimization issue that was giving me a linkage error:
xtensa-lx106-elf-gcc: error: libraries\Arm7Bot\Arm7Bot.a: No such file or directory

xtensa-lx106-elf-gcc: error:
Solved this one by commenting out the dot_a_linkage=true line in the library.properties file.
The software now compiles for an ESP8266, now to get in to the testing.



Thursday, 2 February 2017

HOME AUTOMATION: ESP8266, Blynk and OTA Updates

I previously used Blynk to set up remote access to my house via my phone and a electric door strike. Since then I learned of the Arduino Over The Air (OTA) update library that would allow me to remotely update the firmware of my device so naturally I immediately wanted to add this feature.

Arduino OTA Library:

You can read about the library on the Arduino github site here, but basically there are three ways you can implement the OTA update:

  1. Arduino IDE
  2. Web Browser
  3. HTTP Server
I've decided to go for the Arduino IDE scenario that is described here.
The requirements for this process are:
  • Arduino IDE (tested with 1.6.8)
  • Python 2.7


Arduino IDE OTA Update:

Basically all you really is the command "ArduinoOTA.begin();" in the setup routine and the command "ArduinoOTA.handle();" in the loop function. This is the bare minimum you need to get it working, but we'll add some more things like error handling and some basic security.

EDIT: I couldn't get the Arduino IDE security feature working on my windows 10 machine, it seems there are a few bugs still being worked out 


Blynk and OTA Code:


/**************************************************************
 * Blynk is a platform with iOS and Android apps to control
 * Arduino, Raspberry Pi and the likes over the Internet.
 * You can easily build graphic interfaces for all your
 * projects by simply dragging and dropping widgets.
 *
 *   Downloads, docs, tutorials: http://www.blynk.cc
 *   Blynk community:            http://community.blynk.cc
 *   Social networks:            http://www.fb.com/blynkapp
 *                               http://twitter.com/blynk_app
 *
 * Blynk library is licensed under MIT license
 * This example code is in public domain.
 *
 **************************************************************
 * This example runs directly on ESP8266 chip.
 *
 * WARNING! ESP8266 SSL support is still experimental.
 *          More info here: https://github.com/esp8266/Arduino/issues/43
 *
 * Note: This requires ESP8266 support package:
 *   https://github.com/esp8266/Arduino
 *
 * Please be sure to select the right ESP8266 module
 * in the Tools -> Board menu!
 *
 * Change WiFi ssid, pass, and Blynk auth token to run :)
 *
 **************************************************************/

#define BLYNK_PRINT Serial    // Comment this out to disable prints and save space
#define RELAY_PIN D1

#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266_SSL.h>
#include <Ticker.h>
#include <ArduinoOTA.h>

// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[] = "XXXX";

// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "XXXX";
char pass[] = "XXXX";
char hostOTA[] = "DoorLock";
char passOTA[] = "XXXX";

bool vPinState = false;               // Set the default virtual pin state
int maxRelayOnTime = 10;              // Set the max on time of the relay 
int minRelayOnTime = 1;               // Set the minimum on time of the relay
int vDelayTime = minRelayOnTime;      // Set the initial delay time value
Ticker doorLatch;                     // Callback fuction instance

void setPinLow()
{
  digitalWrite(RELAY_PIN, 0);
  doorLatch.detach();
}

void setup()
{
  Serial.begin(9600);
  Blynk.begin(auth, ssid, pass);

  pinMode(RELAY_PIN, OUTPUT);
  digitalWrite(RELAY_PIN, 0);

  ArduinoOTA.setHostname(hostOTA);
  //ArduinoOTA.setPassword(passOTA);
  ArduinoOTA.onStart([]() {
    Serial.println("OTA: Start");
  });
  ArduinoOTA.onEnd([]() {
    Serial.println("\nOTA: End");
  });
  ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
    Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
  });
  ArduinoOTA.onError([](ota_error_t error) {
    Serial.printf("Error[%u]: ", error);
    if (error == OTA_AUTH_ERROR) Serial.println("OTA: Auth Failed");
    else if (error == OTA_BEGIN_ERROR) Serial.println("OTA: Begin Failed");
    else if (error == OTA_CONNECT_ERROR) Serial.println("OTA: Connect Failed");
    else if (error == OTA_RECEIVE_ERROR) Serial.println("OTA: Receive Failed");
    else if (error == OTA_END_ERROR) Serial.println("OTA: End Failed");
  });
  ArduinoOTA.begin();
  Serial.println("OTA: Ready");
}

void loop()
{
  ArduinoOTA.handle();
  Blynk.run();
}

BLYNK_WRITE(V0)
{
  // Get the virtual input state
  vPinState = param.asInt();

  // If the virtual input went high
  if(vPinState)
  {
    // Open the relay
    digitalWrite(RELAY_PIN, 1);
    // Turn off the relay after the defined delay time
    doorLatch.attach(vDelayTime, setPinLow);
  }
}

BLYNK_WRITE(V1)
{
  // Get the input from the virtual input slider
  vDelayTime = param.asInt();

  // Constrain the virtual slider input to within the preset bounds
  vDelayTime = constrain(vDelayTime, minRelayOnTime, maxRelayOnTime);
}


How to update your device OTA:

Once you get the code loaded on to your device you should see the unit appear in your list of ports under the 'Tools' heading.
I had to reboot my machine to get this to work for me. Now you can upload code to your device over the network as if it was connected via USB.


Tuesday, 17 January 2017

HOME AUTOMATION: Blynk and IFTTT

I found a few sites showing how to link Blynk with IFTTT using the Maker channel service. This thread on the Blynk forums gives a good rundown of how to create a recipe but some of the details seem to be out of date. To get it working you will need to do the following:

  1. Ping the Blynk server (blynk-cloud.com) and copy the IP address. In Australia I'm getting 45.55.96.146
  2. Create a new IFTTT recipe using the Maker service and use the following parameters:
    1. URL: http://45.55.96.146/YOUR_AUTH_TOKEN/update/PIN_NUMBER?value=VALUE
    2. Method: GET
    3. Content Type: application/json
    4. Body: leave it blank

Remember to replace "YOUR_AUTH_TOKEN" with you actual token from you Blynk project, PIN_NUMBER with the pin you want to set (eg: D1 or V0) and VALUE with the value you want to set. You should end up with something like this:


Sunday, 15 January 2017

HOME AUTOMATION: Web Enabled Relay with Blynk

One of the most useful parts of my home automation system is internet enabled entry control that lets me use my phone to get in to my house when I don't have keys on me or it's just easier to use my phone. This setup requires an electric door strike and an wifi enabled relay.

I've tried a number of ways to get an easy to use solution to work from both the web and my phone including:

I won't go over the pros and cons of each here, I'll just give the details on how to get it working with Blynk.


Why Blynk?

There are a lot or reasons listed on the Blynk website, but the reasons I went for it over the competition were:
  • Android and iOS app
  • Arduino support 
  • Really easy to use
  • Free account option 
  • SSL support
  • Local server support
I'm yet to find anything that was as simple to use as Blynk. From the time I took out my tub of Wemos modules it took me 15 minutes to get a working example (including some troubleshooting!)


To get my wireless relay set up I used the following:
  • Wemos D1 mini (ESP8266)
  • Wemos D1 mini relay shield 
  • 12v power supply 
  • Electric door strike 
  • Soldering iron and heat shrink 
  • Blynk account (done via the app)
  • Computer with Arduino Studio installed and Sparkfun ESP8266 library installed via the library manager
  • Android or iOS device with the Blynk app installed


The default Blynk examples only show how to mirror the pins of the Arduino from the Android/iOS app. I wasn't able to find any way to hold a pin high once triggered for a set period of time within the Android app, so I developed an Arduino sketch (below) that uses virtual IO to trigger and latch physical IO.


Arduino Programming

The Wemos D1 Mini board has a built in USB to serial converter so all we need to do is plug in a micro USB cable to the device and install the required drivers.
Once we have Arduino Studio installed we need to install the toolchain for the ESP8266 board, I did this by following the instructions on the esp8266 github page. Wemos also has some libraries for their boards that give some examples of using their shields.

Once this is all setup the D1 mini can be programmed as you would any other Arduino board. Blynk also has a library that can be installed from the library manager with examples for the ESP8266 boards. One of those examples shows how to connect to Blynk servers using SSL.

Tip: Debugging over serial can be useful to ensure your device is connecting to your wireless network. Make sure your serial terminal is set to the correct baud rate, in the default examples the baud rate is set to 9600 but the default terminal rate is 155200 kbps

I'm using the below program to set the relay on-time via a virtual input and then toggle the relay via another virtual input. You will need the Blynk and Ticker libraries to compile the example.

 /**************************************************************  
  * Blynk is a platform with iOS and Android apps to control  
  * Arduino, Raspberry Pi and the likes over the Internet.  
  * You can easily build graphic interfaces for all your  
  * projects by simply dragging and dropping widgets.  
  *  
  *  Downloads, docs, tutorials: http://www.blynk.cc  
  *  Blynk community:      http://community.blynk.cc  
  *  Social networks:      http://www.fb.com/blynkapp  
  *                http://twitter.com/blynk_app  
  *  
  * Blynk library is licensed under MIT license  
  * This example code is in public domain.  
  *  
  **************************************************************  
  * This example runs directly on ESP8266 chip.  
  *  
  * WARNING! ESP8266 SSL support is still experimental.  
  *     More info here: https://github.com/esp8266/Arduino/issues/43  
  *  
  * Note: This requires ESP8266 support package:  
  *  https://github.com/esp8266/Arduino  
  *  
  * Please be sure to select the right ESP8266 module  
  * in the Tools -> Board menu!  
  *  
  * Change WiFi ssid, pass, and Blynk auth token to run :)  
  *  
  **************************************************************/  
 #define BLYNK_PRINT Serial  // Comment this out to disable prints and save space  
 #define RELAY_PIN D1  
 #include <ESP8266WiFi.h>  
 #include <BlynkSimpleEsp8266_SSL.h>  
 #include <Ticker.h>  
 // You should get Auth Token in the Blynk App.  
 // Go to the Project Settings (nut icon).  
 char auth[] = "XXXXXXXX";  
 // Your WiFi credentials.  
 // Set password to "" for open networks.  
 char ssid[] = "XXXXXXXX";  
 char pass[] = "XXXXXXXX";  
 bool vPinState = false;        // Set the default virtual pin state  
 int maxRelayOnTime = 10;       // Set the max on time of the relay   
 int minRelayOnTime = 1;        // Set the minimum on time of the relay  
 int vDelayTime = minRelayOnTime;   // Set the initial delay time value  
 Ticker doorLatch;           // Callback fuction instance  
 void setPinLow()  
 {  
  digitalWrite(RELAY_PIN, 0);  
  doorLatch.detach();  
 }  
 void setup()  
 {  
  Serial.begin(9600);  
  Blynk.begin(auth, ssid, pass);  
  pinMode(RELAY_PIN, OUTPUT);  
  digitalWrite(RELAY_PIN, 0);  
 }  
 void loop()  
 {  
  Blynk.run();  
 }  
 BLYNK_WRITE(V0)  
 {  
  // Get the virtual input state  
  vPinState = param.asInt();  
  // If the virtual input went high  
  if(vPinState)  
  {  
   // Open the relay  
   digitalWrite(RELAY_PIN, 1);  
   // Turn off the relay after the defined delay time  
   doorLatch.attach(vDelayTime, setPinLow);  
  }  
 }  
 BLYNK_WRITE(V1)  
 {  
  // Get the input from the virtual input slider  
  vDelayTime = param.asInt();  
  // Constrain the virtual slider input to within the preset bounds  
  vDelayTime = constrain(vDelayTime, minRelayOnTime, maxRelayOnTime);  
 }  

Android App:

My Blynk project (Android) looks like this:

New device setup screen
Physical Pin and Virtual Pin Mapping
Slider controlling the unlocked time using Virtual Pin 1
Unlock button linked to Virtual Pin 0

Example configuration of relay on physical pin D1

Example configuration of relay on Physical Pin D4. Note the inverse logic configuration of the LED as it is ON when pin D4 is pulled low.


Tip: if you are using the Wemos boards and use the generic ESP8266 board in the Blynk App the built-in led is pin 2 and the relay is pin 5 (D1 on the wemos web page)


Wiring:

My door strike is set up as per the wiring diagram below. I followed the instructions that came with my door strike.




Conclusion:

And that's it! It's as easy as that. I've had my setup running for a few days now with no issues. My past experience with ESP8266 solutions doesn't give me the greatest confidence in device up-time so I'll monitor the solution and see how stable it is.

It's worth noting that I'm not entirely sure how secure Blynk is, so at the moment I'm being cautious and running a local copy of the Blynk server hosted on my local network. I'll need to do some investigating in to this one.