David Prieto
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # Arduino morse code and functional programming ###### tags: `IB` `Computer Science` `Arduino` In the previous lesson [Starting with Arduino. Installing and first blink](/-TGF1lqLROSs9UcvU0BuBQ) we made a blink. Now we can do a more complex program. ## First code "A" The first code is after the blink. We need to consider that we have a dot and a dash. And they have durations that _depend_ on each other. The idea is that we're going to blink in morse code. For this I need to understand the proportions of the morse code. We can find it in [wikipedia](https://en.wikipedia.org/wiki/Morse_code). ![imagen](https://hackmd.io/_uploads/HJA9ks-TJl.png) {%youtube jPTS-IiYG8Y%} Each student is going to use their own names, and we're going to start by the first letter. In this example I'm going to use A. First we get rid of the comments of the blink so I have only the pure code. You can use this as an example :::warning :warning: Remember that if you copy and paste the code from here, you need to delete all the previous code from your sketch. :warning: If you don't you might find some errors like "I have setup written twice and I don't know which one execute" ::: ```cpp= void setup() { pinMode(LED_BUILTIN, OUTPUT); } void loop() { digitalWrite(LED_BUILTIN, HIGH); delay(1000); digitalWrite(LED_BUILTIN, LOW); delay(1000); } ``` Now we need to think. If we want to have an A, we need to do a dot, then a dash, then a space between letters. Here you have a reminder ![image](https://hackmd.io/_uploads/SywyHu-sle.png) Now these would be the steps that we need to do ![image](https://hackmd.io/_uploads/r1KkI_Woel.png) But since we don't know how to do a dot we need to lower the level of abstraction a little bit. For a dot we need to light up for a lenth of a dot and then we need to light down for a length of a dot because we're in the letter yet. Then we need to light up for three dots to do the dash and then light down for the duration of three dots. If we do this in a shape of a diagram it would be like this: ![image](https://hackmd.io/_uploads/HkPBPuSsxl.png) We can use for example 600 milliseconds as a length for a dot (use another in your sketch). So a dash will be 1800. ```cpp= void setup() { pinMode(LED_BUILTIN, OUTPUT); } void loop() { //dot digitalWrite(LED_BUILTIN, HIGH); delay(600); digitalWrite(LED_BUILTIN, LOW); //space inside a letter delay(600); //dash digitalWrite(LED_BUILTIN, HIGH); delay(1800); digitalWrite(LED_BUILTIN, LOW); //space between letters delay(1800); } ``` :::info I used here some comments to know what I'm doing using `//` ::: The problem of this is that if we want to change the value of the length of the dot, we would have to change 4 lines if we have one letter, but many letters, then... oh boy we have to change a lot. So we're going to **refactor** to add a variable. ## Refactoring and adding a variable //talk about refactoring and manteinability (maintenance) of code We're going to use a variable. dotDuration (that can be changed to any other name). Since it's going to be read in all the code, we're going to define it as a global variable. (outside of the setup and the loop) Let's say that our name is Wenceslao. So the first letter is W. So we need to state a a dot and two dashes. You have the code in the details. :::info There are naming conventions for the variables that depend on the programming language and the context where you are. Probably at some point you will have a small note on this. ::: :::spoiler ```cpp= //we write the variable int dotDuration = 500; // the setup function runs once when you press reset or power the board void setup() { // initialize digital pin LED_BUILTIN as an output. pinMode(LED_BUILTIN, OUTPUT); } // the loop function runs over and over again forever void loop() { //W //dot digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level) delay(dotDuration); digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW delay(dotDuration); //dash digitalWrite(LED_BUILTIN, 1); // turn the LED on (HIGH is the voltage level) delay(dotDuration*3); digitalWrite(LED_BUILTIN, 0); // turn the LED off by making the voltage LOW delay(dotDuration); //dash digitalWrite(LED_BUILTIN, 1); // turn the LED on (HIGH is the voltage level) delay(dotDuration*3); digitalWrite(LED_BUILTIN, 0); // turn the LED off by making the voltage LOW delay(dotDuration*3); //wenceslao } ``` ::: :::info If you see in detail in some `digitalWrite` the code uses `HIGH`, `LOW`, `0` and `1` and `HIGH` is the same as writing `1` and `LOW` is the same as writing `0` ::: ## Functions If we would need to add all this to all the name of **Wenceslao** would need to write _a lot_ of time. To save this, we're going to define **functions**. To create a function in C++ we need to state out of the setup and loop curly braces a line that is "void $NameOfTheFunction()". (This is a simplification) In our case we're going to use "morseDot()" and "morseDash()". MorseDot will do the dot and morse dash will do the, ehem, the dash. So if we have a W we will have to **call** the function The code is this in the details :::spoiler ```cpp= int dotDuration = 500; // the setup function runs once when you press reset or power the board void setup() { // initialize digital pin LED_BUILTIN as an output. pinMode(LED_BUILTIN, OUTPUT); } void morseDot() { digitalWrite(LED_BUILTIN, 1); // turn the LED on (HIGH is the voltage level) delay(dotDuration); digitalWrite(LED_BUILTIN, 0); // turn the LED off by making the voltage LOW delay(dotDuration); } void morseDash() { digitalWrite(LED_BUILTIN, 1); // turn the LED on (HIGH is the voltage level) delay(dotDuration*3); digitalWrite(LED_BUILTIN, 0); // turn the LED off by making the voltage LOW delay(dotDuration); } // the loop function runs over and over again forever void loop() { //W //dot morseDot(); //dash morseDash(); //dash morseDash(); delay(dotDuration*2); } ``` ::: ### Exercise: Write your own name in morse code using these functions. ## Grouping functions If we want to have a more complex diagram we are going to repeat the same thing again, we're going to have a lot of morseDot() and morseDash() calls all over. So we are going create a function that calls the other functions. In the case of A, we're going to create morseA :::info Other implementations are possible ::: ```cpp= void morseW() { //W //dot morseDot(); //dash morseDash(); //dash morseDash(); delay(dotDuration*2); } ``` Now the loop will look something like this: ```cpp= void loop() { morseD(); morseA(); morseV(); morseI(); morseD(); delay(dotDuration*4); } ``` ## Your first library We want to reuse this code for everybody (people do it ) ![image](https://hackmd.io/_uploads/SJCGdc8jlg.png) ## Reference code https://github.com/DavidMenCam/Arduino/blob/main/morse_3/morse_3.ino ![](https://i.imgur.com/IZbDlMI.png)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully