Thursday, May 30, 2024

Caravan/Motor-home leveler part 6 - App Inventor APP

For an idex to all my stories click this text.


This is the sixth (and last story) about my project on building a leveling tool. This was initially build as a leveling tool for caravans/mobile-homes. But I am sure you can find more purposes for this.



The above video shows how the project works. It consists of an ESP82666 with an MPU6050 gyro sensor powered from a battery. As you can see I printed my own casing for this. The hardware creates an Wifi access point. The idea is to put the hardware inside the caravan or mobile home and then you can go outside to level your setup while looking at your phone instead of constantly having to go back inside.

There are 5 previous stories in this series and I urge you to look at least at the first and second story as they describe the hardware setup and the MicroPython program for the ESP8266.

Part 1: the hardware and the files for the casing.
http://lucstechblog.blogspot.com/2024/04/caravanmotor-home-leveler-part-1.html

Part 2: the MicroPython program for the ESP8266 and MPU6050
http://lucstechblog.blogspot.com/2024/05/caravanmotor-home-leveler-part-2.html

Part 3: the javascript program to complete the project.
http://lucstechblog.blogspot.com/2024/05/caravanmotor-home-leveler-part-3.html

You could stop here but the following stories might prove interesting for you.

Part 4: testing the app on your PC instead of on your phone
http://lucstechblog.blogspot.com/2024/05/caravanmotor-home-leveler-part-4-run-on.html

Part 5: turning the javascript program into an Android App
http://lucstechblog.blogspot.com/2024/05/caravanmotor-home-leveler-part-5-build.html



Another (different) app.

The Javascript program that I turned into an app in the previous stories (story 3 and story 4) works and does the job. Nevertheless I was not totally satisfied with the result.
As stated before, I am not a graphic designer and yet I thought I could make a better looking app.

So I started working on an app made with Mit's App Inventor. And as I know that App Inventor is very popular I presume that readers of this weblog might be interested in how this app is programmed.

For those of you that have never worked with App Inventor I urge you to have a look at it. App Inventor is totally free and allows you to build Android and IOS apps in a very easy way. You can distribute the Apps with Google's Play store or download the APK file and send it to the ones you think might need it. You can find App Inventor here: https://appinventor.mit.edu/




This is how the new app looks.

The previous app, the HTML file turned into an app Part 5), takes about 10 Mb memory. The App Inventor APP uses about 12Mb memory. So it is larger but.......
The App inventor App has a custom splash screen and a custom background.

The App Inventor blocks

Just for fun I hereby give you a picture of how the blocks look. Better is to have a look at these in App Inventor itself. You can find the AIA file (source code) at the bottom of this story so you can download it into App Inventor and experiment with it.




The App inventor files

Below you can find a link to the APK file so you can download and run the program on your Android Phone. Next to that you will find the AIA file that can be loaded into App Inventor so you can have a look at how this program is build.

But next to the AIA file you will need two extra files for this App to function and those are:


The splash screen. This screen is displayed when the App starts. You can use this splash screen or make your own. My splash screen is 500 x 841 pixels which gives a good result on most phones.


The background screen.
This is the picture on which the horizontal and vertical lines are drawn just like the middle circle and the red bubble that shows the X and Y coordinates. My version is even lower in resolution: 180 x 350 pixels. Nevertheless it looks rather decent.

Download the files:

Here is the link to the necessary files for this last story in this series:

The App's icon
https://www.mediafire.com/view/h4gr0jbz7t7w7xd/caravan-ico%25282%2529.png/file

Splash screen 
https://www.mediafire.com/view/jzytzodqexyx8g8/Splash2.jpg/file

Background screen
https://www.mediafire.com/view/naof1gv16wrfwto/18ftnw2.jpg/file


App Inventor program (AIA file)
https://www.mediafire.com/file/p8zawpjy0eyvkyq/Carlevel_01_AppInvent.aia/file

