Author Archives: mschoeffler

How to control a DC motor with the Arduino Uno and the L298N Dual Motor Controller

L298N Module

Pin description (for controlling DC motors):
1: + (DC motor 1)
2: – (DC motor 1)
3: If jumper enabled, 5V output on pin 6(e.g. for driving an Arduino)
4: Vcc of motor voltage supply
5: GND
6: 5V output, if jumper enabled
7 (ENA): One of Arduino’s PWM pins can be connected (to the lower pin) to control the speed of motor 1. If the jumper is enabled, motor 1 will run on full speed.
8 (IN1): Controls direction of motor 1
9 (IN2): Controls direction of motor 1
10 (IN3): Controls direction of motor 2
11 (IN4): Controls direction of motor 2
12 (ENB): One of Arduino’s PWM pins can be connected (to the lower pin) to control the speed of motor 2. If the jumper is enabled, motor 2 will run on full speed.
13: + (DC motor 2)
14: – (DC motor 2)

In order to control a DC motor with the Arduino Uno, a motor controller module is required. Such module is needed, for various reasons: For example, the Arduino can’t power DC motors with a voltage higher than 5V. However, many DC motors need more than 5V, especially when they are supposed to move on full speed. Moreover, most DC motors need more power than the Arduino could provide. In this tutorial, the L298N Dual Motor Controller is used to control a single DC motor with the Arduino Uno. The L298N module can also be used to control two motors with different directions and speeds.

List of materials:
– Arduino Uno [Search on Amazon.com | Amazon.de | Amazon.co.uk]
– Jumper wires [Search on Amazon.com | Amazon.de | Amazon.co.uk]
– Jumper wire clamps [Search on Amazon.com | Amazon.de | Amazon.co.uk]
– Breadboard [Search on Amazon.com | Amazon.de | Amazon.co.uk]
– L298N module [Search on Amazon.com | Amazon.de | Amazon.co.uk]
– DC motor [Search on Amazon.com | Amazon.de | Amazon.co.uk]
– USB power boost 5V-to-9V (optional) [Search on Amazon.com | Amazon.de | Amazon.co.uk]
– DC power jack socket (optional) [Search on Amazon.com | Amazon.de | Amazon.co.uk]

Pin Layout:
In order to power the DC motor, two voltage supplies with different voltages are needed. The used DC motor has an operating voltage of 3V up to 12V. As the L298N module drops the voltage by more than 2V, the 5V voltage supply (USB) of the Arduino can’t be used. Therefore, a second voltage supply of 9V is used. In this tutorial, a USB Power boost (5V-to-9V) is used in combination with a DC power jack socket. Then, the power jack socket is connected to the breadboard. The breadboard’s “+” line (Vcc) is connected to pin 1 of the L298N module. The breadboard’s “-” line (GND) is connected to pin 2 of the L298N module. It is important that the L298N module and the Arduino share the same GND. Therefore, the breadboard’s “-” line is also connected to one of the Arduino’s GND pins.

Scheme of the tutorial's setup

Scheme of the tutorial’s setup. An Arduino is wired to an L298N module to control a DC motor.

The Arduino’s pin 6 is connected to the ENB pin of the module. This connection is used to control the speed of the motor and, therefore, using one of the Arduino’s PWM-enabled pins is required. Then, the Arduino’s pins 7 and 8 is connected to the module’s pins IN3 and IN4, respectively. These pins are used to control the direction of the DC motor (IN3=HIGH/IN4=LOW or IN3=LOW/IN4=HIGH).
As a final step, the module’s output pins for the second motor (pin 13 and 14) are connected to the DC motor.

Example source code:

Picture of the setup

Picture of the setup.

This source code drives the motor in four different states: Forward in slow and fast mode as well as backward in slow and fast mode. The functions slow() and fast() write an analog value to the PWM pin that is connected to ENB. The higher the value (0 to 255), the higher the speed of the motor. Please note, that the motor will not work if the values are too low.
In the loop function, the motor is driven forward in slow mode for five seconds. Naturally, the direction of the motor also depends on the direction you mounted the motor as well as on how you connected the motors pin to the module’s pins 13 and 14. Then, the motor drives in fast mode for 5 seconds. Next, the motor changes the direction and is driven in slow mode for 5 seconds as well as in fast mode for 5 seconds.

// (c) Michael Schoeffler 2016, http://www.mschoeffler.de

const int enb = 6; // PWM pin 6
const int in3 = 7;
const int in4 = 8;

void setup() {
 pinMode(in3, OUTPUT);
 pinMode(in4, OUTPUT);
 pinMode(enb, OUTPUT);

}

