HTTPS Requests with Arduino MKR1000

Introduction

My full code: https://create.arduino.cc/editor/bd2-holt/10727619-6096-42a2-b08e-a9ca055ba597/preview

Capture.PNG

To replace Alexa, we are using IF This Then That (IFTTT). This service allows you to easily use applets for different platforms such as: YoutTube, Spotify, eMail, and SMS, among others. It works by reviving a trigger; ‘this’, then processing an output applet; ‘That’.

For our ‘This’ trigger we used the Webhooks applet. This applet allows you to send a HTTPS request (More specifically a POST or GET request, explained later) to webhooks, which will then trigger the output event. The easiest way to trigger webhooks is to copy and paste the unique URL into your browser and hit enter, however we needed to trigger it using Arduino…

Arduino MKR1000

The Arduino we are using for the internet connectivity is the Arduino MKR1000, a board specifically designed for Internet of Things (IoT) projects. The board uses a WiFi101 module which required the installation of libraries to use.

Setting up the MKR1000: To use the MKR1000, you must install the board type into arduino under Boards Manager. Install the SAMD 32bit ARM-cortex boards.

Next the firmware should be updated on your board, and any SSL (Secure Sockets Layer, used for encrypted HTTPS connections) certificates for web hosts should be added to the board. To do this you need to go to WiFi101 file>example sketches>Wifi101 and run the FirmwareUpdater sketch. Once this sketch is loaded go to tools, and run the firmware updater tool.

In this you should update your module to the newest version (See the text on your board’s WiFi101 module for whether you should use A or B version).

And also add SSL certificates for any website your connecting to, do this at the bottom by typing in the host address, e.g. http://www.google.co.uk.

WiFi 101

Using WiFi101 is relatively easy, however is a little more complex that ESP2866; the most common network module for Arduino.

WiFi101.h
WiFiClient.h
WiFiSSLClient.h
WiFiUdp.h
SPI.h

Include the above libraries.

//WiFi router setup
char ssid[] = "Bob's iPhone"; //network SSID (aka WiFi name)
char pass[] = "password123"; //network password
int status = WL_IDLE_STATUS;
const char* host = "maker.ifttt.com";
WiFiSSLClient sslClient;
WiFiClient client;

Setting up the router connection and defining the host we will connect to later: maker.ifttt.com.

void wifiSetup() {
// Check for the presence of the shield
Serial.print("WiFi101 shield: ");
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("NOT PRESENT");
return; // don't continue
}
Serial.println("DETECTED");
// attempt to connect to Wifi network:
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to Network named: ");
Serial.println(ssid); // print the network name (SSID);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
printWifiStatus(); // you're connected now, so print out the status
}

Call this function using wifiSetup()'. WiFi.status() returns true if the module is connected properly. WiFi.begin(ssid, pass) initialises the connection.

The printWifiStatus() is a separate function, which prints to the serial connection information:

void printWifiStatus() {
// print the SSID of the network:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());

// print WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);

// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
Serial.println(ip);
}

After this is done your ready to start (trying) to send POST requests to IFTTT…

HTTPS with WiFi101

To do this you’ll need to use the following code:

void sendMessage() {
if (sslClient.connectSSL(host, 443)) { //also try .connectSSL
Serial.println("IFTTT request in Progress");
//change this to your Maker setting from //https://ifttt.com/services/maker/settings
String data = "randomdata";
sslClient.println("POST /trigger/tank_empty/with/key/bxazzvKgX-iohEv3KRPOr3 HTTP/1.1");
sslClient.println("Host: ");
sslClient.println(host);
sslClient.println("Content-Type: application/text/plain"); //originally //application/json
sslClient.print("Content-Length: ");
sslClient.println(data.length());
sslClient.println();
sslClient.print(data);
sslClient.stop();
Serial.println("IFTTT request Sucessful");
}
else {
Serial.println("IFTTT request failed");
}
}

sslClient.connectSSL(host, port) returns true if it can connect to the host (the port should be 80 or 443, default open networking ports): When I used maker.ifttt.com it failed at this point.

sslClient.println("POST /uniqueURL HTTP/1.1"); tells the host what request type your using; ‘POST’, followed by the specific domain’s url you want to access, followed by HTTP/1.1, the networking protocol used: This is where WiFi101 gets it’s name.

sslClient.println("Content-Type: application/text/plain"); tells the host what format the data you are sending it is. If you want to send extra conditions to IFTTT, this should be application/json.

