---
# System prepended metadata

title: A tutorial on how to build a NightLamp

---

# A tutorial on how to build a NightLamp

## Introduction

### Author
 - Name: Jenny Johannesson 
 - Student Credentials: jj224ed

### Project Overview
This is a tutorial on how to build a nightlamp using a photoresistor and a ESP32 board. A photoresistor is a light sensitive resistor. This is a tutorial only for Windows and not MacOS, Linux. 

### Time To Complete
The time to complete the whole project including installing the necessary software and setting up the hardware and code would be around 3-6 hours. It depends on how much of experience you have from working with IoT or coding in general. 

## Objective
This is my first ever project with programming on hardware, I have some knowledge with software development but never tried this before. This course lets me combine software with hardware and teaches me a better understanding how IoT works. A nightlamp project fits perfectly for a beginner with little to no knowledge on how to progam with hardware because here you get a visual conformation that your code is working. 
The prupose of the lamp is pretty self explainatory but to clarify, you can use this lamp with the purpose of light up a room when it gets dark without even lifting a finger!

## Material
I bought a starter kit from amazon.se where the whole product costed around 360:- in swedish krona. 

- ESP32-Wrover x1
![](https://i.imgur.com/71XdYOd.png)
This device is programmed with Micropython. 
- GPIO Extention Board x1
![](https://i.imgur.com/gqMv3ig.png)
This board allows us to connect important parts that are needed such as jumperwires. 
- Breadboard x1
![](https://i.imgur.com/c6IQ7i1.png)
A breadboard allows you to connect your extra components needed in a more practical way and makes connection easier. 
- Photoresistor x1
![](https://i.imgur.com/2TWhjv8.png)
A photoresistor is a light sensitive resistor. It is an active component that decreases resistance when bightness (light) is received by the surface of the component. 
- Resistors:

10KΩ x1 ![](https://i.imgur.com/oXPa22l.png) 220Ω x1 ![](https://i.imgur.com/guZ2HSD.png)
A resistor is a passive electrical component that limits or regulatees the flow of current in an electronic circuit. 
- Led x1
![](https://i.imgur.com/1oiphWx.png)
A led is a type of diode, all diodes only work if current is flowing in the correct direction and have two poles.
- Jumper M/M x4
![](https://i.imgur.com/3EDZX3j.png)
A jumper wire are used so that we can write and execute our code which can be used to pass power and data.

## Computer setup


#### IDE
- Atom

#### OS
- Windows 10

#### Before you start
- Install Atom [from here](https://atom.io/packages/pymakr)
- Install pymakr [from here](https://atom.io/)
- Create an account on Ubidots [here](https://ubidots.com/)

#### Installation of packages
When you have open up Atom you navigate to the settings page: ***File > Settings*** this is where you will install the pymakr. OBS For you it will say install.
![](https://i.imgur.com/aObCDvE.png)

To publish data over MQTT, install the libraries [umqtt.robust ](https://github.com/micropython/micropython-lib/tree/master/micropython/umqtt.robust) and 
[umqtt.simpl](https://github.com/micropython/micropython-lib/tree/master/micropython/umqtt.simple)
### Setting up the project


1. To flash your board, download the file the school has provided and to this [website](https://nabucasa.github.io/esp-web-flasher/), press the connect button and choose your device. 
2. The next step is to press the erase button and wait until it is done.
![](https://i.imgur.com/FuZYMKo.png)
  
3. Once it is done you will select the first Offset and set it to 1000, and press the "choose a file" button and select the one you downloaded from school.  
4. Got to the Atom editor. When the board is connected, a message in the console will pop up saying it is connected.
5. When connected the next step is to create a new directory to manage the code and library. A suggestion is to name the new directory "NightLamp". Once you have created the directory you go up to the meny and select ***Open a project*** and search for your new directory. 
6. In the folder "NightLamp" is where we are going to manage out libraries, main and boot codes. Click on the folder and add new file and name it "***main.py***", repeat this process but name the other file to ***"boot.py"***. (See under under headline "Code" on what to write in the files you just created). 
![](https://i.imgur.com/STjcQV6.png)

7. Create a new folder to add the libraries simple and robust. A suggestion is to name the folder "libraies". Add two new files in the folder with the names "robust.py" and "simple.py". 
8. copy the code from the github repository that is linked under headline "Installation of packages".
9. Last step is to synchronize your project, this is done by going to the upper menu and select ***Packages > Pymakr > Synchronize project***.

## Putting everything together 

### Hardware
![](https://i.imgur.com/nstkCAN.jpg)

#### Breadboard right side

- Connect the photoresistor on row ***g*** pin ***40-43***
- Connect the yellow jumper on row ***f*** pin ***42***
- Connect the green jumper on row ***i*** pin ***45*** and row ***gnd*** pin ***45***
- Connect the resistor (10KΩ) on row ***j*** pin ***42*** and row ***ext 3.3V*** pin ***42*** 
- ![](https://i.imgur.com/VlJk9og.jpg)
![](https://i.imgur.com/uJrjBMZ.jpg)
#### Breadboard left side
- Connect the yellow jumper on row ***a*** pin ***12***
- Connect the blue jumper on row ***c*** to pin ***18*** (25 for the extension board) and the other end on row ***c*** pin ***34***
- Connect green on ***gnd*** pin ***39*** and on row ***a*** pin ***39***
- Connect the resistor (220Ω) on row ***b*** pin ***34-38***
- Connect the led lamp on row ***c*** pin ***38-39***
![](https://i.imgur.com/US0Gs8k.jpg)





### Platform 
The cloud based platform Ubidots was the perfect choice for this kind of project, this platform is compatible with communication for the ESP32 usbcable and the MQTT.
Another advantage for choosing Ubidots is because they offer a free version and the interface is simple and easy to learn. 
The advantage Ubidots had against other platforms were: 
- Ease of use
- The available documentation
- Free to use
### The code
The first part here is the code to have the photoresistor and the lamp to work, this part you will write in the main file you created before.

***The import Pin:*** is a class which you use to create a pin which is an object used to control I/O pins, also known as GPIO. 
***The import PWM:*** stands for Pulse width Modulation, which is a way to gen an artificial analog output in a digital pin.
***The import ADC:*** is a class that provides an interface to analog to digital convertors. 

The text after # is comments.
```
from machine import Pin,PWM,ADC
import time

pwm =PWM(Pin(25,Pin.OUT),1000)  # Creates the pwm object
adc=ADC(Pin(36))  # Creates the adc object
adc.atten(ADC.ATTN_11DB)  # Setting the amount of attenutation of the adc input
adc.width(ADC.WIDTH_10BIT) # Sets the data widht (resolution)

try:
    while True:
        adcValue=adc.read()
        pwm.duty(adcValue) # Sets the duty cycle
        print(adc.read())   # Read ADC and return read result.
        time.sleep_ms(100)
except:
    pwm.deinit() # Turns off the pwm

```
#### Ubidots code
To send data to Ubidots write this code in to the boot.py file you created before: 

```
import time

import network

import machine as machine

sta_if = network.WLAN(network.STA_IF); sta_if.active(True)

sta_if.scan() # Scan for available access points

sta_if.connect("SSID", "PASSWORD") # Connect to an AP

sta_if.isconnected()

time.sleep(3)
```

The next part is the code that will create the functions to check the internet connection and upload the data to Ubidots. OBS In order for the MQTT protocol to work it is crusial that the token is the same as in Ubidots. 
Because of privacy reasons I will not include my wifi credentials.

```from umqtt.robust import MQTTClient

token = “Your-Ubidots-token-here” 
clientID = “random-name_or_IMEI device ID” 
client = MQTTClient("clientID", "industrial.api.ubidots.com", 1883, user = token, password = "Your-password")

def checkwifi():
    while not sta_if.isconnected():
        time.sleep_ms(500)
        print(".")
        sta_if.connect()

def publish():
    while True:
       checkwifi()
       client.connect()
       time.sleep(20)
       publish()

```
After this you need to synchronize your project again. In the upper menu, select ***Packages > Pymakr > Synchronize project***.
When it has finished synchronize it will run automatically.

### Transmitting the data/connectivity
The data is sent via Mqtt protocol to the platform Ubidots and it is done so over wifi with the data being sent frequently. My esp32 is connected directly to my computer via a micro usb cable. 

### Presenting the data

![](https://i.imgur.com/djA47mE.png)

![](https://i.imgur.com/H1NFBA5.png)
- The data is being saved on Ubidots every minute
- The data consisting of <100 in value is when the flashlight is pointing towards the photoresistor. 
- The data around 300 in value is when it is in a room during the day around 17:15. 
- The value exceeding >500 is when the photoresistor have a box over it, giving the illusion of darkness. 

### Finalizing the Design
At the moment the design is far from complete and not quite as powerful as I would liked it to be. For the final design the lamp should be much bigger and should be able to light up a whole room. Over all this project was fun to do and I learned a lot during it, my expectations in the beginning was that it would be easy but it was much trickier than I thought! 
The only way to visualize and show you how the lamp lights dimps when light comes on it was to put a flashlight towards its direction. Because of the weak light of the led lamp a regular rooflamp would not have done the trick to show you the difference. 
[A link to how it looks at the moment](https://drive.google.com/drive/folders/1ANM7Chs1NyTgj2zJeValy1yHvQJUoOo6?usp=sharing)
Even though the design is not looking good at the moment I am still happy and proud of what I have made! 