void slow() {
 analogWrite(enb, 128);
}

void fast() {
 analogWrite(enb, 255);
}

void loop() { 
 digitalWrite(in3, LOW);
 digitalWrite(in4, HIGH);
 slow();
 delay(5000);
 fast();
 delay(5000);
 // change of direction
 digitalWrite(in3, HIGH);
 digitalWrite(in4, LOW);
 slow();
 delay(5000);
 fast();
 delay(5000);
}

Side Notes:

  • The L298N module can also be used to drive stepper motors.
  • You can also drive more than two motors. Just share the pins 13 and 14 (or 1 and 2) with multiple motors. If multiple motors share the same pins they will also share the direction and speed.
  • The module’s pins 7 to 12 (ENA, IN1, IN2, IN3, IN4 and ENB) work with TTL logic levels (5V). Therefore, we can set the values directly from the Arduino if the same GND is shared.
________________________________________

How to use the “MicroSD Card Adapter” with the Arduino Uno

Pin layout of MicroSD Card Adapter and Arduino Uno.

In this tutorial, it is shown how to read and write SD cards utilizing the “MicroSD Card Adapter” module and Arduino Uno. An major advantage of the module is that it can be used with the SD library that comes with the Arduino IDE. The SD library makes initialization, reading, and writing of the card very easy.

List of materials:
– Arduino Uno [Search on Amazon.com | Amazon.de | Amazon.co.uk]
– Jumper wires [Search on Amazon.com | Amazon.de | Amazon.co.uk]
– MicroSD Card Adapter [Search on Amazon.com | Amazon.de | Amazon.co.uk]
– MicroSD card [Search on Amazon.com | Amazon.de | Amazon.co.uk]

How to connect the “MicroSD Card Adapter” module to the Arduino Uno?

Schematic view of pin layout.

The module comes with a voltage regulator. Therefore, the Arduino’s 5V and 3.3V pin can be used for the voltage supply. The module communicates via SPI (Serial Peripheral Interface) to the Arduino Uno.  The following table shows the complete pin layout.

MicroSD Card Adapter Pin Arduino Uno Pin
CS 4
SCK 13
MOSI 11
MISO 12
VCC 5V
GND GND

How to program the RFID reader?
As mentioned before, reading and writing an SD card is very simple when the standard SD library of the Arduino IDE is used. Make sure to use the latest version of the SD library (Sketch -> Include Library -> Manage Libraries -> Search for “SD”). For example, in my case, version 1.1.0 did not work with the module. Fortunately, version 1.1.1 did work without any problems. Moreover, the SD card must be formatted as FAT16 or FAT32. If something does not work as expected, a good start for debugging is always to upload CardInfo example of the library (File -> Examples -> SD -> CardInfo) to the Arduino and read the messages of the serial monitor.
In this tutorial’s code, a random number between 0 and 9 is written to an SD card. In particular, the number is written to a file named “file.txt”. Next, the content of “file.txt” is read. At the end of the loop function, a delay of 5 seconds is added. Please note that when the Arduino is started, it is checked whether a file named “file.txt” exists (see setup function). If so, the file is deleted.

// (c) Michael Schoeffler 2016, http://www.mschoeffler.de
#include <SD.h> //Load SD library

int chipSelect = 4; //chip select pin for the MicroSD Card Adapter
File file; // file object that is used to read and write data

void setup() {
  Serial.begin(9600); // start serial connection to print out debug messages and data

  pinMode(chipSelect, OUTPUT); // chip select pin must be set to OUTPUT mode
  if (!SD.begin(chipSelect)) { // Initialize SD card
    Serial.println("Could not initialize SD card."); // if return value is false, something went wrong.
  }

  if (SD.exists("file.txt")) { // if "file.txt" exists, fill will be deleted
    Serial.println("File exists.");
    if (SD.remove("file.txt") == true) {
      Serial.println("Successfully removed file.");
    } else {
      Serial.println("Could not removed file.");
    }
  }
}

void loop() {
  file = SD.open("file.txt", FILE_WRITE); // open "file.txt" to write data
  if (file) { 
    int number = random(10); // generate random number between 0 and 9
    file.println(number); // write number to file
    file.close(); // close file
    Serial.print("Wrote number: "); // debug output: show written number in serial monitor
    Serial.println(number);
  } else {
    Serial.println("Could not open file (writing).");
  }

  file = SD.open("file.txt", FILE_READ); // open "file.txt" to read data
  if (file) {
    Serial.println("--- Reading start ---"); 
    char character; 
    while ((character = file.read()) != -1) { // this while loop reads data stored in "file.txt" and prints it to serial monitor 
      Serial.print(character);
    } 
    file.close();
    Serial.println("--- Reading end ---"); 
  } else {
    Serial.println("Could not open file (reading).");
  } 
  delay(5000); // wait for 5000ms
}

