Posted on Leave a comment

3 Way to use a button using OneButton Library

I stumble across a “OneButton” library by Matthias Hertel which allows you to use one button and expanding it’s uses without blocking the program. The code allows setting up a Normal LOW button (button connected to VCC 5V when pressed) or Normal HIGH button (button connected to GND when pressed).

If we look at the state diagram above, we start with state 0. When a button is pressed, the program will jump to state 1 and waiting for the button goes up, if this sequence happened and the timeout occur (state 2), the click() function will be called. If another button down event happened (state 3) followed by button up the doubleclick() function will be called. Then the state machine will go back to start state 0. If the button was pressed initially a bit longer than the press timeout, the press() event will fire, and then the state machine will jump to state 6 and detecting the button up before go back to initial state 0.

So in summary by using this library, we can allow 3 function call for a single button:

  1. Single click
  2. Double click
  3. Long click

Installation

To install the OneButton library you can just go from the Arduino interface and select the menu Sketch->Include Library->ManageLibraries…

You can search for the OneButton Library by Matthias Hertel. At the time of the writing the version 1.3.0 is the latest. You can Click the “install” button to install the library. Now you are ready to use the OneButton Library.

How to use the OneButton Library

To use the library, you will have to include the library at the beginning of your code as shown below:

#include "OneButton.h"

Then initialise the the OneButton variable using the following code:

// setup a new OneButton on pin 2
OneButton button(2, false); // normal LOW, set to true for normal HIGH

The first parameter “2” is telling the code which pin is connected to the button. In this example it is connected to Digital pin 2. You can also connect it to Analog pin, and you have to pass in “A1” if the button is connected to pin Analog 1.

The second parameter “false” is telling the code that the button is normally connected to the GND (LOW) and when it is pressed it will send a HIGH signal to the input pin D2. To illustrate this you can have a look at the following schematic diagram:

The Normal LOW button on the left is connected to the input D2 via pull down resistor R1, and Normal HIGH button is connected to input D3 via pull up resistor R2.

Once this is done, it is time to setup the call back function for in the Setup() section of the Arduino code.

void setup() {
Serial.begin(9600); // Serial begin
// link myClickFunction to a click event
button.attachClick(myClickFunction);
// link myDoubleClickFunction to a doubleclick event
button.attachDoubleClick(myDoubleClickFunction);
// link to long press stop event
button.attachLongPressStop(wipeOutFunction);
// set debouncing time default 50ms
button.setDebounceTicks(80);
}

You will notice at the code above the call back function for Click is called myClickFunction, the call back function for DoubleClick is called myDoubleClickFunction and the call back function for long press is called wipeOutFunction. As also shown above you can also set the debounce time to 80ms, if this is not set the default will be at 50ms.

Now I am applying this to my previous Game Of Life circuit, with the following additional function:

  1. Double click to randomly start the game 8×8 life form
  2. Single click to pause so that we can observe
  3. Long click to wipe out half or life form (the same way Thanos would have done)

To achieve the above, here are the modification to the setup function:

void setup() {
Serial.begin(9600); // Serial begin
pinMode(latchPin, OUTPUT); // Pin configuration
pinMode(clockPin, OUTPUT);
pinMode(dataPin, OUTPUT);
for (int i = 0; i < 8; i++) { // for loop is used to configure common cathodes
pinMode(pins[i], OUTPUT);
digitalWrite(pins[i], HIGH);
}
// link myClickFunction to a click event
button.attachClick(myClickFunction);
// link myDoubleClickFunction to a doubleclick event
button.attachDoubleClick(myDoubleClickFunction);
// link to long press stop event
button.attachLongPressStop(wipeOutFunction);
// set debouncing time
button.setDebounceTicks(debounce);
randomSeed(analogRead(0));
}

The Loop function is now much simplified to the code to display the matrix as follows:

void loop() {
// keep watching the push button
button.tick();
if (started){
// calculate next field
if (millis() - 1000 > lastMillis) {// delay each iteration by 1000 ms
fillNextField();
for (int x = 0; x<8; x++){
for (int y = 0; y<8; y++) {
field[x][y] = nextfield[x][y];
}
}
lastMillis = millis();
}
}
// display output to 8x8 matrix
refreshScreen();
}

The myClickFunction call back is also quite simple to pause and continue the sequence

// this function will be called when the button was pressed 1 time and them some time has passed.
void myClickFunction(){
started = !started;
}

The double click function call back will be used to reset the game by randomly reassigning the 8×8 LEDs

// this function will be called when the button was pressed 2 times in a short timeframe.
void myDoubleClickFunction(){
started = false;
for (int i = 0; i<8; i++) {
for (int j = 0; j<8; j++){
field[i][j] = random(2);
Serial.print("field["); Serial.print(i); Serial.print("]["); Serial.print(j);
Serial.print("]:");
Serial.println(field[i][j]);
}
}
delay(200);
started = !started;
}

