Category: Programming

  • From GitHub Basics to Publishing Your Code Alongside a Paper

    Here are the slides from a talk I gave on how to use Git and GitHub.

    The slides cover everything from the basics of working with GitHub to the steps involved in publishing your code alongside a paper.

    Sharing paper data and analysis code is now routinely expected.
    Beyond that, managing code with GitHub has become an essential part of working on collaborative projects.

    [Updated January 15, 2024] https://www.slideshare.net/slideshow/embed_code/key/vzfmHD9i6I15wI

    From GitHub basics to code management and publishing your code with a paper from Hayato Yamanouchi

    The same material is also available on my personal site.

    Hayato M. Yamanouchi’s personal site

  • Setting Up a Python Environment on Mac with VS Code (Visual Studio Code)! [Memo]

    I decided to set up a Python development environment on my Mac, so here are my notes for future reference.

    Installing Visual Studio Code (VS Code)

    Install the app from the Visual Studio Code website.

    What gets installed is an app you can run as is, so just move it into your Mac’s Applications folder.

    Switching VS Code to Japanese

    Install the “Japanese Language Pack for Visual Studio Code”.

    Select Extensions from the menu bar on the left and type “Japanese Language Pack for Visual Studio Code”.

    Then install the package with that same name that appears at the top of the list.

    After that, restart VS Code and check that the interface is now in Japanese.

    Installing the Python extension

    Next, install the Python extension in the same way.

    Select Extensions from the menu bar on the left, type “Python,” and install Python.

    With this, when you write Python programs in VS Code you can use jupyter, get automatic syntax highlighting, and generally have a working Python development environment.

    Checking that it actually works

    Create a file called test.py in any directory you like.

    Create a new file, choose text, and specify Python as the language.

    Then name it test.py and enter the following into the program:

    print(“Hello World!!”)

    Enter that.

    Then run it with the play button in the upper right.

    Hello World!! will then be displayed in the terminal below.
    Once you get this far, your Python development environment is up and running.

    If you’ve created a virtual environment with Anaconda, you can select the environment you want from the Python interpreter selector in the lower right.
    Alternatively, you can activate the virtual environment with the conda command in the terminal.

  • My elif conditional branching isn’t working!! [Python]

    My elif conditional branching isn’t working!! [Python]

    Have you ever wanted to branch on multiple conditions with an if statement, tried using elif, and found that although no error appears, the results somehow aren’t what you expected?
    If so, the situation described below might be the cause.
    For reference, since I made this mistake myself, I’m writing it down as a note.

    The problematic program

    The problem arises when you write two conditions in the if and elif statements and build a program that includes elif.

    def trable(a, b):
        if a >= 10 & b >= 10:
            print("patern A")
        elif a >= 10 & b < 10:
            print("patern B")
        elif a < 10 & b >= 10:
            print("patern C")
        else:
            print("patern D")
    
    trable(11, 11)
    trable(11, 9)
    trable(9, 11)
    trable(9, 9)

    When you run the program above, you might expect the cases to be sorted into patterns A, B, C, and D in order from the top, but the actual output is as follows.

    patern A
    patern B
    patern C
    patern B

    What if we swap the order?

    def trable(a, b):
        if a >= 10 & b >= 10:
            print("patern A")
        elif a < 10 & b < 10:
            print("patern B")
        elif a >= 10 & b >= 10:
            print("patern C")
        else:
            print("patern D")
    
    trable(11, 11)
    trable(9, 11)
    trable(11, 9)
    trable(9, 9)

    If you swap the code for patterns B and C and write a program that you expect to output A, B, C, and D, the actual output is as follows.

    patern A
    patern D
    patern D
    patern D

    elif itself is used as shown below when you want to define multiple conditions.

    if 条件式A:
      条件式Aが真(True)となった場合の処理
    elif 条件式B:
      条件式Aが偽(False)で、条件式Bが真(True)となった場合の処理
    else:
      条件式Aが偽(False)で、条件式Bも偽(False)となった場合の処理

    However, once the conditional expressions in the if and elif statements involve two conditions, the problem described above is likely to occur.
    As a result, you don’t get the output you intended.

    The tricky part is that no error is raised, so you can’t tell whether it worked until you actually look at the results.

    How to fix it

    When you want to branch into multiple cases using multiple conditions, avoid specifying multiple conditions in an elif statement.

    def resolve(a, b):
        if a>= 10:
            if b >= 10:
                print("patern A")
            else:
                print("patern B")
    
        else:
            if b >= 10:
                print("patern C")
            else:
                print("patern D")
    
    resolve(11, 11)
    resolve(11, 9)
    resolve(9, 11)
    resolve(9, 9)

    It becomes more cumbersome, but doing it this way produces exactly the output you expect.

    Programming has unexpected pitfalls like this, so it’s a good lesson in carefully checking the code you write.

    Addendum (August 2022)

    It turns out the problem was not wrapping the conditions in parentheses.

    def trable(a, b):
        if (a >= 10) & (b >= 10):
            print("patern A")
        elif (a < 10) & (b < 10):
            print("patern B")
        elif (a >= 10) & (b >= 10):
            print("patern C")
        else:
            print("patern D")

    With this change, the branching worked correctly.
    Alternatively, you can also solve it by writing and instead of &.

    def trable(a, b):
        if a >= 10 and b >= 10:
            print("patern A")
        elif a < 10 and b < 10:
            print("patern B")
        elif a >= 10 and b >= 10:
            print("patern C")
        else:
            print("patern D")

    & and and may seem the same, but & also acts as a bitwise AND, so in the original program

    a >= 10 & b < 10

    this apparently means a >= (10 & b) < 10, so with a=9 and b=9 the inequality becomes
    9>=8<10, which evaluates to True.

    It’s tricky, isn’t it…

  • Changing Pulse Wave Frequency and Duty Cycle Using PWM Output [Arduino UNO]

    Changing Pulse Wave Frequency and Duty Cycle Using PWM Output [Arduino UNO]

    What is PWM output?

    PWM stands for pulse width modulation. It is a modulation method that works by changing the duty cycle of a waveform.

    For details, see my previous post.

    PWM output on Arduino

    The Arduino UNO uses a Microchip microcontroller called the ATmega328 as its main chip.
    Once you start digging deep into Arduino programming, you inevitably end up having to read the microcontroller’s datasheet, so it is worth taking a look at least once. (Which is exactly what I am doing now.)

    The Arduino has three timers (Timer/Counter).
    These timers govern all timing in an Arduino program.
    Functions such as delay() and tone() are measured using them.

    Timer/CounterPin numberBitsRolePWM frequency
    Timer05, 68 bitManages Arduino timing
    delay(), millis(), micros(), etc.
    977 Hz
    Timer19, 1016 bitServo library, etc.490 Hz
    TImer23, 118 bittone(), etc.490 Hz

    This time we will change the PWM output by manipulating these timers.
    Incidentally, since this alters the timers at their core, with some ingenuity you might also be able to tweak functions like delay() to your liking. (Although it seems more likely that they will simply be thrown off and behave erratically.)

    Timer0 is generally tied to the system as a whole, so I recommend using Timer1.

    Useful references
    https://playground.arduino.cc/Main/TimerPWMCheatsheet/
    https://www.arduino.cc/en/Tutorial/SecretsOfArduinoPWM
    https://atooshi-note.com/arduino-1hz-pwm/
    http://blog.kts.jp.net/arduino-pwm-change-freq/
    http://garretlab.web.fc2.com/arduino/inside/hardware/arduino/avr/cores/arduino/wiring_analog.c/analogWrite.html

    Program overview

     The overall approach is to change the register settings of the Arduino’s timers so that the PWM output frequency can be set freely.

    The goal is to be able to output low frequencies, so the program is written to output 10 Hz.

    Here we connect an LED to pin 10 and write a program that lets us freely change the frequency and duty cycle of its light.
    Since we are using pin 10, we will use Timer1.

    Program code

    //レジスタの設定を変えるためのもの
    #include <avr/io.h>
    int PWMPin = 10;
    
    //関数の定義
    //frq:周波数 (1Hz~指定できる)
    //duty:指定したいduty比
    void HzWrite(int frq, float duty) { 
    
        // モード指定
      TCCR1A = 0b00100001;
      TCCR1B = 0b00010100; //分周比256を用いる
    
      // TOP値指定
      OCR1A = (unsigned int)(31250 / frq);
    
      // Duty比指定
      OCR1B = (unsigned int)(31250 / frq * duty);
    }
    
    
    void setup() {
      pinMode(PWMPin, OUTPUT);
    }
    
    void loop() {
      HzWrite(10, 0.5);
      delay(5000);
      digitalWrite(PWMPin, LOW);
      delay(5000);
    
    }

    Explanation of the program

    First, include <avr/io.h> so that we can change the register settings.

    #include <avr/io.h>

    Next, to build a function that works together with delay() to repeat a 10 Hz output every five seconds, we define a function called HzWrite. Its arguments let us specify the frequency and the duty cycle.

    void HzWrite(int frq, float duty) { 
    
    }

    Next comes the mode setting.
    The registers used here are TCCR1A/TCCR1B. (TCCR: Timer/Counter Control Register)
    The “1” indicates Timer1; if you want to use Timer2, use TCCR2A/TCCR2B instead.

    To set the PWM frequency to a specific value in Hz, you need to specify the TOP value yourself.
    The larger the TOP value, the lower the output frequency.
    Here we use 10 Hz as an example. Since this is very slow compared with the 16 MHz system clock, a large TOP value and a large prescaler are required. For this reason we use Timer1, which offers the largest range.


    With the 8-bit Timer0 and Timer2, the maximum TOP value is 255 (2^8 – 1), whereas with the 16-bit Timer1 it is 65535 (2^16 – 1).
    (The maximum is one less because the range is 0–255 or 0–65535: the number of values is 2^x, but the largest value is 2^x – 1.)

    Internally, the counter increments (0, 1, 2, …) up to the TOP value, and when it matches OCRxA/OCRxB (x is the counter number; each counter has two output pins, A and B) the pin output changes (e.g., LOW→HIGH). Once the counter reaches the TOP value, it then decrements back down to 0 (65535, 65534, 65533, …), and just as during the increment phase, the pin output changes when the count matches OCRxA/OCRxB.

    On the Arduino UNO you can change how fast this counter increments, to some extent, by changing the prescaler setting. (“To some extent” means you can choose from 1/8/64/256/1024.)
    The prescaler is the ratio (n) used when dividing the frequency (multiplying it by 1/n).
    In other words, dividing 1000 Hz by a prescaler of 10 gives 100 Hz.

    Incidentally, with a prescaler of 1 the timer runs at 16 MHz, the system clock of the Arduino UNO (ATmega328).

    In short, by changing the TOP value, the OCRxA/OCRxB values, and the prescaler, you can freely control the points at which the output switches.

    Since we want 10 Hz here, we use a prescaler of 256 to leave plenty of margin.
    On the Uno the clock is 16 MHz, so one count takes 1 / 16 MHz = 62.5 ns (prescaler 1).
    With a prescaler of 256, counting all the way to TOP takes 62.5 ns x 256 x 65535 = 1.04856 s, so frequencies as low as 1 Hz can be specified.

    This program can generate frequencies from 1 Hz to 31250 Hz.
    However, as you approach 31250 Hz it becomes impossible to specify the duty cycle precisely.
    If you want fine control over the duty cycle, you can only go up to about 300 Hz.

    By changing the prescaler setting in this program, you can build a version that covers the frequency range suited to your own application.

    In TCCR1A/TCCR1B you write what you want to configure.
    The details here are rather involved, so let’s work through them roughly using the datasheet.

    Here the values are given in binary, so they start with 0b. For TCCR1A you set COM1A1, COM1A0, COM1B1, COM1B0, unused, unused, WGM11, WGM10 to 1 or 0.
    For TCCR1B you set unused (ICNC1), unused (ICES1), unused, WGM13, WGM12, CS12, CS11, CS10.

    TCCR1Aの指定(ATmega328データシートより)
    TCCR1Bの指定(ATmega328データシートより)

    First, here we choose Mode 9, whose PWM mode is Phase and Frequency Correct.
    In this case the TOP value is set in OCR1A.

    モードの指定(ATmega328データシートより)

    Therefore WGM13 / WGM12 / WGM11 / WGM10 are 1, 0, 0, 1, respectively.

    出力の指定(ATmega328データシートより)

    For COM1B1 / COM1B0: 0, 0 means no output; 0, 1 means toggle operation (the output is inverted on compare match);
    1, 0 outputs LOW while the counter is between OCR1A/B and TOP and HIGH while it is between 0 and OCR1A/B;
    1, 1 is the inverse of 1, 0.

    Here we drive the output LED between LOW and HIGH at the desired frequency, so COM1B1 / COM1B0 are set to 1, 0.

    We choose 1, 0 because it makes the sketch easier to follow.

    分周比の指定(ATmega328データシートより)

    Since we are using a prescaler of 256 here, CS12/CS11/CS10 are set to 1, 0, 0.

    To summarize, we get the following.

    TCCR1A = 0b00100001;
    TCCR1B = 0b00010010;

    Next we set OCR1A and OCR1B so that the output is generated with the specified frequency and duty cycle.

      // TOP値指定
      OCR1A = (unsigned int)(31250 / frq);
    
      // Duty比指定
      OCR1B = (unsigned int)(31250 / frq * duty);

    Because Phase and Frequency Correct PWM counts up and then back down, the output frequency is given as follows.

    Frequency frq = IC clock frequency / (prescaler * TOP value * 2)

    Conversely, to determine the TOP value:

    TOP value = IC clock frequency / (prescaler x frq x 2)

    With a prescaler of 256 on the Arduino UNO, this gives

    TOP value = OCR1A = 16,000,000 / (256 x frq x 2) = 31250 / frq

    Since we want the LOW/HIGH switching point to be given by OCR1A/OCR1B = duty cycle,

    OCR1B = 31250 / frq x duty

    Unsigned int is used to prevent overflow.

    Here is the main output routine.

    void setup() {
      pinMode(PWMPin, OUTPUT);
    }
    
    void loop() {
      HzWrite(10, 0.5);
      delay(5000);
      digitalWrite(PWMPin, LOW);
      delay(5000);
    
    }

    Set PWMPin, i.e., pin 10, as OUTPUT, and specify the frequency and duty cycle with HzWrite().
    After waiting with delay(), turn the output off with digitalWrite(PWMPin, LOW) and call delay() again.

    That covers the full program and how it works.

    Afterword

    When looking for blog posts on how to change the PWM output frequency, I found far more results by searching for AVR, ATmega328, or 328P than by searching for Arduino.

    This post was only a rough overview, so if you want to dig deeper, I encourage you to look into it yourself.

  • How to Generate Continuous Pulse Waves with Arduino

    How to Generate Continuous Pulse Waves with Arduino

    Introduction

    There are times when you want to output a continuous pulse wave with an Arduino: blinking an LED, producing a sound, using it as a timer, and so on.

    It comes up often and seems simple at first, but the more you look into it, the deeper the topic gets.

    In this post, I introduce several ways to output a continuous pulse wave with an Arduino.

    Changing the timing with delay

    The simplest and easiest approach is to switch the output ON and OFF using the delay function.

    //pinはピン番号
    void loop(){
        digitalWrite(pin, HIGH);
        delay(1000);
        digitalWrite(pin, LOW);
        delay(1000);
    }

    In the program above, the output alternates between HIGH and LOW.
    Since delay is specified in milliseconds, delay(1000) waits for one second.

    In other words, it is a program that turns on and off at 1 Hz.

    However, using the delay() function to set a frequency has many drawbacks.
    With this approach, changing the output duration—say, outputting a 60 Hz signal for 5 seconds—requires a for loop, which is inconvenient.

    That said, because it is so simple, I recommend it when you just want to try something out quickly.

    Using tone()

    The tone() function is commonly used to generate buzzer sounds.
    Official Arduino reference

    This function lets you specify the frequency and the duration.
    So, unlike the delay approach, you can specify the frequency directly without having to calculate it.

    //pinはピン番号
    void loop() {
         tone(pin,60);
    }

    You can write it as tone(pin, frequency) or tone(pin, frequency, duration).

    The duration is given in milliseconds, so it is written the same way as delay.

    The problem with this function is that it cannot produce frequencies of 31 Hz or below.
    In other words, you cannot generate an output at, say, 1 Hz.

    For frequencies above 31 Hz, such as audio tones, it makes setting the frequency very easy, and the code is far shorter and more accurate than using the delay function.

    Using PWM output and changing its frequency

    Using PWM output offers the most flexibility—and it is also the reason this topic gets so deep.

    PWM stands for pulse width modulation.
    For details, see Wikipedia.

    The term alone does not tell you much, but in simple terms, PWM is a way of modulating an output by changing the duty ratio.
    The official Arduino explanation is here.

    Normally, you would set the brightness of an LED by changing the current.
    But when the current is fixed and you still want to change the brightness, you blink the LED at a very high frequency (the flicker fusion threshold for humans is said to be around 30–60 Hz).

    Normally the ON and OFF periods are 1:1 (a duty ratio of 50%), but what happens if you make it 4:1 (80% duty) or 1:4 (20% duty)?
    The former looks bright, and the latter looks dim.

    Modulating the output by changing the pulse width in this way is what PWM output is.

    On the Arduino you can not only produce this output but also change the PWM frequency.
    The idea behind this method is that by changing register settings—that is, the underlying parts of the Arduino—you can change the PWM output frequency.
    By default, the output frequency is 490 Hz, or 980 Hz on some pins.

    I will explain how to do this in detail in a future post.
    Searching for “PWM Arduino change frequency” turns up plenty of explanations.

    After reading through them about four times, it starts to make sense.

    Basically, why not try these approaches and find the one that fits your own purpose?

  • Using Conda Commands on macOS

    Using Conda Commands on macOS

    Here I’ll walk through installing Anaconda on macOS and setting up the terminal environment.

    Installing Anaconda

    Go to the Anaconda homepage and scroll down to find the downloads.

    Choose the installer that matches your environment.
    Since this guide covers macOS, select the 64-bit Graphical Installer.

    Launch the installer and follow the instructions to complete the installation.

    There are two installers for Mac. The 64-bit Graphical Installer installs Anaconda through a GUI, which is the more familiar approach, and unless you have a reason to do otherwise, you can install Anaconda this way.

    The 64-bit Command Line Installer downloads a *.sh file.
    This is a shell script installer, used when you want to install from the terminal.

    Since installing software on Linux is normally done from the terminal, people who are used to Linux may find this route easier. (Probably.)

    Setting up the command line

    When you install on macOS, all that appears in your applications list is Anaconda-Navigator, and as it stands you can’t use Anaconda or Python from the terminal.

    If you want to use the conda command, for example to install packages, you need to activate Anaconda.
    To activate Anaconda (that is, to make the conda command available):

    conda activate

    Run the above.
    The conda command should now work.

    If activating the conda environment every time is a hassle, you can have it activate automatically.
    To do so, run the following in the terminal:

    ~/opt/anaconda3/bin/conda init シェル名

    Use the name of the shell you’re actually using. If you have no idea and have never touched this setting, you’re most likely on the default shell (zsh on macOS), so substitute that for the shell name.

    ~/opt/anaconda3/bin/conda init zsh

    Now, when you restart the terminal, the conda environment will be activated automatically and you won’t need to type conda activate.

    To turn off automatic activation,

    conda config --set auto_activate_base false

    run the following in the terminal.

  • Git: The Ultimate Tool for File Version Control — A Beginner’s Guide

    Git: The Ultimate Tool for File Version Control — A Beginner’s Guide

    What is Git?

    Many of you probably knew about GitHub before you ever heard of Git.
    When looking for a program or piece of software to reference, GitHub pages often come up in search results, and I suspect plenty of people have simply downloaded something from there without really understanding how it works.

    GitHub is indeed a place where programs are shared, but it is more than just a sharing platform—it is a tool for using something called Git online.

    Git is a tool for version control of files.
    By recording the changes you make to your files, it lets you return to any recorded version at any time.

    When you have someone review a presentation manuscript, you probably save the file before review, the reviewed file, and the file you revised based on the comments as separate files.
    With Git, you can handle all of those changes easily, within a single file.

    You can find Git here

    The three places in Git

    A record made with Git—and the act of making that record—is called a “commit”.

    The place where commits accumulate is called a “repository”.
    In other words, a repository is where the change history is kept.
    A repository on your own computer is called a “local repository”, while one hosted remotely, such as on GitHub, is called a “remote repository”.

    To manage files with Git, you designate a folder to be managed by Git.
    Within that folder there are three places:
    the working tree, the staging area, and the Git directory.

    The working tree is where your files live, and simply editing a file here does not yet save the change history as a commit.

    The staging area is where you register the files to be committed.
    Files on the stage likewise have not had their change history saved yet; think of it as the place where you declare, “I am going to commit this file.”

    The Git directory is where commits are stored.
    Files committed here are stored as files that will not be altered.
    In principle, the content recorded by a commit cannot be changed or deleted afterward.
    Once committed to the Git directory, a change is officially recorded in the history.

    Basic usage of Git

    I will leave the detailed usage for you to look up, but here I will give a rough overview of the actual operations.

    Git is generally operated through Git Bash on Windows (installed together with Git) and through the terminal on macOS and Linux. (I will refer to both simply as the terminal here.)

    There are GUI tools that may feel more familiar, but once you get used to it, using Git from the CUI is extremely convenient, so I recommend starting with the CUI from the outset.
    You should get the hang of it within an hour.

    First, to start managing files with Git, create a local repository.
    Begin by moving to the directory you want to manage with Git in the terminal.
    Then,

    git init

    Entering this sets you up for version control with Git.

    Next, to record changes in the staging area,

    git add ファイルパスもしくはディレクトリパス

    Running this registers the specified file in the working tree to the staging area.

    Next,

    git commit

    This commits the files in the working tree.

    To check which files are currently in which state, run

    git status

    Run this command.
    The commit history can be checked by

    git log

    running this command.

    Basically, the workflow is to run git add, then git commit to create a change record, and use git status to check the current state whenever you run into trouble.

    Below is a reference.
    It is a book that is very easy to follow even for beginners, and I referred to it while writing this article.
    If you would like to study this in more depth, I recommend it.

  • Extracting Specific Values from a DataFrame [Python]

    Extracting Specific Values from a DataFrame [Python]

    Extracting a single specific value from a pandas DataFrame in Python is surprisingly tricky.
    DataFrames are designed to be handled as DataFrames, so pulling out a row, slicing, or appending data is very easy.

    But when you try to extract a value, for some reason it does not come out as a value—it stays in DataFrame form, and various other problems come up.

    Here I describe how to extract the value in a DataFrame that satisfies a particular condition.
    There are probably better ways to do this, but this is the best I can manage at my current level.

    First, suppose we have the DataFrame below and want to extract the value 20 outlined in red.

    The catch is that with a simple DataFrame like the one above you can see the index and pull the value out in one step, but with a large dataset it is very hard to check the index number and use it.

    With a large dataset, it is more efficient to extract data using a key column (customer number, ID, etc.) as a clue.
    So let’s try extracting the value in the situation below.

    In other words, suppose we want the value in column B for the row where column A is Aichi.
    You cannot do this in one step; the value is extracted in two stages.

    First, create a DataFrame like the one above.

    import pandas as pd
    df = pd.DataFrame({ 'A' : ["Tokyo", "Aichi", "Osaka"],
                        'B' : [10, 20, 30],
                        'C' : [100, 200, 300]})
    df

    Next, extract the row where column A is Aichi.

    a = df[df["A"] == "Aichi"]
    
    print(a)

    This lets us pull out the row containing Aichi.
    Finally, we extract the value in column B of this row.

    b = a.at[a.index[0], "B"]
    
    print(b)

    Doing this, you can extract the value.
    It is roundabout, but this is the method I currently use.

    If you know of another approach, I would be glad to hear about it in the comments.

    import pandas as pd
    df = pd.DataFrame({ 'A' : ["Tokyo", "Aichi", "Osaka"],
                        'B' : [10, 20, 30],
                        'C' : [100, 200, 300]})
    
    a = df[df["A"] == "Aichi"]
    b = a.at[a.index[0], "B"]
    print(b)

    Here is a summary of the code above.

  • try and except: Exception Handling in Python

    try and except: Exception Handling in Python

    Errors sometimes occur when writing programs in Python.
    Errors are actually helpful, since they tell you that your program has not been put together correctly,
    but there are times when an error stops your program from running at all.

    Sometimes code is syntactically correct yet still raises an error at runtime.
    An error raised when the syntax is grammatically incorrect is called a syntax error,
    while an error that is grammatically correct but logically wrong is called an exception.

    Examples of exceptions include:
    ・TypeError: the operands have incompatible types
    EX. word/2 , 4*number

    ・ZeroDivisionError: division by zero
    EX. 3/0

    ・ValueError: the type is correct, but the value is not appropriate
    EX. int(“string”)

    You can prevent errors before they occur and write logically correct programs by using conditional branching, but another option is to handle errors with exception handling when they do occur.

    That is where try, except comes in.

    try: 
        実行したい処理(例外を含むかもしれない)
    except エラー名:
        例外発生時に行う処理

    You use it like this.
    For example,

    try:
        print(10 / 0)
    except ZeroDivisionError:
        print('できませんでした')
    #出力
    できませんでした

    This is the result.
    Note, however, that except only catches the errors you specify
    (in this program, only ZeroDivisionError), so any other error will still be reported as an error when the program runs.

    When you expect more than one kind of error, add another “except ErrorName:” clause.

    try:
        print(10 / 0)
    except ZeroDivisionError:
        print('できませんでした')
    except ValueError:
        print('値がうまく合致しませんでした')

    You can specify multiple except clauses.

    If you leave out the exception name in the except clause, it will catch every exception.

    try:
        print(10 / 0)
    except:
        print('できませんでした')

    However, because this catches every exception, it will also hide errors that the programmer never anticipated, so use it with great care.

    There are also related keywords in the try-except syntax that let you specify what happens after an exception occurs.
    I will list them briefly here.
    I plan to cover them in detail in another blog post.

    • raise: deliberately raise an exception
    • pass: do nothing after an exception occurs
    • else: run only when no exception occurred
    • finally: always run, whether or not an exception occurred

  • I Want to Control Arduino with Python!

    I Want to Control Arduino with Python!

    Arduino is normally controlled with the Arduino language.
    Sooner or later, though, you will want to do something more complex, or control an Arduino from within another program.

    The module introduced here, pySerial, lets you carry out serial communication with a Raspberry Pi or an Arduino.
    Through serial communication, you can send commands from a Python program to an Arduino or Raspberry Pi and control them from Python.

    Here I introduce the basic code for doing this.
    Just being able to use this will greatly expand what your programs can do.

    How to install

    pip install pyserial

    You can install it by opening Python in a terminal or command prompt.
    Alternatively, you can install it from a terminal inside an IDE such as PyCharm.

    Example code

    This example is a program that turns an LED on and off at one-second intervals.
    I will test it by writing output to pin 13, which drives the LED built into the Arduino.
    On the Python side:

    import serial, time
    
    def main():
        #  COMポートを開く
        print("Open Port")
        ser = serial.Serial("COM3", 9600)
        while True:
            #  LED点灯
            ser.write(b"1")
            time.sleep(1)
            #  LED消灯
            ser.write(b"0")
            time.sleep(1)
    
        print("Close Port")
        ser.close()
    
    if __name__ == '__main__':
        main()

    serial.Serial specifies the port and the serial communication settings.
    For the Arduino UNO, specify 9600.
    This differs from board to board, so check it in the Arduino IDE.

    The b in b”1″ plays a crucial role.
    With the serial.write() function, numbers and strings must be converted to byte sequences before they can be sent over serial.
    The b prefix is what marks the value as a byte sequence.

    Since this program runs in an infinite loop, the LED keeps switching on and off every second until you stop the program.

    Next is the program on the Arduino side.

    void setup() {
      Serial.begin(9600);
      pinMode(13, OUTPUT);
      digitalWrite(13, LOW);  //  初期化
    }
    
    void loop() {
      byte var;
      var = Serial.read();
      switch(var){
        case '0':
          digitalWrite(13, LOW);
          break;
        case '1':
          digitalWrite(13, HIGH);
          break;
        default:
          break;
      }
    }

    Here I use a switch-case statement.
    It makes the program easier to follow.
    For details, take a look at my previous blog post.

    In this code, sending 0 sets the pin LOW and sending 1 sets it HIGH.
    Using this program as a base, you can control an Arduino from a Python program in all sorts of ways.