If everything works correctly, the serial monitor should show a similar output as shown in the following screenshot:

Serial monitor output while using MicroSD Card Adapter.

Video Tutorial

____________________

How to use the ultrasonic sensor/actuator “HC-SR04” with the Arduino Uno

In this tutorial, it is shown how to use the ultrasonic sensor (and actuator) “HC-SR04” with the Arduino Uno. The HC-SR04 has an ultrasonic transmitter and receiver. The transmitter sends out a 40 kHz burst signal (which is not audible by humans). The receiver captures the signal if it is reflected by an obstacle. Therefore, the HC-SR04 can be used for distance measurements and alarm detection systems. The HC-SR04 supports 50 measurements per second and distances between 2cm and about 300cm.

List of materials:
– Arduino Uno [Search on Amazon.com | Amazon.de | Amazon.co.uk]
– Jumper wires [Search on Amazon.com | Amazon.de | Amazon.co.uk]
– ultrasonic sensor HC-SR04 [Search on Amazon.com | Amazon.de | Amazon.co.uk]

How to connect the HC-SR04 to the Arduino?

Schematics of how to connect the HC-SR04 ultrasonic sensor module to the Arduino.

The HC-SR04 module has four pins. The module’s Vcc pin has to be connected with the 5V pin of the Arduino. In this tutorial, the module’s “Trig” pin (trigger) is connected to the Arduino digital pin 2 and the “Echo” pin is connected to Arduino’s digital pin 3. Lastly, the module’s “Gnd” pin is connected to one of the Arduino’s GND pins. Here, a mini breadboard is also utilized so that the HC-SR04 can be connected to the Arduino in an upright position.

How to program distance measurements with the HC-SR04?
The ultrasonic module is used to measure the distance between the module and an obstacle. In order to measure the distance, the module must be prepared to send out the 40 kHz burst signal. The burst signal is sent when the signal of the “Trig” pin goes from HIGH to LOW. In addition, the HIGH signal must have been present for at least 10 microseconds. The module sends a pulse on the echo pin with the duration of the round-trip-time of the burst signal. The round-trip-time is the time from the transmitter to an obstacle and from the obstacle to the receiver. Fortunately, the pulseIn-function covers this use-case perfectly. If the second parameter is HIGH, the pulseIn-function waits for the pin to go HIGH, starts timing, then waits for the pin to go LOW.
In order to obtain the distance, the duration has to be divided by two, since only the one-way distance is of interested (from module to obstacle). Next, the acoustic velocity of the air has to be taken into account which is about 343.5 meters per second (only at a temperature of 20°C). Since the duration measured by the pulseIn-function is in microseconds and we are interested in cm, the  divided duration has to be multiplied by 0.03435.


// (c) Michael Schoeffler 2016, http://www.mschoeffler.de

const int pinTrigger = 2; // pin for sending out the signal
const int pinEcho = 3; // pin for receiving the echo of the signal
long duration = 0; // the roundtrip duration of the signal in us
void setup() {
pinMode(pinTrigger, OUTPUT);
pinMode(pinEcho, INPUT);
Serial.begin(9600); // open serial connection to print out distance values
}

void loop() {
digitalWrite(pinTrigger, LOW); // turn off the trigger
delayMicroseconds(3);
noInterrupts(); // disable interrupts as they might interfere with the measurement
digitalWrite(pinTrigger, HIGH);// prepare to send "trigger" command to module
delayMicroseconds(10); // wait for 10us (module sends signal only, if trigger had a HIGH signal for at least 10 us)
digitalWrite(pinTrigger, LOW); // module sends signal now
duration = pulseIn(pinEcho, HIGH); // waiting for a HIGH signal on the echo pin.
interrupts(); // enable interrupts, we are done with the measurement

// from roundtrip duration to distance:
long durationOneWay = duration / 2; // divided by two, since duration is a roundtrip signal
// acoustic velocity of air at a temperature of 20°C => ~343.5 m/s
// => 0.03435 cm/us
long distance = durationOneWay * 0.03435; // distance in cm
Serial.print("Distance[cm]: ");
Serial.println(distance);

delay(500); // wait for 500ms (added only for debugging reasons)
}

Distance measurement with the Arduino Uno and HC-SR04 module.

