<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: medmor</title>
    <description>The latest articles on Forem by medmor (@medmor_65).</description>
    <link>https://forem.com/medmor_65</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1066727%2Fd322a144-4466-4ac5-8079-b7b5b269a07b.jpeg</url>
      <title>Forem: medmor</title>
      <link>https://forem.com/medmor_65</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/medmor_65"/>
    <language>en</language>
    <item>
      <title>A day at the beach</title>
      <dc:creator>medmor</dc:creator>
      <pubDate>Wed, 05 Jun 2024 18:23:57 +0000</pubDate>
      <link>https://forem.com/medmor_65/a-day-at-the-beach-2k41</link>
      <guid>https://forem.com/medmor_65/a-day-at-the-beach-2k41</guid>
      <description>&lt;p&gt;&lt;em&gt;This is a submission for &lt;a href="https://dev.to/challenges/frontend-2024-05-29"&gt;Frontend Challenge v24.04.17&lt;/a&gt;, CSS Art: June.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Inspiration
&lt;/h2&gt;

&lt;p&gt;To me, June marks the start of summer, bringing to mind just one thing: a perfect day at the beach.&lt;/p&gt;

&lt;h2&gt;
  
  
  Demo
&lt;/h2&gt;

&lt;p&gt;My drawing using just HTML and CSS:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F13cib5tyep2lkddkv9mc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F13cib5tyep2lkddkv9mc.png" alt="A day at the beach" width="800" height="368"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This is a link to the project on &lt;a href="https://stackblitz.com/edit/stackblitz-starters-jbmfav?file=index.html,styles.css"&gt;stackblitz&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Journey
&lt;/h2&gt;

&lt;p&gt;In this project, I gained a deeper understanding of gradients and their impressive effects, as well as box shadows and basic animations.&lt;/p&gt;

</description>
      <category>frontendchallenge</category>
      <category>devchallenge</category>
      <category>css</category>
    </item>
    <item>
      <title>Basic drag and drop implementation for nextjs (react)</title>
      <dc:creator>medmor</dc:creator>
      <pubDate>Tue, 15 Aug 2023 20:00:02 +0000</pubDate>
      <link>https://forem.com/medmor_65/basic-drag-and-drop-implementation-for-nextjs-react-3a75</link>
      <guid>https://forem.com/medmor_65/basic-drag-and-drop-implementation-for-nextjs-react-3a75</guid>
      <description>&lt;p&gt;There are some very good packages that implement drag and drop for react, but they are very complicated for me. They use state management libraries like &lt;code&gt;redux&lt;/code&gt;, and always needed lot of setups to get things right.&lt;/p&gt;

&lt;p&gt;If you just want to change a cursor style, you need to dive in the package codebase and try to understand how it works, and you may not succeed, like &lt;a href="https://github.com/react-dnd/react-dnd/issues/3488"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Why all that? aren't drag and drop just html events like &lt;code&gt;onclick&lt;/code&gt; or &lt;code&gt;onchange&lt;/code&gt;...&lt;/p&gt;

&lt;p&gt;Yes the are, and for simple use cases, the implementation is simpler than using a third-party solution.&lt;/p&gt;

&lt;p&gt;In this article I will show a simple example for drag and drop functionalities.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://stackblitz.com/edit/vercel-next-js-7116vz?file=README.md"&gt;Here &lt;/a&gt;is the example on StackBlitz.&lt;/p&gt;

&lt;h2&gt;
  
  
  Three events needed
&lt;/h2&gt;

&lt;p&gt;To implement this simple example, we need to listen to &lt;code&gt;dragstart&lt;/code&gt; event on the &lt;code&gt;draggable&lt;/code&gt; element, and listen to &lt;code&gt;dragover&lt;/code&gt; and &lt;code&gt;drop&lt;/code&gt; events on the container or &lt;code&gt;droppable&lt;/code&gt; element.&lt;br&gt;
For that we can create two components:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;code&gt;Draggable&lt;/code&gt; component: Here we can use a div that has &lt;code&gt;draggable&lt;/code&gt; attribute and listen to &lt;code&gt;dragstart&lt;/code&gt; event. The implementation could be something like this:
&lt;/li&gt;
&lt;/ol&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { DragEvent } from 'react';

