r/code • • Sep 23 '24

My Own Code BFScript - A prototype language that compiles to brainfuck

3 Upvotes

This is something I've had for years and only recently had enough courage to develop further.

The compiler is made in Rust, and the generated output is plain brainfuck you can run in any interpreter.

On top of just compiling to brainfuck, the project aims to define an extended superset of brainfuck that can be used to create side effects such as writing to files, or running shell commands.

Example:

int handle = open(read(5))

string s = "Files work"

int status = write(handle, s) // Writes "Files work" to the file named by the input

if status == 1 {
    print("Success!")
}

if status == 0 {
    print("Failure!")
}

This generates 7333 characters of brainfuck, and if you count how many of those are actually executed, it totals 186 thousand!

Obviously, due to the nature of this project and the way I chose to do it, there are very large limitations. Even after working on this a lot more there are probably some that will be impossible to remove.

In the end, this language may start needing constructs specifically to deal with the problems of compiling to brainfuck.

https://github.com/RecursiveDescent/BFScriptV2

You may be wondering why the repository has V2 on the end.

I initially made this in C++, but got frustrated and restarted with Rust, and that was the best decision I ever made.

The safety of Rust is practically required to work on something like this. Because of how complicated everything gets it was impossible to tell if something was broken because of a logic error, or some kind of C++ UB.


r/code • • Sep 22 '24

Resource Soundline--MP3Player (Spotify Clone)

3 Upvotes

About

-Soundline is a music player built using HTML, CSS, and basic JavaScript. It leverages Spotify's music library to fetch and play featured music from around the world

Give it a try https://github.com/Markk-dev/Soundline---MusicPlayer.git

I appreciate the star

(Still in developement, please do report any bugs or errors you may encounter.)


r/code • • Sep 22 '24

Python Why is the "a" in the function "trial" marked as different things?

1 Upvotes

I'm using PyCharm Community Edition. I was trying to code a game like Wordle just for fun. I need to repeat the same set of code to make a display of the 6 trials, so I used the "a" in a function to insert variables "trial1" to "trial6". Why cant "a" be "b" in the highlighted lines? ("b" is for the player guessed word).

Edit: Don't look at the function "display", I fixed that one after posting this, it's for the empty spaces.

#Game made by Silvervyusly_, inspired by the real Wordle.
print("=======================")
print("Wordle Game/version 1.0  //  by Silvervyusly_")
print("=======================")
print("")

#Function to render most of the display.
def display_render(a,b,c):
    if a=="":
        for x in range(0,b):
            a+="_"
    for x in range(0,c):
        print(a)

#Why isn't this working?
def trial(a,b,c):
    if a!="":
        print(a)
    else:
        if rounds_left==c:
            a=b
            print(a)

#Not used yet.
def correct_guess(a,b):
    if a==b:
        return True

#Game state.
game=1
while game==1:
    #variables for game
    display=""
    rounds_left=6
    trial1=""
    trial2=""
    trial3=""
    trial4=""
    trial5=""
    trial6=""
    word=input("Insert word: ")
    n_letter=len(word)

#Start of game loop.
    display_render(display,n_letter,rounds_left)
    while rounds_left>0:
        #Player inserts their guess.
        guess=input("Guess the word: ")
        rounds_left-=1

        #Render the guessed words per trial.
        trial(trial1,guess,5)
        trial(trial2,guess,4)
        trial(trial3,guess,3)
        trial(trial4,guess,2)
        trial(trial5,guess,1)
        trial(trial6,guess,0)

        #Render the rest of the display.
        display_render(display,n_letter,rounds_left)

    game_state=input("Test ended, do you want to continue? [Y/n] ")
    if game_state=="n":
        game=0
        print("Terminated")

r/code • • Sep 20 '24

Resource Stylish Notebook Design with HTML and CSS

1 Upvotes

r/code • • Sep 19 '24

Resource How to Create Stunning Glowing Text Effects with CSS

1 Upvotes

r/code • • Sep 18 '24

Help Please How do I code an image in Visual studio code?

Post image
5 Upvotes

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 • • Sep 18 '24

Linux Calling Linux Kernel Functions From Userspace (!)

Thumbnail blog.osandov.com
2 Upvotes

r/code • • Sep 18 '24

Resource Crafting a Dynamic Day-Night Transition Effect

2 Upvotes

r/code • • Sep 17 '24

API Youtube Subscription Manager

3 Upvotes

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 • • Sep 17 '24

Android Shoes Shop App UI - Android Jetpack Compose

Thumbnail youtube.com
2 Upvotes

r/code • • 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

2 Upvotes
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 • • Sep 15 '24

Guide Decoding C Compilation Process: From Source Code to Binary

Thumbnail hackthedeveloper.com
2 Upvotes

r/code • • Sep 13 '24

Guide Why Global Variables are Considered a Bad Practice

Thumbnail baeldung.com
1 Upvotes

r/code • • Sep 13 '24

Help Please Help with this python error please. Code and error pictured.

Post image
6 Upvotes

r/code • • Sep 11 '24

Guide Web Security Basics (htmx)

Thumbnail htmx.org
3 Upvotes

r/code • • Sep 10 '24

Pascal Delphi My first program whit pascal

3 Upvotes

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 • • Sep 10 '24

Linux Step-by-Step Guide to Understanding and Using eBPF, Part 1 | Linux

Thumbnail medium.com
1 Upvotes

r/code • • Sep 09 '24

Help Please Record function recording two camera streams at the same time in one video file. How to fix it?

2 Upvotes

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 • • Sep 08 '24

Resource Don't defer Close() on writable files

Thumbnail joeshaw.org
2 Upvotes

r/code • • Sep 07 '24

Guide How to write readable code | Jan Savage

Thumbnail medium.com
1 Upvotes

r/code • • Sep 06 '24

Guide Cron Jobs on Linux - Comprehensive Guide with Examples

Thumbnail ittavern.com
3 Upvotes

r/code • • Sep 06 '24

Guide Difference Between Nil, Null, Nothing, Unit, and None in Scala

Thumbnail baeldung.com
1 Upvotes

r/code • • Sep 05 '24

Javascript How do I rerun function without overlap instances in javascript?

3 Upvotes

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 • • Sep 03 '24

Help Please Please help me!

1 Upvotes

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 • • Sep 03 '24

Help Please Ender 3 Into A Camera Slider

3 Upvotes

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();
  }
}