Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 4855

Python • servo PCA9685 will not stop

$
0
0
servo will not stop

Code:

import tkinter as tkfrom flask import Flask, render_template, request, redirect, url_forimport sqlite3import timeimport datetime# Manually define SCL and SDA pinsSCL = 3SDA = 2import busiofrom adafruit_pca9685 import PCA9685app_flask = Flask(__name__)DATABASE = 'pill_dispenser.db'# Initialize the PCA9685 objecti2c = busio.I2C(SCL, SDA)pca = PCA9685(i2c)# Set frequency for the PWM signal (typically 50Hz for servos)pca.frequency = 50# Define servo minimum and maximum pulse widths (adjust according to your servo's specifications)servo_min = 150servo_max = 600# Initialize the databasedef initialize_database():    conn = sqlite3.connect(DATABASE)    c = conn.cursor()    c.execute('''CREATE TABLE IF NOT EXISTS pills                 (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, hour INTEGER, am_pm TEXT, bin_number INTEGER)''')    conn.commit()    conn.close()# Add a new pill to the scheduledef add_pill_to_schedule(name, hour, am_pm, bin_number):    if len(get_all_pills()) >= 30:        raise ValueError("Maximum limit of 30 pills reached.")    else:        conn = sqlite3.connect(DATABASE)        c = conn.cursor()        c.execute("INSERT INTO pills (name, hour, am_pm, bin_number) VALUES (?, ?, ?, ?)", (name, hour, am_pm, bin_number))        conn.commit()        conn.close()# Get all pills from the scheduledef get_all_pills():    conn = sqlite3.connect(DATABASE)    c = conn.cursor()    c.execute("SELECT * FROM pills")    pills = c.fetchall()    conn.close()    return pills# Get pills scheduled at the current timedef get_pills_at_schedule(current_time):    conn = sqlite3.connect(DATABASE)    c = conn.cursor()    c.execute("SELECT * FROM pills WHERE hour=? AND am_pm=?", current_time)    pills = c.fetchall()    conn.close()    return pills# Delete a pill from the scheduledef delete_pill_from_schedule(pill_id):    conn = sqlite3.connect(DATABASE)    c = conn.cursor()    c.execute("DELETE FROM pills WHERE id=?", (pill_id,))    conn.commit()    conn.close()# Get a pill by its IDdef get_pill_by_id(pill_id):    conn = sqlite3.connect(DATABASE)    c = conn.cursor()    c.execute("SELECT * FROM pills WHERE id=?", (pill_id,))    pill = c.fetchone()    conn.close()    return pill# Update a pill in the scheduledef update_pill_in_schedule(pill_id, name, hour, am_pm, bin_number):    conn = sqlite3.connect(DATABASE)    c = conn.cursor()    c.execute("UPDATE pills SET name=?, hour=?, am_pm=?, bin_number=? WHERE id=?", (name, hour, am_pm, bin_number, pill_id))    conn.commit()    conn.close()# Function to stop the servodef stop_servo(channel):    try:        pca.channels[channel].duty_cycle = 0  # Set duty cycle to 0 to stop the servo    except Exception as e:        print("Error stopping servo:", e)# Function to set servo angledef set_servo_angle(channel, angle):    try:        angle = max(0, min(angle, 180))  # Clamp angle between 0 and 180 degrees        pulse = int((angle / 180) * (servo_max - servo_min) + servo_min)  # Convert angle to pulse width        pca.channels[channel].duty_cycle = pulse    except Exception as e:        print("Error setting servo angle:", e) # Flask routes@app_flask.route('/')def index():    return render_template('index.html')@app_flask.route('/dispense')def dispense_pills():    try:        # Code to activate the pill dispensing mechanism        # Move servo 0 to a 180-degree position        set_servo_angle(0, 180)        time.sleep(1)  # Wait for 1 second (adjust as needed)        # Stop the servo        stop_servo(0)        return "Pills dispensed"    except Exception as e:        print("Error in dispense_pills route:", e)        return "An error occurred while dispensing pills"@app_flask.route('/schedule')def view_schedule():    try:        pills = get_all_pills()        return render_template('schedule.html', pills=pills)    except Exception as e:        print("Error in view_schedule route:", e)        return "An error occurred while viewing schedule"@app_flask.route('/add_pill', methods=['GET', 'POST'])def add_pill():    if request.method == 'POST':        try:            name = request.form['name']            hour = int(request.form['hour'])            am_pm = request.form['am_pm']            bin_number = int(request.form['bin_number'])  # Assuming bin_number is an integer            add_pill_to_schedule(name, hour, am_pm, bin_number)            return redirect(url_for('view_schedule'))        except ValueError as e:            return render_template('error.html', error=str(e))        except Exception as e:            print("Error in add_pill route:", e)            return "An error occurred while adding pill"    else:        return render_template('add_pill.html')@app_flask.route('/delete_pill/<int:pill_id>')def delete_pill_route(pill_id):    try:        delete_pill_from_schedule(pill_id)        return redirect(url_for('view_schedule'))    except Exception as e:        print("Error in delete_pill_route:", e)        return "An error occurred while deleting pill"@app_flask.route('/edit_pill/<int:pill_id>', methods=['GET', 'POST'])def edit_pill(pill_id):    if request.method == 'POST':        try:            name = request.form['name']            hour = int(request.form['hour'])            am_pm = request.form['am_pm']            bin_number = int(request.form['bin_number'])  # Assuming bin_number is an integer            update_pill_in_schedule(pill_id, name, hour, am_pm, bin_number)            return redirect(url_for('view_schedule'))        except ValueError as e:            return render_template('error.html', error=str(e))        except Exception as e:            print("Error in edit_pill route:", e)            return "An error occurred while editing pill"    else:        try:            pill = get_pill_by_id(pill_id)            return render_template('edit_pill.html', pill=pill)        except Exception as e:            print("Error in edit_pill route:", e)if __name__ == '__main__':    app_flask.run(host='0.0.0.0', port=5000)

Statistics: Posted by bob5731 — Wed Apr 10, 2024 12:51 am



Viewing all articles
Browse latest Browse all 4855

Trending Articles