If the code is uploaded to an Arduino, the output of the serial monitor should show the distance between the module and an obstacle. Since many factors, such as temperature, the obstacle’s material and surface characteristics, have an influence on the accuracy of the measurements, it is very challenging to achieve highly accurate measurements with such a low-cost ultrasonic sensor. Nevertheless, the HC-SR04 is a cheap and easy-to-use ultrasonic module with a wide range of possible applications.

Video Tutorial

_______________

How to use the RFID-RC522 module (RFID reader) with the Arduino Uno

Setup of this tutorial: RFID reader and two RFID tags.

RFID stands for Radio-frequency identification and can be used for many application that require an identification mechanism. In this tutorial, it is shown how to use the RFID-RC522 module with the Arduino Uno. The RFID-RC522 module is an RFID reader, which can read RFID tags in close-range. In order to read an RFID tag, the reader and the tag must have the same frequency. The RFID-RC522 module reads only High frequency tags at 13.56 MHz.
In order to demonstrate the RFID-RC522 module, a simple application is programmed which identifies a user based on an RFID tag.

List of materials:
– Arduino Uno [Search on Amazon.com | Amazon.de | Amazon.co.uk]
– Jumper wires (female/male) [Search on Amazon.com | Amazon.de | Amazon.co.uk]
– RFID-RC522 module [Search on Amazon.com | Amazon.de | Amazon.co.uk]
– RFID tags [Search on Amazon.com | Amazon.de | Amazon.co.uk]

How to connect the RFID-RC522 to the Arduino?

Schematic of how to connect the RFID-RC522 to the Arduino.

The RFID-RC522 module comes with eight pins (of which seven pins are used in this tutorial). In the following, the pin layout is shown as recommended by the documentation of the MFRC522 library (used later in the programming section). The RFID-RC522 module runs with 3.3V. Therefore, the module’s 3.3V pin must be connected to the Arduino’s 3.3V. The module might get damaged, if it is accidentally connected to the Arduino’s 5V pin. The complete pin layout is shown by the following table (works only for the Arduino Uno! Mega, Nano etc. have different recommended pin layouts!):

RFID-RC522 Pin Arduino Uno Pin
SDA 10
SCK 13
MOSI 11
MISO 12
IRQ UNUSED
GND GND
RST 9
3.3V 3.3V

How to program the RFID reader?
The code makes use of an existing RFID library which can be found here: https://github.com/miguelbalboa/rfid. If you are using the Arduino IDE, the library can be easily installed by clicking “Sketch->Include Library->Manage Libraries”. Then, search for “RFID” and you will find an entry with the title “MFRC522 by GithubCommunity”. If you cannot find such an entry, I recommend to visit the official website of the library for further assistance. In order to get the RFID reader running, you have to setup the library itself, a SPI connection, as well as the reader. Luckily, the library offers two very handy convenience functions for reading tags: The first functions allows to detect whether an RFID tag/card is present. The second function reads the RFID tag id. In the following code, a for-loop is used to iterate through the tag. In each iteration, a single byte is read and printed out as hexadecimal value (00..FF). Such an mechanism can be used to identify users, when each user owns a different RFID tag.

// (c) Michael Schoeffler 2014, http://www.mschoeffler.de

#include &lt;SPI.h&gt; // SPI library 
#include &lt;MFRC522.h&gt; // RFID library (https://github.com/miguelbalboa/rfid)

const int pinRST = 9;
const int pinSDA = 10;

MFRC522 mfrc522(pinSDA, pinRST); // Set up mfrc522 on the Arduino

void setup() {
  SPI.begin(); // open SPI connection
  mfrc522.PCD_Init(); // Initialize Proximity Coupling Device (PCD)
  Serial.begin(9600); // open serial connection 
}

void loop() {
  if (mfrc522.PICC_IsNewCardPresent()) { // (true, if RFID tag/card is present ) PICC = Proximity Integrated Circuit Card
    if(mfrc522.PICC_ReadCardSerial()) { // true, if RFID tag/card was read
      Serial.print("RFID TAG ID:"); 
      for (byte i = 0; i &lt; mfrc522.uid.size; ++i) { // read id (in parts)
        Serial.print(mfrc522.uid.uidByte[i], HEX); // print id as hex values
        Serial.print(" "); // add space between hex blocks to increase readability
      }
      Serial.println(); // Print out of id is complete. 
    }
  }
}

If the code has been successfully uploaded to the Arduino and an RFID card or tag is in close-range to the RFID reader, the output on the Serial Monitor (Tools->Serial Monitor, Ctrl+Shift+M) should look like this (picture shows position of the RFID card as well as the corresponding serial monitor output):