The long press will be used to wipe out half of the life form, Thanos would be so proud.

// this function will be called when the long press is finished
void wipeOutFunction(){
started = false;
bool alive = random(2); //dead or alive
for (int i = 0; i<8; i++) {
for (int j = 0; j<8; j++){
if (field[i][j]){
field[i][j] &= alive;
alive = !alive;
}
}
}
}

You can see the result in the following video.

Please let me know what do you think, and please share if you like or drop me a comments and don’t forget to subscribe for more simple Arduino circuits.

Posted on Leave a comment

ESP8266 Secure AP mode

Quite often we take shortcut to make things simple. That that sometimes will come and bite you back. To make sure you always consider security in mind at everything you do. Password is to keep something secure, and not to be forgotten.

In this post, I am trying to show how simple the security can be implemented to ensure that we always have security in mind. There is nothing worse than having a fully working system and then get hacked. This will cause unnecessary stress later.

If you are using ESP8266 in AP mode to setup the WIFI configuration, don’t forget to set the password and make sure you keep it secure by remembering it and not tell anyone.

In order to do this you can set the password when setting the ESP as and AP, this is done using the following code:

WiFi.softAP(WIFI_AP_NAME, AP_PASS);

The second line in the above code passed in “AP_PASS” variable, this will ensure that you can connect to the ESP using the password. You can also leave the second parameter blank to leave it open, but then anyone can connect to it and messed up with your setting. Things to note, the password will need to be more than 8 Characters, otherwise, the function call will fail. The best way to check this is to check the Serial Monitor and modify the above code to be as follow:

Serial.print("Starting AP mode:");
Serial.println(WiFi.softAP(WIFI_AP_NAME, AP_PASS)? "Ready": "Failed!");

When the AP is started, you can see in the Serial monitor window whether the function call WiFi.softAP is success or not. The simple code describing the above can be found below.

/*
   Copyright (c) 2015, Majenko Technologies
   All rights reserved.
   Redistribution and use in source and binary forms, with or without modification,
   are permitted provided that the following conditions are met:
 * * Redistributions of source code must retain the above copyright notice, this
     list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright notice, this
     list of conditions and the following disclaimer in the documentation and/or
     other materials provided with the distribution.
 * * Neither the name of Majenko Technologies nor the names of its
     contributors may be used to endorse or promote products derived from
     this software without specific prior written permission.
   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
   ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
   WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
   ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
   ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/* Create a WiFi access point and provide a web server on it. */

#include 
#include 
#include 

#ifndef APSSID
#define APSSID "ESPap"
#define APPSK  "thereisnospoon"
#endif

/* Set these to your desired credentials. */
const char *ssid = APSSID;
const char *password = APPSK;

ESP8266WebServer server(80);

/* Just a little test message.  Go to http://192.168.4.1 in a web browser
   connected to this access point to see it.
*/
void handleRoot() {
  server.send(200, "text/html", "You are connected");
}

void setup() {
  delay(1000);
  Serial.begin(115200);
  Serial.println();
  Serial.print("Configuring access point...");
  /* You can remove the password parameter if you want the AP to be open. */
  WiFi.softAP(ssid, password);

  IPAddress myIP = WiFi.softAPIP();
  Serial.print("AP IP address: ");
  Serial.println(myIP);
  server.on("/", handleRoot);
  server.begin();
  Serial.println("HTTP server started");
}

void loop() {
  server.handleClient();
}

Hopefully you will find this article useful to secure your IoT devices and saving you the headache of being hacked in the future. If you like this post, please share and don’t forget to subscribe the blog for more article about IoT and Arduino.

Posted on Leave a comment

Arduino LED Matrix “Game of Life”

I was reading a post about someone making a Thanos Gauntlet and simulating wiping off half of the population randomly. So I thought about the “Game of Life” simulation. If you want to know more about “Game of Life” you can read it all up here. So why not trying to make this simulation based on my previous build of the 8×8 LED Matrix. The circuit can be found below:

Using the previous build, I made a few adjustment to the code to simulate the game of life. The first thing to note is to initialise the 8×8 variable to hold the initial life form, the next variable is the next stage after the life form evolved, this is shown as below:

bool field[8][8] = {};
bool nextfield[8][8] = {};

When the program start, we randomly assign the 8×8 matrix with zeros and ones to simulate the initial stage, this is shown in the following code. The code will only be executed when the button is pressed longer than the threshold defined by variable debounce. I define this to be 50ms.

if (buttonpressed == HIGH && millis() - time > debounce){ // set random life
time = millis();
started = false;
for (int i = 0; i<8; i++) {
for (int j = 0; j<8; j++){
field[i][j] = random(2);
Serial.print("field["); Serial.print(i); Serial.print("]["); Serial.print(j);
Serial.print("]:");
Serial.println(field[i][j]);
}
}
delay(200);
started = !started; // start the Game of Life simulation
}