The APK file
https://www.mediafire.com/file/bq9m2chnc0b1vgv/Carlevel_01_AppInvent.apk/file

The APK file is off course the new App. You can download it on your phone install it and you are ready to go (provided you build the hardware from part 1 and part 2)

That makes this series about the caravan/mobile-home leveler complete. I hope you enjoyed it and have some practical use for this project.

Till next time
have fun


Luc Volders









Friday, May 24, 2024

Caravan/Motor-home leveler part 5 - build the app

For an index to all my stories click this text

This is the fifth story in the series about building a device that aids with leveling your caravan or mobile-home. I am sure you will find other purposes for this tool to.

The previous stories in this series are important if you want to build this project yourself.

- The first story discussed building the hardware and a casing for the caravan/mobile-home leveling aid. You can find that story here: http://lucstechblog.blogspot.com/2024/04/caravanmotor-home-leveler-part-1.html
- The second story discussed the MicroPython program for the ESP8266 and how to test the setup. You can read that story here:
http://lucstechblog.blogspot.com/2024/05/caravanmotor-home-leveler-part-2.html
- The third story is about building an HTML file with Javascript that can be opened like a web-page on your mobile-phone and is the actual program that displays the data from the leveling aid. You can find that story here: http://lucstechblog.blogspot.com/2024/05/caravanmotor-home-leveler-part-3.html
- Story 4 showed how to run the software on your PC instead of on your phone. You can read that story here:
http://lucstechblog.blogspot.com/2024/05/caravanmotor-home-leveler-part-4-run-on.html

This story tells how to build a dedicated app from the HTML file. I already mentioned that you could do this in the third story. And I wrote a story some time ago about how to turn an HTML file into a dedicated app. You can read that story here if you missed it:
http://lucstechblog.blogspot.com/2024/04/turn-webpage-into-app.html

As I had some requests from readers that wanted a complete tutorial on how to turn the caravan/mobile-home leveling aid into an app I am happy to oblige. You can use this tutorial for any HTML page with Javascript that you want to turn into a dedicated app.

Description of the app

The app I am going to make is a simple app.
- It has it's own icon so you can find it between all the other icons on your phone's home screen.
- The app has a splash screen. That is a welcoming screen, shown when you start the app.
- After clicking the splash screen the app starts.
- The app gets the data from the ESP8266 and displays it graphically. This is just the Javascript program inside the HTML file.
- The app has an Exit button at the top-right side of the screen that, obviously, exitst the app.

This app is for Android Phones. The Webintoapp service we are going to use offers a possibility for building an app for Apple Phones. Due to the extreme price tags of Apple Phones I do not (want not) own an Apple Phone. Next to that the Webintoapp service charges a sum for building the Apple App while the Android app is free !!!

Download the Javascript file to your computer.

First step is to download the HTML file with the Javascript program to your computer. You can use the download link provided here.

https://app.mediafire.com/jpswchudmlwu5

This link directs your browser to the directory on Mediafire where you can find all files for this project.



There are 2 files we need for building the app:
- caravan-ico.png
- caravan-level.html

The other files are of course necesary for the other stories in this series.

Make a zip file from the html file.

Webinto app needs the HTML file to have a special name. That name is index.html so start with renaming the caravan-level.html file into index.html.
There are loads of programs that run under Windows or Linux that can create a zip file from any files you throw at it.



If you do not have such a program at hand you can use a webservice. I used compress2go.com You can find it here: https://www.compress2go.com/create-zip-file

Just drag the HTML file from your disk to the orange field on the screen and then press the start button at the bottom. After a few moments a new screen opens on which you can download the zip file.


The icon

You can use the caravan-ico.jpg for which I just provided the download link.



You can of course design your own icon. I made mine in The Gimp and it has a resolution of 512 x 512 pixels. This is the maximum size for icons that Webintoapp accepts and gives the best results.



Webintoapp

Now we have gathered everything we need we can visit the service that makes the app.