RFID reader is reading the ID of an RFID card. In addition, the serial monitor output of the program is shown.

Video Tutorial:

____________________

How to build an optical/light barrier with the Arduino, the Keyes laser module (KY-008) and a laser receiver/detector module

Light barrier built with the Arduino, a laser module, and a laser detector module.

In this tutorial, it shown how to build an optical barrier. The barrier detects any movement between the sender and the receiver. The sender is a laser module (Keyes KY-008) that emits red light (wavelength: 650nm). The laser detector/receiver is an unnamed module that returns either a LOW signal or a HIGH signal (no “analog values” in between).

List of materials:

– Arduino Uno [Search on Amazon.com | Amazon.de | Amazon.co.uk]
– Jumper wires (female/male) [Search on Amazon.com | Amazon.de | Amazon.co.uk]
– KY-008 red laser module [Search on Amazon.com | Amazon.de | Amazon.co.uk]
– Unnamed laser detector/receiver [Search on Amazon.com | Amazon.de | Amazon.co.uk]

Schematic of a laser barrier.

How to connect the laser module and laser detector to the Arduino?


The laser module has three pins. Only two pins are used: The “-” pin is connected to one of the Arduino’s GND pins. The “S” pin of the laser module is connected to the Arduino’s pin “2”. Therby, the laser can be switched off or on by sending either a LOW signal or a HIGH signal. The detector module has also three pins. The module’s “VCC” pin is connected to the Arduino’s “5V” pin and the GND of the module is connected to the Arduino’s GND. Lastly, the signal pin”OUT” of the module is connected to pin “3”.

How to program the light/optical barrier?
First, the pin values for the laser and the receiver are initialized. Next, the laser pin is set to OUTPUT mode and the receiver pin is set to INPUT mode. Then, the laser is switched on by setting “pinLaser” to HIGH. In order to monitor the light barrier’s state, a serial connection is started.
In the loop function, the value of the receiver is read. The retrieved value can either be LOW or HIGH. LOW means that the laser does not reach the detector, e.g., something went through the light barrier and is located between the laser and the detector. Then, the value of the detector is written to the console. Finally, a delay of 1000ms is added for convenience purposes (serial monitor is not “flashing” the values).

// (c) Michael Schoeffler 2014, http://www.mschoeffler.de

const int pinLaser = 2; // output signal pin of laser module/laser pointer
const int pinReceiver = 3; // input signal pin of receiver/detector (the used module does only return a digital state)


void setup() {
  pinMode(pinLaser, OUTPUT); // set the laser pin to output mode
  pinMode(pinReceiver, INPUT); // set the laser pin to output mode
  digitalWrite(pinLaser, HIGH); // emit red laser
  Serial.begin(9600); // Setup serial connection for print out to console
}

void loop() {
  int value = digitalRead(pinReceiver); // receiver/detector send either LOW or HIGH (no analog values!)
  Serial.println(value);  // send value to console
  delay(1000); // wait for 1000ms
}

If the code has been successfully uploaded to the Arduino, the output on the Serial Monitor (Tools->Serial Monitor, Ctrl+Shift+M) should look like this:

Serial monitor output of the light barrier example. If something is inside the light barrier, “0” is printed out to the monitor. Otherwise, if the red laser light points to the detecctor, “1” is printed out.

Remarks:
The detector’s LED, which is located next to the detector, indicates whether the detector is connected to a power supply.

Video Tutorial:

____________________

How to blink an LED using an Arduino Uno

An Arduino (Uno) can be used to blink an LED. In this tutorial, an LED is controlled which changes its light status every 1000ms.

List of materials:
– Arduino Uno [Search on Amazon.com | Amazon.de | Amazon.co.uk]
– Jumper wires (female/male) [Search on Amazon.com | Amazon.de | Amazon.co.uk]
– Breadboard [Search on Amazon.com | Amazon.de | Amazon.co.uk]
– LED [Search on Amazon.com | Amazon.de | Amazon.co.uk]
– resistor [Search on Amazon.com | Amazon.de | Amazon.co.uk]

Picture of how to connect an Arduino Uno to an LED.

LEDs have a forward voltage [V] and a forward current [mA]. Typically, the numbers of these two values can be found in the spec of the LED type. The LED used in this tutorial has a forward voltage of 2.2V and a forward current of 30mA. As the Arduino delivers 5V, 2.8V (5V-2.2V) have to be absorbed by a resistor. According to Ohm’s Law R=V/I, a resistor with 93.3 ohms (2.8V/0.03A)  is needed. Since one typically does not have an resistor with exactly 93.3 ohms, the next “higher” one is used. Therefore, a 150 ohms resistor is used in this tutorial. If the forward voltage/current is not known, the use of a 1k ohms resistor is safe in most cases.

