# IoT tutorial on how to build an controller with a joystick/ joystick controller
Nicole Tran Luu - nt222gp
This project is suitable for beginners. This report is a tutorial on how to build a simple model of joystick device. This report teaches stepwise how to set up the computer, give a brief description of the material list and necessary instruction to recreate this project. This model converts the movement from the joystick to analog signals and send it to a database platform for further use.
The estimated time to build this physical model is a maximum of 2-3 hours. The estimated time of the programming would vary, depending on previous coding experience. However, the programme is built with simple libraries and has a structure easy to follow, the estimated time for this programme is around 4 hours. Before starting to build the project it is important to read some background within electronic, IoT, Pycom etc. The estimated time for research is around 2 weeks.
## Objective
As a beginner in this field, it is significant to understand from the basis. Almost all project would need control to either turn on/off or adjust the measurement. For example, a sound detector or humidity indicator could have various conditions for diverse circumstances. Hence, this project will teach how to build a simple control and how it could send the signals from it to a platform. Afterwards, when becoming more experienced in IoT, this project could combine with other projects and develop more complex devices.
As mentioned, there is no particular purpose when developing this system or use of the data. But rather an introduction and to gain more knowledge in IoT. This project purpose is to understand how a remote is construct and how it can wireless control a device. Hence, this project will give a basic knowledge of IoT. Additionally, understand how to build different systems using these small electronic parts.
## Material
| Material |Amount| Link | Cost | Describtion |
| -------- |--------| -------- | -------- |---------|
| Lopy4 |1| [Link](https://pycom.io/product/lopy4/?gclid=CjwKCAjwrvv3BRAJEiwAhwOdM5G74PvaGVQ1_oOuXCI_8RM8d9sS9iKYl0Eyv8faUwkkercAdBY_EBoCqyUQAvD_BwE)| €34.95| An electronic circuit board that enables using MicroPython to build a device. Besides, it is a quadruple network board (WiFi, LoRa, Sigfox and Bluetooth). However, in this tutorial WiFi is used.|
|Expansion board |1| [Link](https://pycom.io/product/expansion-board-3-0/) |€16.00| Enable LoPy4 to connect to USB to the computer. |
|Breadboard |1|[Link](https://www.electrokit.com/produkt/kopplingsdack-400-anslutningar/)| 59.00kr | This component is optional. It simplifies the wiring between the sensors and the electronic board.|
|Analog joystick 2-axel |1|[Link](https://www.electrokit.com/produkt/analog-joystick-2-axel/)|29.00kr| A PS2 style joystick that enables to send signals in 2D, x- and y-axis. Additionally, it has a push-button switch.|
|Wires |10*|[Link](https://www.electrokit.com/produkt/labbsladdar-100mm-hane-hane-30-pack/)|29.70kr |To connect the joystick (or other sensors) to the Lopy4.|
*Table 1. Material list for this project. All components were bought from [Electrokit](https://www.electrokit.com/produkt/lnu-1dt305-tillampad-iot-lopy4-and-sensors-bundle/), the "LNU – 1DT305 Tillämpad IoT – LoPy4 and sensors bundle" and "Sensor Kit – 25 moduler". While links given in the material list is referred to pages to buy the components separately. Hence, this project did not require all the components included from these packages.*
**Depends on connection*
## Comupter setup
### IDE software
An IDE software is required to upload the programme to the Lopy4. For this tutorial, the software *Atom* was used and recommended (for mac). This software is free and has a simple interface which is suitable for beginners. Follow the instruction and install *Atom* from this [link](https://atom.io/). It is required to install a package named *Pymakr*, to be able to connect the Pycom devices to *Atom*. After finishing the installation, open *Atom* and go to *Settings*-->*Package* and then search for *Pymakr* and press install. See Figure 1 for reference.

*Figure 1. Show where to install the extra package*
### Flashing the Firmware
Download [Pycom Firmware Update](https://docs.pycom.io/gettingstarted/installation/firmwaretool/) and follow the instruction to update the Pycom firmware. It is essential to keep the devices updated because it could affect the performance of the system. Attn. Close *Atom* or other IDE software when doing this step, otherwise it might crash during the update.
### Start writing the code
Now, it is time to write the code. Firstly, create a project folder. Afterwards, create a new file by *cmd + N* or go to *File* and *New File*. Save the main code as *main + .py*.
A few steps are required to complete to be able to upload the code to Lopy4.
1. Update the firmware as mentioned in *Flashing the firmware*.
2. **Open** Atom. Go to *File* and *Open* (cmd + O) and go to the project folder created from above and **press** *Open* (do not mark or open the code file itself). After opening the project folder, a similar screen will appear, see Figure 2 where *Joystick* is the name of the project folder. When the folder is opened, the tree in the left side will appear and aswell in the toolbar marked with 3.

*Figure 2. The red circle marked with 1 shows the project tree. Double click the files to open them. 2. Press Pymakr to open the command window (lower window). This window is to upload and connect the Pycom device to the computer.*
3. Connect the Pycom device to the computer with the USB cable. It will now automatically connect to the IDE and WiFi. When it successfully connected, this will shows in the lower window, see Figure 3.

*Figure 3. When Lopy4 is successfully connected to Atom.*
4. Finally, press the button marked with a red circle in the Figure above to upload the code to Lopy4.
## Putting everything together
See Figure 4 for the circuit diagram without using a breadboard. As mentioned, this simple model does not require a breadboard for this project. However, it would be useful later when developing this project. For the component specification read [this](https://www.electrokit.com/uploads/productfile/41015/User_guide.pdf). In the user guide, it mentioned that the analog joystick module needs a 5V source. This expansionboard has the VNN (5V) or 3V3 (3.3V). This project uses the 3.3V and it worked fine. It is only for development setup, because it might need other resistor and a more robust model for production.

*Figure 4. The circuit diagram for this project device.*
## Platform
This project uses Pycoms' platform, Pybytes. It is a free cloud-based platform. When writing *pybytes.send_signal(a,b)* in the program, it will send a signal with value *b* to signal *a* in Pybytes. For example, *pybytes.send_signal(2,1)* will send 1 to signal 2, Up & Down. *** It uses WiFi to send the signal, with the MQTT-server. When using Pybytes, it will automatically use MQTT-server to send the signals. It is a simple platform and recommended for beginners because it has good documentation of instruction and examples.
## The code
See below for the main code.
``` python
# IoT-20 Summer course
# Author: Nicole Tran Luu
# Last edit: 200706
# Import libraries
from machine import Pin
import time
from machine import ADC
JoyXSensorPin = 'P20' # Pin for joystick left and right (analogue)
JoyYSensorPin = 'P18' # Pin for joystick up and down (analogue)
press_in = Pin('P16', mode = Pin.IN) # Pin for joystick press
adc = ADC(bits=10) # create an ADC object bits=10 means range 0-705 the lower value the more vibration detected
xpin = adc.channel(attn=ADC.ATTN_11DB, pin=JoyXSensorPin) # create an analog pin on P16; attn=ADC.ATTN_11DB measures voltage from 0.1 to 3.3v
ypin = adc.channel(attn=ADC.ATTN_11DB, pin=JoyYSensorPin) # create an analog pin on P16; attn=ADC.ATTN_11DB measures voltage from 0.1 to 3.3v
buttom = 0 # Initial case - ON
# While-loop to run this part infinite time
while(1):
val_press = press_in() # get value if high or low
val_x = xpin() # get the analog value of the x-axis
val_y = ypin() # get the analog value of the y-axis
# If statement to turn on and off the joystick controll
if val_press == 0: # If the buttom is pressed
if buttom == 0: # When the buttom is zero, ON --> OFF
print("OFF!") # Print OFF on the command window
buttom = 1 # Save the variable buttom = 1 (for when the controll is off)
else: # else... OFF --> ON
print("ON!")
buttom = 0
# If the joystick is moved in y or x-axis, send a signal to signal 1 and 2.
# Aswell, print ex. NW, SE, SW, N, E...
if buttom == 0: # When the controll is ON, then start to measure the movement
if val_y <= 0: # If the joystick is moved downward
y = "S" # Save y-variable as "S"
pybytes.send_signal(2,-1) # Send value -1 to signal 2
elif val_y >= 1000: # If the joystick is moved upward
y = "N"
pybytes.send_signal(2,1) # Send value +1 to signal 2
else: # If no movement...
y = ""
pybytes.send_signal(2,0) # Send value 0
if val_x <= 0: # Similar statement is done for the x-axis...
x = "E"
pybytes.send_signal(1,1)
elif val_x >= 1000:
x = "W"
pybytes.send_signal(1,-1)
else:
x = ""
pybytes.send_signal(1,0)
print("Direction: ", y + x) # Print the direction in the command window
time.sleep(1) # Pause one second before running the while loop again.
```
## Transmitting the data/connectivity
This device sends the data every second because it has to detect the joystick movement regularly.
This tutorial uses WiFi as the wireless protocol because it does not need more component and setups to connect to the network. While this project is beginners-, then WiFi would be most suitable for this project. For example, Lopy4 needs a LoRa antenna to be able to connect to the LoRa network.
MQTT-server works fine when sending a small package of data. Hence, this project uses MQTT as the transport protocol. It usually works fine when sending a small packet of data. In addition, Pybytes' predefined setting is to use MQTT-server.
## Presenting the Data
The table named Buttom in Figure 5, presents when the control is on and off. It has the value zero when the reading of signals is off and the value one when it is on. The *Up & Down* table and graph represent the movement in the y-direction, the signal two will get a value one when the joystick points upward and negative one when it points downward. Similarly, the data in the x-direction is stored as Left & Right table and graph. Ones the joystick sends a data to Pybytes, it will be stored to the database. Additionally, it will send the signals only if the *Button* has the value one (when it is on).

*Figure 5. Here is an example of the dashboard after sending some signals.*
## Finalizing the Project
Overall, the project performed well. See Figure 6 for the final result of this project. It was hard to decide what device I wanted to make which should be in a level suitable for me as a beginner. It was hard to connect the components because I did not know if any resistors and other components should be implemented to the system. However, I gain a lot of insight and knowledge of this field and find it very interesting. *Pybytes* is very simple and beginner-friendly. However, I would recommend to try out other platforms for a more complex project. I could experience that Pybytes has limited functions. For example, it only has three ways of performing the data which does not cover all the detail I required. Additionally, this project could combine with another project which would result in exciting projects.

*Figure 6. Final setup of the joystick controller*