https://www.webintoapp.com/

Copy this link and put it in your browser to visit the site.

Register or if you already have done so, log in.



As you can see I had already made some apps for previous stories on this weblog.

As we are going to make a new app choose App Maker at the top of the screen.



Standard Webintoapp is set for making a website into an app. We are going to make an HTML file into an app. So choose that option (where the red arrow points).



Then click on select zip file and upload your freshly made index.zip file that contains the index.html file and nothing else.



Fill the next fields in. So give your app a name (I chose Caravan-Leveler) and fill in your Company/Brand name. I just used my own name here.
When you are making updates to an app you can fill in the Major version and Minor version fields. Just leave them as they are at this moment.



In the adjacent column first choose set icon and then upload the caravan-ico.png icon you previously downloaded.


Then chose the colors you want for the toolbar (the top of your screen). I did not make any alterations here. But you can chose another color setting if you want. Click OK when done.

There is a Splash-screen option. Unfortunately that is only usable by Premium developers. If you need a Spalsh screen with your company logo or whatever the consider becoming a Premium developer.
The other options like Certification, Firebase and Admob I left unchanged.

Then click on the last option: Settings.



Make sure you enable JavaScript in the settings menu. Without Javascript our program will not run. Important is also that you Allow HTTP requests as our ESP8266 does not allow HTTPS requests.
And chose the Screen ON option so the app stays active.



Click on the Advanced tab and chose the apps orientation. Set this (for this app) to Portrait.


And in the last tab (Permissions) make sure that the Internet Permission is set on. Our app will not communicate over the internet but direct to the ESP8266. But this option is needed to make sure Wifi is enabled.

Then click on the OK button to save your choices.

Then go back to the right part of the screen and click on the Next button.



A screen opens with the complete overview of your settings. Check if everything is ok and then press Make App on the left-bottom side of the screen.


When the app has been made a new pop-up screen emerges. Here you can fill in some details about the app. As Category I chose Auto & Vehicles but there are many more categories to choose from.

You can also give a short description here about your app.

This information will be shown on a special home-page for this app.
You can find the URL of that homepage in the first field in this pop-up screen.

Click OK, and you're done !!!

The App's homepage.


And this is how the homepage looks.

Save it's URL so you can use it on your phone to download the app, or to send it to friends to share.
From this page you can also download the app to your computer and transfer it from the computer to your phone.


If you lost the URL to the App's homepage you can always go to the dashboard and click on the most right icon next to the App's name and Icon. There is a drop-down menu in which there is a link to the homepage.

If you are lazy, and do not want to build the app yourself, you can use my app's homepage:
https://www.webintoapp.com/store/313868


Transfer the app from your PC to your Phone

There is an easy way to transfer the APK file from your PC to your phone. In fact there are several ways to do that.

- Drive
If you use Google Drive you can upload the App to that service and download it on your phone.

- Telegram
If you use Telegram on your Phone you can use the Telegram web-app and transfer the file from the web-app to your phone. I have demonstrated how to do that in this story on this web-log:

http://lucstechblog.blogspot.com/2023/03/file-transfer-with-telegram.html



Installing the App

If you downloaded the App on your phone with a web-browser from the app's home-page. The APK file will be in the download folder and called app-release. Just click on it and give permission to install it. And again: for lazy people that not build the app themselves can download it from my app's download page: https://www.webintoapp.com/store/313868

If you downloaded the app from Telegram you need to point your file manager to the Telegram folder/directory on your phone. There you will find the APK file with the name app-release. Click on it and give permission to install the App.

That's the complete story.
I hope this project helps you in any way.

Till next time
Have fun


Luc Volders









Thursday, May 16, 2024

Caravan/Motor-home leveler part 4 - Run on your PC

For an index to all my stories click this text

As a reaction to my previous stories on the caravan/mobile-home leveler I received mail from a few readers that wanted to know if they could test the caravan/mobile-home leveler on a PC.