How to connect the LED to the Arduino?

Scheme of how to connect an Arduino Uno to an LED.

The Arduino’s GND pin is connected to the LED’s cathode (usually the short leg). One of the resistor’s pins is connected to the LED’s anode (long leg). The other pin of the resistor is connected to the Arduino’s pin “2”. As current flows only in one direction through the LED, the LED can not be connected the other way around. Resistors can be connected the other way around. Moreover, it does not matter whether the resistor is wired between GND and LED’s cathode or between pin “2” and LED’s anode.

How to program a blinking LED?
First, a variable is defined which stores the information that the LED is controlled with pin “2” (outLED). In addition, another variable is needed, which represents the LED’s state. As the state will be toggled (on, off, on, off,…), the variable is named “toggle”. In the setup function, pin “2” is set to output mode. In the loop function, toggle is inverted by use of the “!”-operator. The “!” is very helpful to describe a blinking state in one line of code. Next, the state stored in “toggle” is written to pin “2”. Finally, a delay of 1000ms is added in order to be able to perceive the blinking effect.

// (c) Michael Schoeffler 2014, http://www.mschoeffler.de

const int outLED = 2; // output pin for LED
boolean toggle = LOW; // variable that is used to store the pin's state (switched on/switched off)

void setup() {
  pinMode(outLED, OUTPUT); // set the LED pin to output mode
}

void loop() {
  toggle = !toggle; // change the state of the LED. If the state represents LOW, then change state to a HIGH value (done by "!" operator) and the outher way around.
  digitalWrite(outLED, toggle); // write state variable to LED pin
  delay(1000); // wait for 1000ms in order to achieve a blinking LED effect
}


Video Tutorial

_________________________

How to use an analog joystick (KY-023) with an Arduino Uno

KY-023 Analog Joystick.

The KY-023 (or KY-23) is an easy-to-use analog joysticks for the Arduino microcontroller. The joysticks features two dimensions (x and y axis) as well as a state that is set when the joystick is pressed. In this tutorial, it is shown how to connect the KY-023 joystick with the Arduino and how to use it.

List of materials:
– Arduino Uno [Search on Amazon.com | Amazon.de | Amazon.co.uk]
– Jumper wires (female/male) [Search on Amazon.com | Amazon.de | Amazon.co.uk]
– KY-023 analog joystick [Search on Amazon.com | Amazon.de | Amazon.co.uk]

Typically, the KY-023 comes as a module with 5 male pins:

  • GND (Ground Pin)
  • +5V (5V Pin)
  • VRX (voltage proportional to x-axis)
  • VRY (voltage proportional to y-axis)
  • SW (joystick pressed PIN)

How to connect the KY-023 to the Arduino?
Connecting the KY-023 to the Arduino is very straight forward. The module’s “GND” has to be connected to the Arduino’s “GND”. As the KY-023 work also 5 Volt, the module’s “+5V” has to be connected to one of the Arduino’s “5V” pins.
The joystick is basically a combination of two potentiometers. This means, when the joystick is moved along the x-axis the resistance changes resulting also in a change of voltage. The voltage can be used to detect the x-position of the joystick by connecting the VRX Pin to an analog input of the Arduino. The same applies for the y-axis. The y-axis’ position can be read by connecting VRY to an analog input. In this tutorial, VRX is connected to “A0” and VRY is connected to “A1”. Lastly, SW is connected to the Arduino’s digital pin “2”.

Picture of how to connect KY-023 to Arduino Uno.

Scheme of how to connect KY-023 to Arduino Uno.

How to program the KY-023 with the Arduino IDE?
The source code is fairly simple. First, we will setup the two analog pins A0 and A1 and the digital pin “2” to detect whether the joystick is pressed. Next, we setup the serial connection which is utilize to print out the current state of the analog joystick on the console.

Then, we read the analog data of the x- and y-axis. Thereby, the analog voltage of the potentiometers is mapped to a digital value between 0 and 1023. If the button is set up as shown in the upper picture/scheme, then moving the joystick to the left will result in an x value of 0. If the button is moved to the right, the x value will be 1023. If the joystick is moved to the top/north, then the y value will be 0. If the joystick is moved down, the y value will be 1023.

