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