Right after the initialisation, the code will set the started variable to true. The program will calculate the next field at every iteration this is done by calling the fillNextField() function, shown in the following code.

}else if (started){
// calculate next field
if (millis() - 1000 > lastMillis) {// delay each iteration by 1000 ms
fillNextField();
for (int x = 0; x<8; x++){
for (int y = 0; y<8; y++) {
field[x][y] = nextfield[x][y];
}
}
lastMillis = millis();
}
}

The rule of Game of Life is as below. Each cell’s existence depends on all the other 8 cells that are surrounding it.

  1. Any live cell with fewer than 2 live neighbours dies, as if by underpopulation
  2. Any live cell with two or three live neighbours lives on to the next generation (cycle)
  3. Any live cell with more than three live neighbours dies, as if by overpopulation.
  4. Any dead cell with exactly 3 live neighbours becomes a live cell, as if by reproduction.

Based on the logic above the getCellsNextState(int x, int y) function is being developed as shown below:

//returns the cell's next state, true if alive, false otherwise
bool getCellsNextState(int x, int y) {
bool shouldBeAlive = false;
shouldBeAlive |= (!field[y][x] && countAliveNeighbours(x, y) == 3);
shouldBeAlive |= (field[y][x] && countAliveNeighbours(x, y) == 3);
shouldBeAlive |= (field[y][x] && countAliveNeighbours(x, y) == 2);
return shouldBeAlive;
}

As you can see the CountAliveNeighbours(x,y) function will count the number of alive neighbours around the cell. This is done by simply iterating from the one cell before and after in x coordinate and one cell before and after in y coordinate. Then we define the boundary condition as per our LED matrix boundary, which is 8 cells x 8 cells. And finally we count how many live cells as per below function.

// counts the alive neighbours this step
int countAliveNeighbours(int x, int y) {
int retVal = 0;
for (int row = y - 1; row <= y + 1; row++) { for (int col = x - 1; col <= x + 1; col++) { if ((row == y && col == x) || (row < 0) || (row > 7) || (col < 0) || (col > 7)) continue;
if (field[row][col]) retVal++;
}
}
return retVal;
}

If all goes well, you should see the following Game of Life simulation similar to the following video.

Congratulations, how you are able to simulate this classic Game of Life and you can modify this to your heart’s content. What you can do next is to stop the simulation and wipe off half of the live form like what Thanos did, and feel the power of the Infinity Gauntlet.

Please share or comments if you like this post, and let me know if you have any questions related to this.

Posted on Leave a comment

Light Saber Build Part 2

This is the continuation of the Light Saber Build Part 1. You can check the previous post to see where I am up to. Just a quick recap from Part 1. I am connecting the DPPlayer to the Arduino Nano and also the saber on-off switch which is connected to D3 and ground as shown in the following circuit.

The next part is to connect the Gyro MPU6050 and the LED strip WS2811. My LED strip consist of 20 controller, each controller is controlling 3 LEDs. Before putting everything together in the case, we are testing to make sure the strip are lighting up properly and also when there is a sudden movement or “a hit” the hit sound effects are being played.

You can see the test result in the following video.

Things to note about the feature of the light saber:

  • Sound effect for saber on and off
  • Switching lightsaber colour when the button are pressed 3 times when the lightsaber is on
  • Toggle the humming sound effect on and off when the button are pressed 5 times when the lightsaber is on
  • Humming sound and special effects when the lightsaber hit an object or there is a change in the angle

Once we tested that the lightsaber are functioning correctly, as per the feature that we want, it is time that we put the case together. I found that this is the most difficult part to get the right combination for the part. I am a big believer in recycling, so I am trying hard to find some spare parts that are lying around that can be used to build the lightsaber. Stay tune for the next write up on the lightsaber case.

If you like this post, please share it, and don’t forget to subscribe and please let me know if you have any questions and I will try to answer them.

Posted on Leave a comment

Light Saber build part 1

Today is May Day, so I though to prepare and finish off my Light Saber build that had been sitting in my shelf for quite sometime. The idea is not new and the circuit is a modification of an existing circuit build by someone else. So it is not by any means original but still fun to build.

So here is the circuit, it is using Arduino nano as the “brain” and MPU6050 gyroscope to detect the movement. It also being equipped with DFPlayer mini for the light Saber effect. The light is using addressable LED strip (WS2811).

I had manage to wire up the circuit by recycling my previous build of Frankenbot. I have not wire up the LED and the gyroscope just yet, this is to ensure that everything is working before moving on to the next part.

Here are the Video of the special effects turning on and off. Stay tune for the part. If you like this, please subscribe and share the content.