The pin mode of the button (for detecting whether the joystick is pressed) uses a pull-up resistor. The result is that the value of the pin will be 0 if the button is pressed. Therefore, the variable name “notPressed” is used in the source code.

// (c) Michael Schoeffler 2014, http://www.mschoeffler.de

const int inX = A0; // analog input for x-axis
const int inY = A1; // analog input for y-axis
const int inPressed = 2; // input for detecting whether the joystick/button is pressed

int xValue = 0; // variable to store x value
int yValue = 0; // variable to store y value
int notPressed = 0; // variable to store the button's state => 1 if not pressed

void setup() {

  pinMode(inX, INPUT); // setup x input
  pinMode(inY, INPUT); // setup y input
  pinMode(inPressed, INPUT_PULLUP); // we use a pullup-resistor for the button functionality
  
  Serial.begin(9600); // Setup serial connection for print out to console
}

void loop() {
  xValue = analogRead(inX); // reading x value [range 0 -> 1023]
  yValue = analogRead(inY); // reading y value [range 0 -> 1023]
  notPressed = digitalRead(inPressed); // reading button state: 1 = not pressed, 0 = pressed

  // print out values
  Serial.print("X: ");
  Serial.println(xValue);
  Serial.print("Y: ");
  Serial.println(yValue);
  Serial.print("Not pressed: ");
  Serial.println(notPressed);

  // The following delay of 1000ms is only for debugging reasons (it's easier to follow the values on the serial monitor)
  delay(1000); // Probably not needed for most applications
}

If the code has been successfully uploaded to the Arduino, the output on the Serial Monitor (Tools->Serial Monitor, Ctrl+Shift+M) should look like this:

Video Tutorial:

_______________

On the validity of virtual reality-based auditory experiments: a case study about ratings of the overall listening experience

It has been a little more than a year that my former colleagues and I published a paper in Springer’s Virtual Reality journal. Unfortunately, the paper is not accessible for free. Fortunately,  Springer allows to publish the submitted manuscript after a 12-month embargo (“self-archiving policy”). Therefore, I decided to publish the paper also on my private website.

The paper is about an experiment in which virtual reality environments are compared to “real-world” environments. For the graphics in the VR environment, we used OGRE as graphics engine and the Oculus Rift (Development Kit – second revision) as output device. A lot of effort was put in the auditory part of the virtual reality environments.

Title: On the validity of virtual reality-based auditory experiments: a case study about ratings of the overall listening experience
Authors: Michael Schoeffler, Jan Lukas Gernert, Maximilian Neumayer, Susanne Westphal and Jürgen Herre
Abstract: In recent years, new developments have led to an increasing number of virtual reality (VR)-based experiments, but little is known about their validity compared to real-world experiments. To this end, an experiment was carried out which compares responses given in a real-world environment to responses given in a VR environment. In the experiment, thirty participants rated the overall listening experience of music excerpts while sitting in a cinema and a listening booth being in a real-world environment and in a VR environment. In addition, the VR system that was used to carry out the sessions in the VR environment is presented in detail. Results indicate that there are only minor statistically significant differences between the two environments when the overall listening experience is rated. Furthermore, in the real-world environment, the ratings given in the listening booth were slightly higher than in the cinema.
PDF Download Link

Slides: “On the validity of virtual reality-based auditory experiments: a case study about ratings of the overall listening experience”, LRZ Munich

A few months ago, I gave a general talk about creating Virtual Reality (VR) environments at the Leibniz-Rechenzentrum in Munich. I just uploaded the slides in case someone else is interested in this topic. A lot of slides focus on how to create auditory stimuli for VR environments. Furthermore, I presented also some results about a study which has been carried out to investigate the differences between “real world” experiments and VR experiments in the context of auditory experiments.
Link to slides: schoeffler_lrz_munich_2015 (AudioLabs Mirror)

In addition to the slides, my students, my supervisor, and I published a Journal Paper that describes the study in more detail (Link to Springer VR).

Web Development with Java in 2015 – A Review

Some months ago, I started to completely redesign one of my web applications. My personal goal was to refresh my knowledge of designing and programming web applications with Java. The web application I started to redesign is isbn-search.co.uk (German version: isbn-buchsuche.de) which is a search engine for books. To put it simple: visitors can lookup information about a book by entering an ISBN (International Standard Book Number).

I finished the first major release version more than seven years ago. It was written in PHP and used a MySQL database which contained all the book data.
About two years ago, I finished the second major release version which was written in Java. The design and user interface stayed more or less the same. The purpose of the second version was to heavily simplify the architecture and source code as I wrote the first release version when I just started my studies in Computer Science and had not that much experience in designing perfect software architectures (In my defense, the first revision needed almost no maintenance and produced a very nice monthly income). 😉

