Showing posts with label IoT. Show all posts
Showing posts with label IoT. Show all posts

Wednesday, August 8, 2018

Espressif ESP32 Tutorial - IR Remote Control using Microsoft Azure




The Project


This tutorial will outline how to create an IR Remote using the ESP32 and then control it from the IoT hub on Microsoft Azure.

Driving an IR remote transmitter using an Arduino is simple, as there is a library, called IRremote.h which does all the hard work. You just need to connect your IR transmitter module signal pin to the appropriate Arduino pin, via a current limiting resistor and you are done. Connecting an Arduino to the cloud takes a bit more work (depending on the model you are using), which is why we wanted to use the ESP32.

Unfortunately, the standard IRRemote.h Arduino library only supports receiving IR signals on the ESP32 not transmitting them. Fortunately, Andreas Spiess has forked the standard library and added ESP32 transmission capability. You will need to download the ESP32-IRremote library, so we can use it with the ESP32. Andreas did this by using ledC PWM. You can now select any pin to use with IRsend(pin). Note this is only for the ESP32, the other board types have defined pins you have to use due to the assigned timers.

The Duinotech Infrared Transmitter Module


The IR transmitting module which I used is the one from Jaycar (branded Duinotech). There is a data sheet available on the Jaycar site but it is fairly sparse and doesn't clearly define the pins on the module.

It appears that this module is based on the KY-005 INFRARED TRANSMITTER MODULE. The specifications for which are:


Operating Voltage 5V
Forward Current 20 ~ 60 mA
Power Consumption 90mW
Operating Temperature -25°C to 80°C [-13°F to 176°F]
Dimensions  18.5mm x 15mm [0.728in x 0.591in]

This being the case, the pin out is as follows:



The signal pin is clearly labeled with an S, the middle pin is GND via a resistor (* which you have to fit yourself to the module) and GND is connected to the third pin (with the "-" adjacent to it). This module is just an infrared diode (which emits at a wavelength of 940 nm).

Thus, we can drive it like any other diode via a current limiting resistor. The value of the resistor depends on what voltage your micro controller digital outputs (DO) are switching, the desired diode forward current and the forward voltage drop characteristic of the diode. So for our design:

VDO = 3.3V
If = 20 mA
Vf = 1.2V (nominally 1.1V but I measured this using my LCR meter)

Then, R = (VDO - Vf) / If
              = (3.3 - 1.2) / 0.02
              = 105 Ω



We will use a 100 Ω resistor in our circuit.



The CIR (Commercial Infrared) Transmission Protocol


As there are usually other sources of infrared radiation (e.g. sunlight and incandescent or LED lights), the 940nm IR transmitter is modulated by a carrier frequency in the 32-40 kHz range. CIR receivers incorporate a bandpass filter tuned to this carrier frequency. This allows the receiver to discriminate between the modulated IR signal and any ambient, unmodulated IR. In effect, the IR receiver is double tuned both to the wavelength of the IR radiation and to the carrier frequency.



Three factors influence CIR range. In order of decreasing importance they are: the power level of the IR emitter, the IR wavelength, and the carrier frequency. An IR emitter's output is proportional to the current through the emitter. Increasing the current will increase the power. Because the duty cycle is usually 50% or less, the emitter can be driven with quite high currents. For optimal range, the IR wavelength of the emitter and receiver should match.



A similar protocol to CIR is IrDA. IrDA was popular in the late 1990's but has largely been replaced by Bluetooth and WiFi. IrDA was designed to be very short range (< 1 m). It does not use any secondary carrier but directly modulates the 850nm IR with the data. Because of this, it is susceptible to interference from ambient IR. In addition, the IrDA transmitter is usually lower power than a CIR transmitter.

An IrDA transmitter with a CIR receiver is a mismatch as is a CIR transmitter with a IrDA receiver. They operate on a different wavelength (940 nm vs 850 nm), IrDA isn't modulated, and the beam angles are different (IrDA limits the beam angle to ±15° while most CIR emitters are ±40° or greater). Such mismatches have major effects on range and reliability.

We will use CIR in our design.

For RF control, both the transmitter and receiver need to be tuned to the same carrier frequency and need to use the same type of modulation. Most RF remotes use ASK (Amplitude Shift Keying) or OOK (On-Off Keying). OOK is really just a special case of ASK. OOK is also called CPCA (Carrier Present, Carrier Absent). You can have a look at the IRremote library to see how this coding is achieved.

