FRDM-MCXN947でMicroPythonを动かす (日本语ブログ) MicroPython, FRDM-MCXN947, ZephyrMicroPython, FRDM-MCXN947, ZephyrMicroPython, FRDM-MCXN947, ZephyrMicroPython, FRDM-MCXN947, Zephyr
MicroPython 's main family R&D , Zephyr's Zephyr , FRDM-MCXN947's FRDM-MCXN947 setting.
Zephyr ポートというのは, MicroPython をZephyr RTOSの上でかす transplanted version です. MicroPython is usually used in microPython. "(Ported version) を志ちますが, MCX シリーズに専用ポートはありません.その代わり, Zephyr が対応しているボードなら动かせるこの士组みを使います (Detailed しくはSection 1.3 ).
ビルド自体は, これまでもできました.ただしボード inherent setting が无かったため, come out on がるのはminimum limitのMicroPythonで,スクリプトをSaveするファイルシステムも无く,I²CもSPIも使えませんでした. This time, the first step is to make the first step.
これでNXPのマイコンでMicroPythonをmake the selection択limbが広がりました.これまでは事実上,上上のクロスオーバーMCUであるi.MX RTシリーズにlimited られていましたが,そこにMCX Nシリーズという,より小scaleで手を出しやすい选択limbがplusわったことになります.
このボードにWired のEthernetが load っている点も见狠せません. MicroPython が安価なボードの多くは, Wi-Fi やBluetooth でネットワークにつなぎます. The purpose is the same as the radio wave, the wired one is the wired one, the scene is the same.この记事の后halfでは,ボードをWebサーバにしてブラウザからLEDをoperationするところまで动かします.
On one side, the restriction is on one side. Zephyr ポートは, チップ専用のポートに比べると Function がtwisting られます.たとえば同じNXPのマイコンでも, i.MX RTけの ports/mimxrt には network.LAN() があってIPアドレスを実行时にSETできますが, Zephyrポートには network モジュール自体がありません. Make the えるのは socket だけで, IP アドレスはビルド时にしかdetermine められません.この记事では, そうした restricts と, 実记にぶつかったproblem のevasion strategy も有めて书いています( section 8.2にorganizing しました).
Since then, MicroPython has begun, and MicroPython has begun ,LED を光らせ,スイッチを読み,I²CやSPIのデバイスを动かし, the last にEthernet をmake うところまでを一通り Explain します. 「MicroPythonをtouchるのは初めて」という方を思定して, on the way, the hand is smooth and the way is omitted.せずに书きました.
この记事の読み方
It’s a long story, it’s a long story, it’s a must.
Zephyr's open environment environment → Section 2.1から
すでにビルドと书き込みが済んでいる方→ Chapter 3から
How to do it first? → Section 8.6 (Example of how to operate an LED)
Chapter ごとにNecessaryなものは时のとおりです.
Chapters 1~5 : FRDM-MCXN947 main body and USB cable [Assignment time: 60 minutes]
Chapter 6 (I²C) : ジャンパ线 2 books [Assignment time: 20 minutes]
Chapter 7 (SPI) : ジャンパ线 1 [Assignment time: 20 minutes]
Chapter 8 (Ethernet) : LAN Controller 1 [Assignment time: 20 minutes]
0. Catalog
Table of contents
MicroPythonとはなんなのか?
1.1 どういうところで使われているのか
1.2 MicroPythonのいいところ,悪いところ
1.3 MCX Maintenance: 「Zephyrポート」form
1.4 This time's の対応でできるようになったこと
1.5 Zephyr's Weakness: Designated by Zephyr
MicroPython Zephyrポートのビルド
2.1 Zephyr open environment environment
2.2 MicroPython のソースをGet する
2.3 ビルドする
2.4 ボードに书き込む
MicroPython ってみる — Basic Editor
3.1 Thonny する
3.2 USB USB
3.3 Accept the confirmation
3.4 「REPL」とは
3.5 スクリプトを书いてみる:Lチカ
3.6 このボードで使えるピンを动べる
3.7 Lチカの色を変えてみる
Edited by: ピン名を公夫する
4.1 まずはスクリプトの中にPINS Dictionary を书く
4.2 config.pyにcutり出す
4.3 ストレージにSaved by してShared by する
4.4 config.pyった3色Lチカ
Editor: スイッチを読む
5.1 スイッチのSTATEを読む
5.2 杀されたことを Cut り込みで知る
User editor: I²C ってみる
6.1 このボードのI²C matter
6.2 ジャンパを2本つなぐ
6.3 バスをスキャンする
6.4 Temperature control
Editor: SPI ってみる
7.1 ループバックでtrial
7.2 CS automatic control system
Editor: Ethernet ってみる
8.1 Wired LAN connection
8.2 このポートのネットワークAPI
8.3 PC direct connection test
8.4 Self-divided IP address
8.5 ボードをWebサーバにする
8.6 LED display operation method
8.7 The power supply is connected to the power supply.
8.8 ハマりやすいPoint
まとめ
References
Additional Notes: LED Operation System Explanation
11.1 ここまでのcontentが1つにまとまっている
11.2 コードの3つのShi hangけ
11.3 Reasons why exceptions are necessary
11.4 Connection: close について
11.5 そのほか気をつける点
11.6 The future of the future
1. MicroPython とはなんなのか?
MicroPythonは,マイコンの上でdirect actionくPython 3のインタプリタです. Damien in 2013 George's Kickstarter fund collection is open now.はオープンソース(MITライセンス)のプロジェクトとして开発が続いています.
"Python 3 processing system" といっても, PC で动くCPython をそのままhold ってきたわけではありません. There are hundreds of KB of ROM and dozens of KB of RAM, and the language can be used in a variety of ways.そのためgrammarはPython 3とほぼ Same as じですが, standard ライブラリはnecessary なものだけがpurpose されています.
その代わりに,マイコンならではのモジュールが意されています. GPIO, I²C, SPI, UART, PWM, ADC and other machine functions.このブログでも machine モジュールを使っていきます.
なお,この章はBackground descriptionです.
すぐに手を动かしたい方はChapter 2へ入んでください.
1.1 どういうところで使われているのか
MicroPython is used to perform tasks, and times are used to perform scenes.
Educational use : BBC micro:bitがMicroPythonをadoptsしたことで,一気に知られるようになりました. Raspberry Pi Pico も MicroPython を formula に サ ポ ー ト し て い ま す.
プロトタイピング:センサをとりあえず动かしてデータを见てみたい,というstageでは.
Jig and measuring device : Manufacturer of ラインの検CHECK Jig や, のように of simple measuring device for 実験 use, 『A small amount of でいいのでEarly work りたい』ものに向いています.
ホビー:Electronic work is divided into different areas.
いずれも sincecessous by early く作る」ここがMicroPython's one-stop proud division といえます.
1.2 MicroPythonのいいところ,悪いところ
このsectionのcontentは, specific のマイコンやポートにlimit らない, MicroPython’s general properties です. Make the judgment of うかどうかをできるように, 両面を挙げておきます.
いいところ
コードが简単に书ける:Python 3のgrammarがそのまま使えます. The character string processing is the same as the operation, and the C processing is the number of lines and the writing is the same.
The answer to the question is: ボードに与続して, 1 line of ずつコマンドを打ち込みながらactionを正かめられます. 「このピンをHIGHにしたらLEDはPointくのか, eliminateえるのか」といったconfirmationが,その fieldで1 row hitつだけで済みます.ハードウェアの挙猙动を Manual detection りで真かめるとき, これは very strong です. (この対情码ENVIREPLとHUびます.Section 3.4 detailed explanationします)
ビルドが要らない:スクリプトを书いて実行するだけです.コンパイル・リンク・书き込みのサイクルが不要なので, trial and error がspeed く ります.
Learn コストがlowい: Python を知っていれば, マイコンのknowledge だけ Foot せば开 められます.
悪いところ
The speed of running is : インタプリタなので, Cで书いたコードに is dozens of times higher than べると, and it is a hundred times higher than ぅくなります. It is necessary to control the necessary processing and high-speed signal processing.ただし対泽はあって,Guan Shuに @micropython.native や @micropython.viper のデコレータをpayけると, その关数だけをネイティブコードにコンパイルできます.それでも足りないoccasionは,そのpartだけCで书いてモジュールとして组み込むこともできます.
メモリを食う: インタプリタ main body and standard ライブラリをマイコンにせる Required があります. Hundreds of KB of RAM, tens of KB of RAM, consumption of books in front of the time. The small さなマイコンでは is now the ではありません.
ガベージコレクションがThe action of the movement is complete and the control is complete.
MCXN947は2MBのフラッシュと512KBのSRAMをチップ上にholdっているので,メモリの点では yuyu をもってMicroPythonを开せられます.
1.3 MCX Maintenance: 「Zephyrポート」form
MicroPythonは,マイコンのkindごとに「ポート」とcallingばれるported versionをholdっています. ports/rp2 (Raspberry Pi Pico), ports/mimxrt (i.MX RT), ports/esp32 といったtool合です. The これらはeach マイコンのレジスタやSDKを is directly 叩く, and the そのチップ専用の実装です.
MCX シリーズについては, このような専用ポートはexistent しません.その代わりに使えるのが ports/zephyr , つまりZephyr RTOSの上で动かすポートです.
Zephyrがサポートしているボードなら, principle of the same "MicroPython" Zephyr Zephyrめ, MicroPython side has a unique and necessary function.
FRDM-MCXN947 は Zephyr が に サ ポ ー ト し て る ボ ー ド な の で, こ の士组 み に ride る こ と が で き ま す.
NXPのマイコンでMicroPython is used
ここで小しorganize しておきます.
NXPのマイコンでMicroPythonを动かそうとしたとき,これまで実性的な选択limbはi.MX RTシリーズでした。 Exclusive use of ポートの ports/mimxrt がRT1010からRT1170までのEVKやTeensy 4 .
Zephyrポートにも前からいくつかNXPボードのSETが入っていましたが, mimxrt1020_evk や mimxrt685_evk_cm33 といったクロスオーバーMCU to けか, frdm_k64f / frdm_kw41z のようにかなり前のKinetis to けで, しかもlater はファイルシステムやI²C/SPIまで全えられたものではありませんでした.
i.MX RT has high performance and high performance, while MCU has a high-end product group. "MicroPython's use of microPython" and its purpose are as follows:
This time, the settings of FRDM-MCXN947 are set up, and the general-purpose MCU is MCX Nシリーズという, より手を出しやすい选択limbs plus わりました.これもThis time's の対応のmeaningのひとつだと思います.
図1: MicroPython Zephyr class
この道には, 强的do と无码 の両方があります. Changsuo, Zephyr, Zephyr, が対応しているボードに纃く unfolds できること. Short place, Zephyr's abstraction, すぶん, チップ専用ポートに比べて「そのボードらしい书きFlavour」が thin くなることです. The specific details will be discussed later.
1.4 This time's の対応でできるようになったこと
Zephyr's own body has been used before, and the settings used for FRDM-MCXN947 have been set up.そのままビルドすると,対语的にコマンドを打ち込むことはできても,ストレージもI²CもSPIも使えない,というSTATEでした.
This time, the following の2つのファイルが本家 micropython/micropython のmasterにマージされました.
ports/zephyr/boards/frdm_mcxn947_mcxn947_cpu0.conf
ports/zephyr/boards/frdm_mcxn947_mcxn947_cpu0.overlay
これによって,时のことができるようになっています.
(1) オンボードのフラッシュをファイルシステムとして使える
FRDM-MCXN947にっている8 MiBのQSPIフラッシュ(Winbond W25Q64JV)の storage_partition を,LittleFSとして /flash にマウントします. The book is saved by the book いたスクリプトをボード上にしておけるようになる, the というmeans で, and the これが一大きい変changes です.
実界にマウントしたstatusでCapacityをconfirmationすると,时のようになります.
>>> import os
>>> os.statvfs('/flash')
(4096, 4096, 2048, 2043, 2043, 0, 0, 0, 0, 255)
ブロックサイズ4096バイト × 2048ブロック = 8 MiB のうち, LittleFS management area をexcept いたabout 7.98 MiB が えます.
(2) MikroBusのSPIが使えるようになった
MikroBusコネクタのSPI( flexcomm6_lpspi6 )をeffectiveにしています.このSPIは, ボード通のdevicetree ではピンDefinition まで意されているものの, status = "disabled" のままになっていました. MOSI/SCK is used for P3_20/P3_21, SAI1 is shared with others.
SAIは Serial Audio Interfaceの slightly, I²SやTDMといったデジタルオーディオのデータをやり出りするためのシリアル・インターフェースです.オーディオコーデックやマイクを行ぐときに使うもので, Same as じピンをSPIとSAIの両squareにsimultaneouslyに Cutり为てることはできません.そのためボード common definition では, どちらともdetermine めずに invalid にしてありました.
では, どちらに使うのか. This time the overlay is valid and the SPI is valid and the judgment is valid. Gen拠は単正で,MicroPythonのZephyrポートにはI²S /SAIをうドライバも machine.I2S のようなクラスもexistent しないからです.つまりSAI1のピンとして半しておいても, MicroPython からは making いようがありません.それならSPIとしてmakes えるようにしたほうが useful だろう, というわけです.
(3) I²CとSPIのドライバが组み込まれるようになった
CONFIG_I2C=y と CONFIG_SPI=y しています.これがないと machine.I2C や machine.SPI を作ろうとしてもFAILURE します.
1.5 Zephyr's Weakness: Designated by Zephyr
さて, ここでZephyrポートの「使いにくいところ」を前に说しておきます.あとで対 Ceをshowすので,まずはquestionを知っておいてください.
Normally MicroPython is used, and the name of MicroPython is specified by name.
# i.MX RTの専用ポート(ports/mimxrt)の場合
led = Pin('D9', Pin.OUT)
# Raspberry Pi Pico の場合
led = Pin(25, Pin.OUT)
# ESP32 の場合
led = Pin(2, Pin.OUT)
Same as NXP's のマイコンでも, i.MX RT's の専用ポートでは 'D9' というボード上の表记そのままの名前が使えます.
ところがZephyr ポートでは, GPIO ポートname とビットposition のタプルでspecified します.
# FRDM-MCXN947(Zephyrポート)の場合
led = Pin(("gpio0", 10), Pin.OUT)
("gpio0", 10) は「GPIO0ポートの10ビット目」,つまりデータシート上のP0_10を Refers to します. The form of the violation is the crossing, and the time is the crossing.
>>> Pin(25, Pin.OUT)
Traceback (most recent call last):
File " ", line 1, in
ValueError: Pin id must be tuple of ("GPIO_x", pin#)
なぜこうなっているかというと, ZephyrのdevicetreeではGPIOが gpio0 , gpio1 ,…というポート単position のデバイスとしてDefinition されていて, その中のビットposition でピンをrefers to すからです. MicroPython side is open and closed.
The problem is that the digital circuit is printed and printed .たとえば っても,そのD9が ("gpio0", 10) であることは,devicetreeを読まないとわかりません. Arduino ヘッダーの D9 や, RGB LED の 赤 といった名前は, MicroPython everything seen えないのです.
これはかなりIt’s inconvenient. Chapter 4 : この対 CeをStep by StepをChasingってIntroductionします.
コラム:Zephyrは「SDKの下注り」としても使われている
Zephyr み込みアプリケーションを书くためのRTOS" というイメージが强いと思います.実记そのとおりなのですが, recently the はもうひとつの使われ方が目立ってきました. Don't use the SDK to install the platform on the ground .
This time's MicroPython Zephyrポートがまさにそれです.ユーザーが书くのはPythonのコードで, Zephyr's existence をconsciousness することはほとんどありません. MicroPy thonのインタプリタ自も, Zephyrのスレッドのひとつとして実行されています.
Example of the same structure: ArduinoCore-zephyrがあります.これはArduinoのAPI( pinMode() , digitalWrite() , Wire , SPI ...)をZephyrの上に実装したもので, Arduino IDEから使うlimitりはZephyrは见えません.けれども下注りはZephyrなので, Zephyrが対応しているボードにArduino environment をhold ち込めることになります.
このように「Zephyrをdirect use」に「Zephyrの上にったものを使う」という选択 Limb が壗えてきています. Zephyr's のボードサポートを preparation することが, そのままMicroPython やArduino's 対応にもつながる, というrelations です.
▲ Catalog に戻る
2. MicroPython Zephyrポートのビルド
ここからは実记に手を动かしていきます.まずはファームウェアをビルドしてボードに书き込みます.
2.1 Zephyr open environment environment
この记事のコマンド Exampleは, macOSやLinuxのシェル(bashやzsh)をpremiseにしています. Windows is easy to use, and the environment is easy to use.
コラム:Windows does not enter the situation
The first conclusion is the book, the Windows PowerShell (cmd.exe), the Windows PowerShell, and the PowerShell .コマンドを书きchangeえても駄目です.
MicroPython's processing is done, and UNIX's dependency is maintained.ビルドを定めている py/mkrules.cmake の中で, cat ・ sed ・ touch が directly call ばれています.たとえばqstr (character sequence テーブル) する箇所は, 时のようなシェルのパイプライン1 で书かれています.
cat … | sed … | (Cプリプロセッサ) | sed … > 出力ファイル
これらのコマンドはWindowsにexistingしません. cmd.exe There cat is sed no ending, and the ending is ending.シェルを変えてもsolvedしないのはこのためです.
実记,MicroPython's main familyのCIでも, Zephyrポートのビルドは ubuntu-latest でのみ実行されています. Windows でのビルドは Thought されていません.
风らわしいのですが, Zephyr's own はネイティブのWindows でビルドできます.この节で IntroductionするZephyrのGetting Started Guideにも、wingetでツールを入れるWindows 到けの手顺があります. MicroPythonをビルドするdan step になって初めて行き诘まる, ということが出こります.
Windows has entered the environment, and the environment of the UNIX environment has improved.どちらでも、この记事のコマンドはそのまま使えます.
WSL2 (Windows Subsystem for Linux). Zephyr's Getting Started Guideでも, Ubuntu's application to the user's hand is easy to use. Import instructions for Microsoft
Git for Windows (Git Bash) やMSYS2のbash environment
なお,ビルドと书き込みだけをUNIX environment で行い, Thonny でのMicroPython operation は Windows side から, という分け方 もできます. ThonnyもmpremoteもWindowsでそのまま动くので, from chapter 3 onwardsはWindowsだけで入められます.
MicroPython Zephyr's environment (west, Zephyr SDK, Python's environment) is not necessary
Zephyr environment construction guide, NXP Japanese language explanation and explanation The まだenvironment is made by the っていない方は, and the まずそちらを refers to the してください.
Zephyr シリーズ Chapter 2 はじめてのビルドと実机动(日本语ブログ)
この记事で Reference していただきたいのは, Kailu environment をインストールする partです. The second half of the story, Zephyr, Zephyr blinky など)をビルドして动かしますが,このブログでビルドするのはZephyrのサンプルではなくMicroPythonです.ビルドの対相をSpecificationするPartだけがviolationうとtestえてください. west build The status of the pass is the same as the work, and the preparation is completed.
Zephyr's formula is the following.
Zephyr Getting Started Guide
Environment ができていれば, ~/zephyrproject のようなディレクトリにwest workspace がpurpose されているはずです. Hereafter はこれを ~/zephyrproject として说します.
2.2 MicroPython のソースをGet する
MicroPython のソースは, Zephyr のworkspace とはdifferent place に Location い て struct い ま せ ん. Zephyr's workspace is dirty, and it's a different place.
git clone https://github.com/micropython/micropython.git
cloneしたら,为られたディレクトリに动ってサブモジュールをGetします.
cd micropython
git submodule update --init lib/micropython-lib
micropython-lib MicroPython uses the standard ライブラリgroup and サブモジュールとしてseparationされています.これをGet the しておかないとビルド时にエラーになるので, forget the れずに実行してください.
The book that appears is the book, the setting for FRDM-MCXN947 is the master of the main house.パッチをあてるNecessaryはありません.
Read the のため, and use the のファイルがあることを to confirm the しておきましょう. micropython ディレクトリにいるSTATUSのまま実行します.
ls ports/zephyr/boards/ | grep mcxn947
frdm_mcxn947_mcxn947_cpu0.conf と frdm_mcxn947_mcxn947_cpu0.overlay の2つが means されればOKです.
なぜファイル名が长いのか
Zephyr では, the same as じボードでもコアやaction モードによってplural の constitute をhold つことがあります. FRDM-MCXN947 Cortex-M33 Cortex-M33 をデュアルで is equipped with しているため, frdm_mcxn947/mcxn947/cpu0 のように「ボードName/SoC name/コアname」specified します. Board qualifier (board qualifier) and board qualifier.
MicroPython's Zephyr ポートは, このmodifier をincluding めた名前でconf/overlay をExploration します.つまり frdm_mcxn947.conf という名前では読み込まれません. frdm_mcxn947_mcxn947_cpu0.conf としてはじめて见されます. The self-divided settings are added to the setting, and the settings are added to the settings.
2.3 ビルドする
まずZephyrの仮 Thinking about the environment をeffectiveにします.
source ~/zephyrproject/.venv/bin/activate
Zephyrのバージョンを合わせます.
cd ~/zephyrproject/zephyr
git checkout v4.4.0
west update
MicroPython's Zephyr ポートが対応を明言しているのは, v3.7 (LTS) and v4.4, そして开発版です. Honke's CIはv4.4でビルドを検证しています.のバージョンになっていると, outside workspace , 通ってもactionがviolationったりすることがあるので,ここでv4.4.0に揃えておきます.
west update HALやライブラリなどのrelated モジュールをtake り正すためのものです. git checkout だけでは不integrationが residualるので,必ずセットで実行してください.
Preparationができたら west build を実行します.
cd ~/zephyrproject
west build -b frdm_mcxn947/mcxn947/cpu0 ~/micropython/ports/zephyr
-b がボード specifies, the last argument is がビルド対相のアプリケーション(MicroPythonのZephyrポート)です. ~/micropython のpartは,実记にcloneしたplaceに読み为えてください.
ビルドが通ると build/zephyr/ の下に zephyr.bin , zephyr.hex , zephyr.elf がGenerationされます.
After 2 episodes, the settings are straight and straight, --pristine (または -p ) The result of the previous return is the result of the previous return.
cd ~/zephyrproject
west build -p -b frdm_mcxn947/mcxn947/cpu0 ~/micropython/ports/zephyr
2.4 ボードに书き込む
FRDM-MCXN947にはMCU-LinkデバッガがオンボードでThe book is written in a different way, the purpose is necessary, and the book is written in a different way.
USB ケーブルはJ17 (MCU-Link side USB コネクタ) connector
図2: USB connector J17 (MCU-Link side) connector
Receive 続したら, west flash を実行するだけです.
cd ~/zephyrproject
west flash
Book き込みがEnd わると, ボードはAutomatic にリセットされてMicroPython がStart します.
このJ17は书き込みだけでなく, MicroPython と対语するためのシリアルcommunication にも使います.つまりケーブル1で书き込みとoperationの両方ができます. Detailed description in Section 3.2 .
▲ Catalog に戻る
3. MicroPython ってみる—Basic editor
ファームウェアが书き込めたら, いよいよMicroPython をtouch っていきます.
3.1 Thonny する
MicroPython is easy to use, and the environment of MicroPython is not necessary.ターミナルソフトでもstructuring いませんが, ここではThonnyをmaking います.
Thonny is MicroPython's first functional function and is also an IDE. Free of charge, Windows / macOS / Linux can be used.
Thonny formula サイト
The basic operation of Thonny's のインストールと is the basic operation, and the following animation is the corresponding part.
MicroPythonをi.MX RTクロスオーバーMCUで动かしてみた(YouTube) — Thonnyの Import PartからRegenerationされます
Thonny is the advantage of the point, and the communication is the same.
The upper part of the book, the upper part of the book, the upper part of the book, the upper part of the book
ボードのファイルシステム( /flash )の中体をGUIで见られる
PCとボードの间でファイルをドラッグ&ドロップでコピーできる
という点です. Chapter 4.
3.2 USB USB
FRDM-MCXN947にはUSB Type-Cのコネクタがpluralあります. MicroPython のコンソールにsystem ぐのはJ17 , MCU-Link side のコネクタです ( Section 2.4の図2と同じ地です).
MicroPython のコンソールは, Zephyr のコンソール( zephyr,console )に出力されます. FRDM-MCXN947のcpu0では,これが flexcomm4_lpuart4 (P1_8 / P1_9) The original MCU-Link MCU-Link VCOM (仮愿COMポート) がっています.
つまりJ17の1书で,ファームウェアの书き込みとコンソールの両方ができます. The main body of MCXN947 is the USB system of the main body, and the composition of this chapter is the USB system.
3.3 Accept the confirmation
ケーブルを行いだらThonnyをStartします.
Thonny's lower right (またはメニューの「実行」→「インタプリタの选択」)から,インタプリタとして「MicroPython (generic) "を Select び, ポートにボードのVCOM をSpecify します.
Windows: COM3 のような名前
macOS: /dev/cu.usbmodem…
Linux: /dev/ttyACM0 など
図3:インタプリタに「MicroPython (generic)」を选ぶ
The うまく system is a がると, the lower のシェル(Shell) ペインにプロンプトが出ます. Ctrl-D (ソフトリセット)を気てみてください.
MicroPython v1.30.0-preview.17.g47e9329e51 on 2026-08-30; zephyr-frdm_mcxn947 with mcxn947
Type "help()" for more information.
>>>
図4: The success of the 続にすると, シェルペイン(ウィンドウ下)にバナーとプロンプトが means される
The last part of zephyr-frdm_mcxn947 with mcxn947 is the focus of attention. zephyr-frdm_mcxn947 はZephyrの CONFIG_BOARD , mcxn947 は CONFIG_SOC から作られる名前です.ここがLook forward to どおりになっていれば, snipe ったボード Use のバイナリが move いているとconfirm できます.
>>> がプロンプトです.ここにPythonのstyleを打ち込めます.まず「Hello, world!」のexpressionから出してみましょう.
>>> print("Hello, world!")
Hello, world!
MicroPython はPython なので, formula をhit つだけでも results が return ります.
>>> 1 + 2
3
>>> "MCX" * 3
'MCXMCXMCX'
ファイルシステムもconfirmationしておきます.
>>> import os
>>> os.getcwd()
'/flash'
>>> os.listdir('/flash')
[]
Start the straight back のカレントディレクトリが /flash になっています.これはThis time the マージされたsetでLittleFSがマウントされているからです.まだ何も志いていないので中体は空です.
3.4 「REPL」とは
いま打ち込んでいるこの対情码ENVIRONMENT をREPLとHUびます. R ead (読む), E val (evaluation価する), P rint (expression す る), L oop (粲 り return す) no initial character で す.
1 line of input force, MicroPython はそれを読み, 実行し, the result を represents し, また时の enter force をWaiting ちます.これがREPLです.
コンパイルして书き込んで実行して, という手顺をStep on the result of がわからないCの开発と比べると, trial and error の回しかたそのものが変わってきます.たとえば「このピンをHIGHにしたらLEDは点くのか, eliminateえるのか」といったconfirmationが, そのfieldで1 line hit つだけで済みます.ハードウェアの挙猙动を Manual detection りで真かめるとき, REPL はvery powerful な props になります.
REPL is easy to use and easy to operate.
キー
Action
Ctrl-C
実行中のプログラムをinterruptionする
Ctrl-D
MicroPython ソを restart する
Ctrl-E
ペーストモードに入る
Ctrl-A
rawREPLモードに入る
Ctrl-B
Normal REPLモードに戻る
Table 1: REPL control system
Ctrl-Cは, unlimited ループに入ってしまったプログラムをstop めるときに使います. Ctrl-D
Ctrl-Eのペーストモードは, plural line のコードをまとめてsticker けるときに使います. Normally REPLは1行ごとにインデントを解釈しようとするので, for 文のようなplural lineのコードをそのままるとうまくいかないことがあります. Ctrl-E して ら コ ー ド を paste り け, Ctrl-D で実行 す る と, ま と め て さ れ ま す.
3.5 スクリプトを书いてみる:Lチカ
ここまではREPLに1行ずつ打ち込んできました.ちょっとしたconfirm にはこれが一半hayいのですが,缲り回しやconditions divergence が into ってくるとさすがに俫なります.そういうまとまったprocessingは, スクリプトとして书いたほうが楽です.
ではスクリプトを书いてみましょう. LED のLチカ(LEDチカチカ)です.
FRDM-MCXN947にはRGBのLEDがっています.まずは红を点杀させてみます.红のLEDはP0_10,つまり ("gpio0", 10) に式がっています.
Thonny's upper part is the upper part of the book, and the second part is the book.
import time
from machine import Pin
led = Pin(("gpio0", 10), Pin.OUT) # 赤LED (P0_10)
while True:
led.value(0) # 点灯
time.sleep(0.5)
led.value(1) # 消灯
time.sleep(0.5)
図5: The upper side of the book. Lower side がシェルペイン
书けたら, ツールバーの「実行」ボタン(Green Triangleのアイコン.ショートカットはF5)を気ます. Thonnyが , ious Generation ched in in in on in MicroPython Today's test is the same as the test, and the test is the same as the test.
The red LED lights up successfully in 0.5 seconds.
Stop it, stop it, stop it, stop it.シェルペインでCtrl-Cを気ても同じように出まります.
ここで「あれ?」と思った方へ
コードをよく见てください. value(0) means turning on the lights, value(1) means turning off the lights. Intuition is the opposite of seeing the truth, and the harmony is the truth.
FRDM-MCXN947のRGB LEDは,アノードコモンでConnect続されています. LED side power supply system, マイコンのピンがマイナス side を lead っ Zhang る-shaped です.つまりピンをLOW(0)にしたときにcurrent が流れてlighting します.このような涚をアクティブ・ローといいます.
図6: The RGB LED part of the FRDM-MCXN947 circuit . LED power supply system
Zephyrのdevicetreeには,このLEDが GPIO_ACTIVE_LOW であるというInformationがちゃんと书かれています.しかしMicroPythonの machine.Pin は,devicetreeのこのフラグを见ずにGPIOを生の値のまま読み书きします(内で gpio_pin_set_raw() をHUんでいます).そのため, 论理をanti転してくれることはありません. 0 を书けばピンはLOWになり,LEDは点きます.
ちなみに, led.value(0) は led.off() とも书けます.つまり led.off() をHUぶとLEDはLight upします. Mingmao と実记のaction が inverse になるので, chaos しそうなときは value(0) / value(1) で书くほうが安全 かもしれません.
もうひとつ Note: toggle() はありません
His のポートのMicroPythonにcustomれていると led.toggle() と书きたくなりますが, Zephyr ポートの Pin にはこのメソッドがありません. Make it a new one.
メソッド/fixed number
Description
value([x])
The quotation is なしで読み出し, the quotation is ありで书き込み
on()
HIGH(1)をoutput
off()
LOW(0)をoutput
init(...)
ピンのsettings update
irq(...)
Cut the り込みハンドラを setting
Pin.IN / Pin.OUT / Pin.OPEN_DRAIN
input and output power
Pin.PULL_UP / Pin.PULL_DOWN
プルアップ / プルダウン
Pin.IRQ_RISING / Pin.IRQ_FALLING
Cut り込みエッジ
Table 2: Zephyrポートの machine.Pin で使えるもの
トグルしたいときは,読んで転して书けば済みます.
led.value(not led.value())
3.6 このボードで使えるピンを动べる
さて,红のLEDが ("gpio0", 10) であることは,どこから来た値なのかを Description しないまま使ってきました.では自分で调べるにはどうすればいいのでしょうか.
この节では,answerえを探しにZephyrのSETファイルまでdropりていきます.小し込み入った说になるので, first をhurry ぐ方は読み飞ばして4 chapterに入んでstructure いません. Chapter 4: では, ここで调べた対応表をOnce made ってしまえば and then dropped は名前でピンを designated できる, という语をします.
Cannian ながら, MicroPython のZephyr ポートには "make えるピンの一覧をexpression する" function がありません. machine モジュールの中身を见ても, ピンの名前は出てきません.
>>> import machine
>>> dir(machine)
Pin , I2C , SPI , UART , PWM , ADC , Timer , WDT といったクラス名が和びます(実记に何が入っているかはビルド时のSETで変わるので, 手元で実行して真かめてください). Pin というクラスがあることはわかりますが.
では,どこを见ればいいのか
AnswerえはZephyrのdevicetreeです.
devicetreeとは
(Zephyr's original content is known as "FRDM-MCXN947 device tree" and "FRDM-MCXN947's device tree is the same as the original one")
devicetree(デバイスツリー)は,ボードにどんなハードウェアがzai っていて, どう式 がっているかを说したテキストファイルです. The もともとはLinux カーネルで uses the われていた士组みで, and the Zephyr もこれを adopts the しています.
「このSoCにはI²Cコントローラが何的あって,それぞれどのアドレスにあって,どのピンに出ていて,effectiveなのか无なのか」といったinformationが, .dts / .dtsi とい拡张子のファイルにstrata structure で书かれています. Zephyr's にこれを読みtake り, necessary なドライバのInitialization コードやピンのsetting をautomatic にGenerationします.
ソースコードにピン号をdirect bookく代わりに,ハードウェアのConstitution information をコードからSeparationしておく、というtestえ方です.おかげで, the same as じアプリケーションのソースをbie のボード to けにビルドしstraight すことができます.
MicroPython のZephyr ポートが ("gpio0", 10) というタプルをRequirement するのも, このdevicetreeのconstruct をそのまま Reflect しているからです. gpio0 のデバイス名で on はdevicetree, 10 はそのポート内のビット Position です.
FRDM-MCXN947のdevicetreeを読む
FRDM-MCXN947 configuration は, Zephyr のリポジトリの下のファイルに书かれています.
zephyr/boards/nxp/frdm_mcxn947/frdm_mcxn947.dtsi
この中の arduino_header というノードに,Arduinoヘッダーのeach ピンがどのGPIOに Department がるかが书かれています.
arduino_header: arduino-connector {
compatible = "arduino-header-r3";
gpio-map = ,
,
,
,
, /* RX */
, /* TX */
,
...
, /* SCK */
, /* SDA */
; /* SCL */
};
は「ヘッダーのD13は gpio0 の25ビット目」というmeans です.これをMicroPythonのタプルに正すと ("gpio0", 25) になります.
Same as じファイルの中に, LED とスイッチのDefinition もあります.
leds {
compatible = "gpio-leds";
green_led: led_1 { gpios = <&gpio0 27 GPIO_ACTIVE_LOW>; ... };
blue_led: led_2 { gpios = <&gpio1 2 GPIO_ACTIVE_LOW>; ... };
red_led: led_3 { gpios = <&gpio0 10 GPIO_ACTIVE_LOW>; ... };
};
gpio_keys {
compatible = "gpio-keys";
user_button_2: button_0 { gpios = <&gpio0 23 ...>; }; /* SW2 */
user_button_3: button_1 { gpios = <&gpio0 6 ...>; }; /* SW3 */
};
红のLEDが &gpio0 10 , つまり ("gpio0", 10) であることがここでconfirmできます. GPIO_ACTIVE_LOW と书かれているのも见えますね. The first explanation is the root of the root.
Every time devicetree を読むのか?
もちろん, every time I return to the これを tune and the べるのは is now the ではありません. 「LEDを光らせたいだけなのにdevicetreeを読む」というのは, MicroPythonの手軽さを台无しにしています.
そこで4 chapter では, この対応expression を once だけ作って, and then は名前で书けるようにするmethod を Introduction します.
3.7 Lチカの色を変えてみる
対泽の前に,タプルspecified inconvenienceさをもう小しphysical senseしておきましょう. 3-color LED light source.
devicetreeから読みtakeった値は时のとおりでした.
color
ピン
タプル
red
P0_10
("gpio0", 10)
green
P0_27
("gpio0", 27)
green
P1_2
("gpio1", 2)
Table 3: RGB LED lighting
import time
from machine import Pin
red = Pin(("gpio0", 10), Pin.OUT, value=1)
green = Pin(("gpio0", 27), Pin.OUT, value=1)
blue = Pin(("gpio1", 2), Pin.OUT, value=1)
while True:
for led in (red, green, blue):
led.value(0) # 点灯
time.sleep(0.5)
led.value(1) # 消灯
Pin() の value=1 は, ピンをOutputにsettingするとsimultaneousにInitial valueをHIGH(lights off)にするSpecificationです.これをpay けないと, set した moment に a moment light ることがあります.
Red→green→green とshunfanに光ればsuccessです.
さて, このコードを见てどう思うでしょうか.
red = Pin(("gpio0", 10), Pin.OUT, value=1)
("gpio0", 10) The part of というに means が読みtake れません. red という変numeral nameをpayけたから読めるだけで,このnumeralだけを见て「redのLED」だとわかる人はいないはずです.
しかも, このdigits えてもエラーにはなりません. ("gpio0", 11) と书いてしまったら, exist するピンなので Pin はnormal に为られ, ただLED らないだけです. 「どこが悪いのか」を探すのに时を取られることになります.
このquestion を, times の Zhang で片Pay けます.
▲ Catalog に戻る
4. Urgent editor: ピン名を公夫する
Zephyr ポートがピン名をprovides してくれないなら, and the intention is to separate it. The policy of それがこの章です.
Step by step を chase っ て, 3 つ の step by step で advance め ま す.
スクリプトの中にlexiconを书く
config.py というfarewellファイルに Cutり出す
ボードのストレージに出いて,すべてのスクリプトからshared
4.1 まずはスクリプトの中にPINS Dictionary を书く
Ichiban 単なのは, スクリプトの前头にPythonのdictionaryを书いてしまうmethodです.
import time
from machine import Pin
PINS = {
"LED_RED": ("gpio0", 10),
"LED_GREEN": ("gpio0", 27),
"LED_BLUE": ("gpio1", 2),
}
red = Pin(PINS["LED_RED"], Pin.OUT, value=1)
while True:
red.value(0)
time.sleep(0.5)
red.value(1)
time.sleep(0.5)
Pin(PINS["LED_RED"], ...) と书けるようになりました.これなら何をしているか一目でわかります.
さらに好いのは,タイプミスがエラーになることです.
>>> Pin(PINS["LED_RD"], Pin.OUT)
Traceback (most recent call last):
File " ", line 1, in
KeyError: LED_RD
First of all, "Numbers and numbers are violated". Dictionary のキーを间violation えれば KeyError でstop まってくれます.これだけでもデバッグの手间がかなり minus ります.
4.2 config.pyにcutり出す
しかし, スクリプトを书くたびにこのdictionary をコピーするのは面流です.実记, LEDだけでなくArduinoヘッダーやMikroBusのピンもDefinitionしたくなるので, Dictionaryはどんどん长くなります.そのたびにallのスクリプトの头にstickerりpayけるのは成実的ではありません.
Pythonらしく,不ファイルに Cutり出してimportしましょう. config.py というファイルを作ります.
PINS = {
# --- Arduinoヘッダー ---
"D0": ("gpio4", 3), # P4_3 (RX)
"D1": ("gpio4", 2), # P4_2 (TX)
"D2": ("gpio0", 29), # P0_29
"D3": ("gpio1", 23), # P1_23
"D4": ("gpio0", 30), # P0_30
"D5": ("gpio1", 21), # P1_21
"D6": ("gpio1", 2), # P1_2
"D7": ("gpio0", 31), # P0_31
"D8": ("gpio0", 28), # P0_28
"D9": ("gpio0", 10), # P0_10
"D10": ("gpio0", 27), # P0_27 (CS)
"D11": ("gpio0", 24), # P0_24 (MOSI)
"D12": ("gpio0", 26), # P0_26 (MISO)
"D13": ("gpio0", 25), # P0_25 (SCK)
"D14": ("gpio4", 0), # P4_0 (SDA)
"D15": ("gpio4", 1), # P4_1 (SCL)
"A2": ("gpio0", 14), # P0_14
"A3": ("gpio0", 22), # P0_22
"A4": ("gpio0", 15), # P0_15
"A5": ("gpio0", 23), # P0_23
# --- バス(Zephyrのデバイスノード名) ---
"I2C": "lpi2c@94800", # flexcomm2_lpi2c2 (arduino_i2c)
"SPI": "spi@93000", # flexcomm1_lpspi1 (D10〜D13)
"MIKROBUS_I2C": "lpi2c@95800", # flexcomm3_lpi2c3
"MIKROBUS_SPI": "spi@b6000", # flexcomm6_lpspi6
# --- MikroBusのGPIO ---
"MIKROBUS_RST": ("gpio1", 3),
"MIKROBUS_CS": ("gpio3", 23),
"MIKROBUS_SCK": ("gpio3", 21),
"MIKROBUS_MISO": ("gpio3", 22),
"MIKROBUS_MOSI": ("gpio3", 20),
"MIKROBUS_PWM": ("gpio3", 19),
"MIKROBUS_INT": ("gpio5", 7),
"MIKROBUS_RX": ("gpio1", 16), # GPIOとして使える.UARTのRXではない
"MIKROBUS_TX": ("gpio1", 17), # GPIOとして使える.UARTのTXではない
"MIKROBUS_SCL": ("gpio1", 1),
"MIKROBUS_SDA": ("gpio1", 0),
# --- エイリアス ---
"LED_RED": ("gpio0", 10), # = D9
"LED_GREEN": ("gpio0", 27), # = D10
"LED_BLUE": ("gpio1", 2), # = D6
"SW2": ("gpio0", 23), # = A5
"SW3": ("gpio0", 6), # P0_6
}
すべてdevicetreeから転记した値です.
いくつか complements します.
RGB LED is shared with Arduino.
Red LED (P0_10) is the same as Arduino D9 D9. Same as green D10, blue D6. Arduino シールドをinsert すときは, これらのピンを うとLED も一丝に光ります. Inverse wording, シールドがD6やD9をmakes っていると, LED のつもりでoperation するとシールドlateral influence が出ます.
SDA/SCLはA4/A5ではありません.
Arduino UNO R3 のボードでは, I²C のSDA/SCL がA4/A5 と same wiring になっていることが多く,「A4=SDA,A5=SCL」と覚えている方も多いと思います.しかしFRDM-MCXN947ではviolationいます. I²CはAREFの neighborにある専用のSDA/SCLピン(Zephyrのdevicetree上ではD14/D15)に出ていて,これはP4_0/P4_1です. A4 (P0_15) and A5 (P0_23), I²C system independent GPIO. Chapter 5: でジャンパを性ぐときにimportant になるので, 覚えておいてください.
SW2はA5と同じピンです.
ユーザースイッチのSW2 (P0_23)は, Arduino ヘッダーのA5と Same as the じピンに system がっています. A5's output is the same as the circuit's influence, and the attention is the same.
バスは character string is specified by します.
machine.I2C と machine.SPI のid parameterは,タプルではなくZephyrのデバイスノード名の character stringです. "lpi2c@94800" の 94800 は,MCXN947のメモリマップ上のペリフェラルのアドレス(0x94800)です.ここもdevicetree originの値です.
4.3 ストレージにSaved by してShared by する
config.py ができました.
スクリプトは「モジュール」として読み込める
The first step is the first step, and the import step is the first step to complete the step.
config.py はSpecial formのファイルではありません. PINS = { ... } と书いただけの、ごく ordinary Pythonのスクリプトです. Lチカのスクリプトと同じ,ただのテキストファイルです.
Python では,こうしたスクリプトをhis のスクリプトから読み込んで使えます.読み込まれるlateral をモジュールとHUび, 譭み込むorderが import です.
from config import PINS
これは「 config.py を読み込んで実行し,その中で为られた PINS .py config config.py PINS という means になります.がのままモジュール名になります. の中体が実行されるので というdictionary ができあがり, それをこちらで使える, というわけです.
よく making う definition や Off number を比ファイルにまとめておいて, necessary なスクリプトから読み込む.これはPython でごくGeneral なやり方で, MicroPython でも Same じように使えます.
どこに志けばよいか
では config.py をボードのどこに出けば,すべてのスクリプトから import できるでしょうか.
MicroPythonは,モジュールを sys.path に和んだディレクトリからExploringします. Confirmation.
>>> import sys
>>> sys.path
['', '.frozen', '/flash/lib']
/flash/lib が入っています.これはThis time the マージされた setting is LittleFS がマウントされたときに, the startup process ( _boot.py ) is an automatic addition of してくれるものです.
つまり /flash/lib/config.py としてsaveすれば,どのスクリプトからも from config import PINS でめるということです.
Thonny's home
Thonnyのメニューから「expression」→「ファイル」を选ぶと, the left side of the screen shows the されます. The upper half is for the PC side, and the lower half is for the MicroPython side.
図7:Thonny's config.py /flash/lib
Handy and smooth.
The second half (ボード side)が /flash をexpressしていることをconfirmする
ボードlateral のペインでright クリック →「新しいディレクトリ」を选び, lib を作る
作られた lib をダブルクリックして中に入る
The first half (PC side)で config.py をright クリック →「/flash/lib へアップロード」を选ぶ
Set it and confirm it.
>>> import os
>>> os.listdir('/flash/lib')
['config.py']
コマンドラインからoperation occasion (mpremote)
Thonny is easy to use, easy to operate, easy to operate, and easy to use. mpremote pip install mpremote でインストールできます.
まず lib ディレクトリを作ります.
mpremote mkdir :/flash/lib
その中に config.py をコピーします.
mpremote cp config.py :/flash/lib/config.py
スクリプトを実行するだけなら,ボードにSave せずに実行することもできます.
mpremote run blink.py
4.4 config.pyった3色Lチカ
Get ready. Section 3.7 のコードを书き正してみましょう.
import time
from machine import Pin
from config import PINS
red = Pin(PINS["LED_RED"], Pin.OUT, value=1)
green = Pin(PINS["LED_GREEN"], Pin.OUT, value=1)
blue = Pin(PINS["LED_BLUE"], Pin.OUT, value=1)
while True:
for led in (red, green, blue):
led.value(0) # 点灯
time.sleep(0.5)
led.value(1) # 消灯
Section 3.7 と见比べてください.无いは, Pin() に多しているものだけです.
red = Pin(("gpio0", 10), Pin.OUT, value=1) # 3.7節
red = Pin(PINS["LED_RED"], Pin.OUT, value=1) # こちら
("gpio0", 10) のようなdigitsはどこにも出てきません. 「Red・Green・Blue LEDをshunpanに光らせる」という meaning図が,そのままコードになりました.
これで, 1.5 sections of で挙げたZephyr ポートの weak points, 実 use ほぼ to eliminate できました. config.py At one time, it was done by setting the いてしまえば, and then it was reduced by the ずっと making it えます.
なお, ここで使っている config.py のfull textは4.2に contained せてあります.そのままコピーして使ってください.
トラブルシューティング:うまくimportできないときは
config.py をsetting the いたのに ImportError が出るoccasionは, time をconfirmationしてください.
ソフトリセットをtrial す.シェルペインでCtrl-Dを気ます. MicroPython is imported onceするので, ファイルを出きchange えても古いものが使われることがあります.これが一买よくあるreason です.
Confirm the place of purchase . os.listdir('/flash/lib') で config.py が见えるか真かめます. lib ディレクトリを作る前にアップロードして, /flash/ の正下に式かれてしまっているケースがよくあります.
sys.path をConfirmationする. import sys; print(sys.path) に /flash/lib が入っているか见ます. Enter the っていなければ, /flash のマウントに failure している possibility があります.
ファイル名をconfirmedする. from config import PINS で読めるのは config.py という名前のファイルだけです. Don't forget to save the name before you save it.
▲ Catalog に戻る
5. Editor: スイッチを読む
Chapter 3ではLEDを光らせました. GPIO's contribution is very important. Today's degree is reversed, and the force is applied.
FRDM-MCXN947には,ユーザーが免费に使えるスイッチが2つっています. SW2 and SW3 are the same.ここではSW2を使います.
図8:ユーザースイッチSW2とSW3のposition
この章にAdditional parts は要りません.ボードとUSBケーブルだけで入められます.
5.1 スイッチのSTATEを読む
SW2はP0_23 がっていて, config.py に SW2 として入れてあります.
from machine import Pin
from config import PINS
sw = Pin(PINS["SW2"], Pin.IN, Pin.PULL_UP)
print(sw.value())
Pin.IN でEnter force setting, Pin.PULL_UP でInternal resistance is effective.
なぜプルアップが必なのか
このスイッチは, Otsu すとピンがGND に行がる路になっています. The opposite is true, the opposite is true, and the opposite is true. The state of the electricity is stable and the voltage is stable.
プルアップresistant をeffectiveにすると, していないときはピンがpower side にciteき上げられてHIGH になります. Otsu し た と き だ け GND に cue か れ て LOW に な り ま す.これで両squareのstateがはっきりします.
つまり読み出される値は时のようになります.
Oshita していない → 1
Oshita している → 0
ここでも 0 が です.
LEDのときと同じアクティブ・ローの考え方で( section 3.5 ),このボードではよく出てくるshapedです.
実行して真かめてみましょう.
>>> print(sw.value())
1
杀していないので 1 が回りました.しながら実行すれば 0 になります.
粲り回し読む occasion
Status を monitoring し続けるなら, こうなります.
import time
from machine import Pin
from config import PINS
sw = Pin(PINS["SW2"], Pin.IN, Pin.PULL_UP)
last = sw.value()
while True:
now = sw.value()
if now != last:
print("押された" if now == 0 else "離された")
last = now
time.sleep_ms(20)
In the previous chapter, の値と比べて, 変化したときだけ means しています. Each time, it means すると, and it means している间ずっと出力され続けてしまうためです.
この法をポーリングと淳ます. The official group is pure and simple, and the shortcomings are small and clear. sleep_ms(20) の间にスイッチが阿されて里されると, 见出してしまいます.かといって Interval を Short くすると, その分だけCPU がこのConfirmation にcharge やされます.
5.2 杀されたことを Cut り込みで知る
そこで使えるのが开り込みです.
「ピンのSTATEが変化したら,この关数をHUんでほしい」とHow to log in, how to deal with it, how to do it. See escape.
machine.Pin では irq() メソッドで登录します.
import time
from machine import Pin
from config import PINS
sw = Pin(PINS["SW2"], Pin.IN, Pin.PULL_UP)
n = 0
def pressed(pin):
global n
n += 1
print(" 割り込み %d 回目 value=%d" % (n, pin.value()))
sw.irq(handler=pressed, trigger=Pin.IRQ_FALLING)
print("SW2を数回押してください(30秒間)")
for i in range(30):
time.sleep(1)
sw.irq(handler=None)
print("合計 %d 回検出しました" % n)
実行してSW2を10 repayment resultsです.
SW2を数回押してください(30秒間)
割り込み 1 回目 value=0
割り込み 2 回目 value=0
割り込み 3 回目 value=0
(中略)
割り込み 10 回目 value=0
合計 10 回検出しました
The number of times is pressed, and the number of times is called, and the number of times is called.
コードの読みかた
trigger には, どの変化でHUんでほしいかをspecified します.
Specify
mean
Pin.IRQ_FALLING
HIGH→LOW の変化(このボードでは「した」)
Pin.IRQ_RISING
LOW→HIGH の変化(「 」)
`Pin.IRQ_FALLING \
Pin.IRQ_RISING`
䡡方
Table 4: irq() の trigger できるもの
ここでは pledge したinstant だけknow りたいので Pin.IRQ_FALLING をspecify しています.
handler に crossing す pass number は, quotation を 1 つ Receive け take るよ う に书 き ま す. Call ばれるときに, cut り込みの起きた Pin オブジェクトが多されるためです. The above example is では pin.value() として, そのピンの値を読んでいます.
global n がNecessary なのは, Guan Shu の外にある変数 を书きchange えるためです.これはPythonのNormalなdeterminationまりで,MicroPythonでも同じです.
The last sw.irq(handler=None) is the last one. Undo it, let it go.
ハンドラの中で print() してよいのか
Cut り込みハンドラの中では, time のかかるprocess やメモリを ensure するprocess をavoid けるのが principle です. print() はどちらにも道てはまるので, originally I avoided it.
ただしMicroPythonの irq() には hard というcitation があり, established value は hard=False です.このとき, ハンドラは Cut り込みが出きた Instant ではなく, 小し后の安全なタイミングにまわして実行されます.そのため print() を书いてもquestion ありません.
hard=True をSpecify すると, cut り込みがきた instantly に実行されます.応 Answer はspeed くなりますが, print() やメモリsure はできなくなります.まずはestablishedのままでstructureいません.
チャタリングについて
Mechanical contact switch, the contact contact is instantaneous and the contact is fine and fine ON/OFF is turned on and off.これをチャタリングとcall び, 1 round of pressing しただけでcut り込みが多も入るreason になります.
FRDM-MCXN947のSW2でしたかぎりでは, 10 times of pressingに対して Cut り込みは 10 times, チャタリングは観measure されませんでした.ただしスイッチの Individual しかたによってはRISE こりうるので, 数が合わないときは, The previous time has passed, and the time has passed, and the short time has passed, and the short time has passed, and the time has passed.
▲ Catalog に戻る
6. Usage editor: I²Cを使ってみる
GPIO's sub-I²C's. Temperature is good.
6.1 このボードのI²C matter
FRDM-MCXN947にはP3T1755というtemperatureセンサが开っています. I²CとI3Cの両方に対応した, decomposition energy 12ビット, accuracy ±0.5℃のセンサです.
ところが,これをMicroPythonからそのまま読むことはできません. The reason is :
MCXN947のI3C1は, the device tree is on the device tree.
pinmux_i3c1: pinmux_i3c1 {
group0 {
pinmux = ,
;
...
};
};
つまりSDAがP1_16, SCLがP1_17です.
One side, MicroPython's Zephyr's ポートにはI3C's のドライバがありません. machine モジュールにあるのは I2C だけで, I3C というクラスは EXISTENCE しないのです.つまりMicroPythonからは,このセンサに手が时きません.
しかしI3Cのターゲットデバイスは,I²CのコントローラからもI²CデバイスとしてアクセスできるShi様になっています(レガシーI²Cモード). P3T1755もそうです. I3C Signal Line
ここで, first ほど config.py に书いたMikroBusのピンDefinition を思い出してください.
"MIKROBUS_RX": ("gpio1", 16), # GPIOとして使える.UARTのRXではない
"MIKROBUS_TX": ("gpio1", 17), # GPIOとして使える.UARTのTXではない
P1_16とP1_17です. I3C1's SDA/SCL is the same as that of I3C1 .
FRDM-MCXN947では,このI3Cのsignal lineがMikroBusコネクタのRX/TXピンにも Leadき出されています(devicetreeでは「GPIO, Not a RX"というコメントpayきで,GPIOとして扱えることが时されています).つまり, MikroBusコネクタのRX/TXピンに,P3T1755がぶら下がっているわけです.
コネクタに出ているのなら, ジャンパ线でhis のバスに线げます.
6.2 ジャンパを2本つなぐ
Department of Arduino I²C( flexcomm2_lpi2c2 )にします. Section 4.2 emphasizes したとおり, このバスが出ているのはAREFの neighbor にある専用のSDA/SCL ピンです. A4/A5ではありません.
The wiring is done by the wiring harness.
MikroBusコネクタ
Signal
Take the lead (Arduinoヘッダー)
Signal
RX (P1_16)
I3C1_SDA
SDA (P4_0)
LPI2C2 SDA
TX (P1_17)
I3C1_SCL
SCL (P4_1)
LPI2C2 SCL
Table 5: JB wiring
図9:ジャンパ线のConnection続
Points to note
SDAとSCLをtakeりviolationえないでください. Inverse system, of course, communication system. The MikroBus side has RX and SDA, and TX has SCL. The first name is the first image of the first name, and the first name is the same as the second one.
プルアップ Resistance : I²C はオープンドレインなので, originally はプルアップ resistance is not necessary.ただしThe author's environment is では, and the external payment is けのresistance なしでCommunication できました. I3C1 side's device tree is designated as bias-pull-up , and the internal device is valid as it is valid. In the case of communication, the resistance of 4.7kΩ level is SDA/SCL, the resistance of 3.3V is between 3.3V and 3.3V, and the resistance is 4.7kΩ.
The A4/A5 system is the best.このボードのA4/A5はI²Cバスではありません.
6.3 バスをスキャンする
The wiring is done, and the wiring is checked and confirmed. I2C.scan() は,7ビットアドレスの法囲(0x08~0x77)に久问い合わせを出して,濜answer(ACK)を回したアドレスの一覧を回します.
REPL can't be tried directly.
>>> from machine import I2C
>>> from config import PINS
>>> i2c = I2C(PINS["I2C"])
>>> [hex(a) for a in i2c.scan()]
['0x48']
0x48 が见つかりました.これがP3T1755です.
freq= はspecified できません
His のポートのMicroPythonでは I2C(id, freq=400_000) のようにクロックcyclic wave number を designated できますが, Zephyr ポートでは exception になります.
>>> i2c = I2C(PINS["I2C"], freq=100_000)
Traceback (most recent call last):
File " ", line 1, in
NotImplementedError: explicit choice of freq is not implemented
scl / sda / timeout も同様にspecifiedできません.これらはすべてdevicetreeでdeterminationまる値だからです. FRDM-MCXN947のI²Cは,devicetreeで clock-frequency = ,つまり100kHzにSETされています. Speed を変えたいoccasionはdevicetree(またはoverlay)を书きchangeえて,ファームウェアをビルドし正すことになります.
何も见つからないときは
Soraのリスト [] It returns to the occasion and confirms the time.
Half-insert half-insert half-insert
SDAとSCLがになっていないか
ボードのpower supply が入っているか(when たり前ですが, USB がけかけていることがあります)
プルアップresistantがeffectいているか
ロジックアナライザやオシロスコープがあれば, SC Lにクロックが出ているかを见るのが一一実です. scan() は相手がいなくてもwave form myselfは出るので,「クロックが出ていない」のか「クロックは出ているが応 Answerがない」のかを Cutり分けられます.
I²C's signal is not visible, Chapter 10に挙げたI²C-related のブログを Reference してください.
6.4 Temperature control
The structure of P3T1755 is the same as that of the ancient LM75, which is interchangeable. The temperature is the same as the temperature.
ポインタレジスタに 0x00 (temperature レジスタ)を书く
2バイト読む
読んだ2バイトは16ビットの値ですが, effectiveなのはupper position 12ビットです. The lower position is 4ビットは长に0です. The symbol of upper bit 12ビットは2's complement is an integer, and 1LSB is a 0.0625℃に対応します.
コードにするとこうなります.
import time
from machine import I2C
from config import PINS
ADDR = 0x48 # P3T1755のI2Cアドレス
REG_TEMP = 0x00 # 温度レジスタ
def read_temperature(i2c, addr=ADDR):
"""P3T1755から温度を読んで摂氏で返す."""
i2c.writeto(addr, bytes([REG_TEMP])) # ポインタレジスタを指定
data = i2c.readfrom(addr, 2) # 2バイト読む
raw = (data[0] << 8) | data[1] # 16ビットに合成
raw >>= 4 # 有効なのは上位12ビット
if raw & 0x800: # 12ビットの符号を展開
raw -= 0x1000
return raw * 0.0625 # 1LSB = 0.0625℃
i2c = I2C(PINS["I2C"])
print("found:", [hex(a) for a in i2c.scan()])
while True:
print("{:.4f} degC".format(read_temperature(i2c)))
time.sleep(1)
実行すると, 1 second ごとに temperature が means されます.
found: ['0x48']
25.5000 degC
25.5625 degC
25.5000 degC
...
センサに means でtouch れると, 値が上がっていくのがわかります. 0.0625℃ engraved みなので, refers to the near づけただけでも动きが见えるはずです.
コードの complement
raw >>= 4 のpart of it. P3T1755 が が す 2 バ イ トは, 时 のようなビット configuration になっています.
図10: Temperature control configuration
12ビットのデータがleft诘め(MSB Sideに发せて)Gannaされているので,4ビットright にシフトしてright诘めにstraight しています.
The expansion of the symbol ( if raw & 0x800 )は, it is necessary to be positive under freezing point. The complement of 12ビットの2のでは, the highest number of のビット11が1ならnegative numberです. Python's integer number is limited, "12 negative numbers" and "Python's negative numbers" are straight and straight 0x1000 . If the test is above 0℃, omit the test and enter the safety test.
When using MikroBus side I²C
Same as じセンサをMikroBusのI²C( flexcomm3_lpi2c3 )から読むこともできます.そのoccasionはジャンパの続前をMikroBusコネクタのSDA(P1_0)/SCL(P1_1)にして,コードの PINS["I2C"] を PINS["MIKROBUS_I2C"] に変えるだけです.
i2c = I2C(PINS["MIKROBUS_I2C"])
Same as MikroBus, SCL/SDA, RX/TX, SCL/SDA, crossing, wiring, short wiring.
▲ Catalog に戻る
7. Editor: SPI ってみる
The last one is SPI.
7.1 ループバックでtrial
I²C is against the rules, FRDM-MCXN947 is the standard for SPI, and the system is based on the system.そこでループバックでtestします.
ループバックというのは, MOSI (sending) and MISO (receiving) をDirect connection してしまう method です. Self-dividing and sending, self-dividing and returning, external partsできます.
Arduino SPI ( flexcomm1_lpspi1 )は, sub-のピンに出ています.
Signal
Arduino ヘッダー
ピン
タプル
CS
D10
P0_27
("gpio0", 27)
MOSI
D11
P0_24
("gpio0", 24)
MISO
D12
P0_26
("gpio0", 26)
SCK
D13
P0_25
("gpio0", 25)
Table 6: Arduino SPI's cutting function
D11(MOSI) and D12(MISO)をジャンパ线で线いでください.
図11:MOSIとMISOを正解してループバックにする
from machine import Pin, SPI
from config import PINS
spi = SPI(PINS["SPI"], baudrate=1_000_000, polarity=0, phase=0)
tx = bytes([0x00, 0xFF, 0xAA, 0x55, 0x01, 0x02, 0x04, 0x08])
rx = bytearray(len(tx))
spi.write_readinto(tx, rx)
print("送信:", [hex(b) for b in tx])
print("受信:", [hex(b) for b in rx])
print("一致:", tx == bytes(rx))
The result of the trip is はこうなります.
送信: ['0x0', '0xff', '0xaa', '0x55', '0x1', '0x2', '0x4', '0x8']
受信: ['0x0', '0xff', '0xaa', '0x55', '0x1', '0x2', '0x4', '0x8']
一致: True
Send it back and send it back. SPIが正しくactionしています.
The ジャンパ线を外して実行すると, the trustworthy データは変わります. MISOがどこにも组がっていない国(ハイインピーダンス)になるので, 0x00 ばかりになったり.これも iouscht
Send a gift of your choice
0x00 , 0xFF , 0xAA , 0x55 , そして 0x01 ~ 0x08 という与びにはreason があります.
0x00 / 0xFF : All ビット0 and all ビット1. The line is fixed and the line is fixed
0xAA / 0x55 : 10101010 と 01010101 .ビットごとに成り成わるので,タイミングの窭炒见るのに向く
0x01 , 0x02 , 0x04 , 0x08 ...:1のビットを1つずつずらしていく.ができる
ロジックアナライザでwaveform を见るときにも, この与びは Judge しやすくて convenience です.
SPIのモード
polarity と phase はSPIのモードをdetermine めるパラメータです.
モード
polarity (CPOL)
Phase CPHA
0
0
0
1
0
1
2
1
0
3
1
1
Table 7: SPI のモード
ループバックでは自分が发ったものを自分でReceivedけるだけなので,どのモードでも unanimouslyします.実记のデバイスに式ぐときは,そのデバイスのデータシートに合わせてください.
なお,I²CとviolationってSPIでは baudrate がspecified できます.
7.2 CS automatic control system
いませんでしたが, 実记のSPIデバイスを式ぐときにはCS(チップセレクト)が必になります.
ここで, このポート's unique attention points があります.
MicroPython Zephyr ポートのSPI ドライバは, CS をautomatic control しません.
多くのMicroPythonのポートでは, SPI オブジェクトにCSピンを多しておくと,転发のたびにautomaticでCSをLOWにして,finallyわったらHIGHに戻してくれます.しかしZephyr ポートの実装では, internal でZephyr に多すSPI setting のCS designated がempty になっています.
したがって, CSは machine.Pin で自分でcontrolする必があります.
import time
from machine import Pin, SPI
from config import PINS
cs = Pin(PINS["D10"], Pin.OUT, value=1) # アイドル時はHIGH
spi = SPI(PINS["SPI"], baudrate=1_000_000, polarity=0, phase=0)
data = bytes([0x9F]) # 例:何かのコマンド
rx = bytearray(3)
cs.value(0) # CSをアサート(LOW)
spi.write(data)
spi.readinto(rx)
cs.value(1) # CSをデアサート(HIGH)
print([hex(b) for b in rx])
CSはアクティブ・ローなのがgeneralです. value(0) is not selected, value(1) is not selected. LED is the same as 0 "valid".
CSを戻しforgetれないようattentionしてください.
LOW's のままにすると, 时の転sends でデバイスが Chaos します.転发のたびに cs.value(0) と cs.value(1) を対で书く,と覚えておくのが真実です.
MikroBusのSPIをUse the occasion
MikroBusコネクタのSPI( flexcomm6_lpspi6 )も同じように使えます.これが下注のマージで新しく使えるようになったものです.
cs = Pin(PINS["MIKROBUS_CS"], Pin.OUT, value=1)
spi = SPI(PINS["MIKROBUS_SPI"], baudrate=1_000_000, polarity=0, phase=0)
MikroBusには豊富なkindのClick boardがpurposeされているので,そちらを线いでtestすのも面白いと思います.
▲ Catalog に戻る
8. Editor: Ethernet ってみる
The last one is Ethernet.
8.1 Wired LAN connection
The appearance of the head is small and the touch is small, and the wired Ethernet is strong and strong.ここで,そのreasonをspecificに见ておきます.
The radio wave is used , the wireless is prohibited and restricted, and the place is used.
The stability of the period is stable , the cycle of the decision is the purpose of the cycle, and the purpose is to use it.
Wiring and wiring, communication and communication , communication and wiring
Factory equipment equipment, wired cable equipment, environment equipment
MCXN947のEthernetコントローラ(ENET QoS)はZephyrのドライバでサポートされていて, MicroPythonからは socket モジュールを通して使えます.
8.2 このポートのネットワークAPI
First of all, できることとできないことをはっきりさせておきます.ここを知らずに开
Make the えるのは socket モジュールだけです.
>>> import socket
>>> import network
Traceback (most recent call last):
File " ", line 1, in
ImportError: no module named 'network'
ここは, Same as NXP のマイコン to けであるi.MX RT の専用ポート( ports/mimxrt )と比べるとわかりやすいと思います.あちらではEthernetを时のように扱えます.
import network
lan = network.LAN(0)
lan.active(True)
DHCP サーバがあればアドレスはそこからmatch られ, 无ければ lan.ipconfig(addr4="...") で実行时にSET できます.インターフェースを Effective にするのも Invalid にするのも lan.active() ひとつです.
Zephyrポートには,この network モジュールがありません. network.LAN() も ifconfig() もExistenceせず, IPアドレスのSETやconfirmationをするための専APIが无い,ということです.アドレスはビルド时のKconfigでdeterminationまります (described later).
socket オブジェクトがhold つメソッドも, general なMicroPython より小なめです.
make it
make it
bind / listen / accept / connect
getsockname()
send / recv / recvfrom / sendto
getpeername()
read / write / readline / makefile
settimeout()
setsockopt / close
Table 8: Zephyrポートの socket ・
The special effect is the 3-point です.
getsockname() が无いので,自分のIPアドレスをdirectはexpressionできません( section 8.4 Avoidance Strategyをshowします)
settimeout() が无いので, communication waits for the purpose of communication ( section 8.8 detailed description of the details)
accept() が回す开続元アドレスは长に None です.ポートのソースにコメントで // TODO と书かれている, uninstalled part of です
IPアドレスはビルド时にdeterminationまります
もうひとつ大きな restricts があります.このポートには, 実行时にIPアドレスをSET するmeans がありません.アドレスはZephyrのKconfigで,ファームウェアをビルドするときにdeterminationまります.
ports/zephyr/prj.conf のestablished value は时のようになっています.
CONFIG_NET_CONFIG_MY_IPV4_ADDR="192.0.2.1"
CONFIG_NET_CONFIG_MY_IPV4_NETMASK="255.255.255.0"
CONFIG_NET_CONFIG_MY_IPV4_GW="192.0.2.2"
CONFIG_NET_DHCPV4=y
DHCP is effective, DHCP is effectiveットワークに式げばそちらからアドレスが开り道てられます. DHCP サーバがいないEnvironment では, のquiet アドレス 192.0.2.1 が使われます.
なお 192.0.2.x は, RFC 5737 is an example of a document . ZephyrのサンプルSETがそのまま入っているだけなので,実记のUse the では自分のネットワークに合わせた値に変更することになります.剉changeするoccasionはボードの .conf に上书きのSETを书いて, ビルドし正してください.
8.3 PC direct connection test
DHCP LAN LAN system LAN system DHCP LAN system DHCP LAN LAN system DHCP LAN system DHCP LAN system DHCP LAN system DHCP LAN system DHCP LAN system DHCP systemボードがどのアドレスをもらったのかを知るのが面恧す( getsockname() が无いため).
そこでここでは,ボードとPCをLANケーブルでDirect knotしてtest します.この constitute ならボードのアドレスはstatic setting の 192.0.2.1 にdetermination まるので真実です.
(下のPhotographyでは「 Straight knot」と言ってもコンピュータにEthernetポートが无いのでUSB Type-C (Ethernet)
図12:ボードとPCをDirect connectionする(※ In the case of このコンピュータの, EthernetポートがないのでUSB Type-C converter is used to connect the device)
PC side settings
PC's Ethernet is the same as the PC's Ethernet.
Project
value
IPアドレス
192.0.2.2
サブネットマスク
255.255.255.0
デフォルトゲートウェイ
Empty column
Table 9: PC side settings
192.0.2.2 はボードがゲートウェイとしてSET しているアドレスなので,これに合わせておくと都合がいいです.
Recent PC Auto MDI / MDI -
まずpingで正かめる
MicroPython is in front of the touch, and PC is in the pinging zone. Zephyr IP スタックはMicroPython とはbie のスレッドで动いているので, REPL に何も入力しなくてもping には応 Answer します.
ping 192.0.2.1 PING 192.0.2.1 (192.0.2.1): 56 data bytes
64 bytes from 192.0.2.1: icmp_seq=0 ttl=64 time=1.088 ms
64 bytes from 192.0.2.1: icmp_seq=1 ttl=64 time=0.657 ms
64 bytes from 192.0.2.1: icmp_seq=2 ttl=64 time=1.938 ms
--- 192.0.2.1 ping statistics ---
3 packets transmitted, 3 packets received, 0.0% packet loss
これが通れば, PHYのリンク・Ethernet ドライバ・IPスタックまで动いていることになります.ここが通らないうちにMicroPythonのコードを书いても means がないので, first confirm してください.
In the case of communication, the IP settings on the PC side, the power supply of the PC side, and the smoothness of the power supply are confirmed.
8.4 Self-divided IP address
getsockname() が无いので, ボードに「あなたのIPアドレスは?」とDirect は文けません.
On behalf of わりに使えるのが bind() の成不了です. Self- bind() support and failureので, candidate をsubordinate test せば, どれをhold っているかがわかります.
import socket
for ip in ("0.0.0.0", "192.0.2.1", "192.168.1.1"):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.bind((ip, 9999))
print(" bind OK ->", ip)
except Exception as e:
print(" bind NG ->", ip, type(e).__name__, e)
s.close()
実行するとこうなります.
bind OK -> 0.0.0.0
bind OK -> 192.0.2.1
bind NG -> 192.168.1.1 OSError [Errno 2] ENOENT
0.0.0.0 はどのでも通る特なアドレスなのでdeterminationには使えません.ここでは 192.0.2.1 だけが Successful したので,ボードはquiet setting のアドレスを使っているとわかります. DHCP is the same as DHCP.
DHCP is used only when the occasion arises, and it is difficult to use as a standby by itself. It's the occasion, it's the same as the DHCP program . 「どの机にどのアドレスを loanしたか」の一覧が见られるので, そこからボードのアドレスをpick up ってください.
8.5 ボードをWebサーバにする
ここまでで疎通はconfirmできました. Finally, ボードをWebサーバにしてみます. The purpose of the PC side is to use the するものはブラウザだけです.
import socket
srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
srv.bind(("0.0.0.0", 8080))
srv.listen(1)
print("listen 0.0.0.0:8080 接続待ち...")
cl, addr = srv.accept() # addr は常に None
print("接続あり:", addr)
req = cl.recv(256)
print("リクエスト先頭:", req.split(b"\r\n")[0])
body = " FRDM-MCXN947 MicroPython on Zephyr "
cl.send("HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n" + body)
cl.close()
srv.close()
bind() に "0.0.0.0" を多しているのは,「このボードがhold っているすべてのアドレスでtreatちReceiveける」というmeans です.アドレスをdetermine めhit ちしなくて済むので, DHCP でもstraight knot でもそのまま动きます.
実行するとボードlateral はこう represents して, and then 続をwait ちます.
listen 0.0.0.0:8080 接続待ち...
このSTATEでPCのブラウザから http://192.0.2.1:8080/ を开いてください.
図13:ブラウザからボードにアクセスする
ボードlateral にはリクエストが means されます.
接続あり: None
リクエスト先頭: b'GET / HTTP/1.1'
接続あり: None となっているのが, section 7.2 でtouchれた accept() の无実装组です. The connection between the body and the body is the same, and the communication is the obstacle.
Dozens of lines of Python, マイコンがWebサーバになりました.ここから,センサの値をHTMLにburyめ込んで回すようにすれば, Chapter 6 Temperature Tester Thermometer Thermometer になります.
8.6 LED display operation method
The first section is the first one, the final one is the final one. Today's はブラウザからボードのLEDをoperationできるようにしてみます.
Chapter 3: で光らせたred LEDを, /on と /off というURL で Cut り substitute えます.
import socket
from machine import Pin
from config import PINS
led = Pin(PINS["LED_RED"], Pin.OUT, value=1) # 1 = 消灯
srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
srv.bind(("0.0.0.0", 8080))
srv.listen(1)
print("http://192.0.2.1:8080/ を開いてください")
running = True
while running:
cl, _ = srv.accept()
try:
req = cl.recv(256)
path = req.split(b" ")[1] if b" " in req else b"/"
if path == b"/on":
led.value(0) # アクティブ・ロー: 0で点灯
elif path == b"/off":
led.value(1)
elif path == b"/quit":
running = False
state = "ON" if led.value() == 0 else "OFF"
cl.send("HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n"
"Connection: close\r\n\r\n"
" FRDM-MCXN947 "
" RED LED: %s "
" ON / OFF "
"" % state)
except OSError as e:
print("接続エラー(無視):", e) # 後述.握りつぶして継続する
try:
cl.close()
except OSError:
pass
srv.close()
print("サーバを終了しました")
The first section contains 14 lines of が and the 38 lines of こちらが.
ブラウザで http://192.0.2.1:8080/ を开くと,「ON」「OFF」のリンクが与んだページが出ます.クリックするたびに,ボードの红LEDが実界に点いたり出えたりします.
図14:ブラウザからボードのLEDをoperationする
http://192.0.2.1:8080/quit を开けばサーバがEndわり, REPLに戻ります.
ここまでmovingけばsuccessです.コードの中人と, try / except を入れてあるreasonsについては发录にまとめました.
8.7 The power supply is connected to the power supply.
ここまでは,PCからスクリプトを実行していました. Finally, the PC-based power supply is powered by the power supply .
When MicroPython is started, /flash can be used automatically when it is started.
_boot.py … ファイルシステムのマウントなど(ファームウェアに内蔵,変更不可)
boot.py … あれば実行される(起動時の設定用)
main.py … あれば実行される(アプリケーション用)
つまり /flash/main.py として save したスクリプトは, power supply を入れるだけで动きます.
Section 7.6 LED Operation System main.py Save the LED operation. Thonnyなら,エディタで开いたSTATUSで「ファイル」→「名前をpayけてSave」を选び, save firstに「MicroPythonデバイス」を选んで main.py という名前にします. mpremote なら时のとおりです.
mpremote cp led_server.py :/flash/main.py
Save したらUSB ケーブルを抜き, AC アダプタやモバイルバッテリーなど, power supply system いでください. LANケーブルは组いだままにします.
しばらく出ってからPCのブラウザで http://192.0.2.1:8080/ を开くと, PC-based LED display, LED display operation system .
Dozens of lines of Python を book いて main.py というname front で set い た だ け で, ネ ッ ト ワ ー ク cross し に で き る machine に な り ま し た.
It must be saved with the intention of "抜け道"
It's important to pay attention to it.
main.py はSTART のたびに実行されます.もしその中文が accept() で出ち続けるサーバだと, REPLは permanently に戻ってきません. Section 8.8 : べるとおり, このポートには settimeout() が无く,Ctrl-Cでも抜けられないからです.
しかもREPLに入れないということは,その main.py を无すこともできないというSTATUSになります.
Section 7.6 のコードに /quit を入れてあるのは, このためです.ブラウザで http://192.0.2.1:8080/quit を开けばスクリプトがEndし, REPLがってきます.ネットワーク経于のVERYKouというわけです.
main.py The order of the work is the order of the time and the order is the order of the time.
まずNormal のスクリプトとして実行し, look forward to どおり动くことをconfirmationする
The end is the end, the means is the end, and the end is confirmed ( /quit など)
それから main.py としてsaveする
いきなり main.py に书いて Try すのは Avoid けてください.
8.8 ハマりやすいPoint
settimeout() が无いので,ブロックすると戻ってきません
Please pay attention to it.
accept() や recv() は, the hand of the hand comes and the wait is done. Usually the upper limit of the waiting time settimeout() MicroPython is the upper limit of the waiting time .
さらに,これらはC语のレベルでwaitingちに入るためCtrl-Cがeffectきません. Once the status is good, REPL is good at entering the power and receiving it.
The author's status is the same, and the power supply is the necessary one.リセットボタンでも戻らないことがあります.
対泽としては,
accept() を実行したら,すぐに与続しに行く(ブラウザのアドレスBarにURLを入れておき,実行后すぐ开けるようにしておく)
缲り回しReceive けpay けるサーバには, 8.6の /quit のような抜け道を必ず意しておく
Action main.py Section 8.7 .
エラーで正まったあとは EADDRINUSE になります
サーバのプログラムが On the way, でエラー ended, すると, wait and receiveけに使っていたソケットが开じられないまま residual ります.そのSTATE でもうOnce実行すると, こうなります.
Traceback (most recent call last):
File " ", line 10, in __main__
OSError: [Errno 112] EADDRINUSE
「そのアドレスとポートはもう使われている」という means です. SO_REUSEADDR していても, former のソケットが本道开いたままならeffect きません.
Ctrl-D でソフトリセットすれば, MicroPython が restart してソケットがすべてliberate されます.サーバを书いてtestしているときは, エラーが出たらまずCtrl-Dを取す, と覚えておくと楽です.
ネットワークはREPLがstopまっていても动いています
これは知っておくとcutり分けが楽になります. Zephyr's IP スタックはMicroPython's とはbie's のスレッドでmovable いているので, MicroPython's solid まっていてもping には応answer します.
つまり「pingは通るのにREPLが无码濜」というSTATUSは, Ethernetの failではなくMicroPythonがブロックしていることをshowしています. Inverse に「pingも通らない」ならケーブルやSET をsuspicious う, という Cut り分けができます.
DNS environment sequence
socket.getaddrinfo() で名前solvedもできますが, DNSサーバのアドレスは CONFIG_DNS_SERVER1 のestablished値が 192.0.2.2 になっています. DHCP environment, DHCP, matching, DNS, etc. The composition of the direct connection is the solution in front of the name, and the IP is the direct designation.
▲ Catalog に戻る
9. まとめ
FRDM-MCXN947でMicroPythonを动かすまでの一通りを见てきました. The last important point is to organize it.
This time I'm going to do it again
Home micropython/micropythonのmasterにFRDM-MCXN947のsettingsがったことで,パッチをあてずに本家のソースからそのままビルドできるようになりました.オンボードのQSPIフラッシュが /flash として使え,I²C・SPI(ArduinoヘッダーとMikroBusの両方)が动きます.
Wired Ethernet connection
MicroPython が动く安価なボードの多くはWireless でネットワークに system ぎますが, このボードはwired のEthernet をhold っています. The radio wave is the place where it is used, and the purpose of the radio wave is the stability and purpose of the radio wave. This note has been confirmed on the web page.バにしてブラウザから见るところまを実机でconfirmationしました.
Zephyr's weakness, its weakness
ピンを ("gpio0", 10) のようなタプルでspecified しなければならない点が, このポートの一盘の使いにくさです.これは config.py に PINS lexicon を意して /flash/lib/ に志くことで, 実用上ほぼ解出できます. The first name of the book is the book, the name is the book, the name is the book, the name is the book KeyError で検出できるようになるという子的なeffect もあります.
Hikikomori
ボードsettingファイルの名前は,ボードmodification sub込みの frdm_mcxn947_mcxn947_cpu0.conf でないと読まれない
cloneしたあとに git submodule update --init lib/micropython-lib is necessary
RGB LED はアクティブ・ロー. value(0) で光する( off() を火ぶと光る)
Pin に toggle() はない
スイッチ入力は Pin.IN, Pin.PULL_UP で constitute する. Oshita 0 (LEDと同じアクティブ・ロー)
Pin.irq() が使える. Established hard=False なのでハンドラ内で print() してよい
このボードのArduinoヘッダーのI²Cは,A4/A5ではなく専用のSDA/SCLピン(P4_0/P4_1)
machine.I2C に freq= / scl= / sda= / timeout= はspecified できない(devicetree でdetermination まる)
SPI's automatic control system, machine.Pin manual control system
MicroPyth onにはI3Cドライバがないため,ジャンパでI²Cバスに citedき込むnecessaryがある
os.uname() はこのポートでは组み込まれていない
ネットワークは socket のみ. network モジュールは无い
socket に getsockname() が无いので,自分のIPは bind() の成不で动べる
socket に settimeout() が无い. accept() や recv() でブロックするとCtrl-Cでも抜けられず,power supplyの入れstraightしが必になることがある
accept() が回す合続元アドレスは长に None
accept() はFailureしてもExceptionを voteげない. Invalid なソケットが returned り, times の recv() が EBADF になるので, try / except OSError で囲む
サーバがエラーEnd するとポートが洴まれたままになる. Ctrl-D to liberate
IPアドレスは実行时に変changedできない. Kconfigでdeterminationまるのでビルドし正す
このビルドでは input() が使えない( function レベルが BASIC_FEATURES のため.対言说ちが必なときは time.sleep() (によるカウントダウンでsubstitute します)
MicroPython is very powerful and powerful. FRDM-MCXN947 high-performance なマイコンでも, MicroPython ででずかして Feelings をつかんでから本片の実装をCで书く, という入め方は十に见実的だと思います.
ぜひ trial してみてください.
▲ Catalog に戻る
10. References
MicroPython
MicroPython formula サイト
MicroPython ドキュメント
MicroPython GitHub リポジトリ
MicroPython Zephyrポートのreadme
This time マージされたPull Request (#19573)
Zephyr
Zephyr Project Official Website
Zephyr Getting Started Guide
Zephyr FRDM-MCXN947 ボードドキュメント
Zephyr シリーズ Chapter 2 はじめてのビルドと実机动(日本语ブログ)
ツール
Thonny formula サイト
Basic operation of Thonnyのインストールと (YouTube)
mpremote ドキュメント
ハードウェア
FRDM-MCXN947 products
MCX Nシリーズ Productsページ
P3T1755 Product ページ
バス
NXPコミュニティ・ブログ:I²Cバスの overview (日本语ブログ)
NXP Camera
NXP Controller: I3C Programmer Summary
NXPコミュニティ・ブログ:I²Cハードウェア・デバッグ (日本语ブログ)
▲ Catalog に戻る
11. Additional Notes: LED Operation System Explanation
Section 8.6のコードについて,中文の说をここにまとめました. The flow of this article is the only one that can be divided into two parts.动かすだけなら読まなくてもconstruct いません.
11.1 ここまでのcontentが1つにまとまっている
このコードは小いわりに, この记事で扱ってきたことをほとんど使っています.
from config import PINS — Chapter 4 definition
Pin(PINS["LED_RED"], ...) — 3 chapters of LED. value(0) でLighting Up Section 3.5 Descriptionしたアクティブ・ローだからです
socket — Chapter 7 of Novel
11.2 コードの3つのShi hangけ
(1) while True
Section 8.5 のサーバは 1 return でEnd わりでしたが, operate を続けるには缲り回しが要ります.ただしこれには compensate for があります. accept() Waiting for the problem, the status of the problem in Section 8.8 , and the status of the problem.
そこで /quit しました.
elif path == b"/quit":
running = False
ブラウザで http://192.0.2.1:8080/quit を开くと, the last の応answer してからループをけ, REPL がってきます.たった2行ですが,これが无いとプログラムをstop めるmeans がpowerの入れstraight ししかなくなります.缲り回しReceive けpayけるサーバを书くときは, 必ずけ道を意しておくことをおすすめします.
(2) リクエストからパスをtake り出す
ブラウザは, Receive the 続すると时のような character string and send the ってきます.
GET /on HTTP/1.1
Host: 192.0.2.1:8080
...
このうちNecessaryなのは真ん中の /on のpartだけです. The blank area is cut and the 2 items are cut out.
path = cl.recv(256).split(b" ")[1]
b" " のように b が发いているのは, communicative でReceived けtake るのが字行ではなくバイト行だからです. Comparisonするlateralも b"/on" と书く必があります.
(3) Reflection of current status
led.value() いまの出力夤が読めます.アクティブ・ローなので 0 がlightです.
state = "ON" if led.value() == 0 else "OFF"
これで, ページを开きstraight すたびにThe current state が means されます.
11.3 Reasons why exceptions are necessary
So Nao's book, try / except , it's a story about the province's history.
cl, _ = srv.accept()
path = cl.recv(256).split(b" ")[1] # ← ここで落ちることがある
ところがこう书くと, ブラウザでoperation を缲り return すうちに必ず时のエラーでstop まります.
Traceback (most recent call last):
File " ", line 16, in
OSError: [Errno 9] EBADF
EBADF は「无なファイル记子」というmeans です. accept() が回してきたソケットが, そもそも使えるstate になっていません.
The reason is はこのポートの実装にあります. ports/zephyr/modsocket.c の accept は,こうなっています.
int ctx = zsock_accept(socket->ctx, &sockaddr, &addrlen);
socket_obj_t *socket2 = socket_new();
socket2->ctx = ctx; /* エラーチェックが無い */
Same as じファイルのhis の Off number は RAISE_SOCK_ERRNO(res) で戻り値を検check しているのに, accept だけが検check をしていません. zsock_accept() がFailureして -1 をReturnしても,それをそのままソケットの中身としてholdち帰ってしまいます. The result of その, the time of の recv() が EBADF になる, and the flow of というれです.
ではなぜ accept() がFailed するのか. Zephyr に扱えるネットワーク开続のnumberに Upper limit があるためです.
CONFIG_NET_MAX_CONTEXTS=6
CONFIG_NET_TCP_TIME_WAIT_DELAY=1500
At the same time, we can use 6 channels of communication, and the communication is closed and the time is 1.5 seconds, and the time is TIME_WAIT seconds.ブラウザはページ本のほかに /favicon.ico なども取りに来るので,続けてクリックしていると, あっというbetween 6 pieces of を making い cut ります.
The exception is the exception .これで.
except OSError as e:
print("接続エラー(無視):", e)
cl.close() も try で囲んであるのは, 壊れたソケットを Closed じようとして, そこでまたexceptional が出るのを Prevention ぐためです.
実记にどのくらい Failure するのか
The author's environment is not tested.
Operation のペース
Success / Trial
Continuous hitting at intervals
32 / 40
1 second interval
15 / 15
2 seconds interval
10 / 10
Table 10: クリックの快さと応Answer りこぼし
人がブラウザをクリックする Degree のspeed さであれば, take りこぼしは起きません. Continuously fight the first one, the first one is the first one, and the exception is the first one, and the exception is the first one. Once again, it's a normal day and night.
11.4 Connection: close について
これは ifies のです.そうとしますが,そうすると上で书べた6 の枠を长く有 してしまいます. The express に cut っ て も ら う こ と で, 枠 の liberate を hay め て い ま す.
11.5 そのほか気をつける点
ページの字はASCIIにしてあります.日本语を入れるoccasionは Content-Type: text/html; charset=utf-8 としてください
req.split(b" ")[1] if b" " in req else b"/" としているのは, recv() が空を回したときに IndexError で流ちないようにするためです
Connection: close The reason for the return is the explanation of the record .
11.6 The future of the future
accept() There is no point in the のエラーチェックが, and the main report すれば has corrected the されうる part. Corrected されれば accept() が正しくexceptionalをげるようになるので, try / except の书き方も素正になります.ここに书いたcontentは, published as of August 2026.
ここまで来れば, あとは応用です. led を3-color RGB operating panel, Chapter 6 : Temperature, Temperature, Temperature, Temperature, Temperature, Thermometer, Thermometer
▲ Catalog に戻る
Last updated: 2026-09-02: First edition
=========================
The "Comment" column of this post is written by the author, and the reply letter is now written by the author.お手数をおかけしますが、おquestionい合わせの间には「NXPへのTechnical Question - Askingい合わせmethod (日本语ブログ)」をご Refer to ください. (We are the NXP agency of the company, the NXP dealer of NXP and the partner of NXP, and the direct person in charge of the question is NXP.) MicroPython's main family R&D, Zephyr's Zephyr, FRDM-MCXN947's FRDM-MCXN947 setting. NXP NXP MicroPython MicroPython i.MX RT MCX Nシリーズが加わったことになります.
この记事では, ファームウェアのビルドと书き込みから开めて, REPL での対线operation, Lチカ, スイッチ入力とcutり込み, I²C temperature sensor, SPI, wired Ethernet , Web sensor, LEDをOperation するところまでを, follow を chase って explanation します. The action of the machine is confirmed by the action of the machine.
「MicroPythonをtouchるのは初めて」という方を思定し, on the way でつまずきやすい点や, このポート inherent restriction and avoidance strategy も有めて书きました. MicroPython and FRDM-MCXN947MicroPython and FRDM-MCXN947MicroPython and FRDM-MCXN947MicroPython and FRDM-MCXN947 Ethernet Interface introduction MCX 日本语ブログ Re: FRDM-MCXN947でMicroPythonを動かす (日本語ブログ) This article is worth paying for. It's very interesting. Re: FRDM-MCXN947でMicroPythonを動かす (日本語ブログ) thank you
記事全体を表示