interface DraggableProps {
  children?: React.ReactNode;
  className?: string;
  onDragStart?: (e: DragEvent&amp;lt;HTMLElement&amp;gt;) =&amp;gt; void;
}
export default function Draggable(props: DraggableProps) {
  const onDragStart = (e: DragEvent&amp;lt;HTMLElement&amp;gt;) =&amp;gt; {
    if (props.onDragStart) {
      props.onDragStart(e);
    }
  };
  return (
    &amp;lt;div className={props.className} onDragStart={onDragStart} draggable&amp;gt;
      {props.children}
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;ol&gt;
&lt;li&gt;
&lt;code&gt;Droppable&lt;/code&gt; component: Here also we can use a div and listen to &lt;code&gt;dragover&lt;/code&gt; and &lt;code&gt;drop&lt;/code&gt; events. The implementation could be something like this:
&lt;/li&gt;
&lt;/ol&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { DragEvent } from 'react';

interface DroppableProps {
  children?: React.ReactNode;
  className?: string;
  onDrop?: (e: DragEvent&amp;lt;HTMLElement&amp;gt;) =&amp;gt; void;
  onDragOver?: (e: DragEvent&amp;lt;HTMLElement&amp;gt;) =&amp;gt; void;
}
export default function Droppable(props: DroppableProps) {
  const onDrop = (e: DragEvent&amp;lt;HTMLElement&amp;gt;) =&amp;gt; {
    e.preventDefault();
    if (props.onDrop) {
      props.onDrop(e);
    }
  };
  const onDragOver = (e: DragEvent&amp;lt;HTMLElement&amp;gt;) =&amp;gt; {
    e.preventDefault();
    if (props.onDragOver) {
      props.onDragOver(e);
    }
  };
  return (
    &amp;lt;div className={props.className} onDrop={onDrop} onDragOver={onDragOver}&amp;gt;
      {props.children}
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Note that we can pass callbacks to those components. Those callback will be used by the parent components to manage their state based on those events.&lt;/p&gt;
&lt;h2&gt;
  
  
  Manage the state in the parent component
&lt;/h2&gt;

&lt;p&gt;In this example, the parent component state consiste of:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Tho containers: one for the even numbers and the other for the odd ones.
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; const [containers, setContainers] = useState&amp;lt;
    { name: string; numbers: number[] }[]
  &amp;gt;([
    { name: 'odd', numbers: [] },
    { name: 'even', numbers: [] },
  ]);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;ul&gt;
&lt;li&gt;&lt;p&gt;An array of items: just array of integers.&lt;br&gt;
&lt;code&gt;const [items, setItems] = useState([1, 2, 3, 4, 5, 6, 7, 8, 9]);&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The current dragged item:&lt;br&gt;
&lt;code&gt;const [currentItem, setCurrentItem] = useState&amp;lt;number&amp;gt;();&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;To manage the state we use an &lt;code&gt;onDragStart&lt;/code&gt; callback to set the currentItem.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  const onDragStart = (item: number) =&amp;gt; {
    setCurrentItem(item);
  };
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And an &lt;code&gt;onDrop&lt;/code&gt; callback to accepte the number or refuse it on each container.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  const onDrop = (index: number) =&amp;gt; {
    if (containers[index].name == 'even') {
      if (currentItem % 2 == 0) {
        console.log('accept even number');
        setItems((items) =&amp;gt; items.filter((item) =&amp;gt; item != currentItem));
        containers[index].numbers.push(currentItem);
        setContainers((containers) =&amp;gt; containers);
      } else {
        console.log('refuse odd number');
      }
    } else {
      if (currentItem % 2 != 0) {
        console.log('accept odd number');
        setItems((items) =&amp;gt; items.filter((item) =&amp;gt; item != currentItem));
        containers[index].numbers.push(currentItem);
        setContainers((containers) =&amp;gt; containers);
      } else {
        console.log('refuse even number');
      }
    }
  };
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The full example is &lt;a href="https://stackblitz.com/edit/vercel-next-js-7116vz"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Support touch devices
&lt;/h2&gt;

&lt;p&gt;Just add a polyfill that enables HTML5 drag drop support on mobile (touch) devices. like &lt;a href="https://github.com/Bernardo-Castilho/dragdroptouch"&gt;this &lt;/a&gt;one.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;      {(navigator.maxTouchPoints ||
        'ontouchstart' in document.documentElement) &amp;amp;&amp;amp; (
        &amp;lt;Script src="/DragDropTouch.js" /&amp;gt;
      )}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>javascript</category>
      <category>beginners</category>
      <category>nextjs</category>
      <category>react</category>
    </item>
    <item>
      <title>Control rc car using raspberry pi (Part 5 : Wire up raspberry pi...)</title>
      <dc:creator>medmor</dc:creator>
      <pubDate>Sun, 13 Aug 2023 12:37:52 +0000</pubDate>
      <link>https://forem.com/medmor_65/control-rc-car-using-raspberry-pi-part-5-wire-up-raspberry-pi-5a65</link>
      <guid>https://forem.com/medmor_65/control-rc-car-using-raspberry-pi-part-5-wire-up-raspberry-pi-5a65</guid>
      <description>&lt;p&gt;The next image show how we can wire up the raspberry pi to the motor driver to control the two motors of the rc car.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--GWR0bal2--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8f8ijz4gxuaqam3hh0gc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--GWR0bal2--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8f8ijz4gxuaqam3hh0gc.png" alt="Wiring the car to the raspberry py" width="800" height="695"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I did my best, but I know it's a messy drawing.&lt;/p&gt;

&lt;h3&gt;
  
  
  Change the &lt;code&gt;server.py&lt;/code&gt; to control the car
&lt;/h3&gt;

&lt;p&gt;You can find the project at github &lt;a href="https://github.com/medmor/carProjectServer/tree/main"&gt;here&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In the server script, we will use a &lt;code&gt;Car&lt;/code&gt; class to wrap all the needed functionalities to control the car.&lt;br&gt;
For example: &lt;code&gt;car.runForward()&lt;/code&gt;, &lt;code&gt;car.setSpeed()&lt;/code&gt;, &lt;code&gt;car.turnLeft()&lt;/code&gt; ...&lt;/p&gt;

&lt;p&gt;The final server script look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from bottle import post, route, static_file, run
from car import Motor, Car

car = Car(Motor(23, 24), Motor(18, 15, 14))

@route("/")
def index():
    return static_file("index.html", root="./")

@post("/right")
def right():
    car.turnRight()

@post("/left")
def left():
    car.turnLeft()

@post("/center")
def center():
    car.resetDir()

@post("/forward/&amp;lt;amount&amp;gt;")
def forwardWithSpeed(amount):
    car.setSpeed(int(amount))
    car.runForward()

@post("/backward/&amp;lt;amount&amp;gt;")
def backwardWithSpeed(amount):
    car.setSpeed(int(amount))
    car.runBackward()

@post("/speed/&amp;lt;amount&amp;gt;")
def speed(amount):
    car.setSpeed(int(amount))

@post("/stop")
def stop():
    car.stop()

@post("/siren")
def siren():
    car.siren()


run(host="0.0.0.0", port=8080, debug=True)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The car needs tow &lt;code&gt;Motor&lt;/code&gt;s instances passed as parameters.&lt;br&gt;
The &lt;code&gt;Motor&lt;/code&gt; class receive 2 or 3 numbers. These numbers are raspberry pi pins out used to control the motor. For more information about the pins, you can see &lt;a href="https://www.raspberrypi.com/documentation/computers/raspberry-pi.html"&gt;here&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I think if I try to explain how the GPIOs are set and used to control the motor and change the speed, the article will be too long. But I think also that by just reading the code and little search, you can understand how it works.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;Car&lt;/code&gt; and The &lt;code&gt;Motor&lt;/code&gt; classes are defined like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import RPi.GPIO as GPIO
import pygame

GPIO.setmode(GPIO.BCM)

class Motor:
    def __init__(self, io1: int, io2: int, io3=-1) -&amp;gt; None:
        self.io1 = io1
        self.io2 = io2
        GPIO.setup(io1, GPIO.OUT)
        GPIO.setup(io2, GPIO.OUT)
        if io3 &amp;gt; 0:
            GPIO.setup(io3, GPIO.OUT)
            self.io3 = GPIO.PWM(io3, 1000)
            self.io3.start(60)

    def forward(self):
        GPIO.output(self.io1, GPIO.HIGH)
        GPIO.output(self.io2, GPIO.LOW)

    def backward(self):
        GPIO.output(self.io1, GPIO.LOW)
        GPIO.output(self.io2, GPIO.HIGH)

    def stop(self):
        GPIO.output(self.io1, GPIO.LOW)
        GPIO.output(self.io2, GPIO.LOW)

    def setSpedd(self, speed: int):
        self.io3.ChangeDutyCycle(speed)


class Car:

    def __init__(self, frontMotor: Motor, backMotor: Motor) -&amp;gt; None:
        self.frontMotor = frontMotor
        self.backMotor = backMotor
        pygame.mixer.init()
        pygame.mixer.music.load("siren.mp3")
        pygame.mixer.music.set_volume(1.0)

    def turnRight(self):
        self.frontMotor.forward()

    def turnLeft(self):
        self.frontMotor.backward()

    def resetDir(self):
        self.frontMotor.stop()

    def runForward(self):
        self.backMotor.forward()

    def runBackward(self):
        self.backMotor.backward()

    def stop(self):
        self.backMotor.stop()

    def setSpeed(self, speed: int):
        self.backMotor.setSpedd(speed)

    def siren(self):
        if(pygame.mixer.music.get_busy()==0):
            pygame.mixer.music.play()
        else:
            pygame.mixer.music.stop()

    #to do : call this method on server stop
    def cleanup():
        GPIO.cleanup()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>beginners</category>
      <category>raspberrypi</category>
      <category>python</category>
      <category>unity3d</category>
    </item>
    <item>
      <title>Control rc car using raspberry pi (Part 4 : Build the controller)</title>
      <dc:creator>medmor</dc:creator>
      <pubDate>Thu, 10 Aug 2023 14:13:46 +0000</pubDate>
      <link>https://forem.com/medmor_65/control-rc-car-using-raspberry-pi-part-4-build-the-controller-2da5</link>
      <guid>https://forem.com/medmor_65/control-rc-car-using-raspberry-pi-part-4-build-the-controller-2da5</guid>
      <description>&lt;h2&gt;
  
  
  The controller app UI
&lt;/h2&gt;

&lt;p&gt;The UI for the app is very simple, just two buttons to run forward and backward, and a text to indicate the speed.&lt;br&gt;
To turn the car, you need to turn the phone.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fl3lni2micdqnegvvf0vc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fl3lni2micdqnegvvf0vc.png" alt="Controller UI components"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You can find the project on github &lt;a href="https://github.com/medmor/CarController.git" rel="noopener noreferrer"&gt;here&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  The controller scripts
&lt;/h2&gt;

&lt;p&gt;Learn to code using Unity is very simple, all you need is to crate a &lt;code&gt;monobehavior&lt;/code&gt; script, attach it to a &lt;code&gt;gameobject&lt;/code&gt; and you are good to go. Make things move!.&lt;/p&gt;

&lt;p&gt;There are three important parts in our app.&lt;/p&gt;
&lt;h3&gt;
  
  
  The UnityWebRequest
&lt;/h3&gt;

&lt;p&gt;We can send web requests by using the &lt;code&gt;UnityWebRequest&lt;/code&gt; class from the namespace &lt;code&gt;UnityEngine.Networking&lt;/code&gt;.&lt;br&gt;
To achieve this I created a singleton script that can be called from all other scripts that needs to send web requests. The script is like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;

public class RequestManager : MonoBehaviour
{
    [SerializeField] private string baseUrl;

    private static RequestManager instance;

    public static RequestManager Instance
    {
        get { return instance; }
        set
        {
            if (instance == null)
            {
                instance = value;
            }
        }
    }

    private void Awake()
    {
        instance = this;
    }

    public void SendRequest(string command)
    {
        StartCoroutine(Upload(command));
    }

    IEnumerator Upload(string command)
    {
        List&amp;lt;IMultipartFormSection&amp;gt; formData = new List&amp;lt;IMultipartFormSection&amp;gt;();

        UnityWebRequest request = UnityWebRequest.Post(baseUrl + command, formData);
        yield return request.SendWebRequest();

        if (request.result != UnityWebRequest.Result.Success)
        {
            Debug.Log(request.error);
        }
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Sendig Requests to run the car forward and backward
&lt;/h3&gt;

&lt;p&gt;The buttons are set to listen to the &lt;code&gt;PointerDown&lt;/code&gt; and &lt;code&gt;PointerUp&lt;/code&gt; events.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public void OnPointerDown()
    {
        isPressed = true;
    }
    public void OnPointerUp()
    {
        isPressed = false;
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;While the pointer is down the speed will increase, and after a threshold in the difference of speed we send a Request for the server.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; void Update()
    {
        if (isPressed)
        {
            if (speed &amp;lt; minSpeed)
            {
                speed = minSpeed;
            }
            speed += speedIncrement * Time.deltaTime;
            if (speed &amp;gt; 100)
            {
                speed = 100;
            }
            if (Mathf.Abs(speed - lastSpeed) &amp;gt; speedDiffrenceThreshold || speed == 100)
            {
                UpdateSpeedIndicator();
                lastSpeed = speed;
                RequestManager.Instance.SendRequest(direction + "/" + (int)speed);
            }

        }
        else if (speed &amp;gt; 0)
        {
            speed = 0;
            lastSpeed = 0;
            UpdateSpeedIndicator();
            RequestManager.Instance.SendRequest("stop"); UpdateSpeedIndicator();
        }

    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;RunController&lt;/code&gt; script is like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;using UnityEngine;
using UnityEngine.UI;

using TMPro;
public class RunController : MonoBehaviour
{
    enum Directions { forward, backward }
    [SerializeField] Directions direction;
    [SerializeField] private Image speedIndicator = default;
    [SerializeField] private float speedDiffrenceThreshold = 10;
    [SerializeField] private float speedIncrement = 5;
    [SerializeField] private float minSpeed = 50;
    [SerializeField] private TextMeshProUGUI speedText;

    private float speed = 0;
    private float lastSpeed = 0;
    private bool isPressed = false;

    void Update()
    {
        if (isPressed)
        {
            if (speed &amp;lt; minSpeed)
            {
                speed = minSpeed;
            }
            speed += speedIncrement * Time.deltaTime;
            if (speed &amp;gt; 100)
            {
                speed = 100;
            }
            if (Mathf.Abs(speed - lastSpeed) &amp;gt; speedDiffrenceThreshold || speed == 100)
            {
                UpdateSpeedIndicator();
                lastSpeed = speed;
                RequestManager.Instance.SendRequest(direction + "/" + (int)speed);
            }

        }
        else if (speed &amp;gt; 0)
        {
            speed = 0;
            lastSpeed = 0;
            UpdateSpeedIndicator();
            RequestManager.Instance.SendRequest("stop"); UpdateSpeedIndicator();
        }

    }
    public void OnPointerDown()
    {
        isPressed = true;
    }
    public void OnPointerUp()
    {
        isPressed = false;
    }
    private void UpdateSpeedIndicator()
    {
        speedText.text = ((int)speed).ToString();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Turning the car left and right
&lt;/h3&gt;

&lt;p&gt;We use the smarthphne accelerometer to turn the car right and left. Unity makes this very simple, We just need to use the built in &lt;code&gt;Input.acceleration&lt;/code&gt;.&lt;br&gt;
The &lt;code&gt;DirectionController&lt;/code&gt; script is like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;using UnityEngine;


public class DirectionController : MonoBehaviour
{
    [SerializeField] private float directionChangeThreshold = 0.15f;
    enum Directions
    {
        center, left, right
    }
    Directions direction = Directions.center;
    Directions lastSentDirection = Directions.center;
    void FixedUpdate()
    {
        if(Input.acceleration.x &amp;gt; directionChangeThreshold)
        {
            direction = Directions.right;
        }
        else if(Input.acceleration.x &amp;lt; -directionChangeThreshold)
        {
            direction = Directions.left;
        }
        else
        {
            direction=Directions.center;
        }
        if(lastSentDirection != direction)
        {
            lastSentDirection = direction;
            RequestManager.Instance.SendRequest(direction.ToString());
        }
    }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>beginners</category>
      <category>unity3d</category>
      <category>raspberrypi</category>
      <category>csharp</category>
    </item>
    <item>
      <title>Control rc car using raspberry pi (Part 3 : Run the server at startup)</title>
      <dc:creator>medmor</dc:creator>
      <pubDate>Sun, 06 Aug 2023 20:55:44 +0000</pubDate>
      <link>https://forem.com/medmor_65/control-rc-car-using-raspberry-pi-part-3-run-the-server-at-startup-3hj4</link>
      <guid>https://forem.com/medmor_65/control-rc-car-using-raspberry-pi-part-3-run-the-server-at-startup-3hj4</guid>
      <description>&lt;h2&gt;
  
  
  Configure the server to run as a service at startup
&lt;/h2&gt;

&lt;p&gt;To set up the server to run at startup using systemd, we need to create a unit file that we will name it &lt;code&gt;carServer.service&lt;/code&gt; under &lt;code&gt;/etc/systemd/system&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;This file will contain the needed configuration informations to start our server at startup. We can configure our service like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[Unit]
Description=Rc Car Server Controller
Wants=network-online.target
After=network-online.target

[Service]
ExecStart=/usr/bin/python3 /usr/local/bin/carProjectServer/server.py
User=enakr
Restart=always
WorkingDirectory=/usr/local/bin/carProjectServer

[Install]
WantedBy=multi-user.target
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here you can see that the file contains multiple sections, and the content is self-explanatory. For example:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The &lt;code&gt;ExecStart&lt;/code&gt; points to our python program that will be run when the service is started. You can change the path to match your workspace folder.&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;After=network-online.target&lt;/code&gt; and &lt;code&gt;Wants=network-online.target&lt;/code&gt; ensure that the service runs after the network is up.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Finally, we need to enable our service by running the command :&lt;br&gt;
&lt;code&gt;sudo systemctl enable rcCarServer.service&lt;/code&gt;.&lt;br&gt;
Now, when you reboot the raspberry, the server should start.&lt;br&gt;
You can check if the server is running with the command:&lt;br&gt;
&lt;code&gt;sudo systemctl status rcCarServer.service&lt;/code&gt;.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Control rc car using raspberry pi (Part 2 : The web server)</title>
      <dc:creator>medmor</dc:creator>
      <pubDate>Sun, 30 Jul 2023 23:11:53 +0000</pubDate>
      <link>https://forem.com/medmor_65/control-rc-car-using-raspberry-pi-part-2-the-web-server-129k</link>
      <guid>https://forem.com/medmor_65/control-rc-car-using-raspberry-pi-part-2-the-web-server-129k</guid>
      <description>&lt;h2&gt;
  
  
  Building the web server
&lt;/h2&gt;

&lt;p&gt;In this part, we will start building the web server that will run on raspberry pi and will receive commands to control the rc car.&lt;/p&gt;

&lt;h3&gt;
  
  
  The framework used
&lt;/h3&gt;

&lt;p&gt;We will use &lt;a href="https://bottlepy.org/docs/dev/"&gt;Bottle&lt;/a&gt; a lightweight web framework for python.&lt;br&gt;
This is the first time I use python to build a web server and it was a very positif experience.&lt;br&gt;
With Bottle.py, all you need is:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Create a file, I named it &lt;code&gt;server.py&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Create a route.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;And run the server.&lt;br&gt;
The minimal code needed to run a server is:&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from bottle import route, run

@route('/')
def index():
    return "Hello world"

run(host='localhost', port=8080)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To let other devices on the same network connect to the server, we will change the last line to &lt;code&gt;run(host='0.0.0.0', port=8080)&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Thats it, the server is running and can be accessed from other devices in the same network.&lt;/p&gt;

&lt;h3&gt;
  
  
  Create the routes
&lt;/h3&gt;

&lt;p&gt;The routes could be implemented differently, but for simplicity we will use six routes :&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Tree routes to control the front wheels: &lt;code&gt;/right&lt;/code&gt;, &lt;code&gt;/left&lt;/code&gt; and &lt;code&gt;center&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Tree routes to control the rear wheels: &lt;code&gt;/forward/&amp;lt;speed&amp;gt;&lt;/code&gt;, &lt;code&gt;backward/&amp;lt;speed&amp;gt;&lt;/code&gt; and &lt;code&gt;/stop&lt;/code&gt;. We use, in the tow first routes, a wildcard &lt;code&gt;&amp;lt;speed&amp;gt;&lt;/code&gt;, to make the routes dynamic and change the speed of the car. The speed is an int that can change from 0 to 100, I will explain how to use it in the next parts.&lt;br&gt;
The code of the server.py is :&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from bottle import post, route, run

@route("/")
def index():
    return "RC Car Server"


@route("/right")
def right():
    return "Car turning right"


@route("/left")
def left():
    return "Car turning left"


@route("/center")
def center():
    return "Car turning center"


@route("/forward/&amp;lt;speed&amp;gt;")
def forward(speed):
    return "Car running froward at speed : " + speed


@route("/backward/&amp;lt;speed&amp;gt;")
def backward(speed):
        return "Car running backward at speed : " + speed


@route("/stop")
def stop():
        return "Car stopped, the speed is : 0"

run(host="0.0.0.0", port=8080)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Thats it for the server, we will improve it in next parts&lt;/p&gt;

</description>
      <category>beginners</category>
      <category>raspberrypi</category>
      <category>python</category>
      <category>unity3d</category>
    </item>
    <item>
      <title>Control rc car using raspberry pi (Part 1 : Introduction)</title>
      <dc:creator>medmor</dc:creator>
      <pubDate>Sun, 30 Jul 2023 14:39:21 +0000</pubDate>
      <link>https://forem.com/medmor_65/control-rc-car-using-raspberry-pi-part-1-introduction-59oh</link>
      <guid>https://forem.com/medmor_65/control-rc-car-using-raspberry-pi-part-1-introduction-59oh</guid>
      <description>&lt;p&gt;This is my first post on Dev.to. I want to write about my last fun project for my kids.&lt;/p&gt;

&lt;p&gt;This project was started as learning opportunity and to reuse some old staff, and both goals have been achieved.&lt;/p&gt;

&lt;p&gt;The old staff reused in this project are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A raspberry pi 4 that I was using as a &lt;a href="https://kodi.tv/"&gt;kodi&lt;/a&gt; server.&lt;/li&gt;
&lt;li&gt;A sheep non-working rc car.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;What to learn from this project:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Build a minimal webserver using &lt;a href="https://bottlepy.org/docs/dev/"&gt;bottle.py&lt;/a&gt;, to receive commands from a smartphone.&lt;/li&gt;
&lt;li&gt;Setup the python script as service that run at startup, using systemctl.&lt;/li&gt;
&lt;li&gt;Build a minimal controller app for a smartphone, using &lt;a href="https://unity.com/products/unity-engine"&gt;Unity&lt;/a&gt;. (the app uses the smartphone accelerometer or gyroscope to control the car direction).&lt;/li&gt;
&lt;li&gt;Wire up raspberry pi gpio to a motor driver to control the two motors of the car.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;And let's go, this is the final result:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--UFfdaXQ---/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lkb8br8ilj32r22tzabo.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--UFfdaXQ---/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lkb8br8ilj32r22tzabo.gif" alt="The final result of the project" width="240" height="426"&gt;&lt;/a&gt;&lt;br&gt;
&lt;strong&gt;More details in the next parts.&lt;/strong&gt;&lt;/p&gt;

</description>
      <category>beginners</category>
      <category>raspberrypi</category>
      <category>python</category>
      <category>unity3d</category>
    </item>
  </channel>
</rss>