The previous stories on this project showed how to install the software on your mobile phone. Installing it on your PC for testing at home is actually easy to do.

The MicroPython program for the ESP8266

First thing to do is to adapt the program for the ESP8266.
In the project the program creates an access point. For using it at home you need to start the program as a wifi device.

To adapt the program, connect the ESP8266 to your computer with an USB cable and start Thonny to Edit the program.

MAKE SURE TO REMOVE THE BATTERIES BEFORE CONNECTING THE ESP8266 TO YOUR COMPUTER. NEVER USE BATTERIES AND THE USB CONNECTION AT THE SAME TIME AS THAT MIGHT DAMAGE YOUR ESP8266 OR EVEN WORSE: DAMAGE YOUR COMPUTER BEYOND REPAIR.

I will give here the part of the original program we need to change. It looks like this

'''
Caravan and Mobile Home leveling aid
http://lucstechblog.blogspot.com/

Version with http server
The x and y values are rounded
ESP is configured as Access Point
'''

from machine import Pin, I2C
import utime
import math
from lucsmpulib import init_mpu, get_data

import socket
import network

ssid = 'Caravan-Leveler'
password = '123456789'

ap = network.WLAN(network.AP_IF)
ap.active(True)
ap.config(essid=ssid, password=password)

while ap.active() == False:
  pass

print('Connection successful')
print(ap.ifconfig())

i2c = I2C(scl=Pin(5), sda=Pin(4), freq=400000) # esp8266
init_mpu(i2c)

 

This is the part where the libraries are imported and the Accesspoint is activated. Replace this part with the following code:

'''
Version with http server
version where the x and y values are rounded
ESP is station
'''

from machine import Pin, I2C
import utime
import math
from lucsmpulib import init_mpu, get_data

import socket
import network

ssid = "YOUR-ROUTERS-NAME"
pw = "PASSWORD"

print("Connecting to wifi...")

# wifi connection
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect(ssid, pw)
print('Waiting for connection.',end="")
while wifi.isconnected() == False:
    utime.sleep(1)
    print('', end='.')
print("")

ip = wifi.ifconfig()[0]

print("Connected with IP adress : "+ip)

i2c = I2C(scl=Pin(5), sda=Pin(4), freq=400000) # esp8266
init_mpu6050(i2c)


And this is what you should replace it with. The program now acts as a standard wifi device (station), makes contact with your browser, and gets an IP address. The reswt of the program stays the same.

Make sure that you replace YOUR-ROUTERS-NAME and PASSWORD with your routers credentials.



You need to run the adapted program with a USB connection to your computer as we need to get the IP address the ESP8266 has gotten from your router. Your's will of course be different.

And now we have the IP address.

The Javascript program.

The Javascript program is more than 300 lines long.
Use a text editor like notepad to load the program. An HTML file is just a plain ASCII text.
Use the search function in the editor to find this line:

