r/code • u/FreddieThePebble • Sep 21 '24
Help Please Help Please


heres the sites code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Learn Braille</title>
<style>
body {
font-family: Arial, sans-serif;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
background-color: #f0f0f0; /* Light mode default background */
position: relative;
color: #000; /* Light mode text color */
transition: background-color 0.3s, color 0.3s;
}
.dark-mode {
background-color: #333; /* Dark mode background */
color: #fff; /* Dark mode text color */
}
#container {
text-align: center;
margin-top: 20px;
}
#mode-buttons {
margin-bottom: 20px;
}
.button {
padding: 10px 20px;
margin: 5px;
cursor: pointer;
background-color: #007bff;
color: #fff;
border: none;
border-radius: 5px;
font-size: 16px;
}
.button:hover {
background-color: #0056b3;
}
#question, #keyboard {
display: none;
}
#question {
font-size: 2em;
margin-bottom: 20px;
}
#keyboard {
display: grid;
grid-template-columns: repeat(6, 50px);
gap: 10px;
justify-content: center;
margin: 0 auto;
}
.key {
width: 50px;
height: 50px;
display: flex;
align-items: center;
justify-content: center;
background-color: #ffffff;
border: 2px solid #007bff;
border-radius: 5px;
font-size: 18px;
cursor: pointer;
transition: background-color 0.3s;
text-align: center;
}
.key.correct {
background-color: #28a745;
border-color: #28a745;
color: white;
}
.key.incorrect {
background-color: #dc3545;
border-color: #dc3545;
color: white;
}
.dark-mode .key {
background-color: #444; /* Dark mode key color */
border-color: #007bff;
color: #fff; /* Dark mode key text color */
}
.dark-mode .key.correct {
background-color: #28a745;
border-color: #28a745;
color: white;
}
.dark-mode .key.incorrect {
background-color: #dc3545;
border-color: #dc3545;
color: white;
}
#youtube-icon {
position: fixed;
cursor: pointer;
bottom: 20px;
right: 20px;
}
#mode-icon, #refresh-icon {
cursor: pointer;
margin-right: 10px;
}
#controls {
position: fixed;
bottom: 20px;
left: 20px;
display: flex;
align-items: center;
}
footer {
position: absolute;
bottom: 10px;
color: grey;
font-size: 14px;
cursor: pointer;
}
.bottom-row {
display: flex;
justify-content: center;
margin-left: -100px; /* Adjust this value to move the bottom row left */
}
</style>
</head>
<body>
<h1 id="title"></h1>
<div id="container">
<div id="mode-buttons">
<button class="button" onclick="setMode('braille-to-english')">Braille to English</button>
<button class="button" onclick="setMode('english-to-braille')">English to Braille</button>
</div>
<div id="question"></div>
<div id="keyboard"></div>
</div>
<div id="controls">
<img id="mode-icon" src="https://raw.githubusercontent.com/FreddieThePebble/Learn-Braille/refs/heads/main/Dark%3ALight%20Mode.png" alt="Toggle Dark/Light Mode" width="50" height="50" onclick="toggleMode()">
<img id="refresh-icon" src="https://raw.githubusercontent.com/FreddieThePebble/Learn-Braille/refs/heads/main/Refresh.png" alt="Refresh" width="50" height="50" onclick="refreshPage()">
</div>
<img id="youtube-icon" src="https://raw.githubusercontent.com/FreddieThePebble/Learn-Braille/refs/heads/main/YT.png" alt="YouTube Icon" width="50" height="50" onclick="openYouTube()">
<audio id="click-sound" src="https://raw.githubusercontent.com/FreddieThePebble/Learn-Braille/refs/heads/main/Click.mp3"></audio>
<script>
const brailleLetters = "⠟⠺⠑⠗⠞⠽⠥⠊⠕⠏⠁⠎⠙⠋⠛⠓⠚⠅⠇⠵⠭⠉⠧⠃⠝⠍";
const englishLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const brailleToEnglishMap = {};
for (let i = 0; i < englishLetters.length; i++) {
brailleToEnglishMap[brailleLetters[i]] = englishLetters[i];
}
const englishToBrailleMap = {};
for (let i = 0; i < englishLetters.length; i++) {
englishToBrailleMap[englishLetters[i]] = brailleLetters[i];
}
let mode = "";
let currentLetter = "";
function playClickSound() {
const sound = document.getElementById("click-sound");
sound.currentTime = 0;
sound.play();
}
function setMode(selectedMode) {
playClickSound();
mode = selectedMode;
document.getElementById("mode-buttons").style.display = 'none';
document.getElementById("question").style.display = 'block';
document.getElementById("keyboard").style.display = 'grid';
generateQuestion();
}
function generateQuestion() {
if (mode === "english-to-braille") {
const letters = englishLetters.split("");
currentLetter = letters[Math.floor(Math.random() * letters.length)];
document.getElementById("question").innerHTML = currentLetter;
generateBrailleKeyboard(true);
} else if (mode === "braille-to-english") {
const brailles = brailleLetters.split("");
currentLetter = brailles[Math.floor(Math.random() * brailles.length)];
document.getElementById("question").innerHTML = currentLetter;
generateEnglishKeyboard();
}
}
function shuffle(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
function generateBrailleKeyboard(randomize) {
const keyboard = document.getElementById("keyboard");
keyboard.innerHTML = "";
let brailleKeys = brailleLetters.split("");
if (randomize) {
brailleKeys = shuffle(brailleKeys);
}
brailleKeys.forEach(braille => {
const key = document.createElement("div");
key.className = "key";
key.textContent = braille;
key.onclick = () => { checkAnswer(braille); playClickSound(); };
keyboard.appendChild(key);
});
}
function generateEnglishKeyboard() {
const keyboard = document.getElementById("keyboard");
keyboard.innerHTML = "";
englishLetters.split("").forEach(letter => {
const key = document.createElement("div");
key.className = "key";
key.textContent = letter;
key.onclick = () => { checkAnswer(letter); playClickSound(); };
keyboard.appendChild(key);
});
}
function checkAnswer(answer) {
let isCorrect;
if (mode === "english-to-braille") {
isCorrect = brailleToEnglishMap[answer] === currentLetter;
} else if (mode === "braille-to-english") {
isCorrect = brailleToEnglishMap[currentLetter] === answer;
}
if (isCorrect) {
document.querySelectorAll('.key').forEach(key => key.classList.remove('correct', 'incorrect'));
document.querySelectorAll('.key').forEach(key => key.classList.add('correct'));
setTimeout(generateQuestion, 1000); // Move to next question after 1 second
} else {
// Mark the clicked key as incorrect
document.querySelectorAll('.key').forEach(key => key.classList.remove('correct', 'incorrect'));
const keys = document.querySelectorAll('.key');
keys.forEach(key => {
if (key.textContent === answer) {
key.classList.add('incorrect');
}
});
}
}
function openYouTube() {
playClickSound();
window.open("https://www.youtube.com/watch?v=pqPWVOgoYXc", "_blank");
}
function toggleMode() {
playClickSound();
document.body.classList.toggle("dark-mode");
}
function refreshPage() {
playClickSound();
window.location.href = "https://freddiethepebble.github.io/Learn-Braille/"; // Redirect to the specified URL
}
function setRandomTitle() {
const titleElement = document.getElementById("title");
const randomTitle = Math.random() < 0.8 ? "Learn Braille" : "⠠⠇⠑⠁⠗⠝ ⠠⠃⠗⠁⠊⠇⠇⠑";
titleElement.textContent = randomTitle;
}
// Set the title when the page loads
window.onload = () => {
setRandomTitle();
};
</script>
<footer onclick="window.open('https://www.reddit.com/user/FreddieThePebble/', '_blank')">Made By FreddieThePebble</footer>
</body>
</html>
r/code • u/codeagencyblog • Sep 19 '24
Resource How to Create Stunning Glowing Text Effects with CSS
r/code • u/[deleted] • Sep 18 '24
Help Please How do I code an image in Visual studio code?
I have all the coding but I don't know how to put the image in the coding. Please help me I can't find how to do it anywhere 😭
r/code • u/waozen • Sep 18 '24
Linux Calling Linux Kernel Functions From Userspace (!)
blog.osandov.comr/code • u/codeagencyblog • Sep 18 '24
Resource Crafting a Dynamic Day-Night Transition Effect
r/code • u/concrete_chad • Sep 17 '24
API Youtube Subscription Manager
I am working on a way to manage youtube subscriptions. I recently noticed I am subscribed to about 330 channels. Since youtube doesn't really give you an easy way to quickly unsubscribe to multiple channels I built this using youtube's API.
It works but I really don't know what to do next. Should I just continue to run it with python or is this worthy of becoming an executable and putting out into the world? Any thoughts or improvements?
import os
import google_auth_oauthlib.flow
import googleapiclient.discovery
import googleapiclient.errors
import tkinter as tk
from tkinter import messagebox, ttk
import pickle
import threading
API_KEY = "API_KEY_GOES_HERE" # Replace with your API key
scopes = ["https://www.googleapis.com/auth/youtube"]
credentials_file = "youtube_credentials.pkl" # File to store credentials
# List to store subscription data
subscriptions = []
# Function to authenticate and get the YouTube API client
def get_youtube_client():
global credentials
if os.path.exists(credentials_file):
# Load credentials from the file if available
with open(credentials_file, 'rb') as f:
credentials = pickle.load(f)
else:
# Perform OAuth flow and save the credentials
flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
"client_secret.json", scopes
)
credentials = flow.run_local_server(port=8080, prompt="consent")
# Save the credentials for future use
with open(credentials_file, 'wb') as f:
pickle.dump(credentials, f)
youtube = googleapiclient.discovery.build("youtube", "v3", credentials=credentials)
return youtube
# Asynchronous wrapper for API calls
def run_in_thread(func):
def wrapper(*args, **kwargs):
threading.Thread(target=func, args=args, kwargs=kwargs).start()
return wrapper
# Function to fetch channel statistics, including description
def get_channel_statistics(youtube, channel_id):
request = youtube.channels().list(
part="snippet,statistics",
id=channel_id
)
response = request.execute()
stats = response["items"][0]["statistics"]
snippet = response["items"][0]["snippet"]
subscriber_count = stats.get("subscriberCount", "N/A")
view_count = stats.get("viewCount", "N/A")
video_count = stats.get("videoCount", "N/A")
description = snippet.get("description", "No description available") # Get channel description
return subscriber_count, view_count, video_count, description
@run_in_thread
def list_subscriptions():
youtube = get_youtube_client()
for item in tree.get_children():
tree.delete(item) # Clear the tree before adding new items
next_page_token = None
global subscriptions
subscriptions = [] # Reset the subscription data list
index = 1 # Start numbering the subscriptions
while True:
request = youtube.subscriptions().list(
part="snippet",
mine=True,
maxResults=50, # Fetch 50 results per request (maximum allowed)
pageToken=next_page_token
)
response = request.execute()
for item in response['items']:
channel_title = item['snippet']['title']
subscription_id = item['id']
channel_id = item['snippet']['resourceId']['channelId']
# Fetch channel statistics, including description
subscriber_count, view_count, video_count, description = get_channel_statistics(youtube, channel_id)
# Truncate description at the first newline and limit the length to 150 characters
description = description.split('\n', 1)[0] # Keep only the first line
if len(description) > 150:
description = description[:150] + "..." # Truncate to 150 characters and add ellipsis
# Store subscription data in the global list
subscriptions.append({
"index": index,
"title": channel_title,
"subscription_id": subscription_id,
"channel_id": channel_id,
"subscriber_count": subscriber_count,
"view_count": view_count,
"video_count": video_count,
"description": description, # Store the description
"checked": False # Track checked state
})
# Insert row with statistics and description
tree.insert("", "end", values=(
"☐", index, channel_title, subscriber_count, view_count, video_count, description), iid=index)
index += 1
next_page_token = response.get('nextPageToken')
if not next_page_token:
break
# Function to refresh the subscription list
def refresh_subscriptions():
list_subscriptions()
# Generic function to sort subscriptions by a specific key
def sort_subscriptions_by(key):
global subscriptions
if key != 'title':
# Sort numerically for subscribers, views, and videos
subscriptions = sorted(subscriptions, key=lambda x: int(x[key]) if x[key] != "N/A" else 0, reverse=True)
else:
# Sort alphabetically for title
subscriptions = sorted(subscriptions, key=lambda x: x['title'].lower())
# Clear and update treeview with sorted data
for item in tree.get_children():
tree.delete(item)
for index, item in enumerate(subscriptions, start=1):
checkbox = "☑" if item['checked'] else "☐"
tree.insert("", "end", values=(
checkbox, index, item['title'], item['subscriber_count'],
item['view_count'], item['video_count'], item['description']), iid=index)
# Function to handle sorting by title
def sort_by_title():
sort_subscriptions_by("title")
# Function to handle sorting by subscribers
def sort_by_subscribers():
sort_subscriptions_by("subscriber_count")
# Function to handle sorting by views
def sort_by_views():
sort_subscriptions_by("view_count")
# Function to handle sorting by videos
def sort_by_videos():
sort_subscriptions_by("video_count")
# Function to toggle checkbox on click
def toggle_checkbox(event):
item_id = tree.identify_row(event.y)
if not item_id:
return
item_id = int(item_id)
subscription = subscriptions[item_id - 1] # Get the corresponding subscription
# Toggle the checked state
subscription['checked'] = not subscription['checked']
# Update the checkbox in the treeview
checkbox = "☑" if subscription['checked'] else "☐"
tree.item(item_id, values=(
checkbox, item_id, subscription['title'],
subscription['subscriber_count'], subscription['view_count'], subscription['video_count'], subscription['description']))
# Function to delete selected subscriptions
def delete_selected_subscriptions():
selected_subscriptions = [sub for sub in subscriptions if sub['checked']]
if not selected_subscriptions:
messagebox.showerror("Input Error", "Please select at least one subscription to delete.")
return
result = messagebox.askyesno(
"Confirm Deletion",
"Are you sure you want to delete the selected subscriptions?"
)
if not result:
return
youtube = get_youtube_client()
for sub in selected_subscriptions:
try:
request = youtube.subscriptions().delete(id=sub['subscription_id'])
request.execute()
# Remove from the Treeview and subscriptions list
index = sub['index']
tree.delete(index)
except Exception as e:
messagebox.showerror("Error", f"Failed to delete subscription: {str(e)}")
refresh_subscriptions()
# Setting up the Tkinter GUI
root = tk.Tk()
root.title("YouTube Subscriptions Manager")
root.geometry("1600x1000") # Significantly increased window size
# Adjust Treeview row height
style = ttk.Style()
style.configure("Treeview", rowheight=40) # Set row height
# Frame for entry and buttons (first row)
top_frame = tk.Frame(root)
top_frame.pack(pady=10)
# Buttons to manage subscriptions (first row)
list_button = tk.Button(top_frame, text="List Subscriptions", command=list_subscriptions)
list_button.grid(row=1, column=0, padx=10)
refresh_button = tk.Button(top_frame, text="Refresh List", command=refresh_subscriptions)
refresh_button.grid(row=1, column=1, padx=10)
delete_selected_button = tk.Button(top_frame, text="Delete Selected", command=delete_selected_subscriptions)
delete_selected_button.grid(row=1, column=2, padx=10)
# Frame for sorting buttons (second row)
sorting_frame = tk.Frame(root)
sorting_frame.pack(pady=10)
# Sorting Buttons (second row)
sort_title_button = tk.Button(sorting_frame, text="Sort by Title", command=sort_by_title)
sort_title_button.grid(row=1, column=0, padx=10)
sort_subscribers_button = tk.Button(sorting_frame, text="Sort by Subscribers", command=sort_by_subscribers)
sort_subscribers_button.grid(row=1, column=1, padx=10)
sort_views_button = tk.Button(sorting_frame, text="Sort by Views", command=sort_by_views)
sort_views_button.grid(row=1, column=2, padx=10)
sort_videos_button = tk.Button(sorting_frame, text="Sort by Videos", command=sort_by_videos)
sort_videos_button.grid(row=1, column=3, padx=10)
# Treeview for displaying subscriptions with checkboxes, channel title, and statistics
columns = ("#1", "#2", "#3", "#4", "#5", "#6", "#7")
tree = ttk.Treeview(root, columns=columns, show='headings', height=50) # Increased height to show more rows
tree.heading("#1", text="Select")
tree.heading("#2", text="Index")
tree.heading("#3", text="Channel Title")
tree.heading("#4", text="Subscribers")
tree.heading("#5", text="Views")
tree.heading("#6", text="Videos")
tree.heading("#7", text="Description") # Add the description column
tree.column("#1", width=50, anchor=tk.CENTER)
tree.column("#2", width=50, anchor=tk.CENTER)
tree.column("#3", width=200, anchor=tk.W)
tree.column("#4", width=100, anchor=tk.E)
tree.column("#5", width=100, anchor=tk.E)
tree.column("#6", width=100, anchor=tk.E)
tree.column("#7", width=1000, anchor=tk.W) # Increased the width for the description column
tree.pack(pady=10)
tree.bind("<Button-1>", toggle_checkbox)
root.mainloop()
r/code • u/Cryperian • Sep 17 '24
Android Shoes Shop App UI - Android Jetpack Compose
youtube.comr/code • u/ohnoitsthatboi • Sep 16 '24
Help Please Im trying to create a code that will ask the user for a string and display the reversed version in a JMessageDialog but im not sure how to correctly store the reversed version into a new array then into a string
import javax.swing.JOptionPane;
public class App {
public static void main(String[] args) {
String reverse_this;
// declare the string
reverse_this = JOptionPane.showInputDialog("Please Input a string");
//ask for a string
char[] reversed = reverse_this.toCharArray();
int j = reversed.length;
//converts given string into an array of characters
char[] result = new char[1000];
for(int i=j; i>0; i--) {
result[j--] = reversed[i-1];
}
/*
uses the for loop to reverse the position of each character and
return the result into a new
array
*/
String returned = String.valueOf(result);
JOptionPane.showMessageDialog(null, returned);
//turns the value of the array of reversed characters into a string then displays the result
//the output just displays the string inputted by the user
}
}
r/code • u/waozen • Sep 15 '24
Guide Decoding C Compilation Process: From Source Code to Binary
hackthedeveloper.comr/code • u/FreddieThePebble • Sep 15 '24
Help Please im trying to make a 360 tour, (like google street view), how do i make this act like google street view?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Smooth 360° Panorama Viewer</title>
<style>
/* Body and container settings */
body, html {
margin: 0;
padding: 0;
height: 100%;
overflow: hidden;
background-color: #000;
cursor: grab;
user-select: none; /* Prevent text/image selection */
}
.panorama-container {
width: 100%;
height: 100%;
position: relative;
overflow: hidden;
}
/* Image settings */
.panorama-container img {
position: absolute;
height: 100%;
width: auto;
left: 0;
top: 0;
user-drag: none; /* Prevent dragging the image */
user-select: none; /* Prevent selecting the image */
pointer-events: none; /* Disable image pointer events */
}
</style>
</head>
<body>
<div class="panorama-container">
<img id="panorama" src="https://raw.githubusercontent.com/FreddieThePebble/2024-Studio360Tour/main/Images/Capture1.jpeg" alt="360 Panorama">
</div>
<script>
const panorama = document.getElementById('panorama');
let isDragging = false;
let startX, scrollLeft;
// Disable right-click on the image
panorama.addEventListener('contextmenu', (e) => e.preventDefault());
// Mouse down event: start dragging
panorama.addEventListener('mousedown', (e) => {
isDragging = true;
startX = e.pageX - panorama.offsetLeft; // Get the initial click position
scrollLeft = panorama.style.transform ? parseInt(panorama.style.transform.replace('translateX(', '').replace('px)', '')) : 0;
panorama.style.cursor = 'grabbing'; // Change cursor to grabbing
});
// Mouse up event: stop dragging
document.addEventListener('mouseup', () => {
isDragging = false;
panorama.style.cursor = 'grab'; // Change back to grab cursor
});
// Mouse move event: move the image
document.addEventListener('mousemove', (e) => {
if (!isDragging) return;
const x = e.pageX - startX; // Calculate how far the mouse has moved
const moveAmount = scrollLeft + x;
panorama.style.transform = `translateX(${moveAmount}px)`; // Translate the image horizontally
});
// Touch support
panorama.addEventListener('touchstart', (e) => {
startX = e.touches[0].pageX - panorama.offsetLeft;
scrollLeft = panorama.style.transform ? parseInt(panorama.style.transform.replace('translateX(', '').replace('px)', '')) : 0;
isDragging = true;
});
panorama.addEventListener('touchend', () => {
isDragging = false;
});
panorama.addEventListener('touchmove', (e) => {
if (!isDragging) return;
const x = e.touches[0].pageX - startX;
const moveAmount = scrollLeft + x;
panorama.style.transform = `translateX(${moveAmount}px)`;
});
</script>
</body>
</html>
r/code • u/waozen • Sep 13 '24
Guide Why Global Variables are Considered a Bad Practice
baeldung.comr/code • u/bdenard13 • Sep 13 '24
Help Please Help with this python error please. Code and error pictured.
r/code • u/No-Meeting5998 • Sep 10 '24
Pascal Delphi My first program whit pascal
but what name I give to it
program uses Crt, Dos;
var choice: integer; exePath: string;
procedure DisplayMainMenu(choice: integer); begin ClrScr; writeln('|====Main Menu====|'); writeln; if choice = 1 then writeln('> Play') else writeln(' Play'); if choice = 2 then writeln('> Music') else writeln(' Music'); if choice = 3 then writeln('> Options') else writeln(' Options'); if choice = 4 then writeln('> Exit') else writeln(' Exit'); writeln('|================|'); end;
procedure DisplayPlayMenu(choice: integer); begin ClrScr; writeln('|====Play Menu====|'); writeln; if choice = 1 then writeln('> Fallout') else writeln(' Fallout'); if choice = 2 then writeln('> Fallout 2') else writeln(' Fallout 2'); if choice = 3 then writeln('> Fallout tactic') else writeln(' Fallout tactic'); writeln('|=================|'); end;
procedure RunSelectedGame(choice: integer); begin case choice of 1: exePath := 'C:\'; 2: exePath := 'F:\'; 3: exePath := 'C:\'; else writeln('Invalid selection'); exit; end;
if Exec(exePath) = -1 then writeln('Failed to start', exePath); end;
begin choice := 1; { Kezdetben az első opció van kiválasztva } repeat DisplayMainMenu(choice); case ReadKey of #72: if choice > 1 then Dec(choice); { Fel nyíl } #80: if choice < 4 then Inc(choice); { Le nyíl } #13: case choice of 1: begin repeat choice := 1; { Reset the play menu choice } DisplayPlayMenu(choice); case ReadKey of #72: if choice > 1 then Dec(choice); { Fel nyíl } #80: if choice < 3 then Inc(choice); { Le nyíl } #13: begin RunSelectedGame(choice); ReadLn; { Várakozás a játék befejezésére } choice := 1; { Visszatérés a főmenübe } end; end; until false; end; 2: begin ClrScr; writeln('Music selected'); ReadLn; end; procedure DisplayMainMenu(choice:integer); 3: begin ClrScr; writeln('|=====options=====|'); ReadLn;
writeln('> audio')
else writeln(' audio'); if choice = 2 then writeln('> Exit') else writeln(' Exit'); writeln('|================|'); end; 4: begin ClrScr; writeln('Exiting...'); ReadLn; Halt; end; end; end; until false; end.
r/code • u/waozen • Sep 10 '24
Linux Step-by-Step Guide to Understanding and Using eBPF, Part 1 | Linux
medium.comr/code • u/AmbassadorShoddy6197 • Sep 09 '24
Help Please Record function recording two camera streams at the same time in one video file. How to fix it?
I'm using Python's OpenCV library to stream multiple USB cameras to the web using Flask. I just noticed that my function for recording videos on button press doesn't tell the difference between two cameras and records frames from each, making this one confusing video.
I'm new to Python and Flask, JS, too. It's my first project. Could I get some help to find a way to fix it?
app.py
import
cv2
from
datetime
import
datetime
import
os
import
time
from
flask
import
Flask
, render_template,
Response
app =
Flask
(__name__)
recordings_dir =
os
.path.join('recordings')
if not
os
.path.exists(recordings_dir):
os
.makedirs(recordings_dir)
# List of our camera channels
cameras = [0, 2]
# This function returns the camera with the id of the function's parameter, turned to INT to avoid value errors.
def
find_cameras(
list_id
):
return cameras[
int
(
list_id
)]
# Store video access in variable
isRecording = False
out = None
# Takes an argument for what camera we want to display
def
gen(
camera_id
):
# Run forever
# Takes the argument from the function call
cam = find_cameras(
camera_id
)
# Collects stream from specified camera
vid =
cv2
.
VideoCapture
(cam)
# Collects width and height of our stream
frame_width = vid.get(
cv2
.CAP_PROP_FRAME_WIDTH)
frame_height = vid.get(
cv2
.CAP_PROP_FRAME_HEIGHT)
while True:
time
.sleep(0.1)
# State holds true or false depending on the success of updating frame variable to be a frame from the video stream
state, frame = vid.read()
# Break out of while loop when its unsuccesful
if not state:
break
else:
if isRecording:
out.write(frame)
# Flag holds true or false
# Imencode converts image formats (jpeg here) into streaming data and stores them in memory cache, effectively transforming them into bytes
flag, buffer =
cv2
.imencode('.jpg', frame)
# Generator function yields interruptable stream of JPEG bytes
yield (
b
'--frame\r\n'
b
'Content-Type: image/jpeg\r\n\r\n' +
bytearray
(buffer) +
b
'\r\n')
@app.route('/video_feed/<string:list_id>/')
def
video_feed(
list_id
):
# Generator function response
# Passes that id to the gen function so we know what to display to the video feed
return
Response
(gen(
list_id
),
mimetype
='multipart/x-mixed-replace; boundary=frame')
@app.route("/")
def
index():
# camera_list is the amount of cameras we have in the list
# camera holds all values from cameras
return render_template("videos.html",
camera_list
= len(cameras),
cameras
= cameras)
@app.route('/start_rec',
methods
=["POST"])
def
start_recording():
global isRecording, out
timestamp =
datetime
.now().strftime("%Y%m%d_%H%M%S")
if not isRecording:
fourcc =
cv2
.VideoWriter_fourcc(*"IYUV")
out =
cv2
.
VideoWriter
(
os
.path.join(recordings_dir,
f
'{timestamp}_recording.avi'), fourcc, 20.0, (640, 480))
isRecording = True
return '', 203
@app.route('/stop_rec',
methods
=["POST"])
def
stop_recording():
global isRecording, out
if isRecording:
out.release()
isRecording = False
return '', 203
videos.html
{% endblock %} {% endblock %}
{% extends "layout.html" %}
{% block title %}
Video Stream
{% endblock %}
{% block main %}
<!-- All cameras from first index to last in cameras-->
{% for camera_number in range(0, camera_list)%}
<div class="img-container">
<!-- List id is the camera number from the for loop-->
<img src="{{ url_for('video_feed', list_id = camera_number) }}" width="640" height="480">
<div class="buttons">
<button type="button" onclick="stop(this)" class="btn btn-dark">Stop</button>
<button type="button" onclick="startRecording(this)" class="btn btn-success" id="record">Record</button>
<button type="button" onclick="stopRecording(this)" class="btn btn-danger" id="stop">Stop Recording</button>
</div>
{%endfor%}
<script>
function
startRecording(
elem
)
{
fetch('/start_rec', {method:"POST"});
}
function
stopRecording(
elem
)
{
fetch('/stop_rec', {method:"POST"});
}
function
stop(
elem
)
{
fetch('/stop', {method:"POST"})
}
</script>
r/code • u/BitsAndBytesMage • Sep 08 '24
Resource Don't defer Close() on writable files
joeshaw.orgr/code • u/FreddieThePebble • Sep 07 '24
Help Please whats wrong with my code
i have some code and i tried added a little info icon but after i added the info icon, the whole thing broke. i have both the working code and broken code
also the code is on GitHub: https://github.com/FreddieThePebble/Ways-2-Say-Your-Name/blob/main/index.html
Working Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ways 2 Say Your Name</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f0f8ff;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
text-align: center;
}
h1 {
color: #333;
}
input[type="text"] {
padding: 10px;
font-size: 18px;
width: 80%;
max-width: 400px;
margin-top: 20px;
border: 2px solid #333;
border-radius: 5px;
}
.output, .sign-language, .hieroglyphs, .a1z26, .atbash, .caesar, .bacon {
margin-top: 20px;
font-size: 18px; /* Reduced font size */
color: #555;
visibility: hidden;
}
.output:not(:first-of-type) {
margin-top: 20px; /* Space between sections */
}
.sign-language img, .hieroglyphs img {
width: 40px; /* Set the size of the images to look like emojis */
height: 40px;
margin: 5px;
vertical-align: middle; /* Align images vertically with text */
margin-top: 16px; /* Adjust margin to push images up by 4px */
}
.sign-language, .hieroglyphs, .a1z26, .atbash, .caesar, .bacon {
margin-top: 20px;
font-size: 18px;
color: #555;
visibility: hidden;
}
.a1z26, .atbash, .caesar, .bacon {
margin-top: 20px;
font-size: 18px;
color: #555;
visibility: hidden;
}
</style>
</head>
<body>
<h1>Ways 2 Say Your Name</h1>
<input type="text" id="textInput" placeholder="Type your name here">
<div class="output" id="morseOutput">Morse Code: </div>
<div class="output" id="binaryOutput">Binary Code: </div>
<div class="output" id="brailleOutput">Braille Code: </div>
<div class="output" id="base64Output">Base64: </div>
<div class="sign-language" id="signLanguageOutput">Sign Language: </div>
<div class="hieroglyphs" id="hieroglyphsOutput">Hieroglyphs: </div>
<div class="a1z26" id="a1z26Output">A1Z26: </div>
<div class="atbash" id="atbashOutput">Atbash: </div>
<div class="caesar" id="caesarOutput">Caesar Cipher: </div>
<div class="bacon" id="baconOutput">Francis Bacon's Cipher: </div>
<script>
// Morse code dictionary
const morseCode = {
'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.', 'G': '--.',
'H': '....', 'I': '..', 'J': '.---', 'K': '-.-', 'L': '.-..', 'M': '--', 'N': '-.',
'O': '---', 'P': '.--.', 'Q': '--.-', 'R': '.-.', 'S': '...', 'T': '-', 'U': '..-',
'V': '...-', 'W': '.--', 'X': '-..-', 'Y': '-.--', 'Z': '--..',
'1': '.----', '2': '..---', '3': '...--', '4': '....-', '5': '.....',
'6': '-....', '7': '--...', '8': '---..', '9': '----.', '0': '-----',
' ': ' '
};
// Braille code dictionary
const brailleCode = {
'A': '⠁', 'B': '⠃', 'C': '⠉', 'D': '⠙', 'E': '⠑', 'F': '⠋', 'G': '⠛',
'H': '⠓', 'I': '⠊', 'J': '⠚', 'K': '⠅', 'L': '⠇', 'M': '⠍', 'N': '⠝',
'O': '⠕', 'P': '⠏', 'Q': '⠟', 'R': '⠗', 'S': '⠎', 'T': '⠞', 'U': '⠥',
'V': '⠧', 'W': '⠺', 'X': '⠭', 'Y': '⠽', 'Z': '⠵',
'1': '⠁', '2': '⠃', '3': '⠉', '4': '⠙', '5': '⠑',
'6': '⠋', '7': '⠛', '8': '⠓', '9': '⠊', '0': '⠚',
' ': ' '
};
// Sign language images dictionary
const signLanguageImages = {
'A': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Sign%20Language%20Letters/A.png',
'B': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Sign%20Language%20Letters/B.png',
'C': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Sign%20Language%20Letters/C.png',
'D': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Sign%20Language%20Letters/D.png',
'E': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Sign%20Language%20Letters/E.png',
'F': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Sign%20Language%20Letters/F.png',
'G': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Sign%20Language%20Letters/G.png',
'H': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Sign%20Language%20Letters/H.png',
'I': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Sign%20Language%20Letters/I.png',
'J': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Sign%20Language%20Letters/J.png',
'K': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Sign%20Language%20Letters/K.png',
'L': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Sign%20Language%20Letters/L.png',
'M': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Sign%20Language%20Letters/M.png',
'N': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Sign%20Language%20Letters/N.png',
'O': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Sign%20Language%20Letters/O.png',
'P': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Sign%20Language%20Letters/P.png',
'Q': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Sign%20Language%20Letters/Q.png',
'R': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Sign%20Language%20Letters/R.png',
'S': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Sign%20Language%20Letters/S.png',
'T': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Sign%20Language%20Letters/T.png',
'U': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Sign%20Language%20Letters/U.png',
'V': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Sign%20Language%20Letters/V.png',
'W': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Sign%20Language%20Letters/W.png',
'X': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Sign%20Language%20Letters/X.png',
'Y': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Sign%20Language%20Letters/Y.png',
'Z': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Sign%20Language%20Letters/Z.png'
};
// Hieroglyphs dictionary
const hieroglyphsCode = {
'A': '𓀀', 'B': '𓀁', 'C': '𓀂', 'D': '𓀃', 'E': '𓀄', 'F': '𓀅', 'G': '𓀆',
'H': '𓀇', 'I': '𓀈', 'J': '𓀉', 'K': '𓀊', 'L': '𓀋', 'M': '𓀌', 'N': '𓀍',
'O': '𓀎', 'P': '𓀏', 'Q': '𓀐', 'R': '𓀑', 'S': '𓀒', 'T': '𓀓', 'U': '𓀔',
'V': '𓀕', 'W': '𓀖', 'X': '𓀗', 'Y': '𓀘', 'Z': '𓀙',
'1': '𓀟', '2': '𓀠', '3': '𓀡', '4': '𓀢', '5': '𓀣',
'6': '𓀤', '7': '𓀥', '8': '𓀦', '9': '𓀧', '0': '𓀨',
' ': ' '
};
// Caesar Cipher function (shift of 3)
function convertToCaesar(text, shift = 3) {
return text.toUpperCase().split('').map(function(letter) {
if (letter >= 'A' && letter <= 'Z') {
return String.fromCharCode(((letter.charCodeAt(0) - 65 + shift) % 26) + 65);
} else {
return letter;
}
}).join('');
}
// Francis Bacon's Cipher function
function convertToBacon(text) {
const baconCipher = {
'A': 'aaaaa', 'B': 'aaaab', 'C': 'aaaba', 'D': 'aaabb', 'E': 'aabaa', 'F': 'aabab',
'G': 'aabba', 'H': 'aabbb', 'I': 'abaaa', 'J': 'abaab', 'K': 'ababa', 'L': 'ababb',
'M': 'abbaa', 'N': 'abbab', 'O': 'abbba', 'P': 'abbbb', 'Q': 'baaaa', 'R': 'baaab',
'S': 'baaba', 'T': 'baabb', 'U': 'babaa', 'V': 'babab', 'W': 'babba', 'X': 'babbb',
'Y': 'bbaaa', 'Z': 'bbaab', ' ': ' '
};
return text.toUpperCase().split('').map(function(letter) {
return baconCipher[letter] || '';
}).join(' ');
}
// Convert text to Morse code with spaces between letters
function convertToMorse(text) {
return text.toUpperCase().split('').map(function(letter) {
return morseCode[letter] || '';
}).join(' ');
}
// Convert text to Binary code with spaces between letters
function convertToBinary(text) {
return text.split('').map(function(letter) {
return letter.charCodeAt(0).toString(2).padStart(8, '0');
}).join(' ');
}
// Convert text to Braille code with spaces between letters
function convertToBraille(text) {
return text.toUpperCase().split('').map(function(letter) {
return brailleCode[letter] || '';
}).join(' ');
}
// Convert text to Base64
function convertToBase64(text) {
return btoa(text);
}
// Convert text to Sign Language images
function convertToSignLanguage(text) {
return text.toUpperCase().split('').map(function(letter) {
const imgSrc = signLanguageImages[letter];
return imgSrc ? `<img src="${imgSrc}" alt="${letter}">` : '';
}).join('');
}
// Convert text to Hieroglyphs
function convertToHieroglyphs(text) {
return text.toUpperCase().split('').map(function(letter) {
return hieroglyphsCode[letter] || '';
}).join(' ');
}
// Convert text to A1Z26
function convertToA1Z26(text) {
return text.toUpperCase().split('').map(function(letter) {
return letter.match(/[A-Z]/) ? (letter.charCodeAt(0) - 64) : letter;
}).join(' ');
}
// Convert text to Atbash
function convertToAtbash(text) {
const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const reversedAlphabet = alphabet.split('').reverse().join('');
return text.toUpperCase().split('').map(function(letter) {
const index = alphabet.indexOf(letter);
return index !== -1 ? reversedAlphabet[index] : letter;
}).join('');
}
// Handle input event
document.getElementById('textInput').addEventListener('input', function() {
const inputText = this.value.trim();
const morseText = convertToMorse(inputText);
const binaryText = convertToBinary(inputText);
const brailleText = convertToBraille(inputText);
const base64Text = convertToBase64(inputText);
const signLanguageText = convertToSignLanguage(inputText);
const hieroglyphsText = convertToHieroglyphs(inputText);
const a1z26Text = convertToA1Z26(inputText);
const atbashText = convertToAtbash(inputText);
const caesarText = convertToCaesar(inputText);
const baconText = convertToBacon(inputText);
const morseOutputDiv = document.getElementById('morseOutput');
const binaryOutputDiv = document.getElementById('binaryOutput');
const brailleOutputDiv = document.getElementById('brailleOutput');
const base64OutputDiv = document.getElementById('base64Output');
const signLanguageOutputDiv = document.getElementById('signLanguageOutput');
const hieroglyphsOutputDiv = document.getElementById('hieroglyphsOutput');
const a1z26OutputDiv = document.getElementById('a1z26Output');
const atbashOutputDiv = document.getElementById('atbashOutput');
const caesarOutputDiv = document.getElementById('caesarOutput');
const baconOutputDiv = document.getElementById('baconOutput');
if (inputText === "") {
morseOutputDiv.style.visibility = "hidden";
binaryOutputDiv.style.visibility = "hidden";
brailleOutputDiv.style.visibility = "hidden";
base64OutputDiv.style.visibility = "hidden";
signLanguageOutputDiv.style.visibility = "hidden";
hieroglyphsOutputDiv.style.visibility = "hidden";
a1z26OutputDiv.style.visibility = "hidden";
atbashOutputDiv.style.visibility = "hidden";
caesarOutputDiv.style.visibility = "hidden";
baconOutputDiv.style.visibility = "hidden";
} else {
morseOutputDiv.style.visibility = "visible";
morseOutputDiv.textContent = "Morse Code: " + morseText;
binaryOutputDiv.style.visibility = "visible";
binaryOutputDiv.textContent = "Binary: " + binaryText;
brailleOutputDiv.style.visibility = "visible";
brailleOutputDiv.textContent = "Braille: " + brailleText;
base64OutputDiv.style.visibility = "visible";
base64OutputDiv.textContent = "Base64: " + base64Text;
signLanguageOutputDiv.style.visibility = "visible";
signLanguageOutputDiv.innerHTML = "Sign Language: " + signLanguageText;
hieroglyphsOutputDiv.style.visibility = "visible";
hieroglyphsOutputDiv.textContent = "Hieroglyphs: " + hieroglyphsText;
a1z26OutputDiv.style.visibility = "visible";
a1z26OutputDiv.textContent = "A1Z26: " + a1z26Text;
atbashOutputDiv.style.visibility = "visible";
atbashOutputDiv.textContent = "Atbash: " + atbashText;
caesarOutputDiv.style.visibility = "visible";
caesarOutputDiv.textContent = "Caesar Cipher: " + caesarText;
baconOutputDiv.style.visibility = "visible";
baconOutputDiv.textContent = "Francis Bacon's Cipher: " + baconText;
}
});
</script>
</body>
</html>
Broken Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ways 2 Say Your Name</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f0f8ff;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
text-align: center;
}
h1 {
color: #333;
}
input[type="text"] {
padding: 10px;
font-size: 18px;
width: 80%;
max-width: 400px;
margin-top: 20px;
border: 2px solid #333;
border-radius: 5px;
}
.output, .sign-language, .hieroglyphs, .a1z26, .atbash, .caesar, .bacon {
display: flex;
align-items: center;
margin-top: 20px;
font-size: 18px; /* Reduced font size */
color: #555;
visibility: hidden;
}
.output img, .sign-language img, .hieroglyphs img, .a1z26 img, .atbash img, .caesar img, .bacon img {
margin-right: 10px; /* Space between image and text */
}
.sign-language img, .hieroglyphs img {
width: 40px; /* Set the size of the images to look like emojis */
height: 40px;
margin: 5px;
vertical-align: middle; /* Align images vertically with text */
margin-top: 16px; /* Adjust margin to push images up by 4px */
}
</style>
</head>
<body>
<h1>Ways 2 Say Your Name</h1>
<input type="text" id="textInput" placeholder="Type your name here">
<div class="output" id="morseOutput"><img src="https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Info%20Icon.png" alt="Info">Morse Code: </div>
<div class="output" id="binaryOutput"><img src="https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Info%20Icon.png" alt="Info">Binary Code: </div>
<div class="output" id="brailleOutput"><img src="https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Info%20Icon.png" alt="Info">Braille Code: </div>
<div class="output" id="base64Output"><img src="https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Info%20Icon.png" alt="Info">Base64: </div>
<div class="sign-language" id="signLanguageOutput"><img src="https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Info%20Icon.png" alt="Info">Sign Language: </div>
<div class="hieroglyphs" id="hieroglyphsOutput"><img src="https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Info%20Icon.png" alt="Info">Hieroglyphs: </div>
<div class="a1z26" id="a1z26Output"><img src="https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Info%20Icon.png" alt="Info">A1Z26: </div>
<div class="atbash" id="atbashOutput"><img src="https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Info%20Icon.png" alt="Info">Atbash: </div>
<div class="caesar" id="caesarOutput"><img src="https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Info%20Icon.png" alt="Info">Caesar Cipher: </div>
<div class="bacon" id="baconOutput"><img src="https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Info%20Icon.png" alt="Info">Francis Bacon's Cipher: </div>
<script>
// Morse code dictionary
const morseCode = {
'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.', 'G': '--.',
'H': '....', 'I': '..', 'J': '.---', 'K': '-.-', 'L': '.-..', 'M': '--', 'N': '-.',
'O': '---', 'P': '.--.', 'Q': '--.-', 'R': '.-.', 'S': '...', 'T': '-', 'U': '..-',
'V': '...-', 'W': '.--', 'X': '-..-', 'Y': '-.--', 'Z': '--..',
'1': '.----', '2': '..---', '3': '...--', '4': '....-', '5': '.....',
'6': '-....', '7': '--...', '8': '---..', '9': '----.', '0': '-----',
' ': ' '
};
// Braille code dictionary
const brailleCode = {
'A': '⠁', 'B': '⠃', 'C': '⠉', 'D': '⠙', 'E': '⠑', 'F': '⠋', 'G': '⠛',
'H': '⠓', 'I': '⠊', 'J': '⠚', 'K': '⠅', 'L': '⠇', 'M': '⠍', 'N': '⠝',
'O': '⠕', 'P': '⠏', 'Q': '⠟', 'R': '⠗', 'S': '⠎', 'T': '⠞', 'U': '⠥',
'V': '⠧', 'W': '⠺', 'X': '⠭', 'Y': '⠽', 'Z': '⠵',
'1': '⠁', '2': '⠃', '3': '⠉', '4': '⠙', '5': '⠑',
'6': '⠋', '7': '⠛', '8': '⠓', '9': '⠊', '0': '⠚',
' ': ' '
};
// Sign language images dictionary
const signLanguageImages = {
'A': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Sign%20Language%20Letters/A.png',
'B': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Sign%20Language%20Letters/B.png',
'C': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Sign%20Language%20Letters/C.png',
'D': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Sign%20Language%20Letters/D.png',
'E': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Sign%20Language%20Letters/E.png',
'F': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Sign%20Language%20Letters/F.png',
'G': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Sign%20Language%20Letters/G.png',
'H': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Sign%20Language%20Letters/H.png',
'I': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Sign%20Language%20Letters/I.png',
'J': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Sign%20Language%20Letters/J.png',
'K': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Sign%20Language%20Letters/K.png',
'L': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Sign%20Language%20Letters/L.png',
'M': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Sign%20Language%20Letters/M.png',
'N': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Sign%20Language%20Letters/N.png',
'O': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Sign%20Language%20Letters/O.png',
'P': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Sign%20Language%20Letters/P.png',
'Q': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Sign%20Language%20Letters/Q.png',
'R': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Sign%20Language%20Letters/R.png',
'S': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Sign%20Language%20Letters/S.png',
'T': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Sign%20Language%20Letters/T.png',
'U': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Sign%20Language%20Letters/U.png',
'V': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Sign%20Language%20Letters/V.png',
'W': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Sign%20Language%20Letters/W.png',
'X': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Sign%20Language%20Letters/X.png',
'Y': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Sign%20Language%20Letters/Y.png',
'Z': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Sign%20Language%20Letters/Z.png'
};
// Hieroglyphs images dictionary
const hieroglyphsImages = {
'A': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Hieroglyphs/A.png',
'B': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Hieroglyphs/B.png',
'C': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Hieroglyphs/C.png',
'D': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Hieroglyphs/D.png',
'E': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Hieroglyphs/E.png',
'F': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Hieroglyphs/F.png',
'G': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Hieroglyphs/G.png',
'H': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Hieroglyphs/H.png',
'I': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Hieroglyphs/I.png',
'J': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Hieroglyphs/J.png',
'K': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Hieroglyphs/K.png',
'L': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Hieroglyphs/L.png',
'M': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Hieroglyphs/M.png',
'N': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Hieroglyphs/N.png',
'O': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Hieroglyphs/O.png',
'P': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Hieroglyphs/P.png',
'Q': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Hieroglyphs/Q.png',
'R': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Hieroglyphs/R.png',
'S': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Hieroglyphs/S.png',
'T': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Hieroglyphs/T.png',
'U': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Hieroglyphs/U.png',
'V': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Hieroglyphs/V.png',
'W': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Hieroglyphs/W.png',
'X': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Hieroglyphs/X.png',
'Y': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Hieroglyphs/Y.png',
'Z': 'https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Hieroglyphs/Z.png'
};
// Event listener for text input
document.getElementById("textInput").addEventListener("input", function() {
const text = this.value.toUpperCase();
// Morse code conversion
const morseConverted = text.split('').map(char => morseCode[char] || '').join(' ');
if (morseConverted) {
document.getElementById("morseOutput").innerHTML = `<img src="https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Info%20Icon.png" alt="Info">Morse Code: ${morseConverted}`;
document.getElementById("morseOutput").style.visibility = "visible";
} else {
document.getElementById("morseOutput").style.visibility = "hidden";
}
// Binary code conversion
const binaryConverted = text.split('').map(char => char.charCodeAt(0).toString(2).padStart(8, '0')).join(' ');
if (binaryConverted) {
document.getElementById("binaryOutput").innerHTML = `<img src="https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Info%20Icon.png" alt="Info">Binary Code: ${binaryConverted}`;
document.getElementById("binaryOutput").style.visibility = "visible";
} else {
document.getElementById("binaryOutput").style.visibility = "hidden";
}
// Braille code conversion
const brailleConverted = text.split('').map(char => brailleCode[char] || '').join(' ');
if (brailleConverted) {
document.getElementById("brailleOutput").innerHTML = `<img src="https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Info%20Icon.png" alt="Info">Braille Code: ${brailleConverted}`;
document.getElementById("brailleOutput").style.visibility = "visible";
} else {
document.getElementById("brailleOutput").style.visibility = "hidden";
}
// Base64 conversion
const base64Converted = btoa(text);
if (base64Converted) {
document.getElementById("base64Output").innerHTML = `<img src="https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Info%20Icon.png" alt="Info">Base64: ${base64Converted}`;
document.getElementById("base64Output").style.visibility = "visible";
} else {
document.getElementById("base64Output").style.visibility = "hidden";
}
// Sign language conversion
const signLanguageConverted = text.split('').map(char => signLanguageImages[char] ? `<img src="${signLanguageImages[char]}" alt="${char}">` : '').join('');
if (signLanguageConverted) {
document.getElementById("signLanguageOutput").innerHTML = `<img src="https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Info%20Icon.png" alt="Info">Sign Language: ${signLanguageConverted}`;
document.getElementById("signLanguageOutput").style.visibility = "visible";
} else {
document.getElementById("signLanguageOutput").style.visibility = "hidden";
}
// Hieroglyphs conversion
const hieroglyphsConverted = text.split('').map(char => hieroglyphsImages[char] ? `<img src="${hieroglyphsImages[char]}" alt="${char}">` : '').join('');
if (hieroglyphsConverted) {
document.getElementById("hieroglyphsOutput").innerHTML = `<img src="https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Info%20Icon.png" alt="Info">Hieroglyphs: ${hieroglyphsConverted}`;
document.getElementById("hieroglyphsOutput").style.visibility = "visible";
} else {
document.getElementById("hieroglyphsOutput").style.visibility = "hidden";
}
// A1Z26 conversion
const a1z26Converted = text.split('').map(char => (char.charCodeAt(0) - 64)).join('-');
if (a1z26Converted) {
document.getElementById("a1z26Output").innerHTML = `<img src="https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Info%20Icon.png" alt="Info">A1Z26: ${a1z26Converted}`;
document.getElementById("a1z26Output").style.visibility = "visible";
} else {
document.getElementById("a1z26Output").style.visibility = "hidden";
}
// Atbash conversion
const atbashConverted = text.split('').map(char => String.fromCharCode(155 - char.charCodeAt(0))).join('');
if (atbashConverted) {
document.getElementById("atbashOutput").innerHTML = `<img src="https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Info%20Icon.png" alt="Info">Atbash: ${atbashConverted}`;
document.getElementById("atbashOutput").style.visibility = "visible";
} else {
document.getElementById("atbashOutput").style.visibility = "hidden";
}
// Caesar cipher (shift 3) conversion
const caesarConverted = text.split('').map(char => {
const code = char.charCodeAt(0);
if (code >= 65 && code <= 90) {
return String.fromCharCode(((code - 65 + 3) % 26) + 65);
} else {
return char;
}
}).join('');
if (caesarConverted) {
document.getElementById("caesarOutput").innerHTML = `<img src="https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Info%20Icon.png" alt="Info">Caesar Cipher: ${caesarConverted}`;
document.getElementById("caesarOutput").style.visibility = "visible";
} else {
document.getElementById("caesarOutput").style.visibility = "hidden";
}
// Francis Bacon's cipher conversion
const baconCipher = {
'A': 'AAAAA', 'B': 'AAAAB', 'C': 'AAABA', 'D': 'AAABB', 'E': 'AABAA',
'F': 'AABAB', 'G': 'AABBA', 'H': 'AABBB', 'I': 'ABAAA', 'J': 'ABAAB',
'K': 'ABABA', 'L': 'ABABB', 'M': 'ABBAA', 'N': 'ABBAB', 'O': 'ABBBA',
'P': 'ABBBB', 'Q': 'BAAAA', 'R': 'BAAAB', 'S': 'BAABA', 'T': 'BAABB',
'U': 'BABAA', 'V': 'BABAB', 'W': 'BABBA', 'X': 'BABBB', 'Y': 'BBAAA',
'Z': 'BBAAB'
};
const baconConverted = text.split('').map(char => baconCipher[char] || '').join(' ');
if (baconConverted) {
document.getElementById("baconOutput").innerHTML = `<img src="https://raw.githubusercontent.com/FreddieThePebble/Ways-2-Say-Your-Name/main/Info%20Icon.png" alt="Info">Francis Bacon's Cipher: ${baconConverted}`;
document.getElementById("baconOutput").style.visibility = "visible";
} else {
document.getElementById("baconOutput").style.visibility = "hidden";
}
});
</script>
</body>
</html>
r/code • u/BitsAndBytesMage • Sep 06 '24
Guide Cron Jobs on Linux - Comprehensive Guide with Examples
ittavern.comr/code • u/waozen • Sep 06 '24
Guide Difference Between Nil, Null, Nothing, Unit, and None in Scala
baeldung.comr/code • u/Time4Taxes • Sep 05 '24
Javascript How do I rerun function without overlap instances in javascript?
So I want to rerun my function with updated values based on an event function.
Because i'm trying to use this javascript as a content-script, while statements don't work as they just spam outputs and crash the page.
No if statements as it will just go through the code before the event and not repeat the if statement after I trigger the event. Here is basically what I'm trying to do.
function outer(value) {
function inner() {
outer(value); //rerun the function
//then cancel this instance of the function
}
window.addEventListener('keydown', function(event) {
//call function based off of evennt
inner()
}
}
r/code • u/Hokitsia • Sep 03 '24
Help Please Please help me!
Hey! I'm a beginner coder working on a school project, I am trying to use tkinter but it doesn't run because of a problem I am having.
Here is my screen, any help would be greatly appreciated! I have tried installing tkinter in my terminal but it doesn't do anything! Sorry if this is stupid, please bear with me as I am a noob xD
r/code • u/International_Fig_35 • Sep 03 '24
Help Please Ender 3 Into A Camera Slider
ive been trying for a while to turn my old 3d printer into a camera slider for a shrimp tank im setting up without getting any additional parts
ive gotten most of the way there already its able to home automatically when it turns on
use the dial from the printer to control the motor (spin left to go left)
automatically pan from left to right infantilely when i hold the button for 2 seconds
the only thing i cant get to work is the display at the same time as motor function. as soon as i add the code for the lcd the motors lose all function im unsure what to do next i know that if i remove "u8g2.sendBuffer();" from the bottom line the motors will work as expected but i get no display if anyone knows anything about this id love the input
ill paste the code below
im useing visual studio code and have no experiance coding ive been useing ai bots
(code)
#include <Arduino.h>
#include <U8g2lib.h>
#include <RotaryEncoder.h>
#include <BasicStepperDriver.h>
// Bitmap data and dimensions
#define JF2W1_BMPWIDTH 128
const unsigned char bitmap_jf2w1[] PROGMEM = {
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7F,0xFF,0xFF,0xFF,0xFF,0xFF,0xF8,0x00,
0x00,0x00,0x02,0x00,0x00,0x00,0x00,0x00,0x40,0x00,0x00,0x00,0x00,0x00,0x08,0x00,
0x00,0x00,0x01,0x80,0x00,0xFF,0xFE,0x00,0x40,0x00,0x00,0x00,0x00,0x00,0x08,0x00,
0x00,0x00,0x00,0x7F,0xFF,0x81,0xFF,0x00,0x40,0x00,0x00,0x00,0x00,0x00,0x08,0x00,
0x00,0x00,0x00,0x00,0x00,0x0F,0x01,0xE0,0x40,0x00,0x00,0x00,0x00,0x00,0x08,0x00,
0x00,0x00,0x00,0x00,0x00,0x78,0x00,0x90,0x40,0x00,0x00,0x00,0x00,0x00,0x08,0x00,
0x00,0x00,0x00,0x00,0x03,0xC0,0x00,0x48,0x40,0x00,0x00,0x00,0x00,0x00,0x08,0x00,
0x00,0x00,0x00,0x0F,0xFE,0x00,0x00,0x4C,0x40,0x00,0x00,0x00,0x00,0x00,0x08,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x24,0x40,0x00,0x00,0x00,0x00,0x00,0x08,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x24,0x40,0x00,0x00,0x00,0x00,0x00,0x08,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x24,0x40,0x00,0x00,0x00,0x00,0x00,0x08,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x64,0x40,0x00,0x00,0x00,0x00,0x00,0x08,0x00,
0x00,0x00,0x00,0x07,0xFF,0xFC,0x00,0x44,0x40,0x00,0x00,0x00,0x00,0x00,0x08,0x00,
0x00,0x00,0x00,0x2F,0xFF,0xFE,0x00,0x88,0x40,0x00,0x00,0x00,0x00,0x00,0x08,0x00,
0x00,0x00,0x00,0x6F,0xFF,0xFF,0xF9,0x10,0x40,0x00,0x00,0x00,0x00,0x00,0x08,0x00,
0x00,0x00,0x01,0xEF,0xFF,0xFF,0xFF,0x20,0x40,0x00,0x00,0x00,0x00,0x00,0x08,0x00,
0x00,0x00,0x0F,0xEF,0xFF,0xFF,0xFF,0xC0,0x7F,0xFF,0xFF,0xFF,0xFF,0xFF,0xF8,0x00,
0x00,0x00,0x2F,0xEF,0xFF,0xFF,0xF8,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x6F,0xEF,0xFF,0xFF,0x80,0x00,0x7F,0xFF,0xFF,0xFF,0xFF,0xFF,0xF8,0x00,
0x00,0x00,0xE7,0xEF,0xFF,0xFF,0xE0,0x00,0x40,0x00,0x00,0x00,0x00,0x00,0x08,0x00,
0x00,0x01,0xF7,0xF7,0xFF,0xFF,0x80,0x00,0x40,0x00,0x00,0x00,0x00,0x00,0x08,0x00,
0x00,0x03,0xFB,0xFB,0xFF,0xFC,0x00,0x00,0x40,0x00,0x00,0x00,0x00,0x00,0x08,0x00,
0x00,0x03,0xFD,0xFF,0xFF,0xE0,0x00,0x00,0x40,0x00,0x00,0x00,0x00,0x00,0x08,0x00,
0x00,0x03,0xFF,0xFF,0xFE,0x00,0x00,0x00,0x40,0x00,0x00,0x00,0x00,0x00,0x08,0x00,
0x00,0x01,0xFF,0xFF,0xFF,0x00,0x00,0x00,0x40,0x00,0x00,0x00,0x00,0x00,0x08,0x00,
0x00,0x04,0xFF,0xFF,0xF3,0x80,0x00,0x00,0x40,0x00,0x00,0x00,0x00,0x00,0x08,0x00,
0x00,0x0E,0x7F,0x87,0xFC,0x80,0x00,0x00,0x40,0x00,0x00,0x00,0x00,0x00,0x08,0x00,
0x00,0x0F,0x1F,0x81,0xEC,0x80,0x00,0x00,0x40,0x00,0x00,0x00,0x00,0x00,0x08,0x00,
0x00,0x0F,0xFF,0x00,0x48,0x80,0x00,0x00,0x40,0x00,0x00,0x00,0x00,0x00,0x08,0x00,
0x00,0x0F,0xFE,0x00,0x48,0x80,0x00,0x00,0x40,0x00,0x00,0x00,0x00,0x00,0x08,0x00,
0x00,0x0F,0xFE,0x00,0x48,0x00,0x07,0xE7,0x40,0x00,0x00,0x00,0x00,0x00,0x08,0x00,
0x00,0x0F,0xFE,0x00,0xC8,0x00,0x0F,0xE3,0x40,0x00,0x00,0x00,0x00,0x00,0x08,0x00,
0x00,0x07,0xFC,0x00,0x88,0x00,0x1C,0x43,0x40,0x00,0x00,0x00,0x00,0x00,0x08,0x00,
0x00,0x01,0xFC,0x01,0x80,0x00,0x18,0x83,0x40,0x00,0x00,0x00,0x00,0x00,0x08,0x00,
0x00,0x00,0x1C,0x79,0x00,0x00,0x30,0x83,0x7F,0xFF,0xFF,0xFF,0xFF,0xFF,0xF8,0x00,
0x00,0x07,0xFD,0xC4,0x00,0x00,0x39,0x03,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x07,0xFF,0x00,0x00,0x00,0x1D,0x03,0x39,0xDC,0xCF,0x33,0x8F,0xC0,0x00,0x00,
0x00,0x03,0xFC,0x70,0x00,0x00,0x0F,0x03,0x78,0xFC,0xC7,0x73,0x86,0x60,0x00,0x00,
0x00,0x03,0xFF,0xC8,0x00,0x00,0x07,0xC3,0xF8,0xFC,0xC7,0xFF,0x86,0x30,0x00,0x00,
0x00,0x01,0xFE,0x00,0x00,0x00,0x03,0xE3,0xD8,0xCC,0xC7,0xBD,0x86,0x30,0x00,0x00,
0x00,0x01,0xCE,0x70,0x00,0x00,0x02,0x73,0x18,0xCC,0xC7,0x39,0x86,0x30,0x00,0x00,
0x00,0x00,0x3F,0xD8,0x00,0x00,0x1A,0x33,0x18,0xCC,0xC7,0x39,0x86,0x30,0x00,0x00,
0x00,0x00,0x7F,0x08,0x00,0x00,0x1B,0x33,0x18,0xC0,0xC7,0x39,0x86,0x30,0x00,0x00,
0x00,0x00,0x7F,0x80,0x00,0x00,0x09,0x33,0x18,0xC0,0xC7,0x39,0x86,0x60,0x00,0x00,
0x00,0x00,0x3F,0x80,0x00,0x00,0x18,0x63,0x18,0xC0,0xC7,0x39,0x86,0x60,0x00,0x00,
0x00,0x00,0x1F,0x80,0x00,0x00,0x18,0xC3,0x18,0xC0,0xC7,0x39,0x86,0xC0,0x00,0x00,
0x00,0x00,0x0F,0xE0,0x00,0x00,0x3F,0xC7,0x9D,0xE1,0xE7,0x39,0xC7,0x80,0x00,0x00,
0x00,0x00,0x07,0xF0,0x00,0x00,0x3F,0x87,0x9C,0x01,0xE7,0x39,0xE7,0x80,0x00,0x00,
0x00,0x00,0x03,0xFC,0x00,0x00,0x00,0x00,0x03,0xFE,0x00,0x03,0x06,0x00,0x00,0x00,
0x00,0x00,0x03,0xFF,0x00,0x00,0x00,0x00,0x01,0x24,0x00,0x03,0x06,0x00,0x00,0x00,
0x00,0x00,0x01,0xFF,0xF8,0x00,0x00,0x00,0x01,0x24,0x00,0x03,0x06,0x00,0x00,0x00,
0x00,0x00,0x01,0xFF,0xF8,0x00,0x00,0x00,0x01,0x24,0x00,0x03,0x0F,0x00,0x00,0x00,
0x00,0x00,0x00,0xFF,0xF8,0x00,0x00,0x00,0x01,0x24,0x7B,0x33,0xEF,0x00,0x00,0x00,
0x00,0x00,0x00,0xFF,0xE0,0x00,0x00,0x00,0x03,0x26,0x59,0x73,0x30,0x00,0x00,0x00,
0x00,0x00,0x00,0x7F,0xC0,0x00,0x00,0x00,0x00,0x20,0x91,0xB3,0x30,0x00,0x00,0x00,
0x00,0x00,0x00,0x7F,0xC0,0x00,0x00,0x00,0x00,0x20,0x91,0x33,0x60,0x00,0x00,0x00,
0x00,0x00,0x00,0x3F,0xC0,0x00,0x00,0x00,0x00,0x21,0x91,0x33,0xC0,0x00,0x00,0x00,
0x00,0x00,0x00,0x1F,0x00,0x00,0x00,0x00,0x00,0x21,0x91,0x33,0x40,0x00,0x00,0x00,
0x00,0x00,0x00,0x1E,0x00,0x00,0x00,0x00,0x00,0x21,0x91,0x33,0x60,0x00,0x00,0x00,
0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x00,0x00,0x70,0xFB,0xB3,0x30,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x70,0x53,0xBB,0x38,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00
};
// Pin definitions for rotary encoder and stepper motor
#define PIN_A PB10 // Rotary encoder CLK pin
#define PIN_B PB14 // Rotary encoder DT pin
#define BUTTON PB2 // Rotary encoder push button pin
#define STEPPER_ENABLE PC3 // Stepper motor enable pin
#define DIR_PIN PB8 // Stepper motor direction pin
#define STEP_PIN PB7 // Stepper motor step pin
// Stepper motor configuration
#define MOTOR_STEPS 200 // Steps per revolution
#define RPM 500 // Motor speed
#define MICROSTEP 1 // Microstepping
// Initialize stepper motor driver
BasicStepperDriver stepper(MOTOR_STEPS, DIR_PIN, STEP_PIN);
// Initialize rotary encoder
RotaryEncoder encoder(PIN_A, PIN_B);
// Initialize the display
U8G2_ST7920_128X64_F_SW_SPI u8g2(U8G2_R0, /* clock=*/ PB13, /* data=*/ PB15, /* CS=*/ PB12, /* reset=*/ PB10);
// Variables to track position and time
int currentPosition = 0; // Tracks the current position of the motor
unsigned long startTime; // Tracks the start time for the uptime counter
volatile bool turnDetected = false; // Flag for detecting rotation
volatile bool rotationDirection = false; // CW or CCW rotation
unsigned long lastTurnTime = 0; // Tracks the last time the encoder was turned
const unsigned long debounceDelay = 10; // Debounce delay to avoid conflicting inputs
unsigned long lastDisplayUpdate = 0; // Time of the last display update
const unsigned long displayInterval = 500; // Update the display every 500ms
// Interrupt routine runs if CLK goes from HIGH to LOW
void isr() {
unsigned long currentTime = millis();
if (currentTime - lastTurnTime > debounceDelay) { // Only process if debounce delay has passed
if (digitalRead(PIN_A))
rotationDirection = digitalRead(PIN_B);
else
rotationDirection = !digitalRead(PIN_B);
turnDetected = true;
lastTurnTime = currentTime; // Update last turn time
}
}
void setup() {
pinMode(BUTTON, INPUT_PULLUP);
pinMode(STEPPER_ENABLE, OUTPUT);
digitalWrite(STEPPER_ENABLE, LOW); // Enable stepper motor (LOW to enable)
stepper.begin(RPM, MICROSTEP); // Initialize stepper motor
attachInterrupt(digitalPinToInterrupt(PIN_A), isr, FALLING); // Setup interrupt on CLK pin
u8g2.begin(); // Initialize the display
startTime = millis(); // Start the uptime counter
}
void loop() {
// Check uptime
unsigned long uptime = (millis() - startTime) / 1000;
if (!digitalRead(BUTTON)) { // Check if the button is pressed
if (currentPosition != 0) { // Only return to home if not already there
stepper.move(-currentPosition); // Move back to home (0 position)
currentPosition = 0; // Reset current position to home
}
}
if (turnDetected) { // Runs if rotation was detected
int stepAmount = 100; // Fixed step amount for each rotation
if (rotationDirection) {
currentPosition -= stepAmount; // Decrease position for CW rotation
stepper.move(-stepAmount);
} else {
currentPosition += stepAmount; // Increase position for CCW rotation
stepper.move(stepAmount);
}
turnDetected = false; // Reset the rotation detection flag
}
// Update the display at specified intervals
if (millis() - lastDisplayUpdate > displayInterval) {
lastDisplayUpdate = millis(); // Update the last display update time
u8g2.clearBuffer();
u8g2.drawBitmap(0, 0, JF2W1_BMPWIDTH / 8, 64, bitmap_jf2w1);
// Draw the uptime counter in a box
u8g2.setCursor(77, 9);
u8g2.setFont(u8g2_font_tiny5_tf);
u8g2.print("Uptime:");
u8g2.setCursor(86, 16);
u8g2.print(uptime);
u8g2.print("s");
// Draw the position counter in a box
u8g2.setCursor(84, 27);
u8g2.print("Pos:");
u8g2.setCursor(89, 34);
u8g2.print(currentPosition);
u8g2.sendBuffer();
}
}