The lines of code after this are saying that I’m about to send data, the length of the data, and the data itself.
sslClient.stop(); ends the POST request.

Conclusion

If this worked correctly your custom IFTTT applet should have triggered. Unfortunately I didn’t have the time to fully troubleshoot the problem. However I am fairly convinced it is in the formatting of my HTTP request. The formatting is very important and is occasionally server host specific. Alternatively it is because maker.ifttt.com is denying access for my specific Arduino MAC address, however this is very unlikely.

Using this code I successfully connected to and received data from google.co.uk, but it didn’t seem to work with maker.ifttt.com, but did work with zapier.com (an IFTTT alternative which seemed to have website flaws stopping me from using it). It also worked with ifttt.com

For our hand in we will be using a LCD screen to provide feedback instead.

(Bob & Alex) Alexa -> Arduino MKR1000

Introduction

Following on from last week where I setup a custom Alexa skill… The next stage is to get the Arduino setup with WiFi and communicating through Shiftr.io ( https://shiftr.io/bobIOT/project-arduino ). Shiftr.io is a IoT prototyping service which makes the connection of simple data between devices more simple.

For my Arduino I am using the MKR1000, a board with WiFi built in (WiFi 101). It is smaller, a little slower and slightly less powerful: it’s based on the Arduino Zero.

Testing

With this skill I couldn’t figure our how to change the invocation name of the Alexa SmartHome skill template, so I was stuck with “Alexa, turn the kettle on”. I think it will mean diving into the Alexa javascript code, which I’ll do at another time.

For this prototype I unfortunately lost the code.

Conclusions

The Alexa skill could be a very cool addition to our product, but doing so would mean creating a fully custom skill from scratch, without templates for the JavaScript code for the Alexa. Communicating all the data required for user feedback would be a task too difficult for the time frame we have.

Next week

From this we have decided to use IFTTT to send a text notification to the user’s phone once the water tank is empty on the plant feeder.

(Bob & Alex) Initial Alexa integration attempt

Introduction

For our smart growing station, we wanted to integrate analytics of our plants into an Alexa feedback system. It was initially quite confusing on how to achieve this, but the following is what I found…

Setting up a custom Alexa skill

Alexa Capture 1.PNG

Using the Amazon Web Developer service, you can create a custom skill. A skill is a programmed feedback protocol using Alexa. The tutorial I was trying to follow was to generate a random fact on request of the user.

To do this custom skill you need to set a few parameters:

•The invocation name: i.e. What Alexa responds to when you which to invoke your skill.

•Intents and slots: This is the Alexa equivalent of defining a function in the code, the ‘Intent’ being the function name e.g. tellMeFact, and the slot being arguments for that function. e.g. factName, factInfo, factTime, factFriend

•Samples (sample utterances) is a way to further define your interactions with Alexa. Such as “Alexa, tell me a fact”, followed by “Send this fact to {factFriend}”, which could message your friend the fact you found out.

•Endpoint: The endpoint is where you do the processing on the commands given to Alexa. The preferred method for this is using Amazon’s Lambda service. Which allows you to host an online computing function. In this case, it is to receive the request from Alexa and to return a space fact in the form of a string.

Testing

I did manage to get the Alexa skill working in the end, it retrieved the fact from my hosted Lambda computing service. The code for the lambda program is below:

code capture 1.PNGcode capture 2.PNG

code capture 3.PNG

Conclusion

Now I have learnt to create a custom Alexa skill I can edit this existing example to integrate with my Arduino over Wi-Fi. This will require changing the Invocation name, samples, intents and slots, as well as edit the lambda code.

(Bob & Alex) Project overview

Introduction

We (Bob Holt and Alex Newburg) are working together to produce the next part of our project; A smart home planter station, this is to fit the “For Effecting Behaviour Change” section of the brief. We believe by creating a salad leaf and herb growing station we can influence consumers thinking about what it takes to produce food, hopefully reducing the willingness to waste food. It will also have a direct environmental impact: Eliminating carbon emissions from transporting food, since it will be grown where it is to be cooked with.

Proposal

We propose to make a watering station with a variety of ‘smart’ features:

•Auto watering/watering reminder system: A moisture sensor combined with either a pump or a gravity/valve system.

•Tank refill notifications: This will be achieved using a water level sensor and a notification to Amazon Alexa, or via text message.

•A UV LED lighting system to increase growth speed of the plants: Put on a timer to allow the plants to grow at night as well as day.

•Notifications for fully grown plants: Using an IR emitter/receiver pair to detect once plants have reached a certain height, the user will be notified by Alexa.

•Progress reports from Alexa: Asking Alexa “How is my garden doing?” To bring up an audio overview of how many plants are fully grown, the water level, and any other diagnostics we feel necessary.

(Bob and Richard) Smiling Tips Box

For this week myself and Richard Channing created a smiling customer tips box. It’s composed of the heartbeat sensor from my week 2 post, the relay from Richards week 2 post, the led array from week 3, and a motor, as well a resistor and 2 LEDs.

The Code

Link to our code for this project (Arduino Create)

The code for this project got quite complicated quite quickly. We used 1 library (the ledcontrol library from github previously mentioned). as well as 7 global variables, 2 arrays of byte variables, 1 of our own functions (printFace(bool)), 2 if / else statements, and 2 for loops. For a total of 68 lines of code.

The printFace(bool) function:

Capture - printFace.PNG

Rather that re-typing the for loops every time we want to change the LED array’s display, I’ve given it’s own function with 1 parameter; doesSmile. If I were to type:

doesSmile(true);

Then the led array would be set to display the smile. (the for loops are explained in greater depth in week 3’s post).

The main loop():

Capture - Main Loop.PNG

The main loop is where all the action happens:

Initially we we’re going to keep the LED array and motor on by using the millis() function. However instead we decided to use delay(), to avoid complication if a second coin were to be inserted before the timer had reached 2000 milliseconds.

Next we read the pin for the IR emitter/receiver (heartbeat) sensor. and stored this in the int sensorValue which was globally defined. If the value read by the sensor is significantly higher than the background infrared noise, then a series of events happens:

  1. The time of the event triggering is stored to lastRun.
  2. The LED verification pin is triggered (so I know if the array isn’t working).
  3. The LED array is changed to a smile.
  4. The relay is switched on.
  5. A 2 second delay is triggered.

In the else statement the LED verification pin, LED array, and relay are all switched off.

The Electronics

fritzing.jpg

In our circuit we used the relay to close our second circuit with the motor and 9V battery.  The LED array took 5V from the Uno, the heartbeat sensor also. Occasionally the array glitches out because it doesn’t get a high enough current from the board.

Initially we had a big problem with the relay switch. After one or two clicks while attached to the motor it would get stuck in the closed position. Reasons to this could have been the back e.m.f. (electro magnetic force) generated by the motor, so we stuck in a diode on the output of the switch, however this didn’t seem to change anything apart from making the behaviour of the switch more predictable. Every fourth click of the relay it was still getting stuck.

We concluded that the back e.m.f. must be greater than the peak inverse voltage (PVI). We added in a second diode (this time an led) and the circuit now works perfectly.

The rest of the components were fairly easy to use. The heartbeat sensor had 3 pins, +, -, S (signal). The led array was a little more complicated with 5 pins, VCC, GND, DIN, CS, and CLK. These 3 pins create a Serial Peripheral Interface Bus (SPI), this is a serial connection to the MAX7219CNG chip on the array board which controls the array.

Voltage Regulator L7809CV

Hi, this is a second post for week 2 of the mini project, focusing on the L7809CV voltage regulator.

Voltage regulators explained

Voltage regulators do pretty much what they say on the tin, they decrease the voltage (and current) to a certain level. In the case of this component it limits the output to 9V and 1.5A. And can take a maximum input voltage of 35V, with a recommended minimum of 15V.[1] This voltage regulator wasn’t really suited fora 9V battery, but the circuitry is valid nonetheless.

There are 3 types of voltage regulator: linear, switching, and zenner diode[3]. Linear diodes give a constant voltage output, by using a potential divider circuit (essentially just a resistor). Switching regulators have a much higher efficiency than linear reguators 85% compared to 50% respectfully. However they produce electrical noise which can be complicated to overcome in a circuit. Zenner diodes can also be appropriated as regulators for very low voltage applications, with the output pulled from across the diode. The diode shunts all voltage above it’s breakdown voltage, acting as a regulator.

The circuit

Regulators need a capacitor to ground on the input and output of the component. The capacitor on the output is most important, this is to increase the stability of the output current.[2] The capacitor on the input is to reduce the source impedance (resistance of the input source).

 

 

References

[1] – http://www.farnell.com/datasheets/2307057.pdf?_ga=2.103517824.1809073407.1519564850-527651698.1512323702&_gac=1.207744294.1518449837.EAIaIQobChMI5Lmssdqg2QIVzRXTCh3P9ARlEAYYASABEgKJyfD_BwE

[2] – https://electronics.stackexchange.com/questions/232935/why-is-there-always-a-capacitor-on-input-and-output-of-a-voltage-regulator

[3] – https://www.lifewire.com/types-of-voltage-regulators-818851

Heartbeat Sensor

Hi, this is my second week blog post. The sensor I have this week is the heartbeat sensor. It was very difficult to get working, mainly because of the poor design of the sensor. However I got it to work and this is how I did it:

heartbeat sensor.jpg

The Sensor

The heartbeat sensor is made from an infrared (IR) emitter and receiver. When you put your finger over the receiver the sensor can register the slight differences in how much IR light passes through your finger, when blood passes through your finger due to your pulse there is a slight dip in the amount of the IR light that passes though.

To find your heartbeat a finger is lightly placed on the receiver pad. If you stay very still and do it underneath a bright light, then you can register differences in the IR signal. The signal is an analogue electrical signal you can interpret with the Arduino Uno.

Attempt 1

The code: ArduinoCreate Sensor Fail 1 Code

This code was based off of code found from Stack Overflow

This code was way too sensitive to changes in the signal from the sensor. It ended up just flashing at really fast speeds not relevant to my heart rate.

Attempt 2

The code: ArduinoCreate sensor fail 2 code

This code was based off of code found from Stack Overflow

This attempt worked in a similar way to the last, with slightly altered way of processing the data. It was closer to finding my heartbeat but then I realised when I took my finger away it just carried on flashing.

Attempt 3 (Success)

The code: ArduinoCreate sensor success code

After my numerous failures I decided to mess around with the physical environment as well as the code. I found that placing a bright light above my thumb increased the accuracy, and if I’m honest I’m not sure entirely why.

The code was also far better (and simpler).  It worked by reading the pin. finding the change and applying a modulus to it (abs()). Then if the change is greater than 0 (i.e if there is a significant change), then flash the led. The value 0 can be changed to vary it’s sensitivity.

Conclusion

This sensor was a nightmare to get working, but it is very useful. Not so much for detecting heartbeats, but for use as a short range motion sensor. The IR emitter/receiver pairing on one board is very useful.

New code I learnt during this week:

abs() – Used to find the magnitude of a number
&& || – AND and OR logic statements
float – float variable type, used to store decimal numbers

Tilt Switch

Hi, this is my first week blog post.

For my initial component I have been given a mercury tilt switch. It is a pretty simple component consisting of a blob of mercury in a glass tube, with two electrodes at the end [1].

When tilted the mercury covers the electrodes and completes the circuit, allowing for a current to flow.

 

 

 

tilt switch image

An advantage of a tilt switch above all other types of switch is that it is non-degrading. [2] It also has a very low resistance, so can be used in high current applications.

Meaning it should last indefinitely as long as the electronics don’t corrode or the glass smash.

 

History and Uses

The mercury tilt switch is an extinct component. It used to be used for a variety of uses: Machinery tilt detection, lighting control for car boot lids, anti-mine tampering, and vending machines [3].

The mercury tilt switch has been replaced by the tilt switch using a ball bearing, this is because of mercury’s toxicity. The only disadvantage of the ball bearing is that it requires debouncing, since the ball bearing bounces when tilted, creating an initially jittery connection. Since mercury is a liquid debouncing isn’t needed. [4]

 

Test and Coding

A link to my code: My Tilt Switch Code

Fritzing didn’t have my tilt switch with 3 pins (GND, Signal, IN) so I used their 2 pin tilt switch and just put the wires on the breadboard nearby.

Tilt Switch_bb.pngTilt Switch_schem.png

The code for this was very simple, as were the electronics. All that had to be done is digitally reading pin 8, detecting whether there was a current. If yes, then the LED was switched on.

A potential project to use this in would be an alarm clock which you push over to turn off the alarm.

 

References

[1] – http://www.russell-scientific.co.uk/mercury-switches-21-c.asp

[2] – https://ipfs.io/ipfs/QmXoypizjW3WknFiJnKLwHCnL72vedxjQkDDP1mXWo6uco/wiki/Mercury_switch.html

[3] – United States, Mercury study report to Congress, DIANE Publishing, 1997 ISBN 1-4289-0372-0, page 2-11

[4] – https://en.wikipedia.org/wiki/Mercury_switch