fetch(`http://192.168.4.1`).then(function(response) {

Replace the IP address 192.168.4.1 with the address Thonny showed. In my example it should look like this:

fetch(`http://192.168.178.231`).then(function(response) {

Then save the file with exact the same name in a directory on your PC.
Open that directory and click on the HTML file.



And here is the caravan/mobile-home leveler running in my browsers screen on my PC.

Clicking anywhere in the screen with your mouse will open the program full-screen. Clicking the red exit button in the top-right corner makes the screen smaller again. You can resize it to any size you like and the program will adjust automatically.

Several parts of the program were taken from my book on Javascript: Javascript tips. This book does not teach how to program in Javascript but gives more than 500 tips that can make programming in Javascript a lot easier.


Click this line (or the book) to find the book on Amazon.

That's it for now
Have fun

Luc Volders





Friday, May 10, 2024

Caravan/Motor-home leveler part 3 - Software for your mobile

For an index to all my stories click this text.

This is the third part of my project on building a caravan/mobile-home leveling aid.

The video shows how this device works. You put the box on the table or floor of your caravan/mobile-home and outside you can level the caravan by looking at the screen of your phone/tablet. The devices are connected by Wifi. No need to walk back and forth to see if your camper is level.

The first story in this series showed how to build the hardware. You can read that here:
http://lucstechblog.blogspot.com/2024/04/caravanmotor-home-leveler-part-1.html

The second story discussed the MicroPython program for the ESP8266 and the MPU6050. You can find that story here:
http://lucstechblog.blogspot.com/2024/05/caravanmotor-home-leveler-part-2.html

This story tells how to build the program for your mobile phone.

The structure of the (Javascript) program

The program is written as a web page with Javascript.
This makes it very small (about 7k) and portable. It will work on a computers screen, a tablet and on your phone.

There are some tricks in the program.

- It will automatically adjust to the width and height of your screen.
- If you resize your screen (on a notebook) it will adjust automatically
- There is a text that is made visible on the screen and then disappear
- Clicking the window/screen resizes it to full screen
- Received data from the ESP8266 is text the program converts it into a floating point number
- The floating point number is converted to an integer value
- The horizontal and vertical lines are made with CSS
- The centre circle and the bubble are created in CSS

The program itself is fairly complicated and more than 300 lines of code. And to tell the thruth: I was fairly proud of myself when I got it all working.

- It starts with CSS code to draw the lines, the centre circle and the red bubble.
- Every second it fetches the x and y values from the ESP8266
- These values are put at the bottom of the screen
- It tests if the values are positive or negative so it knows where to position the bubble
- The x value is then converted to the position on the half of the screen height.
- The width of the bubble is halved and with the converted x value determines the place of the bubble on the length axis.
- The y value is converted to the position on the half of the screen width.
- The height of the bubble is halved and together with the converted y value determines the location of the bubble on the width axis

As stated the program is an HTML file. So it is a website with Javascript that fetches the data from your ESP8266 and displays that graphically.
This means that there is no quit button. To stop the program you will have to close your browser.

Click here to locate the book on Amazon

The code uses some neat tricks that come from my book Javascript tips. That book is not a tutorial about programming in Javascript but just a book chock-full of tips and tricks that show how to get things done in Javascript.

The program.

Like said above the program consists of more than 300 lines of CSS, HTML and Javascript code. So it is far to large to discuss here in detail.
I also do not want to publish it here as that would make this page too bulky. Therefore I herebye give you two options to download the code.



Point your QR-code reader program here and you will get a link to the download location.

https://www.mediafire.com/file/7q2vlg55gs0ctk5/caravan-level.html/file

This is the download link. Click this link and you will be directed to the download location. You can also copy this link and then open it in your browser to visit the download location.

Click the light-blue part where it says caravan-level-html



At the bottom of your screen a message will appear and click on the Download button.

After a very short time a new message will appear telling that the file has been downloaded and that you can open it. Don't do that at.



With your file manager on your phone open the downloads folder. And there is the file caravan-level.html
Click that file.



The file has (of course) the name caravan-level.html

The file is now permanent on your phone/tablet.
So when on the camping site just go to the phones settings. Select the wifi settings and connect to the caravan-leveler accesspoint.

The previous story in this series showed how you can connect to the hardware device with an Android phone. The procedure for a tablet is of course likewise. On a notebook you will need to find the Caravan-Leveler accesspoint and then connect to it's IP address with your browser. I presume the procedure for an Apple notebook/Ipad or Iphone is likewise but unfortunately I do not own these devises so I can not test that.
Please read that story so you know how the procedure works. You can find it here:
http://lucstechblog.blogspot.com/2024/05/caravanmotor-home-leveler-part-2.html

Then open the file manager, go to the downloads folder and click the caravan-level.html file.

And there it is. And the caravan is on a steep slope in this picture !!!

All files for this project (until now)

https://app.mediafire.com/jpswchudmlwu5

This link is useful on your PC as it directs you to the folder on Mediafire where you can download all files for this project: the hardware schematic, the STL files for the case, the MicroPython file for the ESP8266 and the HTML file.

That is all.

Well just one more thing.
On this weblog I discussed a nice web-service that allows you to turn a web-page into an app. Just search this weblog and you will find it.

Till next time.
Have fun


Luc Volders












Friday, May 3, 2024

Caravan/motor-home leveler part 2 (MicroPython software)

For an index to all my stories click this text

This is the second story about building a caravan/motorhome leveling aid. This story focusses on the software for the ESP8266. 

Short intro:
I am going to show how to build an electronic device that you can put on your motorhome/caravan's table. And then that device sends it data to an app on your phone. So you can go outside and look at your phone's screen while leveling your caravan/motorhome !!




The above video demonstrates how the device works. It is not connected to an USB powersupply as it is powered by batteries. And the hardware communicates wiressly with the phone.

The previous story showed how to build te hardware and casing for this project. You really need that setup to continue. Here is a link to that story:
http://lucstechblog.blogspot.com/2024/04/caravanmotor-home-leveler-part-1.html

Programming the ESP8266 is done with Thonny as the program is written in MicroPython.

If you want to know more about Thonny and programming in MicroPython please consider buying one of my books listed at the bottom of this page. These books focus on the Raspberry Pi Pico and Pico W (the wifi version) but most of the programs and details also work on the ESP8266 and ESP32 after altering the pin numbers.

Considerations.

In a previous story on this weblog I demonstrated how to get human readable data: plain angles in degrees from an MPU6050. That program is usefull for starting several projects. But that framework displays it's data in Thonny's shell. You can find that story here:
http://lucstechblog.blogspot.com/2024/04/mpu6050-data-in-degrees-instead-of.html

That is of no use for this project. We want to see the angles in a simple manner on our Phone's screen. So the program needs to send it's data over wifi.
The caravan/mobilehome leveling aid is build for campers that are installing their caravan/mobile home on a camping site or in the free nature. The problem that occurs in such situations is that is most of the time no wifi is available.
So the software needs to start as a Access Point (AP) so your phone can contact it.

The other thing to consider is that the information that the ESP8266 is going to send over Wifi must be accessible on your phone. So it must be send in a form that we can pick up by a program for Android.

Both issues are taken care off in the next program.

The MPU6050 Library

Using the MPU6050 in a MicroPython program requires a library.
A MicroPython library is actually just a MicroPython program that simplifies a certain problem. In this case the problem is the communication with the MPU6050.

For your convenience I hereby give the library as discussed before:

'''
Luc Volders library for MPU6050
'''

from machine import Pin, I2C
import time
 
def init_mpu(i2c, address=0x68):
    i2c.writeto_mem(address, 0x6B, b'\x00')
    time.sleep_ms(100)
    i2c.writeto_mem(address, 0x19, b'\x07')
    i2c.writeto_mem(address, 0x1B, b'\x00')
    i2c.writeto_mem(address, 0x1B, b'\x00')
    i2c.writeto_mem(address, 0x1C, b'\x00')
 
def read_data(i2c, addr, address=0x68):
    high = i2c.readfrom_mem(address, addr, 1)[0]
    low = i2c.readfrom_mem(address, addr + 1, 1)[0]
    value = high << 8 | low
    if value > 32768:
        value = value - 65536
    return value
 
def get_data(i2c):
    readx = read_data(i2c, 0x3B) / 16384.0
    ready = read_data(i2c, 0x3B + 2) / 16384.0
    readz = read_data(i2c, 0x3B + 4) / 16384.0
    
    return readx, ready, readz


Copy this program and paste it in a new empty tab in Thonny's editor. Then save it to your ESP8266's memory into the lib folder. Use the name lucsmpulib.py

If you have any problems with this please refer to the story about the MPU6050 which you can read here: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx


The MicroPython program

And here is the program that makes the magic happen.

'''
Caravan and Mobile Home leveling aid
http://lucstechblog.blogspot.com/

Version with http server
The x and y values are rounded
ESP is configured as Access Point
'''

from machine import Pin, I2C
import utime
import math
from lucsmpulib import init_mpu, get_data

import socket
import network

ssid = 'Caravan-Leveler'
password = '123456789'

ap = network.WLAN(network.AP_IF)
ap.active(True)
ap.config(essid=ssid, password=password)

while ap.active() == False:
  pass

print('Connection successful')
print(ap.ifconfig())

i2c = I2C(scl=Pin(5), sda=Pin(4), freq=400000) # esp8266
init_mpu(i2c)

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 80))
s.listen(5)


def webpage():
    readx, ready, readz = get_data(i2c)
 
    x = math.atan2(ready, math.sqrt(readx * readx + readz * readz)) * 180 / math.pi
    y = math.atan2(-readx, math.sqrt(ready * ready + readz * readz)) * 180 / math.pi
    z = math.atan2(readz, math.sqrt(readx * readx + ready * ready)) * 180 / math.pi
    
    print("=======================================================")
    
    print(1, x)   # Tilt angles X-axis
    print(2, y)   # Tilt angles Y-axis
    if (x <= 0):
        x = math.floor(x)
    else:
        x = math.ceil(x)
    if (y <= 0):
        y = math.floor(y)
    else:
        y = math.ceil(y)
        
    html = ""
    html = html + '<!DOCTYPE html>'
    html = html + '<html>'
    html = html + 'Hi, this is the Pico'
    html = html + '<br>'
    html = html + '===================='
    html = html + '<br>'
    html = html + 'X = ' + str(x)
    html = html + '<br>'
    html = html + 'Y = ' + str(y)
    html = html + '<br>'
    html = html + '</html>'
    return (html)

while True:
  conn, addr = s.accept()
  print('Got a connection from %s' % str(addr))
  request = conn.recv(1024)
  print('Content = %s' % str(request))
  conn.send('HTTP/1.1 200 OK\n')
  conn.send('Access-Control-Allow-Origin: *\n')
  conn.send('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS\n')
  conn.send('Access-Control-Allow-Headers: Content-Type\n')
  conn.send('Content-Type: text/html\n')
  conn.send('\n')
  response = webpage()
  conn.send(response)
  conn.close()


Let's get into some details:

from machine import Pin, I2C
import utime
import math
from lucsmpulib import init_mpu, get_data

import socket
import network


These lines import the necessary libraries. Quite a lot. All the libraries (except lucsmpulib) are included in the standard installation of MicroPython. The only extra library is lucsmpulib which you can install as discussed above.

ssid = 'Caravan-Leveler'
password = '123456789'

ap = network.WLAN(network.AP_IF)
ap.active(True)
ap.config(essid=ssid, password=password)

while ap.active() == False:
  pass

print('Connection successful')
print(ap.ifconfig())


This is where the access point is created. The name of the access point (which you can find in the wifi section in your phone) is Caravan-Leveler and it's password is 123456789. You can change the name and password to your own liking but make sure to use something that is easy to remember.

i2c = I2C(scl=Pin(5), sda=Pin(4), freq=400000) # esp8266
init_mpu(i2c)


The i2c connection to the MPU6050 is activated, with the pins where the MPU6050 is connected to the ESP8266.

def webpage():
    readx, ready, readz = get_data(i2c)
 
    x = math.atan2(ready, math.sqrt(readx * readx + readz * readz)) * 180 / math.pi
    y = math.atan2(-readx, math.sqrt(ready * ready + readz * readz)) * 180 / math.pi
    z = math.atan2(readz, math.sqrt(readx * readx + ready * ready)) * 180 / math.pi

A function is created that builds the webpage that is going to be send to your phone or tablet.
The function starts with getting the raw x,y and z data from the MPU6050 and then uses some complicated math to recalculate this into human readable x,y and z degrees. We are not going to use the z value though.

print("=======================================================")
    
    print(1, x)   # Tilt angles X-axis
    print(2, y)   # Tilt angles Y-axis
    if (x <= 0):
        x = math.floor(x)
    else:
        x = math.ceil(x)
    if (y <= 0):
        y = math.floor(y)
    else:
        y = math.ceil(y) 

For our convenience and only for testing purposes the calculated values are printed in Thonny's shell. Please be aware that this only works when the ESP is connected to your computer through USB. In the real world you will have the ESP powered by the batteries and then there is no connection to your computer.

SAFETY WARNING:
Do not connect the ESP8266 to your computer with an USB cable while the batteries are placed. This might damage the ESP8266 or even damage your computer beyond repair. Use the batteries or the USB connection. I accept no responsibility for any damage done by not following these rules.


    html = ""
    html = html + '<!DOCTYPE html>'
    html = html + '<html>'
    html = html + 'Hi, this is the Pico'
    html = html + '<br>'
    html = html + '===================='
    html = html + '<br>'
    html = html + 'X = ' + str(x)
    html = html + '<br>'
    html = html + 'Y = ' + str(y)
    html = html + '<br>'
    html = html + '</html>'
    return (html)

These are the lines that build the actual webpage. Do not alter anything of these lines or the program on your phone (which is to follow) might not work.

while True:
  conn, addr = s.accept()
  print('Got a connection from %s' % str(addr))

The endless loop constan looks if some device is asking for a connection. If that is so a message is printed in Thonny's shell. Again: this is only for debugging purposes and not functioning in a real world environment.

  request = conn.recv(1024)
  print('Content = %s' % str(request))
  conn.send('HTTP/1.1 200 OK\n')

The connection is accepted and a confirmation is send to the phone/tablet that wants access.

  conn.send('Access-Control-Allow-Origin: *\n')
  conn.send('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS\n')
  conn.send('Access-Control-Allow-Headers: Content-Type\n')
  conn.send('Content-Type: text/html\n')
  conn.send('\n')

This is very important. These lines are a safety measure from webservices. These lines assure that an external device (your phone/tablet) can get access to the data on this ESP. If these lines are omitted your phone's connection to the ESP will be rejected. This was covered on a previous story here on this weblog which you can find here: http://lucstechblog.blogspot.com/2024/03/solving-cors-error-in-micropython.html

  response = webpage()
  conn.send(response)
  conn.close()

The last step is to send the webpage and close the connection.

That's the complete software for the ESP8266 caravan/mobilehome leveling tool.

First test.

Let's see if this functions like we intended.

First step is to open your wifi settings on your phone.


In the Wifi settings there might be a listing of several access points in the environment. At your actual campsite I doubt there are so many as seen here. Look for the access point with the name Caravan-Leveler. Click on that to activate the connection.

The phone might ask for a password when you make the connection for the first time and then fill in 123456789.
If you have changed the name of the Access point and Password in the above program look for the right name and fill in your chosen password.

Then open a web-browser on your phone.
In the web-browser fill (in the search bar) in the IP address of the Access-Point.
ESP8266's always have 192.168.4.1



And here is the web-page that your browser will show.
The X and Y values will be different of course and depending on the angle your caravan-leveler is at.
As you can see in my test the X value was 32 so the leveler was tilted.

Try and play with this a bit.

Please try and play with this setup a bit. Use a set triangle (geo-driehoek in Dutch) to put your Caravan-Leveler at a certain angle and look what values the webpage shows.

Please note that every time you want a new reading you will have to refresh the webpage.

Next step.

This is fun but not very practical. Next step is a nice looking webpage with a red dot that moves over the screen showing at what angle the caravan-leveler is.
I actually made two versions of the software. One version in Javascript which you can convert into an APP for Android or use in your browser. And the other version is an APP made in APP-Inventor. But that is for next episode.

Till next time.
Have fun

Luc Volders