Therefore, it was time for a third major revision as the majority of the visitors has started to use mobile devices to access the web application. So I started to improve the second revision of the web application. I had two (non-personal) goals: First, to further improve the architecture of the web application in order to add new features in almost no time. Second, to have a web application that looks always good even if accessed by smartphones with small displays. Furthermore, I wanted only one version of the website that supports both, mobile and desktop devices.

Based on my requirement analysis, I came up with these technologies:

Meta-modeling
The Eclipse Modeling Framework comes with a nice editor allowing to graphically design meta models. EMF uses Ecore as standard format for the meta models. Ecore is very similar to OMG’s MOF (sometimes one reads that Ecore is a subset of MOF, and sometimes one read Ecore is a de-facto reference implementation of MOF etc.).

EMF Editor

Meta-model editor of Eclipse Modeling Framework.

Designing meta-models with EMF is very easy when you have learned the ropes. The first hours with EMF might be a bit frustrating as EMF is a very comprehensive framework and one might not know where to start. However, in my opinion, the frustration is worth the gain in productivity.

Once you have the graphic representation of your meta-model, the next step is to us them to generate some source code. In EMF the source code generation is more or less just pressing a button. There are tons of options, e. g. you can choose whether you want adapter classes, interface classes etc.

Persisting
For persisting the model data, I used Hibernate. Hibernate is a well known and widely used object-relational mapping framework that maps an object-oriented domain model (like Ecore models) to a traditional relational database. If you are familiar with Hibernate, you know that you have to write annotations or mapping files in order to map your classes to tables etc. Luckily, there exists already a solution that does all the work for you: Teneo. Teneo is a so-called model-relational mapping and runtime database persistence solution that integrates EMF with Hibernate. Once Teneo is configured, it stores all your model data into a database. A big advantage of Teneo is that it is highly configurable. For example, you can decide how to solve the inheritance mapping problem.

Database Connection Handling
The more visitors a website has, the more queries are sent to its database (if it has one). If in addition some computationally intensive queries are sent, the database might be overloaded. Especially in such a scenario, a more advanced handling of the database connections is very helpful. I chose c3p0 as it allows me to perfectly configure the connection handling. For example, you can select the minimum and maximum number of connections, the maximum idle time of connections, the maximum number of statements per connection and so on. Once you are done with the configuration, you need not to care about idling database connections etc. anymore.

Java Servlets and JSF
My code contains some business logic which is implemented as Java servlets. There is nothing special to tell, the servlets get requests and send responses.
The User Interface was implemented with Java Server Faces (JSF). I did not write all the code in plain JSF, I made as much use as possible of PrimeFaces framework.

Screenshot of the website isbn-search.co.uk

A screenshot showing the responsive design of the website isbn-search.co.uk.

PrimeFaces
PrimeFaces is a component library for JSF-based web-applications. PrimeFaces features more than hundred components ranging from simple buttons to very powerful data tables. All components are mobile-friendly, which made PrimeFaces the perfect choice for my ISBN search application. The framework does not only feature components, it comes with a nice theme-roller and ajax functionality to let the user interface smoothly interact with all the objects that live in the backend (servlets, JAVA beans etc.).
Although PrimeFaces is a very comprehensive and powerful framework, getting started is not that hard. Once you know the ropes, you can easily design and implement your website.
The major disadvantage of PrimeFaces is that it is not “100% open source”. Major versions are released as “Community Downloads” free for everyone. If you rely on bugfixes or features of minor versions, you must subscribe to the so-called ELITE or PRO support options. In my case, the latest community version had all the features I needed to implement my website.

PrettyFaces
Last but not least, my project needed some SEO-friendly URLs. I chose PrettyFaces as it worked well with the other technologies I used. Using PrettyFaces is rather simple, you configure URLs by mapping files. External (SEO-friendly) URLs are mapped to the project’s internal URLs. Since I have only eight or nine different “types” of URLs, my config file has only a few lines.

In summary, it was a lot of fun the implement the website by using many “state of the art” frameworks. It is good to know that the Java ecosystem offers many options to architect, develop and deploy a website for mobile and desktop devices. Certainly, I have to admit, that not everything worked directly out of the box. Most effort went into setting up and configuring all the different libraries and integrate them into the web application. However, once this is done, the development is rather fast.

Next, I want to start a new web project using a completely different ecosystem. I’m thinking of using Python+Django since it got a lot of attention lately and becomes more and more popular among web developers.