<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Dan Ionescu on Medium]]></title>
        <description><![CDATA[Stories by Dan Ionescu on Medium]]></description>
        <link>https://medium.com/@ionescu.dan84?source=rss-3e5520b513d5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*VgqqKHe99Zl95pBa.jpg</url>
            <title>Stories by Dan Ionescu on Medium</title>
            <link>https://medium.com/@ionescu.dan84?source=rss-3e5520b513d5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 07:20:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ionescu.dan84/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Workday Progressbar With Google Calendar Integration]]></title>
            <link>https://medium.com/@ionescu.dan84/workday-progressbar-with-google-calendar-integration-b266aabd32a8?source=rss-3e5520b513d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/b266aabd32a8</guid>
            <category><![CDATA[google-calendar]]></category>
            <category><![CDATA[raspberry]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[electronics]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Dan Ionescu]]></dc:creator>
            <pubDate>Mon, 10 Jul 2023 08:48:08 GMT</pubDate>
            <atom:updated>2023-09-26T14:27:04.334Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fJqESJKvHOYgZhzOFh4SLw.jpeg" /></figure><p>I’m delighted to introduce you to a captivating project I recently discovered on GitHub, to which I’m now a proud contributor. The beauty of this venture lies in its simplicity and practicality. It offers a compelling way to visualize your entire workday, from sunrise to sunset, in your very own workspace.</p><p>Our primary tool for this creation is a microcontroller called Raspberry Pi Pico W. This mighty gadget teams up with Google Calendar to present your day’s events on a LED strip. In my own experience, I’ve found that it integrates seamlessly with the aesthetic of my living space furniture. The end result is not just functional, but also an aesthetically pleasing addition to my room.</p><p>What makes this even more thrilling is the project’s open-source nature. I was so drawn to the idea and execution that I didn’t hesitate to roll up my sleeves and dive in as a contributor. My inaugural contribution was adding an easy WiFi setup, making the project even more user-friendly!</p><p>I wholeheartedly encourage everyone to embrace the open-source community. If you find a project that resonates with you, don’t hesitate to contribute. It’s a wonderful way to learn, grow, and make an impact on projects that inspire you.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F2jZ6_BY2pis%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D2jZ6_BY2pis&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F2jZ6_BY2pis%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/8cfed7f223986110049e74dfc48d088d/href">https://medium.com/media/8cfed7f223986110049e74dfc48d088d/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FMDij1lKcI70%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DMDij1lKcI70&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FMDij1lKcI70%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/29cf2d649a3293820b3bb7836918552f/href">https://medium.com/media/29cf2d649a3293820b3bb7836918552f/href</a></iframe><h3>The Build Steps</h3><p>Let’s dive into the impressive capabilities of this project.</p><p>At its most basic, the LED strip acts as a progress bar, taking you from the start of the day through to its conclusion using a hardcoded configuration. In this fundamental setup, there’s no need for any integration with Google Calendar.</p><p>For a more enriched experience, an advanced configuration allows you to set up a public calendar that interacts directly with the Pi Pico. With this in place, the start and end times of your day, along with all the events, are directly fetched from Google and visually represented on your LED strip.</p><p>Here are the steps we’ll be walking through:</p><ol><li>Gathering the materials and tools: Getting everything you need in place.</li><li>Preparing the Pi Pico: Uploading the necessary code onto the microcontroller.</li><li>How Does The Code Work? Explaining the code</li><li>Configuring Google Calendar Integration: This is an advanced, optional step that allows for even more personalized display.</li><li>Wiring And Creating The Device: Setting up the hardware components.</li><li>Future Improvements and Motivation: Discussing potential enhancements and the driving force behind the project.</li></ol><h3>Step 1: Gathering the Materials and Tools</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YgX-NYhE0bfu37OWIv65KA.jpeg" /></figure><p><strong>Tools:</strong></p><p>Solderin iron</p><p>Laptop</p><p>Wire cutters</p><p>USB — C to USB — A cable for programming the Pi</p><p><strong>Materials:</strong></p><p>Raspberry Pi Pico W</p><p>5V Addressable LED strip (we used a 1 m, 144 LED, WS2812B Eco).</p><p>USB charger with USB-C cable ( &gt;= 1 A )</p><p>Aluminium led profile</p><p>Various wires</p><p>Plastic enclosure for the Pi</p><p><strong>Skils:</strong></p><p>Basic soldering skills</p><p>Experience with dev boards: installing software, uploading code, modifying files</p><p>Optional: Configuring Google cloud API</p><h3>Step 2: Preparing the Pi Pico</h3><p>In this section, we’re going to address how to update the firmware on your Raspberry Pi Pico W board, install the necessary software, and upload the code for the project.</p><ol><li>After acquiring your Raspberry Pi Pico W, your first step is to install the most recent firmware on the board. The Raspberry Pi Foundation provides an excellent guide on how to do this. All you have to do is follow the instructions <a href="https://www.raspberrypi.org/documentation/rp2040/getting-started/#getting-started-with-micropython">here</a>.</li><li>Next, you’ll need to download Thonny, an accessible tool for editing and uploading code to your board. You can download it from <a href="https://thonny.org/">here</a>. It is compatible with Linux, Windows, and Mac operating systems.</li></ol><p>With the groundwork laid, it’s time to acquire the project code from GitHub. For Linux users, I’ll provide a step-by-step guide, assuming you already have git installed on your system.</p><pre>cd ~<br>git clone https://github.com/veebch/hometime.git<br>cd hometime<br>git checkout a7f061caabb1aeede6bdeb07b33bb97bfbb6a420<br>mv config_example.py config.py</pre><p>Explanation:</p><ul><li>Navigate to the home directory.</li><li>Clone the repository locally.</li><li>Change directory to “hometime,” the cloned git repository.</li><li>Set the repository to a specific commit in time (one that I’ve tested and confirmed works). If you’re feeling adventurous, you can omit this step to try the latest version.</li><li>Rename ‘config_example’ to ‘config’. The code uploaded to the board expects to see a file named “config.py.”</li></ul><p><strong>3.</strong> Next, modify the config.py according to your requirements.</p><p>In a basic configuration, we’ll manually set the working day start/end hours. This means we’ll omit the “CALENDAR” and “APIKEY” values and ensure “GOOGLECALBOOL” is set to False. A separate step is dedicated for integrating with the Google Calendar API.</p><ul><li>Set your timezone “TIMEZONE”. The default is “Europe/Zurich”; choose one from this list.</li><li>Choose the number of LED pixels “PIXELS”. Note: if you have the default one-meter LED strip, leave the default as 144.</li><li>Set the “GPIOPIN” for controlling the LED strip.</li><li>You can also set RGB values for the bar “BARCOL”, and events “EVENTCOL”.</li><li>If you need the strip to display from right to left, set “FLIP” to True.</li><li>In the “SCHEDULE” config dictionary, change (if you like) the ‘clocking’ and ‘clockout’ values for each day.</li></ul><p>With the configuration set up, you’re ready to bring your visual workday schedule to life.</p><p><strong>4. </strong>Upload the code</p><ul><li>Plug in the Pico W into your laptop.</li><li>Check that the serial port has permissions for your current user.</li><li>In Linux, you can simply use ‘ls’, then look for something like /dev/ttyACM0 or /dev/ttyUSB0.</li></ul><pre>ls -l /dev/tty*<br>....<br>crw-rw---- 1 root dialout 166, 0 iul 8 11:44 /dev/ttyACM0<br>...</pre><ul><li>Open Thonny IDE</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MZzZTyG2zuO3mwl8GkZm1A.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XlBWtW_d-trv4WjIs7Fa0A.png" /></figure><p>If you can’t locate Raspberry Pi Pico at the bottom left of the screen, you may need to adjust the permissions for the dialout user. To do this, replace &lt;username&gt; with your current Linux logged-in username.</p><pre>sudo usermod -a -G dialout &lt;username&gt;</pre><ul><li>Within Thonny, navigate to the location where you cloned your repository.</li><li>Select ‘ap_templates’, ‘phew’, ‘config.py’, ‘main.py’ using Ctrl, then right click on the selection and choose “Upload to /”.</li><li>To start the program in debug mode, simply click on “main.py” from the “Raspberry Pi Pico” section at the bottom left (refer to the accompanying images for more detail). You should then see something similar to the following in the log:</li></ul><pre>MicroPython v1.20.0 on 2023-04-26; Raspberry Pi Pico W with RP2040<br>Type &quot;help()&quot; for more information.<br>&gt;&gt;&gt; %Run -c $EDITOR_CONTENT<br>Entering setup mode...<br>2023-07-08 12:05:52 [info   / 152kB] &gt; starting catch all dns server on port 53<br>2023-07-08 12:05:52 [info   / 149kB] &gt; starting web server on port 80<br>run for 18000</pre><ul><li>If you see this message, it indicates that the Pi has booted correctly, and it has started its own access point to which you can connect and set Wi-Fi credentials for your router. The access point name is “Pi Pico”. If you’re using your phone, you might need to disable mobile data, as this can sometimes interfere with the local Pico network (because it doesn’t provide internet; see photos for reference).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XRp-b7k-jQ3VaD8zPavkrw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WZ_92YjeppdR_C2Yp7iHuw.png" /></figure><ul><li>When you click on the Pi Pico network, it should redirect you to a browser session. If not, please navigate to “pipico.net”.</li><li>Next, set your SSID and Password in the setup browser window, then click “Save”. The Pico will reboot and attempt to connect to your Wi-Fi network.</li><li>On the serial debugger in the Thonny editor, you should see something like:</li></ul><pre>023-07-08 16:01:50 [debug  / 125kB] &gt; parsed template: ap_templates/redirect.html (took 8 ms)<br>2023-07-08 16:01:51 [info   / 123kB] &gt; POST /chat (200 OK) [133ms]<br>Saving wifi credentials...<br>2023-07-08 16:02:00 [debug  / 141kB] &gt; parsed template: ap_templates/configured.html (took 10 ms)<br>2023-07-08 16:02:00 [info   / 139kB] &gt; POST /configure (200 OK) [418ms]<br>2023-07-08 16:02:00 [debug  / 129kB] &gt; parsed template: ap_templates/redirect.html (took 9 ms)<br>2023-07-08 16:02:00 [info   / 126kB] &gt; GET /generate_204 (200 OK) [222ms]<br>2023-07-08 16:02:00 [debug  / 149kB] &gt; parsed template: ap_templates/redirect.html (took 17 ms)<br>2023-07-08 16:02:00 [info   / 147kB] &gt; GET /generate_204 (200 OK) [227ms]<br>Resetting...<br>Connection lost (device reports readiness to read but returned no data (device disconnected or multiple access on port?))</pre><pre>Use Stop/Restart to reconnect.</pre><ul><li>If you reconnect the serial port now, you should see the Pico connected to the Wi-Fi. At this stage, something like this should be displayed in the serial. Concurrently, the LED strip will initiate with a rainbow pattern before displaying the progress bar.</li></ul><pre>MicroPython v1.20.0 on 2023-04-26; Raspberry Pi Pico W with RP2040<br>Type &quot;help()&quot; for more information.<br>&gt;&gt;&gt; %Run -c $EDITOR_CONTENT<br>2023-07-08 17:24:27 [debug  / 151kB]  - got ip address<br>Connected to wifi, IP address 192.168.1.110<br>Entering application mode.<br>Connected to WiFi<br>Rainbow!<br>Turn off all LEDs<br>Grab time: https://timeapi.io/api/TimeZone/zone?timezone=Europe/Bucharest</pre><pre>setting time<br>Begin endless loop<br>Updating from Google Calendar<br>[&#39;2023-07-07T09:00:00+03:00&#39;, &#39;2023-07-07T09:15:00+03:00&#39;, &#39;2023-07-08T09:00:00+03:00&#39;, &#39;2023-07-08T09:30:00+03:00&#39;, &#39;2023-07-08T19:00:00+03:00&#39;, &#39;2023-07-08T19:30:00+03:00&#39;]<br>[&#39;2023-07-07T09:00:00+03:00&#39;, &#39;2023-07-07T09:15:00+03:00&#39;, &#39;2023-07-08T09:00:00+03:00&#39;, &#39;2023-07-08T09:30:00+03:00&#39;, &#39;2023-07-08T19:00:00+03:00&#39;, &#39;2023-07-08T19:30:00+03:00&#39;]<br>clockin: 9.0<br>True 9.0 19.5 17.41333<br>Pour yourself a cup of ambition<br>...</pre><h3>Step 3: How Does the Code Work</h3><p><strong>Main logic:</strong></p><ul><li>The try-except block determines whether there is a WiFi configuration file present.</li><li>If the file is found, it attempts to connect to WiFi using the credentials stored in the file.</li><li>If the connection is successful, it enters the application mode.</li><li>If the connection fails or an exception occurs, it enters the setup mode.</li></ul><p>In the <strong>application mode</strong> loop:</p><ul><li>The code retrieves the current time from a web API using the set_time function. It parses the response, extracts the relevant date and time components, and updates the internal RTC (Real-Time Clock) of the microcontroller.</li><li>The code determines the current day of the week using the whatday function.</li><li>If the googlecalbool flag is set to true, the code retrieves today’s appointment times from a Google Calendar using the get_today_appointment_times function. It sorts and stores the appointment times.</li><li>The code checks if the current day is a working day based on the configured schedule or the Google Calendar events. It uses the atwork function to determine if the current time falls within the working hours.</li><li>If it’s a working day, the code adjusts the NeoPixel strip to display a progress bar representing the current time within the working hours. The bar function is responsible for setting the colors of the LEDs on the strip accordingly.</li><li>The code checks if there are any Google Calendar events happening at the current time using the eventnow function. If there is an event, it sets the eventbool flag to true.</li><li>If the current time is close to the end of the working hours (within 10 seconds), the microcontroller is reset using the machine_reset function to prepare for the next day.</li><li>If the flip flag is enabled, the code flips the orientation of the progress bar on the NeoPixel strip using the flipit function.</li><li>The code periodically checks for updated Google Calendar events to keep the progress bar synchronized. It resets the check counter (googleindex) after a certain number of iterations (checkgoogleevery).</li><li>The NeoPixel strip is updated with the new LED colors, and the code waits for 1 second before the next iteration of the loop.</li></ul><p>In the <strong>setup mode</strong>:</p><ul><li>The code sets up a local access point (AP) and a web server to allow users to configure the WiFi credentials for the device.</li><li>The AP name, domain, and template paths are defined.</li><li>The code defines several routes for the web server, including an index route (ap_index), a configuration route (ap_configure), and a catch-all route (ap_catch_all).</li><li>The ap_index function renders the index HTML template for users to enter their WiFi credentials.</li><li>The ap_configure function saves the entered WiFi credentials to a file and triggers a reboot of the microcontroller to apply the new configuration.</li><li>The ap_catch_all function handles any other routes and redirects to the AP domain if necessary.</li><li>The AP is started with the defined settings, and the web server is run.</li><li>Users can connect to the device’s AP, access the provided web pages, enter their WiFi credentials, and submit them for configuration.</li><li>Once the configuration is completed, the microcontroller reboots and enters the application mode with the newly configured WiFi credentials.</li></ul><h3>Step 4: Configuring Google Calendar Integration</h3><p>The truly captivating aspect of this project is its integration with Google Calendar. This feature, however, requires additional steps and the use of a “public calendar.” Essentially, you’ll need to create a separate public calendar on a Google account. Though this means anyone can view its events, the upside is that you can remotely configure the start/end time of each day and display these events on your LED strip.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aoCP3TXQFMMoIE38ZhThmQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tTwre0yZ0xzXKKdYgsQTlg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LnMrpWIkw-945POQZ1bPyw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MujAE7hkuyUAmEpQnVTh2g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I0QRq87zu8cs7qpiBVVbIA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gx7eYF_8S-P03a40ihpdqw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UF-och28LhWhG8MCxDq18Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c83-gKLi95AKsINxHjGUDQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FSGeCCMSqMPhWWodWiXCmw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hMWlb-xBLqcipK6fKg38Ww.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nqyB7RVUzOJM-zIH6LBq8g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6OSoRpnXuEU8YrwueHtTuw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BgOFZOPqwvNSaX3U0ald1g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*du0lUuSjFwP1YqaeZ1GrjA.png" /></figure><p>Follow these steps to set it up:</p><ol><li>Log into your Google account in your browser.</li><li>Open Google Calendar: <a href="https://calendar.google.com/calendar">https://calendar.google.com/calendar</a></li><li>Click on “Other calendars,” then “Create new calendar.”</li><li>Set a name and description for your new calendar, then click “Create Calendar.”</li><li>Click on the three dots beside the calendar name on the left bar, then select “Settings and sharing.”</li><li>Check the box for “Make available to public.”</li><li>Scroll down and copy the “Calendar ID” for later use.</li><li>Open <a href="https://console.cloud.google.com/projectselector2/apis/dashboard">https://console.cloud.google.com/projectselector2/apis/dashboard</a></li><li>Click on “Create project,” set a name for the project, and click “Create.”</li><li>On the project page, search for “calendar” API, click on “Google Calendar API,” then click “Enable.”</li><li>Go to “Credentials,” select “Create Credentials,” then “API Key,” and copy this key for later use.</li><li>Return to the Google Calendar page <a href="https://calendar.google.com/calendar">https://calendar.google.com/calendar</a> and add two recurring events for each day: a “start day” event from 9:00 to 9:05, and an “end day” event from 17:00 to 17:05.</li><li>Test the integration using curl commands in a Linux terminal. Replace the placeholders in the first few lines with your actual values:</li></ol><pre>API_KEY=&quot;YOUR_API_KEY&quot;<br>TIME_MIN=&quot;2023-05-21T00:00:00Z&quot;<br>TIME_MAX=&quot;2023-05-28T23:59:59Z&quot;<br>CALENDAR_NAME=&quot;YOUR_CALENDAR_ID&quot;<br>encoded_calendar_name=$(echo &quot;$CALENDAR_NAME&quot; | sed &#39;s/ /%20/g&#39;)<br>curl &quot;https://www.googleapis.com/calendar/v3/calendars/${encoded_calendar_name}/events?key=${API_KEY}&amp;timeMin=${TIME_MIN}&amp;timeMax=${TIME_MAX}&quot;it should return a json like:</pre><pre>{<br> &quot;kind&quot;: &quot;calendar#events&quot;,<br> &quot;etag&quot;: &quot;\&quot;p33sff2nrivrvu0g\&quot;&quot;,<br> &quot;summary&quot;: &quot;Hometime&quot;,<br> &quot;updated&quot;: &quot;2023-07-05T08:50:54.763Z&quot;,<br> &quot;timeZone&quot;: &quot;Europe/Bucharest&quot;,<br> &quot;accessRole&quot;: &quot;freeBusyReader&quot;,<br> &quot;defaultReminders&quot;: [],<br> &quot;nextSyncToken&quot;: &quot;CPj3ivuX9_8CEAAYCiDR6oaDAg==&quot;,<br> &quot;items&quot;: [<br> {<br>  &quot;kind&quot;: &quot;calendar#event&quot;,<br>  &quot;etag&quot;: &quot;\&quot;3377094035406000\&quot;&quot;,<br>  &quot;id&quot;: &quot;7mo82l9d0ggad882ua6t3gcash_20230705T060000Z&quot;,<br>  &quot;status&quot;: &quot;confirmed&quot;,<br>  &quot;htmlLink&quot;: &quot;https://www.google.com/calendar/event?eid=N21vODJsOWQwZ2dhZDg4MnVhNnQzZ2Nhc2hfMjAyMzA3MDVUMDYwMDAwWiBjX2QzODM0YTc4YzQ0NDE3OTIyMTBkNWNmMTRlNjRhMTAzNzRkNDUxYzQxMzdkM2EwNTFjMGU5MjQzMWFjNTQ1OWJAZw&quot;,</pre><p>…</p><p>14) Modify the following lines from config.py and upload them tho the pi</p><pre>CALENDAR = &quot;your calendar id&quot;<br>APIKEY = &quot;INSERT YOUR APIKEY&quot;<br>...<br>GOOGLECALBOOL = True    # ensure this is set to True<br>...</pre><h3>Step 5: Wiring and Creating the Device</h3><p>For the wiring, the process is quite straightforward:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mnS_Ch08rBUoNbB07QzmZw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9i2M1ZQj5q_NnhEH0ia-FQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Dd-W_2Q--urceYTcRk-bQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w8JIk9XppV8AQZt07Es4hA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QKKKE13imX_DrvZ98CVxyQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hId4vqdV7BE3UqTDx-EhGg.jpeg" /></figure><ol><li>Connect the USB cable from the charger to the Pico.</li><li>Next, you need to identify the LED strip pins. My strip has a (-) sign for one of the wires (which, unfortunately, isn’t black), along with another red wire (which I assumed was +) and a different color wire that I assumed was the signal. This is the tricky part because I didn’t have any instructions for it. Fortunately, my assumptions were correct.</li><li>Connect the Pi’s VBUS to the LED strip’s (+).</li><li>Connect one of the Pi’s (-) to the LED strip’s (-).</li><li>Connect the Pi’s 15th pin to the LED strip’s signal pin. Please note that GPIO pin 15 is the 20&#39;th pin. Please consult the pdf pinout file</li></ol><p><a href="https://datasheets.raspberrypi.com/picow/PicoW-A4-Pinout.pdf?_gl=1*r4o66o*_ga*NjgyODg0NzAuMTY5NTczNzc0Mw..*_ga_22FD70LWDS*MTY5NTczNzc0My4xLjAuMTY5NTczNzc0My4wLjAuMA..">Official pinout here</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Sm4ydaEDXW10vHUiRtC7w.png" /></figure><p>At this point, the LED strip should light up (provided it’s within the correct hour intervals).</p><p>I measured the power consumption with a multimeter, and it’s less than 500mAh. Note that the VBUS does not pass through the Pico — it draws directly from your USB charger. Ensure that the charger can deliver more than 500mAh to be on the safe side.</p><p>Then, I soldered some longer, thinner wires from the Pico to the LED strip and placed the Pico inside a plastic enclosure, which I hid behind my TV. I then attached the aluminium LED profile with the strip onto my furniture and masked the whole setup.</p><p>Don’t forget to consult the pictures :)</p><h3>Step 6: Future Improvements and Motivation</h3><p>I was captivated by this project the moment I saw it, so I decided to replicate it myself. Wanting to improve it — starting with the WiFi configuration part — I forked the repository and pushed the code. I am grateful to the repository owner for their promptness and proactiveness.</p><p>While this is not my original idea, I greatly appreciate open-source work and wanted to create a tutorial for this project. My hope is that this will make it easier for others to recreate this project. I also encourage you to do the same with ideas that pique your interest.</p><p>Possible enhancements for this project could include creating a web-based setup for full configuration, and finding an alternative method for connecting to Google Calendar so that it doesn’t need to be public.</p><p>I hope you find this as exciting as I do!</p><p>For more of my intriguing projects, please visit my GitHub profile: <a href="https://github.com/danionescu0">https://github.com/danionescu0</a></p><p>For some fun projects by veebch (the original creator of this project), check out: <a href="https://github.com/veebch">https://github.com/veebch</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b266aabd32a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Home Assistant Geiger Counter Integration]]></title>
            <link>https://medium.com/@ionescu.dan84/home-assistant-geiger-counter-integration-274f1728bc3f?source=rss-3e5520b513d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/274f1728bc3f</guid>
            <category><![CDATA[sensors]]></category>
            <category><![CDATA[geiger-counter]]></category>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[ota]]></category>
            <category><![CDATA[home-assistant]]></category>
            <dc:creator><![CDATA[Dan Ionescu]]></dc:creator>
            <pubDate>Sun, 03 May 2020 08:31:35 GMT</pubDate>
            <atom:updated>2020-05-03T08:31:35.872Z</atom:updated>
            <content:encoded><![CDATA[<h3>Motivation</h3><p>In this tutorial i’m going to show how you how to add custom sensors to HASS (home assistant) more specifically a geiger counter but the process is similar for other sensors too.</p><p>We’ll be using the NodeMCU board, an arduino based geiger counter and an already installed home assistant.</p><p>The integration will be based on a MQTT server (public or private) and i’m going to take you step by step with this.</p><p>In case you don’t know what is home-assistant please visit their page <a href="https://www.home-assistant.io/">https://www.home-assistant.io/. I</a>t’s a well known home automation platform that’s very well maintained and highly customizable.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FauRfZ5q2SrY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DauRfZ5q2SrY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FauRfZ5q2SrY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/177ed9dd76efaf7945e72d88bd55822b/href">https://medium.com/media/177ed9dd76efaf7945e72d88bd55822b/href</a></iframe><p><strong>You’ll be learning about:</strong></p><p>- advanced configuration for Home Assistant</p><p>- NodeMCU (development board) and how to program it with the Arduino IDE</p><p>- OTA (over the air updates) using the Arduino IDE for the NodeMCU board</p><p>- how to connect a serial device to the NodeMCU</p><p>- manually installing a MQTT server on linux (optional)</p><p>Basic assumptions:</p><p>- you have Home Assistant up and running</p><p>- you know a bit about electronics</p><p>- you have Arduino IDE installed</p><h3>Principle of Work</h3><p>Our goal is to show on HomeAssistat (HASS) the readings from the geiger counter. On one side we have a HASS server up and running somewhere it may be a raspberry pi or other device and on the other side we have the geiger counter.</p><p>The geiger counter has a <a href="https://blog.startingelectronics.com/how-to-use-arduino-serial-ports/">serial port,</a> one solution will be to attach directly the serial port to the RaspberryPi on which the HASS runs.</p><p>Some reasons why it may not be a good ideea:</p><p>- there is no physical space there</p><p>- we have some some other device on the serial port</p><p>- we want to attach an environmental sensor that should be placed outside instead of the geiger counter</p><p>Ok so we’re going to explore another possibility make the connection through WIFI:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*tZGsHhcJWOQjKqI8me7lHg.jpeg" /></figure><p>The HASS supports reading sensor data and displaying that through an <a href="https://randomnerdtutorials.com/what-is-mqtt-and-how-it-works/">MQTT server,</a> this kind of server is a lite weight connection for small devices one device publish a message on a “topic” the other listens on that topic to receive the message. So HASS will listen, and we need something that will publish the message.</p><p>Our sensor knows only to talk over the serial line so we’ll use a board that can read a serial line and that can connect over WIFI and talk to the MQTT server. A cheap board that does this is the <a href="https://www.nodemcu.com/index_en.html">NodeMCU.</a></p><p>The NodeMCU can be programmed with Arduino IDE. The sketch is pretty simple, it does the following:</p><p>- connects to WIFI</p><p>- maintains a MQTT connection with the server and retries the connection when failed or disconnected</p><p>- listens to serial incoming data as a series of integers</p><p>- once an integer arrives it sends it through MQTT to a specific topic</p><h3>Assemble the Device</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/0*L9go0zCNG_oX6QKC" /></figure><p>We’ll be using breadboards and wires so it’s fairly simple, we have a few steps:</p><p>- put the NodeMCU on the breadboard</p><p>- connect the geiger tube to the geiger counter (watch out for polarity)</p><p>- VIN goes to geiger counter +</p><p>- GND goest to geiger counter -</p><p>- NodeMCU D7 (pin 13) goes to geiger TX</p><p>- NodeMCU D8 (pin 15) goes to geiger RX</p><p>- power NodeMCU through micro USB from the computer</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/0*Ec5bEgss2Lx9HNtk" /></figure><h3>Upload the Code</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/0*LUiZ9UTLXyRFcUbp" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/0*yk5XPXXfRpqsi15l" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/0*3bs7-E2OE7SuiAHk" /></figure><p>We’re going to use Arduino IDE and we’ll make sure we have the NodeMCU board installed and the Adafruit_MQTT library installed.</p><p>1. Clone the github repository: <a href="https://github.com/danionescu0/arduino">https://github.com/danionescu0/arduino </a>and copy the sketch from projects/HASSGeigerIntegration to your arduino sketchbook location</p><p>2. Open Arduino IDE and install NodeMCU</p><p>- go to File -&gt; Preferences , in the Additional Boards Manager URLs add <a href="http://arduino.esp8266.com/stable/package_esp8266com_index.json">http://arduino.esp8266.com/stable/package_esp8266com_index.json </a>if you already have something there put a coma in front and click ok</p><p>- from Tools -&gt; Board -&gt; Board Manager type “nodemcu” and select the entry esp8266 by ESP8266 Community, and press install</p><p>3. Install Adafruit_MQTT</p><p>- go to Tools -&gt; Manage Libraries -&gt; search “Adafruit_MQTT” and install “Arduino MQTT library”</p><p>4. Plug in the USB cable in your computer and configure the board:</p><p>- go to Tools -&gt; Board -&gt; select NodeMcu 1.0</p><p>- Tools -&gt; Port -&gt; your USB port</p><p>- leave the other settings unchanged</p><p>4. In the sketch change your WIFI credentials to match your own:</p><pre>#define STASSID &quot;ssid&quot; // Replace with your WIFI SSID<br>#define STAPSK  &quot;pass&quot; // Replace with your WIFI password&lt;/p&gt;</pre><p>5. Upload the sketch to your board and after the upload reset the board from the button</p><p>6. Open the serial monitor, if all has gone well you should see some output like this:</p><pre>Booting<br>IP address: 192.168.1.168OTA enabled<br>Connecting to MQTT... MQTT Connected!<br>{&quot;radiation&quot;: 0.03}..</pre><h3>Configure HomeAssistant</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/0*em5etItymXSBHglU" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/0*NnB4EkoJJ1Qr1vVM" /></figure><p>We’re going to assume that you have home assistant up and running. On my system i have HASSOS version 3.12 on a RaspberryPi. If your version of home assistant is too old or very new some features may differ. This tutorial works for sure with 3.12 version.</p><p>If your don’t have Home Assistant installed , check out their official installation guide: <a href="https://www.home-assistant.io/getting-started/">https://www.home-assistant.io/getting-started/</a></p><p>Before advancing with the instalation make sure the NodeMCU is plugged and it publishing data.</p><p>Ok we’ll have a series of steps here too for the configuration:</p><p>1. Install “file editor” if you don’t have it in the menu, here is the official tutorial: <a href="https://www.home-assistant.io/getting-started/configuration/">https://www.home-assistant.io/getting-started/configuration/</a></p><p>2. Edit “/config/configuration.yaml” file and add the following and save it</p><p>- the mqtt section if you don’t have it already</p><pre>mqtt:<br> broker: broker.hivemq.com<br> discovery: true<br> discovery_prefix: ha</pre><p>- the sensors section</p><pre>sensor:<br> - platform: mqtt<br>   name: &quot;Radiation&quot;<br>   state_topic: &quot;ha/radiation&quot;<br>   unit_of_measurement: &#39;uSv&#39;<br>   unique_id: &quot;radiation&quot;<br>   value_template: &quot;{{ value_json.radiation }}&quot;</pre><p>3. From Configuration -&gt; Server controls : press “Check configuration” the check the yaml config file for errors, and then press “restart” and wait until it’s restarted</p><p>4. From Overview -&gt; Top right corner menu -&gt; Configure UI -&gt; press the + button from the bottom right</p><p>5. Select “sensor” from the list -&gt; in the “entity” field search for “sensor.radiation” , in the name field write “Radiation” and click ok, it should be on the main page now</p><h3>Configuring Your Own MQTT Server [Optional]</h3><p>Let’s discuss a bit about MQTT</p><p>“MQTT is a Client Server publish/subscribe messaging transport protocol. It is light weight, open, simple, and designed so as to be easy to implement. These characteristics make it ideal for use in many situations, including constrained environments such as for communication in Machine to Machine (M2M) and Internet of Things (IoT) contexts where a small code footprint is required and/or network bandwidth is at a premium.”</p><p><em>Citation from the official MQTT 3.1.1 specification.</em></p><p>So basically we can publish a message somewhere on one side and on the other side we can listen for those messages and do something with the data. MQTT support “topics”, topics are strings that the broker uses to filter messages for each client so if we publish a message to “/radiation” topic a listener must subscribe to the same topic to get the messages that we’re sending.</p><p>Here is a great tutorial about MQTT in detail: <a href="https://www.hivemq.com/mqtt-essentials/">https://www.hivemq.com/mqtt-essentials/</a></p><p>Using the free hive server there are some disadvantages like:</p><p>- anyone listening to your topic will receive your messages</p><p>- if it goes down or requires payment later on you won’t be able to use it (unless you pay)</p><p>- if anyone that publish messages to the same topic you’ll receive their messages too, they may publish incompatible messages and break your HASS graphs</p><p>Using a private server</p><p>If you don’t want to use the public free server you have the option of a private server. We’re going to install the Mosquitto MQTT on a ubuntu / debian server like a raspberry pi or computer.</p><p>Mosquitto is a server that implements MQTT protocol and it’s free.</p><p>To install it log into your raspnerry pi or other debian based server and run:</p><pre>sudo apt update<br>sudo apt install -y mosquitto mosquitto-clients<br>sudo systemctl enable mosquitto.service</pre><p><em>This will update the repository, install mosquiito server and client and enable it a service to run at startup</em></p><p>To get the server ip execute:</p><pre>hostname -I</pre><p>and it will output something like:</p><pre>192.168.1.52 172.17.0.1 172.18.0.1</pre><p><em>So my ip is 192.168.1.52, in the commands below</em> <em>replace it with your own ip</em></p><p>You can test the MQTT server by publishing a message and receiving it with the console tool, for this two terminals must be opened one that listens for a message, one that will publish the message.</p><p>First in a terminal run this command to listen for a message on “/some-topic”</p><pre>mosquitto_sub -h 192.168.1.52 -t /some-topic</pre><p>Open another terminal and publish a message to that topic:</p><pre>mosquitto_pub -h 192.168.1.52 -t /some-topic -m &#39;{&quot;humidity&quot;: 74.0}&#39;</pre><p>In the first terminal you should see <em>‘{“humidity”: 74.0}’</em> printed out.</p><p>Special attention:</p><p>- this setup assumes that HASS, Mosquitto and NodeMCU are connected to the same WIFI network and there are no firewall rules and they can communicate freely</p><p>- the Mosquitt MQTT server has no username/password, if you do want to setup credentials check this out: <a href="http://www.steves-internet-guide.com/mqtt-username-password-example/">http://www.steves-internet-guide.com/mqtt-username-password-example/ </a>Also you would need to configure the credentials in Home Assistant and in the arduino sketch</p><h3>OTA (Over the Air Updates) for the NodeMCU</h3><p>Over the air updates means that the development board can be flashed wirelesly without the need of a physical cable.</p><p>Arduino IDE supports this functionality for ESP8266 series and some other boards:</p><p>- requires initial flash over the USB cable</p><p>- creates a virtual port over WIFI and it’s visible only from Arduino IDE</p><p>- no Serial debug information is available</p><p>- supports protection with password</p><p>To enable OTA in a ESP8266 sketch first include the library:</p><pre>#include &quot;ArduinoOTA.h&quot;</pre><p>Also define this sketch password constant:</p><pre>#define SKETCHPASS &quot;some_password&quot;</pre><p>In the setup section add these lines:</p><pre>while (WiFi.waitForConnectResult() != WL_CONNECTED) {<br>     Serial.println(&quot;Connection Failed! Rebooting...&quot;);<br>     delay(5000);<br>     ESP.restart();<br>   }<br>   ArduinoOTA.setPassword(SKETCHPASS);<br>   ArduinoOTA.onStart([]() {<br>       String type;<br>       if (ArduinoOTA.getCommand() == U_FLASH) {<br>         type = &quot;sketch&quot;;<br>       } else { // U_FS<br>         type = &quot;filesystem&quot;;<br>       }<br>       Serial.println(&quot;Start updating &quot; + type);<br>   });<br>   ArduinoOTA.onEnd([]() {<br>       Serial.println(&quot;\nEnd&quot;);<br>   });<br>   ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {<br>       Serial.printf(&quot;Progress: %u%%\r&quot;, (progress / (total / 100)));<br>   });<br>   ArduinoOTA.onError([](ota_error_t error) {<br>       Serial.printf(&quot;Error[%u]: &quot;, error);<br>       if (error == OTA_AUTH_ERROR) {<br>         Serial.println(&quot;Auth Failed&quot;);<br>       } else if (error == OTA_BEGIN_ERROR) {<br>         Serial.println(&quot;Begin Failed&quot;);<br>       } else if (error == OTA_CONNECT_ERROR) {<br>         Serial.println(&quot;Connect Failed&quot;);<br>       } else if (error == OTA_RECEIVE_ERROR) {<br>         Serial.println(&quot;Receive Failed&quot;);<br>       } else if (error == OTA_END_ERROR) {<br>         Serial.println(&quot;End Failed&quot;);<br>       }<br>   });<br>   ArduinoOTA.begin();<br>   Serial.print(&quot;IP address: &quot;);<br>   Serial.println(WiFi.localIP());</pre><p>And in the loop section add this line:</p><pre>ArduinoOTA.handle();</pre><p>After your initial code upload after the board boots up you should see in the Arduino IDE in the Tools-&gt;Port section two types of ports:</p><p>Serial ports: /dev/ttyUSB0 (for example)</p><p>Network ports: esp8266-xxxxx at 192.168.1.xxx</p><p>Now you can select the network port and upload the sketch remote, you will be prompted for the sketch password (the one that you have defined in a constant above)</p><h3>Conclusions, Future Work</h3><p>This tutorial can be easily modified to send data about other types of sensors:</p><p>- if your sensor is directly supported by NodeMCU through a library, just pool data from the sensor and directly push it through MQTT</p><p>- if the sensor library doesn’t work with NodeMCU but it’s only for Arduino then upload your code to the arduino , output the value through the serial line and read it in the NodeMCU and push it (just like we did with the geiger counter)</p><p>We can even modify it to send data from multiple sensors like so:</p><p>- connect your sensors to the NodeMCU</p><p>- poll data from each sensor</p><p>- for each of the sensor publish the data to a different topic</p><p>- in the HASS define multiple sensors (like we did with the geiger) that will listen to different topics</p><h3>If you have questions and suggestions please leave them as comments !</h3><h3>If you like my tutorial, and <a href="https://youtu.be/auRfZ5q2SrY">video</a> and <a href="https://github.com/danionescu0/arduino">github</a> repository consider giving it a favorite / star / like so others can find it quicker.</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=274f1728bc3f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DIY Rain Prediction Using Arduino, Python and Keras]]></title>
            <link>https://medium.com/@ionescu.dan84/diy-rain-prediction-using-arduino-python-and-keras-747609df2a3f?source=rss-3e5520b513d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/747609df2a3f</guid>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[arduino]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-inteligence]]></category>
            <category><![CDATA[weather-prediction-app]]></category>
            <dc:creator><![CDATA[Dan Ionescu]]></dc:creator>
            <pubDate>Wed, 17 Jul 2019 13:27:32 GMT</pubDate>
            <atom:updated>2019-07-17T13:27:32.803Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dQ-y9Mktj4ER1M3AHNUmRQ.jpeg" /></figure><p>First a few words about this project the motivation, the technologies involved and the end product that we’re going to build.</p><p>So the big aim here is obviously to predict the rain in the future (we’ll try 6 hours). The prediction will be a yes or no (boolean in programming terms). I’ve searched from tutorials on this matter and I haven’t found one that is complete in every way. So mine will take this to a whole new approach and get into every aspect of it. For that we’re going to:</p><ul><li><strong>build</strong> the weather station ourselves. The station should be completely off grid with a solar panel, and a extremely low power mode (a few dozens microamps hour)</li><li><strong>program</strong> the station so it gather data and transmits it every ten minutes to a base station</li><li><strong>collect</strong> the data on the base station and store it (in a database)</li><li>using <strong>neural networks</strong> (Keras library) and other Python libraries like pandas filter, clean and preprocess the data, then feed it to a neural network to train a “model” for predicting that it shall or not rain</li><li>finally <strong>predict</strong> whether or not it will rain on the next 6 hours and notify users via email</li></ul><p>I’ve personally used this weather station to collect data (you can download the data in the next steps if you wish). With only about 600 days of weather data the system can make a prediction if it will rain or not in the next 6 hours with an accuracy of around 80% depending on the parameters which is not that bad.</p><p>This tutorial we’ll take you through all the necessary steps to predict rainfall from scratch. We’ll make an end product that does a practical job, without using external weather or machine learning API-s. We’ll learn along the way how to build a practical weather station (low power and off the grid) that really collects data over long periods of time without maintenance. After that you’ll learn how to program it using Arduino IDE. How to collect data into a database on a base station (server). And how to process the data (Pandas) and apply neural networks (Keras) and then predict the rainfall.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*HAU97_0W932a3KqBzLE8Mw.jpeg" /></figure><h3>If you like this project, you can find out more stuff like this on: <a href="https://github.com/danionescu0">Github</a>, <a href="https://www.instructables.com/member/danionescu/instructables/">Instructables</a> and <a href="http://www.youtube.com/c/DanIonescu">YouTube</a></h3><p><strong>Parts:</strong></p><p>1. Small plastic box with detachable lids (mine has screws). The box size should be big enough to fit the small components and batteries. My box has 11 x 7 x 5 cm</p><p>2. three AAA battery holder</p><p>3. three AAA rechargeable batteries</p><p>4. 6V small solar panel</p><p>5. Arduino Pro Mini 328p</p><p>6. a diode, 1N4004 (to prevent reverse current from the batteries to the panel)</p><p>7. a small NPN transistor and 1k resistor (for switching power to the components on and off)</p><p>8. a <a href="https://www.ebay.com/itm/5PCS-Rain-Water-sensor-water-Level-Sensor-module-Depth-of-Detection-for-Arduino/200959003806?hash=item2eca170c9e:g:G6IAAOSwT2daRxaz:rk:6:pf:0">rain</a> sensor</p><p>9. HC-12 serial communication module</p><p>10. HC-12 <a href="https://www.ebay.com/itm/HC-12-USB-CC1101-433Mhz-Wireless-Serial-Port-Module-Wireless-Module-for-Arduino-/201725104033">USB serial module</a> (for the base station)</p><p>11. <a href="https://www.adafruit.com/product/2652">BME280</a> bosch sensor module (for humidity, temperature, pressure)</p><p>12. <a href="https://www.ebay.com/itm/Lichtsensor-BH1750-Modul-I2C-Bus-Arduino-GY-302-Helligkeits-Sensor-Raspberry-Pi/252725768417?hash=item3ad7a130e1:g:0vYAAOSw7Spb33fL:rk:5:pf:0">BH1750</a> light sensing module</p><p>13. PCB, wires, solder, KF301–2P plug in screw connector, male&amp;female pcb connectors, glue</p><p>14. 3.3V regulator</p><p>15. a base station: a PC, or a development board running all the time. It’s role it’s gathering data, training the rain prediction model and making predictions</p><p><strong>Tools:</strong></p><p>1. USB to serial FTDI adapter FT232RL to program the Arduino Pro Mini</p><p>2. Arduino IDE</p><p>3. Drill</p><p>4. Fine blade saw</p><p>5. Screwdrivers</p><p>6. Soldering iron</p><p>7. Wire cutter</p><p><strong>Skills:</strong></p><p>1. Soldering, check this tutorial</p><p>2. Basic arduino programming</p><p>3. Linux service configuration, package installation</p><p>4. Some programming skills</p><h3>Step 2: Building the Weather Station</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3SXwxxmvUFXeZpNlV-0cPw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lSafHNwtPSzhHonXDRUNSA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VESzOLkYY8TwzRsDB95hBw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C7hk89U40x9w9prFxQjRbQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nhTqQz9g_A4uRYAnONAPDQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0FcosNfXURCCYxRUyprGtQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*70tY3woK8_FasHW97URqoQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_P7dZLdB2nkyFE4qPnRHXw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G966BF5k_3CgA79NrVB3lQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K__jRGzaTZAdw-cwYXbXUg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ElJmprSySf_2KrHMNVbvfQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1XWUFkoG6pICNI8bfotZpQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y9zqrTfPlquZ_2F4_w7lfw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jtiLGLahOTIv_YuxK4b7dw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aJlQv9ZAGjhP28yK-qPW5w.png" /></figure><p>The weather station is composed from the following sets of components:</p><p><strong>1.</strong> the box with the solar panel glued to it</p><p><strong>2</strong>. the PCB with the electronics inside</p><p><strong>3.</strong> the battery holder also inside</p><p><strong>4. </strong>the BME280 and light and rain sensors on the outside</p><p><strong>1.</strong> The box needs 4 holes, one for the solar panel wires, other three for the sensors that will be placed on the outside. First drill the wholes, they should be large enough for the male-female wires to stick out and go to the sensors. After the wholes are drilled, glue the panel to one side of the box and get it’s wires through a hole inside</p><p><strong>2. </strong>The PCB will hold the arduino, HC-12, 3.3V regulator, diode, transistor, resistor and two KF301–2P</p><ul><li>first solder the two female PCB connectors on the PCB for the arduino, solder the male pcb connectors to the arduino and place the arduino on the PCB</li><li>the arduino led should be removed or at least one of it’s pin. this is <strong>very important</strong> because the led will draw a large amount of power. Be careful not to damage other components</li><li>solder the transistor, resistor, and 3.3V regulator</li><li>solder the two KF301–2P. One will be for the solar panel, the other for the battery holder</li><li>solder three female PCB connectors: for the light sensor, BME280 and rain sensor</li><li>solder small wires to connect all the PCB components (check the pictures and the fritzing schamatic)</li></ul><p><strong>3. </strong>place 3 charged AAA NiMH batteries inside the holder and place it inside the box, connecting the wires into the KF301–2P connector</p><p><strong>4. </strong>connect the BME280 and light sensors from outside the box to their corresponding male connectors</p><p>For the rain sensor, solder three wires (Gnd, Vcc, signal) to it, and to the other side solder male pins that will go inside the box to its corresponding male connectors</p><p>The final thing it would be to place the station to it’s final position. I’ve chose a position that is sheltered from the rain and snow. I’ve chosen longer wires for the rain sensor and placed it separately in the rain on a steady support. For the main box i’ve chosen a special kind of tape with adhesive (check the pictures) but anything that holds the box will do.</p><h3>Step 3: Arduino Code</h3><p>In this step you’ll learn what external libraries are needed, we’re overview the code and how it works and of course you’ll get to download it or copy-paste it into Arduino IDE and upload it to the weather station.</p><p>The role of the weather station is to transmit to a base station every 10 minutes data about it’s sensors.</p><h3>First let’s describe what the weather station program does:</h3><p><strong>1. </strong>read sensors data (humidity, temperature, pressure, rain, light, voltage)</p><p><strong>2.</strong> transmits the encoded data through a second software serial line.</p><p>The encoded data looks like this:</p><pre>H1:78|T1:12|PS1:1022|L1:500|R1:0|V1:4010|</pre><p>The statement from above will mean that: humidity from station “1” is 78 percent, temperature from station 1 is 12 degrees, pressure is 1022 bars, light level 500 lux, rain 0, and voltage 4010 millivolts</p><p><strong>3.</strong> power off the auxiliary components: sensors and communication device</p><p><strong>4.</strong> puts the arduino in sleep mode for 10 minutes (this will make it consume less 50 microamps)</p><p><strong>5.</strong> turn on the components and repeat steps 1–4</p><p>One little extra tweak here, if the voltage level is above 4.2 V the arduino will use the normal sleep function “delay(milliseconds)”. This will greatly increase the power consumption and decreasing the voltage rapidly. This effectively prevents the solar panel from overcharging the batteries.</p><blockquote><strong>You can get the code from my Github repository here: </strong><a href="https://github.com/danionescu0/home-automation/tree/master/arduino-sketches/weatherStation">https://github.com/danionescu0/home-automation/tree/master/arduino-sketches/weatherStation</a></blockquote><p>Or copy-pasting it from below, either way <strong>just remove the line with “transmitSenzorData(“V”, sensors.voltage);”</strong></p><pre>#include &quot;LowPower.h&quot;&lt;br&gt;#include &quot;SoftwareSerial.h&quot;<br>#include &quot;Wire.h&quot;<br>#include &quot;Adafruit_Sensor.h&quot;<br>#include &quot;Adafruit_BME280.h&quot;<br>#include &quot;BH1750.h&quot;</pre><pre>SoftwareSerial serialComm(4, 5); // RX, TX<br>Adafruit_BME280 bme; <br>BH1750 lightMeter;<br>const byte rainPin = A0;<br>byte sensorsCode = 1;<br>/**<br> * voltage level that will pun the microcontroller in deep sleep instead of regular sleep<br> */<br>int voltageDeepSleepThreshold = 4200; <br>const byte peripherialsPowerPin = 6;<br>char buffer[] = {&#39; &#39;,&#39; &#39;,&#39; &#39;,&#39; &#39;,&#39; &#39;,&#39; &#39;,&#39; &#39;};</pre><pre>struct sensorData<br>  {<br>      byte humidity;    <br>      int temperature;<br>      byte rain;<br>      int  pressure;<br>      long voltage;<br>      int light;<br>  };<br>sensorData sensors;</pre><pre>void setup() <br>{  <br>    Serial.begin(9600);<br>    serialComm.begin(9600);<br>    pinMode(peripherialsPowerPin, OUTPUT);<br>    digitalWrite(peripherialsPowerPin, HIGH);<br>    delay(500);<br>    if (!bme.begin()) {<br>        Serial.println(&quot;Could not find a valid BME280 sensor, check wiring!&quot;);<br>        while (1) {<br>           customSleep(100);<br>        }<br>    }<br>    Serial.println(&quot;Initialization finished succesfully&quot;);<br>    delay(50);<br>    digitalWrite(peripherialsPowerPin, HIGH);<br>}</pre><pre>void loop() <br>{    <br>    updateSenzors();<br>    transmitData();    <br>    customSleep(75);       <br>}</pre><pre>void updateSenzors() <br>{<br>    bme.begin();<br>    lightMeter.begin();<br>    delay(300);<br>    sensors.temperature = bme.readTemperature();<br>    sensors.pressure = bme.readPressure() / 100.0F;<br>    sensors.humidity = bme.readHumidity();<br>    sensors.light = lightMeter.readLightLevel();<br>    sensors.voltage = readVcc();<br>    sensors.rain = readRain();<br>}</pre><pre>void transmitData()<br>{<br>    emptyIncommingSerialBuffer();<br>    Serial.print(&quot;Temp:&quot;);Serial.println(sensors.temperature);<br>    Serial.print(&quot;Humid:&quot;);Serial.println(sensors.humidity);<br>    Serial.print(&quot;Pressure:&quot;);Serial.println(sensors.pressure);<br>    Serial.print(&quot;Light:&quot;);Serial.println(sensors.light);<br>    Serial.print(&quot;Voltage:&quot;);Serial.println(sensors.voltage);<br>    Serial.print(&quot;Rain:&quot;);Serial.println(sensors.rain);<br>    transmitSenzorData(&quot;T&quot;, sensors.temperature);<br>    transmitSenzorData(&quot;H&quot;, sensors.humidity);<br>    transmitSenzorData(&quot;PS&quot;, sensors.pressure);<br>    transmitSenzorData(&quot;L&quot;, sensors.light);<br>    transmitSenzorData(&quot;V&quot;, sensors.voltage);<br>    transmitSenzorData(&quot;R&quot;, sensors.rain);<br>}</pre><pre>void emptyIncommingSerialBuffer()<br>{<br>    while (serialComm.available() &gt; 0) {<br>        serialComm.read();<br>        delay(5);<br>   }<br>}</pre><pre>void transmitSenzorData(String type, int value)<br>{<br>    serialComm.print(type);<br>    serialComm.print(sensorsCode);<br>    serialComm.print(&quot;:&quot;);<br>    serialComm.print(value);<br>    serialComm.print(&quot;|&quot;);<br>    delay(50);<br>}</pre><pre>void customSleep(long eightSecondCycles)<br>{<br>    if (sensors.voltage &gt; voltageDeepSleepThreshold) {<br>        delay(eightSecondCycles * 8000);<br>        return;<br>    }<br>    digitalWrite(peripherialsPowerPin, LOW);<br>    for (int i = 0; i &lt; eightSecondCycles; i++) {<br>        LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);  <br>    }<br>    digitalWrite(peripherialsPowerPin, HIGH);<br>    delay(500);<br>}</pre><pre>byte readRain()<br>{<br>    byte level = analogRead(rainPin);<br>    return map(level, 0, 1023, 0, 100);  <br>}</pre><pre>long readVcc() {<br>    // Read 1.1V reference against AVcc<br>    // set the reference to Vcc and the measurement to the internal 1.1V reference<br>    #if defined(__AVR_ATmega32U4__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)<br>      ADMUX = _BV(REFS0) | _BV(MUX4) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);<br>    #elif defined (__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)<br>      ADMUX = _BV(MUX5) | _BV(MUX0);<br>    #elif defined (__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)<br>      ADMUX = _BV(MUX3) | _BV(MUX2);<br>    #else<br>      ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);<br>    #endif  <br>  <br>    delay(2); // Wait for Vref to settle<br>    ADCSRA |= _BV(ADSC); // Start conversion<br>    while (bit_is_set(ADCSRA,ADSC)); // measuring<br>    uint8_t low  = ADCL; // must read ADCL first - it then locks ADCH  <br>    uint8_t high = ADCH; // unlocks both<br>    long result = (high&lt;&lt;8) | low;<br>    result = 1125300L / result; // Calculate Vcc (in mV); 1125300 = 1.1*1023*1000<br>    <br>    return result; // Vcc in millivolts<br>}</pre><p>Before uploading the code, download and install the following arduino libraries:</p><p>* BH1750 library: <a href="https://github.com/claws/BH1750">https://github.com/claws/BH1750</a> * LowPower library: <a href="https://github.com/rocketscream/Low-Power">https://github.com/rocketscream/Low-Power</a></p><p>* Adafruit Sensor library: <a href="https://github.com/adafruit/Adafruit_Sensor">https://github.com/adafruit/Adafruit_Sensor</a></p><p>* Adafruit BME280 library: <a href="https://github.com/adafruit/Adafruit_BME280_Library">https://github.com/adafruit/Adafruit_Sensor</a></p><p>If you don’t know how to do that, check out <a href="https://learn.sparkfun.com/tutorials/installing-an-arduino-library/all">this</a> tutorial.</p><h3>Step 4: Preparing the Base Station</h3><p>The base station will consist of a<strong> linux computer</strong> (desktop, laptop or development board) with the <strong>HC-12 USB</strong> module attached. The computer must remain always on to collect data every 10 minutes from the station.</p><p>I’ve used my laptop with Ubuntu 18.</p><h3>The installation steps:</h3><p><strong>1.</strong> Install <a href="https://www.anaconda.com/">anaconda</a>. Anaconda is a Python package manager and it will make it easy for us to work with the same dependencies. We’ll be able to control the Python version, and each package version</p><p>If you don’t know how to install it check out this: <a href="https://www.digitalocean.com/community/tutorials/how-to-install-anaconda-on-ubuntu-18-04-quickstart">https://www.digitalocean.com/community/tutorials/h...</a> tutorial and follow the steps 1–8</p><p><strong>2.</strong> Install <a href="https://www.mongodb.com/">MongoDb</a>. MongoDb will be our main database for this project. It will store data about all the sensors time series. It’s schemaless and for our purpose it’s easy to use.</p><p>For installation steps check out their page: <a href="https://docs.mongodb.com/v3.4/tutorial/install-mongodb-on-ubuntu/">https://docs.mongodb.com/v3.4/tutorial/install-mon...</a></p><p>I’ve used an older version of mongoDb 3.4.6, if you follow the tutorial above you’ll get exactly that. In principle it should work with the latest version.</p><p>[Optionally] add an index on date field:</p><pre>mongo <br>use weather <br>db.weather_station.createIndex({&quot;date&quot; : 1})</pre><blockquote><strong>3.</strong> <strong>Download the project from here:</strong> <a href="https://github.com/danionescu0/home-automation">https://github.com/danionescu0/home-automation</a>.</blockquote><blockquote>We’ll be using the weather-predict folder</blockquote><pre>sudo apt-get install git <br>git clone <a href="https://github.com/danionescu0/home-automation">https://github.com/danionescu0/home-automation</a></pre><p><strong>4.</strong> Create and configure anaconda environment:</p><pre>cd weather-predict <br># create anaconda environment named &quot;weather&quot; with python 3.6.2<br>conda create --name weather python=3.6.2 </pre><pre># activate environment<br>conda activate weather</pre><pre># install all packages <br>pip install -r requirements.txt</pre><p>This will create an new anaconda environment and install the needed packages. Some of the packages are:</p><p><a href="https://keras.io/"><strong>Keras</strong></a> (high level neural network layer, with this library we’ll make all our neural network predictions)</p><p><a href="https://pandas.pydata.org/"><strong>pandas</strong></a> (useful tool that manipulates data, we’ll use it heavily)</p><p><a href="https://scikit-learn.org/stable/"><strong>sklearn</strong></a> (data mining and data analysing tools)</p><p><strong>pymongo</strong> (python mongoDb driver)</p><h3>Configure the project</h3><p>The config file is situated in the weather-predict folder and is named config.py</p><p>1. if you install MongoDb remotely or on a different port change the “host” or “port” in the</p><pre>mongodb = {<br>    &#39;host&#39;: &#39;localhost&#39;,<br>    &#39;port&#39;: 27017<br>}<br>...</pre><p>2. Now we need to attach the HC-12 USB serial adapter. Before than run:</p><pre>ls -l /dev/tty*</pre><p>and you should get a list of mounted devices.</p><p>Now insert the HC-12 in a USB port and run the same command again.It should be one new entry in that list, our serial adapter. Now change the adapter port in the config if necessary</p><pre>serial = {<br>    &#39;port&#39;: &#39;/dev/ttyUSB0&#39;,<br>    &#39;baud_rate&#39;: 9600<br>}</pre><p>The other config entries are some file default paths, no need for a change there.</p><h3>Step 5: Use the Weather Station in Practice</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XhdSmlN1jyRVRPrlbTJgdQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B-lhKH1RCCTFVF2ZH32KQw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fz9FjaMWXLRJD7A6SEh6FQ.png" /></figure><p>Here we’ll discuss basic stuff about importing my test data, running some tests on it, setting up your own data, displaying some graphs and setting up an email with prediction for the next few hours.</p><p>If you like to know more about how it works check out the next step “How does it work”</p><p><strong>Importing my already gathered data</strong></p><p>MongoDb comes with a cli command for importing data from json:</p><pre>mongoimport -d weather -c weather_station --file sample_data/weather_station.json</pre><p>This will import the file from sample data into “weather” database and “datapoints” collection</p><p>A <strong>warning</strong> here, if you use my gathered data, and combine it with your newly local data the accuracy might drop because of the small differences in hardware (sensors) and local weather patterns.</p><p><strong>Gathering new data</strong></p><p>One of the base station roles is to store incoming data from the weather station into the database for later processing. To start the process that listens to the serial port and stores in the database just run:</p><pre><strong>conda</strong> activate weather<br><strong>python</strong> serial_listener.py<br># every 10 minutes you should see data from the weather station coming in :<br>[Sensor: type(temperature), value(14.3)]<br>[Sensor: type(pressure), value(1056.0)]<br>...</pre><p><strong>Generating the prediction model</strong></p><p>I’ll presume you have imported my data or “ran the script for a few years” to gather your personialised data, so in this step we’ll process the data to create a model used to predict future rain.</p><pre>conda activate weather<br>python train.py --days_behind 600 --test-file-percent 10 --datapoints-behind 8 --hour-granularity 6</pre><p>* The first parameter — days_behind means how much data into the past should the script process. It’s measured in days</p><p>* — test-file-percent means how much of the data should be considered for testing purpose, this is a regular step in a machine learning algorithm</p><p>* — hour-granularity basically means how many hours into the future we’ll want the prediction</p><p>* — datapoints-behind this parameter will be discussed further into the next section</p><p><strong>View some data charts with all the weather station sensors</strong></p><p>Let’s say for the last 10 days:</p><pre>conda activate weather <br>python graphs --days-behind 10</pre><p><strong>Predict if it will rain in the next period</strong></p><p>We’ll predict if it’s going to rain and send an notification email</p><pre>conda activate weather</pre><pre>python train.py --days_behind 600 --test-file-percent 10 --datapoints-behind 8 --hour-granularity 6</pre><p>Run a batch predict on the test data:</p><pre>python predict_batch.py -f sample_data/test_data.csv</pre><p>It’s important to use the same parameters as in the train script above.</p><p>For the email notification to work log in into your gmail account and <a href="https://myaccount.google.com/lesssecureapps">Turn Allow less secure apps</a> to ON. Be aware that this makes it easier for others to gain access to your account.</p><p>You’ll need two email addresses, a gmail address with the above option activated, and an other address where you’ll receive your notification.</p><p>If you like to receive notifications every hour, put the script into crontab</p><p>To see how all of this is possible check the next step</p><h3>Step 6: How Does It Work</h3><h3>In this last step we’ll discuss several aspects of the architecture of this project:</h3><p><strong>1.</strong> Project overview, we’ll discuss the general architecture and technologies involved</p><p><strong>2.</strong> Basic concepts of machine learning</p><p><strong>3. </strong>How the data is prepared (the most important step)</p><p><strong>4.</strong> How the actual neural network wrapper API works (Keras)</p><p><strong>5.</strong> Future improvements</p><p>I’ll try to give some code example here but bear in mind, that it’s not 100% the code from the project. In the project it’s self the code it’s a bit more complicated with classes and a structure</p><h3>1. Project overview, we’ll discuss the general architecture and technologies involved</h3><p>As we talked earlier, the project has two separate parts. The weather station it’s self which only function is to collect and transmit data. And the base station where all the collection training and prediction will happen.</p><p><strong>Advantages of the separation</strong> of the weather station and the base station:</p><ul><li>power requirements, if the weather station was able to process the data too, it would need substantial power, maybe large solar panels or a permanent power source</li><li>portability, due to it’s small size the weather station can collect data from a few hundred meters away and you can easily change it’s place if needed</li><li>scalability, you can increase the prediction accuracy by building more than one weather stations and spread them around a few hundred meters</li><li>low cost, because it’s a cheap device you can easily build another in case one is lost or stolen</li></ul><p><strong>The database choice</strong>. I’ve chosen MongoDb because it’s nice features: schemaless, free and easy to use API</p><p>Every time sensor data is received the data is saved in the database, a the data entry looks something like this:</p><pre>{	<br>        &quot;_id&quot; : &quot;04_27_2017_06_17&quot;,<br>	&quot;humidity&quot; : 65,<br>	&quot;date&quot; : ISODate(&quot;2017-04-27T06:17:18Z&quot;),<br>	&quot;pressure&quot; : 1007,<br>	&quot;temperature&quot; : 9,<br>	&quot;rain&quot; : 0,<br>	&quot;light&quot; : 15<br>}</pre><p>The database stores data in BSON format (similar to JSON) so it’s easy to read and easy to work with. I’ve aggregated the data under an identifier that contains the date formatted as string to the minutes, so the smallest grouping here is a minute.</p><p>The weather station (when working properly) will transmit a datapoint every 10 minutes. A datapoint is a collection of “date”, “humidity”, “pressure”, “temperature”, “rain” and “light” values.</p><p><strong>The data processing and neural network</strong> technology choice</p><p>I’ve chosen Python for the backend because many major inovations in neural networks are found in Python. A growing community with a lot of Github repositories, tutorials blogs and books are here to help.</p><p>* For the data processing part i’ve used <strong>Pandas</strong> (<a href="https://pandas.pydata.org/"><em>https://pandas.pydata.org/</em></a><em>)</em>. Pandas make working with data easy. You can load tables from CSV, Excel, Python data structures and reorder them, drop columns, add columns, index by a column and many other transformations.</p><p>* For working with neural networks i’ve chosen <strong>Keras</strong> (<a href="https://keras.io/">https://keras.io/</a>). Keras is a high level neural network wrapper over more lower level API’s like Tensorflow and one can build a multi — layer neural network with a dozen lines of code or so. This is a great advantage because we can build something useful on the great work of other people. Well this is the basic stuff of programming, build on other smaller building blocks.</p><h3>2. Basic concepts of machine learning</h3><p>The scope of this tutorial is not to teach machine learning, but merely to outline one of it’s possible use cases and how we can practically apply it to this use case.</p><p>Neural networks are data structures that resemble brain cells called neurons. Science discovered that a brain has special cells named neurons that communicate with other neurons by electrical impulses through “lines” called axons. If stimulated sufficiently (from many other neurons) the neurons will trigger an electric impulse further away in this “network” stimulating other neurons. This of course is a oversimplification of the process, but basically computer algorithms try to replicate this biological process.</p><p>In computer neural nets each neuron has a “trigger point” where if stimulated over that point it will propagate the stimulation forward, if not it won’t. For this each simulated neuron will have a bias, and each axon a weight. After a random initialization of these values a process called “learning” starts this means in a loop an algorithm will do this steps:</p><ul><li>stimulate the input neurons</li><li>propagate the signals through the network layers until the output neurons</li><li>read the output neurons and compare the results with the desired results</li><li>tweak the axons weights for a better result next time</li><li>start again until the number of loops has been reached</li></ul><p>If you like to know more details about this process you can check out this article: <a href="https://mattmazur.com/2015/03/17/a-step-by-step-backpropagation-example/">https://mattmazur.com/2015/03/17/a-step-by-step-ba...</a>. There are also numerous books and tutorials out there.</p><p>One more thing, here we’ll be using a supervised learning method. That means we’ll teach the algorithm the inputs and the outputs also, so that given a new set of inputs it can predict the output.</p><h3>3. How the data is prepared (the most important step)</h3><p>In many machine learning and neural network problems data preparation is a very important part and it will cover:</p><ul><li>get the raw data</li><li>data cleanup: this will mean removing orphan values, aberrations or other anomalies</li><li>data grouping: taking many datapoints and transforming into an aggregated datapoint</li><li>data enhancing: adding other aspects of the data derived from own data, or from external sources</li><li>splitting the data in train and test data</li><li>split each of the train and test data into inputs and outputs. Typically a problem will have many inputs and a few outputs</li><li>rescale the data so it’s between 0 and 1 (this will help the network removing high/low value biases)</li></ul><p><strong>Getting the raw data</strong></p><p>In our case getting data for MongoDb in python is really easy. Given our datapoints collection just this lines of code will do</p><pre>client = MongoClient(host, port).weather.datapoints </pre><pre>cursor = client.find(<br>            {&#39;$and&#39; : [<br>                {&#39;date&#39; : {&#39;$gte&#39; : start_date}},<br>                {&#39;date&#39; : {&#39;$lte&#39; : end_date}}<br>            ]}<br>        )<br>data = list(cursor)<br>..</pre><p><strong>Data cleanup</strong></p><p>The empty values in the dataframe are dropped</p><pre>dataframe = dataframe.dropna()</pre><p><strong>Data grouping &amp; data enhancing</strong></p><p>This is a very important step, the many small datapoins will be grouped into intervals of 6 hours. For each group several metrics will be calculated on each of the sensors (humidity, rain, temperature, light, pressure)</p><ul><li>min value</li><li>max value</li><li>mean</li><li>70, 90, 30, 10 percentiles</li><li>nr of times there has been a rise in a sensor</li><li>nr of times there has been a fall in a sensor</li><li>nr of times there has been steady values in a sensor</li></ul><p>All of these things will give the network information for a datapoint, so for each of the 6 hours intervals these things will be known.</p><p>Zoom on the picture below to see the data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*meAx7DtYEGh-WpRs9FEDVA.png" /></figure><p>After this a new column named “has_rain” will be added. This will be the output (our predicted variable). Has rain will be 0 or 1 depending if the rain average is above a threshold (0.1). With pandas it’s as simple as:</p><pre>dataframe.insert(loc=1, column=&#39;has_rain&#39;, value=numpy.where(dataframe[&#39;rain_avg&#39;] &gt; 0.1, 1, 0))</pre><p><strong>Data cleanup (again)</strong></p><p>- we’ll drop the date column because it’s no use to us, and also remove datapoints where the minimum temperature is below 0 because our weather station it doesn’t have a snow sensor, so we won’t be able to measure if it snowed</p><pre>dataframe = dataframe.drop([&#39;date&#39;], axis=1) <br>dataframe = dataframe[dataframe[&#39;temperature_min&#39;] &gt;= 0]</pre><p><strong>Data enhancing</strong></p><p>Because data in the past might influence our prediction of the rain, we need for each of the dataframe rows to add columns reference to the past rows. This is because each of the row will serve as a training point, and if we want the prediction of the rain to take into account previous datapoints that’s exactly what we should do: add more columns for datapoints in the past ex:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zD2aJtugQvMR-RNxc-z9Eg.png" /></figure><p>So you see that for every sensor let’s say temperature the following rows will be added: “temperature_1”, “temperature_2”.. meaning temperature on the previous datapoint, temperature on the previous two datapoints etc. I’ve experimented with this and I found that a optimum number for our 6 hour groupings in 8. That means 8 datapoints in the past (48 hours). So our network learned the best from datapoins spanning 48 hours in the past.</p><p><strong>Data cleanup (again)</strong></p><p>As you see, the first few columns has “NaN” values because there is nothing in front of them so they should be removed because they are incomplete.</p><p>Also data about current datapoint should be dropped, the only exception is “has_rain”. the idea is that the system should be able to predict “has_rain” without knowing anything but previous data.</p><p><strong>Splitting the data in train and test data</strong></p><p>This is very easy due to Sklearn package:</p><pre>from sklearn.model_selection import train_test_split </pre><pre>...</pre><pre>main_data, test_data = train_test_split(dataframe, test_size=percent_test_data) </pre><pre>...</pre><p>This will split the data randomly into two different sets</p><p><strong>Split each of the train and test data into inputs and outputs</strong></p><p>Presuming that our “has_rain” interest column is located first</p><pre>X = main_data.iloc[:, 1:].values</pre><pre>y = main_data.iloc[:, 0].values</pre><p><strong>Rescale the data so it’s between 0 and 1</strong></p><p>Again fairly easy because of sklearn</p><pre>from sklearn.preprocessing import StandardScaler</pre><pre>from sklearn.externals import joblib</pre><pre>..</pre><pre>scaler = StandardScaler()</pre><pre>X = scaler.fit_transform(X) </pre><pre>...</pre><pre># of course we should be careful to save the scaled model for later reuse</pre><pre>joblib.dump(scaler, &#39;model_file_name.save&#39;)</pre><h3>4. How the actual neural network wrapper API works (Keras)</h3><p>Building a multi layer neural network with Keras is very easy:</p><pre>from keras.models import Sequential</pre><pre>from keras.layers import Dense<br>from keras.layers import Dropout <br>...<br>input_dimensions = X.shape[1] <br>optimizer = &#39;rmsprop&#39;<br>dropout = 0.05<br>model = Sequential()<br>inner_nodes = int(input_dimensions / 2)<br>model.add(Dense(inner_nodes, kernel_initializer=&#39;uniform&#39;, activation=&#39;relu&#39;, input_dim=input_dimensions))<br>model.add(Dropout(rate=dropout))<br>model.add(Dense(inner_nodes, kernel_initializer=&#39;uniform&#39;, activation=&#39;relu&#39;))<br>model.add(Dropout(rate=dropout))<br>model.add(Dense(1, kernel_initializer=&#39;uniform&#39;, activation=&#39;sigmoid&#39;))<br>model.compile(optimizer=optimizer, loss=&#39;mean_absolute_error&#39;, metrics=[&#39;accuracy&#39;]) </pre><pre>model.fit(X, y, batch_size=1, epochs=50)<br>...</pre><pre># save the model for later use<br>classifier.save(&#39;file_model_name&#39;)</pre><p>So what does this code mean? Here we’re building a sequential model, that means sequentially all the layers will be evaluated.</p><p>a) we declare the input layer (Dense), here all the inputs from our dataset will be initializedm so the “input_dim” parameter must be equal to the row length</p><p>b) a Dropout layer is added. To understand the Dropout first we must understand what “overfitting” means: it’s a state in which the network has learned too much particularities for a specific dataset and will perform badly when confronted to a new dataset. The dropout layer will disconnect randomly neurons at each iteration so the network won’t overfit.</p><p>c) another layer of Dense is added</p><p>d) another Dropout</p><p>e) the last layer is added with one output dimension (it will predict only yes/no)</p><p>f) the model is “fitted” that means the learning process will begin, and the model will learn</p><p><strong>Other parameters here:</strong></p><ul><li>activation functions (sigmoid, relu). This are functions that dictate when the neuron will transmit it’s impulse further in the network. There are many, but sigmoid and relu are the most common. Check out this link for more details: <a href="https://towardsdatascience.com/activation-functions-and-its-types-which-is-better-a9a5310cc8f">https://towardsdatascience.com/activation-function...</a></li><li>kernel_initializer function (uniform). This means that all the weights are initialized with random uniform values</li><li>loss function (mean_absolute_error). This function measures the error comparing the network predicted result versus the ground truth. There are many alternatives: <a href="https://keras.io/losses/">https://keras.io/losses/</a></li><li>metrics function (accuracy). It measures the performance of the model</li><li>optimiser functions (rmsprop). It optimizes how the model learn through backpropagation.</li><li>batch_size. Number of datapoints to take once by Keras before applying optimizer function</li><li>epochs: how many times the process it’s started from 0 (to learn better)</li></ul><p>There is no best configuration for any network or dataset, all these parameters can an <strong>should</strong> be tuned for optimal performance and will make a big difference in prediction success.</p><h3>5. Future improvements</h3><p>Let’s start from the <strong>weather station</strong>, I can see a lot of improving work to be done here:</p><ul><li>add a wind speed / direction sensor. This could be a very important sensor that i’m missing in my model</li><li>experiment with UV rays, gas and particle sensors</li><li>add at least two stations in the zone for better data (make some better averages)</li><li>collect a few more years of data, i’ve experimented with just a year and a half</li></ul><p>Some <strong>processing improvements:</strong></p><ul><li>try to incorporate data from other sources into the model. You can start to import wind speed data and combine with the local station data for a better model. This website offers historical data: <a href="https://www.wunderground.com/history/">https://www.wunderground.com/history/</a></li><li>optimize the Keras model better by adjusting: layers, nr of neurons in layers, dropout percents, metrics functions, optimiser functions, loss functions, batch size, learning epochs</li><li>try other model architectures, for example i’ve experimented with LSTM (long short term memory) but it gived slightly poorer results)</li></ul><p>To try different parameters on the learning model you can use</p><pre>python train.py --days_behind 600 --test-file-percent 10 --datapoints-behind 6 --hour-granularity 6 --grid-search</pre><p>This will search through different “batch_size”, “epoch”, “optimizer” and “dropout” values, evaluate all and print out the best combination for your data.</p><p>If you have some feedback on my work please share it, thanks for staying till the end of the tutorial!</p><h3>Step 7: Bonus: Using an Official Weather Dataset</h3><p>I was wondering if I can get better results with a more reliable weather station, so i’ve searched a bit, and i’ve came across “<strong>Darksky AP</strong>I” (<a href="https://darksky.net/dev">https://darksky.net/dev</a>), this is a great tool that provides current and historical weather data with many more sensor data:</p><ul><li>temperature</li><li>humidity</li><li>pressure</li><li>wind speed</li><li>wind gust</li><li>uv index</li><li>visibility</li></ul><p>So this beeing data from an official weather station, and having more parameters I thought it should perform better so i’ve gave it a try. To replicate my findings:</p><p><strong>1.Download</strong> the data from darsky or <strong>import</strong> my MongoDb collection:</p><p><strong>a) Download</strong></p><ul><li>to download your self, first create an account in darsky and get the API key</li><li>replace the API key in download_import/config.py</li><li>also in the config replace the geographic coordonates for the location you want to predict the rain</li><li>in a console activate “weather” anaconda environment and run:</li></ul><pre>python download_import/darksky.py -d 1000</pre><p>- the free version of the API is limited to 1000 requests per day so if you want more data you need to wait for a longer time</p><p><strong>b) Import</strong> my downloaded data for Bucharest city</p><p>- in a console run</p><pre>mongoimport -d weather -c darksky --file sample_data/darksky.json</pre><p><strong>2. When you train</strong> the model specify that it should run on “darksy” dataset</p><pre>python train.py -d 2000 -p 20 -dp 4 -hg 6 --data-source darksky</pre><p><strong>3. To see the results </strong>run predict batch script as before</p><pre>python predict_batch.py -f sample_data/test_data.csv</pre><p>You’ll see that the overall prediction percent has gone from about 80% to 90%. Also the prediction accuracy when accounting only rainy days has gone up.</p><p>So yes, the dataset really matters.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=747609df2a3f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>