i am trying to send angular data from mpu6050 (communicating with esp32-cam over I2C protocol) via websocket. But my project always crashes and stops as soon as the cilent side connects. and here are the programs about my project. I really don't know what is the cause, so can anyone guide me in the direction of solving this problem? thanks a lot.!!
// esp32-cam code
#define run_every(t) for(static uint16_t last_ ;\
(uint16_t)(uint16_t(millis())-last_) >=(t);\
last_ += (t))
#include <ArduinoWebsockets.h>
#include <WiFi.h>
#include <ESPAsyncWebServer.h>
#include "esp_camera.h"
#include <Adafruit_MPU6050.h>
#include <Adafruit_Sensor.h>
#include <Wire.h>
#define sda_ 16
#define scl_ 4
#define motor1 13
#define motor2 12
#define motor3 14
#define motor4 15
TwoWire i2c_mpu = TwoWire(0);
Adafruit_MPU6050 mpu;
const char* ssid = "Drone_"; //Enter SSID
const char* password = "esp32camera"; //Enter Password
#define MAX_LENGTH 50
#define PWDN_GPIO_NUM 32
#define RESET_GPIO_NUM -1
#define XCLK_GPIO_NUM 0
#define SIOD_GPIO_NUM 26
#define SIOC_GPIO_NUM 27
#define Y9_GPIO_NUM 35
#define Y8_GPIO_NUM 34
#define Y7_GPIO_NUM 39
#define Y6_GPIO_NUM 36
#define Y5_GPIO_NUM 21
#define Y4_GPIO_NUM 19
#define Y3_GPIO_NUM 18
#define Y2_GPIO_NUM 5
#define VSYNC_GPIO_NUM 25
#define HREF_GPIO_NUM 23
#define PCLK_GPIO_NUM 22
volatile bool mpuInterrupt;
float prevAngle_x, currentAngle_x;
float a_x,a_y,a_z;
float accAngle_x,gyroAngle_x;
unsigned long time_ = 0;
using namespace websockets;
WebsocketsServer server;
AsyncWebServer webserver(80);
double g_x,g_y,g_z;
void setup()
{
Serial.begin(9600);
i2c_mpu.begin(sda_,scl_,100000);
if (!mpu.begin(0x68,&i2c_mpu)) {
Serial.println("Failed to find MPU6050 chip");
while (1) {
delay(10);
}
}
mpu.setAccelerometerRange(MPU6050_RANGE_16_G);
mpu.setGyroRange(MPU6050_RANGE_250_DEG);
mpu.setFilterBandwidth(MPU6050_BAND_21_HZ);
Serial.println("");
delay(100);
WiFi.softAP(ssid, password);
IPAddress myIP = WiFi.softAPIP();
Serial.print("AP IP address: ");
Serial.println(myIP);
// Wait some time to connect to wifi
Serial.println(WiFi.localIP()); // You can get IP address assigned to ESP
server.listen(82);
Serial.print("Is server live? ");
Serial.println(server.available());
}
void handle_message(WebsocketsMessage msg) {
int commaIndex = msg.data().indexOf(',');
int x_des = msg.data().substring(0, commaIndex).toInt();
int y_des = msg.data().substring(commaIndex + 1).toInt();
Serial.println(String(x_des)+"."+String(y_des) );
}
void loop()
{
run_every(10)
{
mpuInterrupt=true;
}
if(mpuInterrupt)
{
sensors_event_t a, g, temp;
mpu.getEvent(&a, &g, &temp);
g_x = g.gyro.x;
g_y=g.gyro.y;
g_z=g.gyro.z ;
gyroAngle_x = (float)(g_x*0.01);
a_z = a.acceleration.z;
a_y =a.acceleration.y;
a_x=a.acceleration.x;
accAngle_x = (atan2(a_y, a_z))*RAD_TO_DEG;
currentAngle_x = 0.96*(prevAngle_x + gyroAngle_x) + 0.04*(accAngle_x);
prevAngle_x = currentAngle_x;
mpuInterrupt=false;
}
else{
run_every(500)
{
client.send(String(currentAngle_x));
Serial.println(String(currentAngle_x));
}
}
}
code python-cilent
import time
import websocket
import tkinter
from matplotlib import style
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg,NavigationToolbar2Tk
from matplotlib.figure import Figure
import matplotlib.animation as animation
import threading
import asyncio
from tkinter import *
from tkinter import ttk
import tkinter as tk
from tkinter import messagebox
class RingBuffer:
def __init__(self, capacity):
self.capacity = capacity
self.head=0
self.tail = -1
self.queue = [None] * capacity
self.size = 0
def Enqueue(self,item):
if self.size == self.capacity:
print("full")
else:
self.tail=(self.tail+1)% self.capacity
self.queue[self.tail]=item
self.size =self.size +1
def Dequeue(self):
if self.size == 0:
print("empty")
return
else:
tmp = self.queue[self.head]
self.head= (self.head+1 ) % self.capacity
self.size = self.size -1
return tmp
ws = websocket.WebSocket()
ws.connect("ws://192.168.4.1:82/")
style.use('ggplot')
#print(plt.style.available)
figure=Figure(figsize=(5,5),dpi=100)
a = figure.add_subplot(111)
gui = tk.Tk()
gui.wm_title("Drone_Pid")
button_image=PhotoImage(file="C:/Users/Computer/Desktop/Python-AI/GUI-tkinter/image_css/button_mpu.png")
gui.rowconfigure(0, weight=2)
gui.columnconfigure(0, weight=2)
def show_frame(frame):
frame.tkraise()
frame1 = tk.Frame(gui)
frame2 = tk.Frame(gui)
for frame in (frame1, frame2):
frame.grid(row=0, column=0, sticky='nsew')
def get_input():
signal=input_tune.get()
input_tune.delete(0,END)
output_ = "tune."+signal
ws.send(output_)
messagebox.showinfo("command", output_)
def back():
mess = "stop"
show_frame(frame1)
def stop():
a = "stop"
# ser.write((a).encode('utf-8').strip())
ws.send(a)
messagebox.showinfo("command", a)
def start():
a = "start"
ws.send(a)
# ser.write((a).encode('utf-8').strip())
messagebox.showinfo("command", a)
def mpu_send():
show_frame(frame2)
a = "mpu"
ws.send(a)
# ser.write((a).encode('utf-8').strip())
messagebox.showinfo("command", a)
time_now = time.time()
x=0
y=0
x_list=[]
y_list=[]
buf_y = RingBuffer(80)
def init():
a.set_xlim(0, 100)
a.set_ylim(0, 500)
a.set_xlabel("Times")
a.set_ylabel("Degree")
a.set_title("PID_Visualize")
def animate(i,xs,ys):
global x
try:
if(buf_y.size>0):
x = x + 0.5
y = buf_y.Dequeue()
x_list.append((x))
y_list.append(float(y))
#a.clear()
a.plot(x_list,y_list)
except Exception as e:
print(e)
def on_messege():
while True:
m = ws.recv()
if(m):
print(m)
buf_y.Enqueue(m)
time.sleep(0.1)
frame_control = tk.Frame(frame1)
frame_control.pack(side=LEFT, expand=True, fill=tk.BOTH)
frame_AI=tk.Frame(frame1)
frame_space=tk.Frame(frame1)
frame_AI.pack(side=RIGHT,expand=True,fill=tk.BOTH)
frame_space.pack(side=RIGHT,expand=True,fill=tk.BOTH)
text_space=tk.Label(frame_space, text='',bg='black', fg='white', width=5,height=9)
text_space.pack(fill=tk.BOTH)
#mpu send
button_mpu=tk.Button(frame_AI,image=button_image,command=mpu_send, width=200,height=120,borderwidth=5,bg='blue')
button_mpu.pack(fill=tk.BOTH)
#control_
button_start=ttk.Button(frame_control,text="Start",command=start, width=30)
button_stop=ttk.Button(frame_control,text="stop",command=stop, width=30)
button_stop.grid(row=4,column=0)
button_start.grid(row=3,column=0)
text_tune=tk.Label(frame_control, text='Tune_PID', font=("Arial Bold", 15))
text_tune.grid(row=1,column=0)
button_tune=tk.Button(frame_control,text="Submit",command=get_input, width=10,borderwidth=5)
input_tune=tk.Entry(frame_control,bd=10, width=40) # input box
input_tune.grid(row=2,column=0)
button_tune.grid(row=2,column=1)
button_back=ttk.Button(frame2,text="back",command=back)
button_back.pack()
#figure
canvas_plot= FigureCanvasTkAgg(figure,frame2)
canvas_plot.draw()
canvas_plot.get_tk_widget().pack(side=tk.TOP,fill=tk.BOTH,expand=True)
tool = NavigationToolbar2Tk(canvas_plot,frame2)
tool.update()
canvas_plot._tkcanvas.pack(side=tk.TOP,fill=tk.BOTH,expand=True)
# end figure
show_frame(frame1)
t=threading.Thread(target=on_messege)
t.start()
ani_=animation.FuncAnimation(figure,animate,fargs=(x_list,y_list),init_func=init,interval=500)
gui.mainloop()