Microsoft Azure




Azure is Microsoft's catch all name for their cloud services. It covers over 100 different services. The service of interest to us is IoT Hub. You can use Azure IoT Hub to securely connect, monitor and manage billions of devices to develop Internet of Things (IoT) applications. To get started we will connect just one device!

You will need to sign up for a free Azure account. Follow the link above and do this. For some reason Microsoft make you provide credit card details, even for the free account. Note that when you sign up, the email address you provide becomes the name of the default active directory (which wouldn't be my first preference).

It will be interesting comparing the Microsoft IoT hub functionality with node-red, which is another dashboard option that we have had experience with. At this stage I suspect that node-red is much cheaper (free) and simpler but Azure is more robust, secure and scalable. The key features of IoT hub are:
  1. Bidirectional communication with LOTS of devices. Use device-to-cloud telemetry data to understand the state of your devices and define message routes to other Azure services without writing any code. In cloud-to-device messages, reliably send commands and notifications to your connected devices – and track message delivery with acknowledgement receipts. Device messages are sent in a durable way to accommodate intermittently connected devices.
  2. Authentication per device. Set up individual identities and credentials for each of your connected devices, and help retain the confidentiality of both cloud-to-device and device-to-cloud messages. To maintain the integrity of your system, selectively revoke access rights for specific devices as needed.
  3. Automated device registration. Speed up your IoT deployment by registering and provisioning devices with zero touch in a secure and scalable way. IoT Hub Device Provisioning Service supports any type of IoT device compatible with IoT Hub.
  4. Use IoT Edge. Take advantage of IoT Edge to make hybrid cloud and edge solutions. IoT Edge provides orchestration between code and services so they flow securely between cloud and edge to distribute intelligence across a range of devices. Enable artificial intelligence and other advanced analytics at the edge.
Once you have signed up for Azure, you will be presented with a dashboard similar to that shown above.

Create an IoT Hub




Microsoft call their menus "blades" in Azure. No idea why, maybe because it sounds cooler than menu? Anyway, click on the + Create a resource link on the blade to the left of the dashboard. This will open the Azure Marketplace.

In the Marketplace, click on Internet of Things. This will provide a new list of menu options to the right.


We want IoT Hub at the top. Click on this to setup your hub. For subscription select Free Trial and for Resource Group, Create new.

The free tier is intended for testing and evaluation. It allows 500 devices to be connected to the IoT hub and up to 8,000 messages per day. Each Azure subscription can create one IoT Hub in the free tier.

A resource group is a container that holds related resources for an Azure solution. The resource group can include all the resources for the solution, or only those resources that you want to manage as a group.

Select the Region closest to your location. In Australia the options are East and Southeast, which I think refer to Sydney and Melbourne respectively.

To create an IoT hub, you must name the IoT hub. This name must be unique across all IoT hubs. The IoT hub will be publicly discoverable as a DNS endpoint, so make sure to avoid any sensitive information while naming it. Once created, the name can't be changed.

Click the button at the bottom labelled - Next: Size and Scale >>



For pricing and scale tier, select F1: Free tier. That is all that you can adjust on this screen. Click Review + create.

When all previous steps are complete, you can create the IoT hub. Click Create to start the back-end process to create and deploy the IoT hub with the options you chose.

It can take a few minutes to create the IoT hub as it takes time for the back-end deployment to run on the appropriate location servers. Once your new IoT resource has been created, you can customise your dashboard.


Add an IoT Device



Before a device or module can connect to your IoT hub, there must be an entry for that device in the IoT hub's identity registry. A device must also authenticate with the IoT hub based on credentials stored in the identity registry. The device or module ID stored in the identity registry is case-sensitive.

To add a new IoT device, click on + Add, and the Add Device blade will be displayed.

  • Device ID: A case-sensitive string (up to 128 characters long) of ASCII 7-bit alphanumeric characters.
  • Authentication Type: Symmetric Key or X.509 Certificate. I used Symmetric Key. The differences are:
    • Symmetric Key: a unique identity key (security tokens) for each device, which can be used by the device to communicate with the IoT Hub.
    • X.509 Certificate: uses an on-device X.509 certificate and private key as a means to authenticate the device to the IoT Hub. This authentication method ensures that the private key on the device is not known outside the device at any time, providing a higher level of security.
  • Auto Generate Keys: tick.
  • Connect device to IoT hub: enable.

Click on Save, and your new device will be added to the hub. Click on the device ID of the newly added device to see the security keys and connection strings. You will need the device ID and a copy of the primary connection string for insertion into your ESP32 sketch. Now onto the ESP32.

ESP32 Software


You can download a copy of my ESP32 sketch from the Reefwing Gist.  You will need to fill in your SSID, password and primary connection string where indicated.



I spent quite a bit of time trying different tool chains to get everything configured and talking. My initial preference was to use Eclipse with the Arduino tool chain. This would give me a proper IDE and a remote control library that I knew was compatible with all the Arduino's out there.

Unfortunately, importing custom libraries is a bit problematic for the two Eclipse Arduino plug-ins available. It is theoretically possible but I ran out of patience trying to get it to work. The ESP-IDF has its own remote control library but it is not as well documented as the Arduino library. I'm also not familiar with coding the ESP32's natively.



While looking for a way to receive the messages sent from the ESP32 to the cloud I discovered a plug in for Visual Studio Code. It so happens that there is also a plug in for Arduino. Since I was already using this to monitor my IoT hub traffic, I decided to give it a crack with programming the ESP32. It just worked - I was astonished! It does use the Arduino IDE tool chain, so that may be why it was so seamless as I had already got everything working with that first. If IntelliSense complains about a missing library, right click on the light build and edit the c_cpp_properties.json file which contains the include path.




The other thing you will probably have to do is add:

"output": "../build",

To the .vscode/arduino.json file, which can be found under the work space for your sketch. The same location as the c_cpp_properties.json file.  If output is not set, Arduino will create a new temporary output folder each time it compiles your sketch, which means it cannot reuse the intermediate result of the previous build, leading to long verify/upload time. So it is recommended to set the field. Arduino requires that the output path should not be the workspace itself or subfolder of the workspace, otherwise, it may not work correctly. By default, this option is not set. Again, no idea why, you will get a warning if it isn't set when you verify.



Whether you use the Arduino IDE or Visual Studio Code, you need to download the Azure IoT library: ESP32_AzureIoT - An Azure IoT Hub library for ESP32 devices in Arduino.  Unzip and copy this to your Arduino libraries folder.

As a first test, load the GetStarted.ino sketch from the examples folder in the library you just downloaded. This sketch will connect to the IoT hub and continuously send messages containing fake data. You will need to fill in the following blanks in the sketch:

  • DEVICE_ID - copy from your IoT registered device;
  • connectionString - copy from the primary connection string;
  • ssid - the displayed name for your WiFi network; and
  • password - for your WiFi network.

Connect to your ESP32, check the port and board type, then compile and upload the sketch. Open up the serial monitor at 115,200 baud so that you can see what is happening. The monitor should be displaying something like the following.


To confirm that the IoT hub is receiving these messages have a look at the Azure dashboard and you should see these messages arriving.


If you have Visual Studio Code, you can use the Azure IoT extension to monitor messages to your IoT hub. Just select your device and then right click and Start monitoring D2C (Device to Cloud) message. You can also send messages from the cloud to your device from here.


Once this was working, I updated the code to just send a heart beat message back to the cloud, letting us know that it was still alive. Every time the ESP32 does this, it broadcasts an IR remote control code three times. This is the usual methodology for remote controls. Currently it is just broadcasting the Sony power code, but we will look at ways we can start/stop the broadcast and change the code via Azure.

Cloud to Device Message Lifecycle




To guarantee at-least-once message delivery, IoT Hub persists cloud-to-device messages in per-device queues. Devices must explicitly acknowledge completion for IoT Hub to remove them from the queue. This approach guarantees resiliency against connectivity and device failures.

When the IoT Hub service sends a message to a device, the service sets the message state to Enqueued. When a device wants to receive a message, IoT Hub locks the message (by setting the state to Invisible), which allows other threads on the device to start receiving other messages. When a device thread completes the processing of a message, it notifies IoT Hub by completing the message. IoT Hub then sets the state to Completed.

The max delivery count property on IoT Hub determines the maximum number of times a message can transition between the Enqueued and Invisible states. After that number of transitions, IoT Hub sets the state of the message to Dead lettered.

The diagram above shows the lifecycle state graph for a cloud-to-device message in IoT Hub. Luckily, sending messages is a lot more straight forward than implementing the message lifecycle.

Controlling the ESP32 via Azure


Now that we have our ESP32 talking to Azure and broadcasting an IR code burst every 10 seconds we want to be able to control this via the cloud. The easiest way to do this is using Visual Studio Code again.


If you right click on the device, shown in Explorer under Azure IOT HUB DEVICES, then the window above is displayed. The two ways we will look at communicating with our device via the cloud is:

  1. Cloud to Device (C2D) Messaging; and
  2. Triggering a defined device method.
You can try out both.

Cloud to Device Messaging


After uploading the sketch to your ESP32, open the serial monitor from the Arduino IDE. I found the serial monitor function in Visual Studio Code was a bit dodgy. Select Send C2D (Cloud to Device) Message to Device, and a message entry window will open. Type in whatever you want and hit return.

In the Azure IoT Toolkit output window you should see:

[C2DMessage] Sending message to [ESP32_IRBeacon_1] ...
[C2DMessage] [Success] Message sent to [ESP32_IRBeacon_1]

A second or so later, the following will appear in the Serial Monitor:

Info: >>>Received Message [1], Size=14 Message test message
Message callback:
test message

The function which handles message handling in the ESP32 code is MessageCallback(const char* payLoad, int size). The call back function is set during setup() using:

Esp32MQTTClient_SetMessageCallback(MessageCallback);


Invoke a Direct Method


This is the way that I chose to control the IR beacon (since that is its purpose). You can define what methods you want to support in your code. Currently we are only handling start and stop but it would be trivial to add another method to set the IR code transmitted.

The process for invoking a method is the same as for sending a C2D message. Right click on your device in Explorer and select "Invoke Direct Method". A text entry window will open, type in your method name (e.g. stop) and hit enter. In the Azure IoT Toolkit output window you should see:

[DirectMethod] Invokeing Direct Method [stop] to [ESP32_IRBeacon_1] ...
[DirectMethod] Invokeing Direct Method [start] to [ESP32_IRBeacon_1] ...

Yes whoever wrote this code couldn't spell invoking! Then in the Serial monitor:

Info: Try to invoke method stop
Info: Stop sending IR burst and heart beat

The function which handles method handling in the ESP32 code is DeviceMethodCallback(). This call back function is set during setup() using:

Esp32MQTTClient_SetDeviceMethodCallback(DeviceMethodCallback);


Conclusion




If all you want is a dashboard for your IoT application then Node-Red is MUCH simpler to implement. If you need an industrial strength solution then you need something like Azure IoT hub.

Actually, using Visual Studio Code (VSC) was a pleasure, and this will be my go to IDE for Arduino from now on. Controlling and Monitoring your IoT devices via VSC was also very easy once you work out how it operates. The user interface is not very discoverable, you need to hit F1 to access most of the Arduino and Azure commands.

I will publish a short follow up article providing a simple PCB to mount the diagnostic LED's, IR transmitting module and the ARM/DEBUG switch. It is a simple enough circuit that you could do it on a breadboard or veroboard. Note that the Duinotech ESP32 doesn't leave any pins free on one side of a standard breadboard, due to its width. See the photo above. This is one reason I decided to use a PCB.


Thursday, July 12, 2018

Espressif ESP32 Tutorial - Programming (Arduino IDE)

Introduction


As promised in the previous post, let's have a look at the different ways we can program our ESP32. I will start with the Arduino IDE, because I think that will be the most common option. In this post I will only be looking to get the "hello world" of IoT going, that is blinking a LED.



Once I've selected an IDE, we will do something useful with the ESP32 (stay tuned).

Arduino IDE




Installing support for the ESP32 IC is not yet available through the Boards Manager, so the
instructions on the GitHub page should be used. For the Mac OS, it is pretty straight forward.

1. Install the latest version of the Arduino IDE.
2. Open Terminal and execute the following command (copy->paste and hit enter):

mkdir -p ~/Documents/Arduino/hardware/espressif && \
cd ~/Documents/Arduino/hardware/espressif && \
git clone https://github.com/espressif/arduino-esp32.git esp32 && \
cd esp32 && \
git submodule update --init --recursive && \
cd tools && \
python get.py

3. Restart the Arduino IDE.

Support for the ESP32 for Arduino is under constant development, but once everything is installed,
the sketch writing and upload process is similar to other boards. If you are using the Jaycar board, select ESP32 Dev Module as the board type, and ensure that the correct serial port is selected.



Connect your ESP32 Dev Board to your PC via a USB cable and you should be ready to compile and upload your first program. First check that you can see the port which is connected to the ESP32.

On my MacBook Pro (early 2015) running High Sierra, the port on the Duinotech ESP32 Dev Board was not recognized. If this happens, you may need to install the drivers for the USB-serial converter for this board. It uses a CP2102 IC, and the drivers are found on the Silicon Labs CP2102 website:
https://www.silabs.com/products/development-tools/software/usb-to-uart-bridge-vcp-drivers.

After you download the correct driver version for your OS. You will need to install it. On the Mac this involves, unzipping the archive, mounting the DMG disk image and then running the Silicon Labs VCP Driver.pkg. You will need to give permission to run this driver in the Security and Privacy preference (this will pop up). You should now be able to see the port in the Arduino IDE (no need to reboot or restart the IDE).

Open up the Blink Sketch (File -> Examples -> 01. Basics -> Blink), compile and download to your ESP32.

You will probably get this error:

'LED_BUILTIN' was not declared in this scope

There are a couple of traps for new players here,

The standard Arduino boards define the LED_BUILTIN macro in the variant file but apparently the ESP32 Dev Board doesn't. For the Arduino, the built in LED is usually connected to pin 13, on the ESP32 it can be anything. The usual suspects are pins 2, 5 or 16. You can fix this error by adding the following line to the top of the sketch, above the setup() function. For example, if your LED is connected to pin 2:

int LED_BUILTIN = 2;

Unfortunately, the Duinotech ESP32 Dev Board doesn't seem to have a LED connected to a user controllable pin. It does have a blue LED which flashes when communicating via the serial port. It is difficult to be 100% sure that this LED is not controllable since I can't find a schematic for this board. Most development boards have a red power LED and a blue in built LED for user control. Anyway, I resorted to connecting an external LED with a current limiting resistor to GPIO 2.



Note that when the EP32 Dev Board is placed on a standard sized bread board, there will only be one spare row of pins, make sure that this is on the side you want to connect to.

Calculation of the current limiting resistor is done using this formula:

Resistor Value = (Vs – VF)/ IF = 160 ohms (I used 150 ohms since that is what I had)

Where:

Vs = Input Supply DC voltage = 3.3V
VF = LED Forward Voltage = 1.7V
IF = LED current = 10 mA



I measured the LED forward voltage drop (VF) using my LCR meter but you could just get it of the data sheet.

I didn't need to do this, but if you are having trouble uploading, try holding the ‘BOOT’ button while pressing and releasing the ‘RST’ button. This should put the board into boot-loader mode to allow uploads.

While you are here you may want to try some of the other ESP32 example sketches provided. For example ChipID (File -> Examples -> ESP32 -> ChipID) will display your chips MAC address in the serial monitor.



All up that wasn't too painful. I think the Arduino IDE would be a good option if you are already familiar with it and as long as the functionality that you need is available. Not all of the libraries are ESP32 compatible yet (e.g. analogWrite is not available yet although there are work arounds).

Wednesday, July 11, 2018

Espressif ESP32 Tutorial - Getting Started

Introduction


I've just started using the ESP32 for my IoT projects and I wanted to record the experience. So here we are! The ESP32 makes for a great low power IoT sensor hub and is a more capable alternative to the Arduino. The caveat is that there is a bit more mucking around to get it to work. There is also some complexity in getting a dual-core microcontroller to play along with a real-time operating system.

I purchased my board from Jaycar in Australia, I'm sure you can get cheaper versions ordering direct from China.

The toolchain for programming the ESP32 in C is a bit of a pain. You’ll need Espressif’s software library (esp-idf), a cross-compiler and build tools that are specific to the chip (xtensa-esp32-*), and a utility to flash the resulting binary file to the device. There are a few different options to program the ESP32, including:

  1. ESP-IDF - the official IoT development framework for ESP32.
  2. Arduino IDE - requires an add on.
  3. Microsoft Visual Studio Code
  4. Eclipse
  5. PlatformIO
  6. EmbedXcode

In the next post I'll try a few of these to see if any offer advantages over the others.

MicroPython




MicroPython is a complete development environment that runs on the ESP32 processor.

The install is done by flashing a firmware image to the board, and then accessing the serial terminal
running at 115200 Baud to enter commands directly into the interpreter. The image can be
downloaded from this page: https://micropython.org/download/#esp32

The esptool.py program will be installed if you have installed the Arduino addon (it’s what does the
uploading under Arduino), otherwise, it can be installed from its GitHub page at: https://github.com/espressif/esptool.

ESP32


The ESP32 is a dual core 32 bit microcontroller featuring WiFi and Bluetooth, and is able to be programmed with the Arduino IDE through an ESP32 add on. Note that not all libraries or functions that work with the ESP8266 or Arduino are yet functional on this new board.

It utilises the Xtensa® dual-core 32-bit LX6 microprocessor running at 240MHz, which is a step up from the ESP8266, while having similar power consumption.

The ESP32 ESP32 can also interface with other systems to provide Wi-Fi and Bluetooth functionality through its SPI / SDIO or I2C / UART interfaces. The ESP32 module comes preloaded with a ROM image of the AT command set, just like the ESP8266 did. If you want to waste 95% of this chip’s potential by using it as a glorified serial-to-WiFi modem, you are good to go!

The operating voltage of ESP32 ranges from 2.3V to 3.6V. When using a single-power supply, the recommended voltage of the power supply is 3.3V, and its recommended output current is 500 mA or more. My board includes a 5V to 3.3V regulator to allow you to power it via USB.



ESP32 has 34 GPIO pins which can be assigned various functions by programming the appropriate registers. There are several kinds of GPIOs: digital-only, analog-enabled, capacitive-touch-enabled, etc. Analog-enabled GPIOs and Capacitive-touch-enabled GPIOs can be configured as digital GPIOs.

Most of the digital GPIOs can be configured as internal pull-up or pull-down, or set to high impedance. When configured as an input, the input value can be read through the register. The input can also be set to edge-trigger or level-trigger to generate CPU interrupts. For low-power operations, the GPIOs can be set to hold their states.

The ESP32 integrates 12-bit SAR ADCs and supports measurements on 18 channels (analog-enabled pins). Some of these pins can be used to build a programmable gain amplifier which is used for the measurement of small analog signals. The ULP-coprocessor (Ultra Low Power) in ESP32 is also designed to measure voltage, while operating in the sleep mode, which enables low-power consumption.  With the appropriate setting, the ADCs and the amplifier can be configured to measure voltage on 18 pins maximum.

The ESP32 has 10 capacitive-sensing GPIOs, which detect variations induced by touching or approaching the GPIOs with a finger or other objects. The low-noise nature of the design and the high sensitivity of the circuit allow relatively small pads to be used.

ESP32 vs ESP8266


The predecessor of the ESP32 was the ESP8266. The feature comparison between the two boards is shown below.




Feature Summary




You can download the ESP32 data sheet but a summary of the ESP32's features are as follows:
  • 240 MHz dual core Tensilica LX6 microcontroller with 600 DMIPS
  • Integrated 520 KB SRAM
  • Integrated 802.11 b/g/n HT40 Wi-Fi transceiver, baseband, stack and LwIP
  • Integrated dual mode Bluetooth (classic and BLE)
  • 16 MB flash, memory-mapped to the CPU code space
  • 2.3V to 3.6V operating voltage
  • -40°C to +125°C operating temperature
  • Onboard PCB antenna / IPEX connector for external antenna


Sensors:
  • Ultra-low noise analog amplifier
  • Hall sensor - detects magnetic fields
  • 10x capacitive touch interfaces
  • 32 kHz crystal oscillator


34 x GPIO:
  • 3 x UARTs, including hardware flow control
  • 3 x SPI
  • 2 x I2S
  • 18 x ADC input channels
  • 2 x DAC
  • 2 x I2C
  • Infrared Remote Control
  • PWM/timer input/output available on every GPIO pin
  • OpenOCD debug interface with 32 kB TRAX buffer
  • SDIO master/slave 50 MHz
  • Supports external SPI flash up to 16 MB
  • SD-card interface support


Security Related:
  • WEP, WPA/WPA2 PSK/Enterprise
  • Hardware accelerated encryption: AES/SHA2/Elliptical Curve Cryptography/RSA-4096


Performance:
  • Supports sniffer, Station, SoftAP and Wi-Fi direct mode
  • Max data rate of 150 Mbps@11n HT40, 72 Mbps@11n HT20, 54 Mbps@11g, and 11 Mbps@11b
  • Maximum transmit power of 19.5 dBm@11b, 16.5 dBm@11g, 15.5 dBm@11n
  • Minimum receiver sensitivity of -97 dBm
  • 135 Mbps UDP sustained throughput
  • 5 μA power consumption in Deep-sleep

Friday, March 17, 2017

Cayenne Competition

Cayenne




We mentioned Cayenne in an earlier post when we were looking for a video web serving solution for the Raspberry Pi. They provide a drag and drop dashboard for your IoT projects.



They have announced a home automation contest so we thought we would give it a try. The judging criteria for the contest is:
  • Interaction of Arduino hardware and Cayenne software with various areas of the home
  • Use of Cayenne’s Triggers & Alerts and Scheduling features
  • Number of devices and sensors connected
  • Real world practicality and usability

You have to use Cayenne obviously and need to include at least one Arduino.

Connecting an Arduino to the Cayenne Server


This is pretty well documented for the Arduino and Raspberry Pi but there were a few missing steps in getting the connection script to run on our Mac. There are 3 things you need to configure:
  1. Connect your Arduino to your PC. Open up your Arduino IDE, download the Cayenne Library.
  2. Set up your free Cayenne account. Start a new project and add an Arduino. Copy the sketch for your device and paste it into the IDE. Upload the sketch and run it.
  3. This was the tricky bit for us. You need to run a connection script on your Mac which redirects the Arduino traffic to the Cayenne server. The scripts are located under the extras\scripts folder in the main Arduino library folder. The instruction for Linux and OSX is to run: ./cayenne-ser.sh (may need to run with sudo).

Getting the Connection Script to work on a Mac


First you need to find the script. We got to ours using:

cd Arduino/libraries/Cayenne/extras/scripts
As instructed, we then tried:

./cayenne-ser.sh
But received the error:

-bash: ./cayenne-ser.sh: Permission denied
No problem we thought, we will just use sudo

sudo ./cayenne-ser.sh
Received a new error

sudo: ./cayenne-ser.sh: command not found
That's weird. So we tried:

sudo sh ./cayenne-ser.sh
And received another error, but we were getting closer...

This script uses socat utility, but could not find it.

  Try installing it using: brew install socat
So we gave that a shot but we didn't have Homebrew installed. Homebrew is a package manager for the Mac (similar to apt-get on Raspbian). To install Homebrew:

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
Once Homebrew is installed you can use brew to install socat. Socat is a command line based utility that establishes two bidirectional byte streams and transfers data between them. This is used to get information from the Arduino to the Cayenne server.

brew install socat
Once you have done all that, you can run your connection script again. The script ran but didn't use the correct port. You can direct which port to use with the following flag:

sudo sh cayenne-ser.sh -c /dev/tty.usbmodem1421
Use the port listed in the Arduino IDE under Tools -> Port.

Cayenne Hello World


To test your new dashboard connection to the Arduino, the easiest way is to add a switch widget pointed at digital output 13 (D13). On most UNO variants this is also connected to an LED so toggling that pin will toggle the LED. If you don't have an onboard LED then you can always connect an external LED. Don't forget to use a current limiting resistor if you do.

The beauty of this is that you don't even have to add any code to the Arduino sketch, you can just use the connection sketch provided when you start a new project. For completeness we will include the code below, this is for a USB connection. Don't forget to insert the token for your project.

#include <CayenneSerial.h>

// Cayenne authentication token. This should be obtained from the Cayenne Dashboard.
char token[] = "YOUR_TOKEN_HERE";

void setup()
{
  //Baud rate can be specified by calling Cayenne.begin(token, 9600);
  Cayenne.begin(token);
}

void loop()
{
  Cayenne.run();
}



The setup for your button should look like this:


So apart from a bit of messing about to get the connection script to run, it all works as advertised. We might have a crack at the home automation competition if we can think of something original to do...