Zephyr Debut Session ~90 Minutes to Get the FRDM-MCXN947 Working Without Stumbling~ [Main Feature] (Japanese Blog) This article is divided into two parts: the main text (Chapters 0-6 and Appendix A) and the appendix section (Appendices B-G) . The appendix section includes a list of command examples (PowerShell/bash/zsh), assignments for those who finish early, instructions on how to try it on other FRDM boards, a glossary, and frequently asked questions.
table of contents
0. What is this article about?
0.1 Target audience
0.2 The Goal of This Article
0.3 Things to use
0.4 Procedure and Estimated Time Required
0.5 How to read this article
1. What is Zephyr?
1.1 Overview and Features of Zephyr
1.2 Why Zephyr now?
1.3 About FRDM-MCXN947
2. Try out the development environment
2.1 Checking the Environment
2.2 Let's run the Hello World sample.
2.3 Write the blinky sample (LED blinking)
2.4 Let's take a peek inside the sample code
3. Try operating the temperature sensor.
3.1 Build and flash the sample
3.2 Check the value
3.3 Why did it move?
4. Try running the HTTP Server.
4.1 Build and flash the sample
4.2 Trying to control an LED from a browser
4.3 Take a look at the /uptime endpoint
5. Modify the HTTP Server to view the temperature sensor values in a browser.
5.1 What was added?
5.2 Let's actually view it in a browser
5.3 How are the contents of Chapters 3 and 4 combined?
6. Summary
6.1 Things I experienced today
6.2 Resources for trying it again yourself
6.3 How can AI be utilized?
6.4 Cleaning up
Appendix A. When things don't work
A.1 First, check the following
A.2 PowerShell Westbound
A.3 Build errors
A.4 Writing (west flash) error
A.5 Nothing appears on the serial console.
A.6 Network and Browser-Related Features
A.7 Reset procedure when the problem still cannot be fixed
Appendix (separate article):
Appendix B. List of command examples (PowerShell/bash/zsh)
Appendix C. Let's try it (for those who finish early)
Appendix D. To try with other FRDM boards
Appendix E. Glossary
Appendix F. Frequently Asked Questions
Appendix G.HTTP Server Sample Framework
0. What is this article about?
This article was written as a progress guide for the hands-on seminar " Zephyr Debut Session ." In the actual seminar, we will follow the steps outlined in this article.
Even if you didn't attend the seminar, you can reproduce the same content in your own environment by reading this article alone. To that end, I've included command examples and verification points without omitting any. Think of this not as a general explanatory article, but rather as a practical guide to get you to the point where it actually works.
0.1 Target audience
This article is for beginners to Zephyr OS who have heard of it but have never used it, and for those who want to try Zephyr. No prior experience in embedded development is required. Just having some experience reading C language code is sufficient.
0.2 The Goal of This Article
Using the NXP FRDM-MCXN947 board, you will gain hands-on experience in everything from blinking LEDs and reading temperature sensor readings to displaying sensor values via a browser. The goal is for you to take away the successful experience of "easily running apps on Zephyr." Difficult settings and coding will be kept to a minimum in this article.
In this article, we will deliberately work using the command line . While there are convenient tools like NXP's MCUXpresso for VS Code that allow you to build and flash with button operations, we will directly use the west command provided by Zephyr as standard. This is to allow you to experience a neutral, raw Zephyr that is not dependent on any particular vendor's tools. The procedure described here can be used with boards from manufacturers other than NXP, simply by changing the board name.
Today's schedule is as shown in Figure 0.2-1. In Chapter 2, you will become familiar with the development procedure, in Chapters 3 and 4 you will run different functions, and in Chapter 5 you will combine the two.
Figure 0.2-1: Today's Schedule
0.3 Things to use
hardware
FRDM-MCXN947 Evaluation Board
PC (with the following software installed, such as the Zephyr development environment)
Temperature sensor: P3T1755 I3C/I²C bus compatible, ±0.5°C accuracy digital temperature sensor(Installed on the FRDM-MCXN947 evaluation board)
Ethernet cable
software
Zephyr development environment (including west (command for building and flashing Zephyr), Zephyr SDK (a complete set of tools including a compiler), and a Python virtual environment; set up in ~/zephyrproject according to the official Getting Started Guide instructions)
LinkServer (NXP's programming and debugging tool. west flash is used for programming the FRDM-MCXN947.)
Microsoft Visual Studio Code (used for viewing and editing source code and prj.conf (application-specific configuration files))
Terminal software (This article uses Tera Term for Windows for explanation. If you are trying this on macOS or Linux, please use software that can connect to a serial port, such as CoolTerm.)
browser
Git (We will use this to obtain sample code in Chapter 5)
MCUXpresso for VSC ( Not required . *It is installed on the venue PCs, but will not be used in the procedure described in this article.)
*All of these features are already set up on the PCs at the venue.
For those who want to reproduce this on their own PC
To replicate the same setup as the venue PCs, you need to install the software listed above. LinkServer , in particular, is often overlooked. If it's not installed (or not in your PATH), you might be able to build the project, but you won't be able to write it (it will show west flash ). Also, Chapter 4 uses the PC's Ethernet port, so if your laptop doesn't have an Ethernet port, please prepare a USB-Ethernet adapter.
Please refer to one of the following instructions for installation.
Official guide : Getting Started Guide (English). The procedure is the same as the premise of this article (configuration to create a workspace and Python virtual environment .venv in ~/zephyrproject ). LinkServer must be installed separately.
An easy method using NXP tools : [Zephyr ® Series] Part 2: First Build and Operation on Actual Device (NXP Tech Blog, Japanese) . You can install the Zephyr development environment and LinkServer together using MCUXpresso for VS Code and the MCUXpresso Installer. However, the location of the Python virtual environment (under C:\Users\<ユーザー名>\.mcuxpressotools\ on Windows) and the Zephyr folder will differ from that described in this article. Please adjust the folder locations in command example 2.1-1, etc., to match your own environment.
0.4 Procedure and Estimated Time Required
The seminar will be 90 minutes long. The schedule will be roughly as follows:
chapter
Content
guideline
Chapter 0-1
About this article, what is Zephyr?
10 minutes
Chapter 2
Checking the development environment, Hello World, blinking an LED.
25 minutes
Chapter 3
Move the temperature sensor
15 minutes
Chapter 4
Running an HTTP Server
20 minutes
Chapter 5
Displaying temperature on an HTTP server
15 minutes
Chapter 6
summary
5 minutes
[Adjust to match the actual timetable]
If I'm late
Chapters 3 through 5 are independent of each other. Even if you haven't finished the previous chapter, you can start from any chapter by running command example 2.1-1 ( zinit on the venue PC) in a new PowerShell window. For example, if you get stuck in Chapter 3 and time runs out, you can leave Chapter 3 aside for now and start from the first command example in Chapter 4. You can refer to this article later and start again at your own pace.
If it finishes quickly
Appendix C, "Let's Try It ," includes an exercise where you'll modify a sample code slightly and try it out.
When asking a question
If you get stuck, please don't hesitate to raise your hand. When asking questions to the venue staff, or to the AI or acquaintances later while looking at this article, providing the following three points will help us quickly find the cause.
Which command example caused the code block to stop? (The number, like # コマンド例3.1-2 , is on the first line of the code block.)
The line containing the first error (the line with red text or error ; a screenshot is also acceptable).
Execution result of command example A.1-1 (You can see the current folder and the environment settings)
0.5 How to read this article
The sections in Chapters 2 through 5 are arranged in the following order. At the venue, please first complete the procedure to the end and confirm that you have reached this point before listening to the explanation.
What to do in this section (1 line)
Instructions (Example commands. Longer sections are divided into "Step 1," "Step 2," etc.)
Example display (screen and display when successful)
✔ If you can do this much, you're good to go (Check points to make sure it matches the example)
When things don't go well (common stumbling blocks and how to deal with them)
Commentary/Column
The boxes within the text are used in the following ways:
box
Content
When to read
Note
Things you must keep in mind when proceeding with the procedure
Read this before proceeding.
Explanation
What do the operations and code I just performed mean?
After the procedure is complete, the instructor will explain it on the spot at the venue.
column
Background knowledge and related topics
When you have time, or later
If you want to try it on your own PC
Supplementary information for reproducing the results on a computer other than the venue's PC.
When trying it on your own PC
Terms appearing in the main text are listed in Appendix E, Glossary .
If you are reading this article in VS Code
At the venue, you will read this article displayed on the right side of VS Code (Visual Studio Code). Commands within code blocks can be selected by dragging, copied using Ctrl + C , and pasted into PowerShell.
The right-hand area, where the article is displayed (preview), is locked . Therefore, files opened with a command like code prj.conf will always open on the left side. The article on the right will remain as you were reading it.
If you have closed the article on the right, follow these steps to restore it.
Open ~\seminar_text\article_draft.md using "File" → "Open File..." in VS Code.
Ctrl Pressing + K followed by V will display a preview of the article on the right.
Click the preview tab on the right, then open the command palette by pressing Ctrl + Shift + P , and execute "View: Lock Editor Group".
You can close the article_draft.md tab that opened on the left (to prevent accidental overwriting).
If you are reading this in a browser or on the NXP blog, you do not need to follow these steps.
▲ Return to Table of Contents
1. What is Zephyr?
1.1 Overview and Features of Zephyr
Zephyr is an open-source RTOS (Real-Time Operating System) under development by the Linux Foundation. It targets a wide range of hardware, from small microcontrollers to relatively resource-intensive SoCs.
The breadth of its coverage is evident even when looking only at NXP products. From Cortex-M core microcontrollers like the MCX series we'll be using, to Cortex-A core application processors like the i.MX series, it's all covered by the same Zephyr OS. Not having to use different OSs or build environments for each board is a significant practical advantage.
In short, its key feature is that it allows for the separate management of hardware configuration and software functions through the following two mechanisms.
Device tree : A file that describes the hardware configuration, showing "which components are connected to where."
Kconfig : A mechanism for turning software features on or off, specifying "which features to use."
This separation makes it easier to deploy the same application's code to multiple boards.
In other words, the logic of an application written in C or another language doesn't need to directly know "which sensor" is connected to "which bus." The application code simply accesses the device using the name assigned to it in the device tree. You will experience this separation by looking at actual code in sections 2.4 and 3.3.
1.2 Why Zephyr now?
Semiconductor manufacturers are expanding their support for Zephyr, including in their existing product lines. As an RTOS that is not tied to a specific vendor, its presence in the industry is currently growing.
The Zephyr project started in 2016 under the Linux Foundation and has a history of approximately 10 years. It is not a new, immature technology.
It's not just the CPU architecture and peripheral drivers that have been built up during this time. Network-related middleware, such as the TCP/IP stack and HTTP server that you'll experience in Chapters 4 and 5, has also grown into a standard feature built into the Zephyr core. When you think of an OS for microcontrollers, you tend to imagine only a minimal scheduler. The fact that you can consistently enable even this higher-level middleware with Kconfig is one of the reasons to choose Zephyr.
Zephyr is attracting attention as an operating system for products because of its robust security measures. In Europe, the Cyber Resilience Act (CRA) has been enacted, requiring cybersecurity measures for network-connected products, and from September 2026, manufacturers will be obligated to report exploited vulnerabilities. The Zephyr project is preparing to meet these requirements by establishing a system for addressing vulnerabilities and providing long-term support (see column below).
Ultimately, it's difficult to truly understand "what makes it so good" without actually experiencing it. In this article, we'll explore its feel by actually using it.
Column: Zephyr's approach to security
There is a dedicated team (PSIRT) to address vulnerabilities, and it has been registered with the CNA (Computer Security Information Agency) since 2017, which assigns CVE numbers. The goal is to notify manufacturers and release fixes within 30 days of receiving a report, and to make them public within a maximum of 90 days.
Product manufacturers can register with the Vulnerability Alert Registry to receive information about vulnerabilities.
Long-Term Support (LTS) versions of products are maintained for at least five years, including security fixes.
west spdx This allows you to create a list of software included with the product (SBOM).
The encryption function is provided by PSA Crypto (implemented as Mbed TLS). The FRDM-MCXN947 also has a board specification ( frdm_mcxn947/mcxn947/cpu0/ns ) for use with TF-M which uses TrustZone.
The relationship between CRA and Zephyr is summarized on the Cyber Resilience Act page of the official Zephyr documentation. Note that this hands-on session uses unencrypted plain HTTP for simplicity (see section 4.1 for details).
1.3 About FRDM-MCXN947
The FRDM-MCXN947 is an evaluation board equipped with NXP's MCX N947 microcontroller. It features a dual-core Cortex-M33 configuration operating at 150MHz. Peripherals such as GPIO, I2C, I3C, SPI, and Ethernet can be accessed via connectors such as Arduino headers and mikroBus sockets.
This article uses the following components on the board (Figure 1.3-1). In the following text, we will indicate their locations using these numbers, such as "① in Figure 1.3-1".
Figure 1.3-1: Components used in FRDM-MCXN947
number
parts
When to use
①
Debug USB connector (MCU-Link side)
Connecting to a PC. Used for both programming ( west flash ) and serial console. Power is also supplied from here. The MCU-Link is the programming and debugging circuit on the board.
②
RESET button
When you want to restart the program from the beginning (for example, when you missed the serial output)
③
RGB LED
Section 2.3: LED blinking (red blinking), Section 4.2: LED control from a browser (green light)
④
Temperature sensor (P3T1755)
Chapter 3, Chapter 5
⑤
Ethernet connector (RJ45)
In chapters 4 and 5, you will connect the PC directly using an Ethernet cable.
Note : The board has multiple USB connectors. Connecting to any USB connector other than ① will prevent you from writing to the board or using the serial console.
▲ Return to Table of Contents
2. Try out the development environment
2.1 Checking the Environment
In this section, we will open PowerShell and verify that the Zephyr command (west) is available.
The PCs at the venue are set up with a development environment including the west/Zephyr SDK, following the instructions in the official Getting Started guide. You won't need to worry about setting up the environment yourself. MCUXpresso for VSC is also available, but as mentioned in section 0.2, we will be using command line operation in this seminar.
Step 1: Open PowerShell
In the Start menu, type "PowerShell" and launch "Windows PowerShell" (Figure 2.1-1). Do not select "Run as administrator." Administrator privileges are not required for the procedures in this seminar, and running it as administrator could cause problems throughout your entire PC if you make a mistake with a command. You can tell if you are running it as administrator by whether "Administrator:" appears at the beginning of the window tab (or title).
Figure 2.1-1: Opening "Windows PowerShell" from the Start menu
The initial folder (current directory) of PowerShell varies depending on how it is launched. As shown in Figure 2.1-2, it may display PS C:\WINDOWS\system32> even if you are not running it as an administrator. It may open in your home folder ( C:\Users\<ユーザー名> ), or in the VSCode terminal, it will open in the currently selected folder. No matter where you open it, the first cd in the example command will take you to the Zephyr workspace ( ~\zephyrproject ), so there is no problem. ~ is a symbol that represents your home folder.
Figure 2.1-2: Launched PowerShell (Example opened with C:\WINDOWS\system32 )
Step 2: Make west usable.
Before using west, activate the Python virtual environment for Zephyr (an independent Python environment containing all of Zephyr's tools) and set the location of the Zephyr executable to environment variable ZEPHYR_BASE . Copy the following example command, paste it into PowerShell, and execute it.
When pasting
You can paste by right-clicking on the PowerShell window or by pressing Ctrl + V .
If the program is stuck with the last line entered, press Enter to execute.
You can also paste the first line, # コマンド例… , as is (it does nothing in PowerShell).
Other important points are summarized in the "Column: Precautions when copying and pasting commands" at the end of this section.
# コマンド例2.1-1
cd ~\zephyrproject
.\.venv\Scripts\Activate.ps1
$env:ZEPHYR_BASE = "$HOME\zephyrproject\zephyr"
west --version
west topdir
When executed, the version will be displayed in west --version and the workspace location in west topdir as shown below (Figure 2.1-3). The prompt (the PS C:\...> display waiting for command input) will be preceded by (.venv) .
(.venv) PS C:\Users\<ユーザー名>\zephyrproject> west --version
West version: v1.5.0
(.venv) PS C:\Users\<ユーザー名>\zephyrproject> west topdir
C:/Users/<ユーザー名>/zephyrproject
west topdir The display will show / instead of \ as the folder separator, but it points to the same location.
Figure 2.1-3: Execution result of command example 2.1-1
✔If you've reached this point, you're good to go: The prompt will start with (.venv) , and your West version and workspace location will be displayed.
(The output shown below as an "example of execution result" is for comparison with your own screen; do not copy it as a command. Numerical values and version numbers will vary depending on your environment.)
Note: Do not close this PowerShell window.
Enabling the virtual environment and setting ZEPHYR_BASE are only effective within that window . Please keep this window open during the seminar. If you close it, you can return to the previous state by following the steps in "When you reopen PowerShell" below.
When things don't go well
.\.venv\Scripts\Activate.ps1 Then, a message in red text will appear saying, "Script execution is disabled on this system." → After configuring the execution policy as described at the end of the explanation below, run command example 2.1-1 again from the beginning.
west If it says "Not recognized" → Virtual environment activation failed. Check if (.venv) is at the beginning of the prompt ( A.2 ).
cd If you get the message "Cannot be found because the path does not exist," then your workspace may be located in a location other than ~\zephyrproject . If you are trying this in your own environment, please substitute the workspace location.
When I reopened PowerShell
After resetting the environment with the new PowerShell, return to the sample folder you were working in. The PCs at the venue have a command called zinit that does this all at once. Specify the name of the sample you were working in after zinit . For example, if you are in the middle of Chapter 3, execute it as follows:
# コマンド例2.1-2
zinit thermometer
The sample name will be completed by typing part of it and pressing the Tab key. If you execute only zinit without specifying a sample name, you will be in the same state as immediately after executing command example 2.1-1 (the state in ~\zephyrproject ). zinit can also be used in the VS Code terminal.
zinit On PCs without this feature, execute command example 2.1-1, then move to the sample folder as shown in cd ~\handson\thermometer . Immediately after executing command example 2.1-1, you will be in ~\zephyrproject , so executing west build directly will not build the sample.
Explanation: What is being done in command example 2.1-1?
cd ~\zephyrproject — Navigate to the Zephyr workspace (the folder containing west, the Zephyr core, and various modules).
.\.venv\Scripts\Activate.ps1 — This activates the Python virtual environment provided for Zephyr. West itself and various Python tools used for building are installed in this virtual environment. If activation is successful, (.venv) will be displayed at the beginning of the prompt.
$env:ZEPHYR_BASE = "..." — Set the Zephyr main folder as environment variable ZEPHYR_BASE . west will search for the workspace by traversing the folders above the current directory. In the following chapters, we will build in a working folder outside the workspace ( ~\handson\... ). From there, the workspace cannot be found, and west build becomes "unknown command". Setting ZEPHYR_BASE allows west to use it as a clue to find the workspace.
west --version — Check the version display to see if the `west` command itself is working correctly.
west topdir — Displays the workspace locations recognized by west. If you encounter an error here, please review the ZEPHYR_BASE settings.
In articles explaining Linux/macOS, you often see notations like source ~/zephyrproject/.venv/bin/activate and source zephyr/zephyr-env.sh . These are notations for bash/zsh and will not work as is in PowerShell.
zephyr-env.sh The main function is setting ZEPHYR_BASE . Therefore, in PowerShell, you set it directly using $env:ZEPHYR_BASE as shown above. (There is also zephyr-env.cmd available for Windows, but this is for the command prompt. Even if you execute it from PowerShell, the environment variables you set will not remain in PowerShell.)
If you encounter an error message stating "Script execution is disabled" when running Activate.ps1 , it means that the PowerShell execution policy is preventing it. Please run Set-ExecutionPolicy -Scope CurrentUser RemoteSigned once and then try again (this setting is already configured on the venue PCs).
Column: Precautions when copying and pasting commands
Confirmation dialog for pasting multiple lines : In Windows Terminal, when pasting multiple lines, a confirmation message may appear stating, "You are trying to paste multiple lines of text." Please select paste as is.
If an error occurs midway, it will stop there : When pasting multiple lines at once, even if an error occurs in an intermediate line, the subsequent lines will continue to execute. If you see an error in red text, do not rely on the results after that point, and first resolve the cause of the error in the line where it occurred. Until you get used to it, it is safer to copy and execute one line at a time .
The rows marked with # コマンド例… are markers : Please use these numbers when asking questions or referring to Appendix A.
Do not copy the prompt ( PS C:\Users\...> ) : The prompt shown in screenshots and execution examples is not part of the command.
If it doesn't work, please refer to Appendix A , "Troubleshooting." The command examples in this article are also compiled in Appendix B, "List of Command Examples ." Bash and zsh versions for macOS and Linux users are also included there.
Column: How to use zinit on your PC
zinit This is a function registered in your PowerShell profile (a script that is automatically loaded when PowerShell starts). You can create the same thing on your own PC as follows:
First, open the profile in Notepad using the following command (create the file if it doesn't exist).
# コマンド例2.1-3
if (-not (Test-Path $PROFILE.CurrentUserAllHosts)) { New-Item -Force $PROFILE.CurrentUserAllHosts | Out-Null }
notepad $PROFILE.CurrentUserAllHosts
Open Notepad, add the following content, and save it. This is not a command to paste into PowerShell and execute, but rather content to write to your profile .
function zinit {
param([string]$Sample)
Set-Location ~\zephyrproject
. .\.venv\Scripts\Activate.ps1
$env:ZEPHYR_BASE = "$HOME\zephyrproject\zephyr"
west --version
west topdir
if ($Sample) { Set-Location ~\handson\$Sample }
}
Once saved, reopen the PowerShell window and zinit will become available. Running the profile also requires the execution policy settings ( RemoteSigned ) explained in this section. Note that if you write Japanese in the profile, you need to pay attention to the character encoding (Windows PowerShell cannot correctly read Japanese characters contained in UTF-8 files without a BOM). The above content only contains alphanumeric characters, so you can save it as is.
If you want to try it on your own PC: Environment setup
This time, the environment will be pre-configured on the venue's PCs, but you can also set up the same environment on your own PC. For installation instructions, please refer to Section 0.3 , "For those who want to reproduce the issue on their own PC."
2.2 Let's run the Hello World sample.
In this section, we will build the hello_world sample, write it to the board, and verify that characters are displayed on the serial console.
From this point onward, do not directly edit the samples in zephyr/samples/ , but copy them to your working folder ( ~\handson ) before using them (Figure 2.2-1). Leave zephyr/samples/ as the original sample collection without making any changes, and perform all experiments and modifications only within your own folder.
Figure 2.2-1: Copy the sample to your working folder and use it.
Step 1: Copy the sample to your working folder.
hello_world Copy the sample to your working folder and then move into that folder.
# コマンド例2.2-1
New-Item -ItemType Directory -Force ~\handson | Out-Null
Copy-Item -Recurse ~\zephyrproject\zephyr\samples\hello_world ~\handson\hello_world
cd ~\handson\hello_world
After execution, if the prompt shows PS C:\Users\<ユーザー名>\handson\hello_world> , you have successfully moved. Just to be sure, if you execute ls , you should see src , CMakeLists.txt , prj.conf , etc. lined up.
Step 2: Build
Note: Don't forget the final .
. (space and period) at the end of the line means "build the application in the current directory." It's easy to cut off when copying, so please check after pasting. The board name after -b , including / and // , will also result in an error if even one character is different. Please copy and paste instead of retyping manually.
# コマンド例2.2-2
west build -p auto -b frdm_mcxn947/mcxn947/cpu0 .
The initial build may take several minutes. Please wait until the prompt returns.
If the build is successful, a table showing FLASH and RAM usage will appear at the end of the output.
(前略)
[xxx/xxx] Linking C executable zephyr\zephyr.elf
Memory region Used Size Region Size %age Used
FLASH: xxxxx B 2 MB x.xx%
RAM: xxxx B 320 KB x.xx%
SRAMX: 0 B 96 KB 0.00%
IDT_LIST: 0 B 32 KB 0.00%
Generated files: (後略)
[Replaced with the actual output from the venue's PC]
✔If you've reached this point, you're good to go: At the end of the output, a table showing the usage of FLASH and RAM will appear. Now you have the program ready to write to the microcontroller.
If an error occurs, the message will be displayed. Zephyr error messages are often numerous and can be difficult to track at first. The trick is to first look for the line that starts with error . You should either carefully read the message or use AI to understand it. Common errors and their solutions are summarized in A.3 Build Errors .
Step 3: Prepare to write
Before writing, prepare the following two things.
(1) Connect the PC and the board with a USB cable.
Connect ① (Debug USB connector, MCU-Link side) in Figure 1.3-1 to your PC using a USB cable (Figure 2.2-2). The LED on the board will light up, indicating that the power is on. Note that a USB cable designed for charging only will not support data communication; please use a cable that supports data communication.
Figure 2.2-2: Connect the USB cable to ① in Figure 1.3-1.
(2) Keep the serial console open.
hello_world This program outputs a string only once immediately after startup and then terminates. If you open the serial console after writing the program, you will miss the output. Therefore, open the serial console (a screen that displays the output of the board's printf , etc., on your PC) and connect before writing the program . This time we will use Tera Term as the terminal software. Please connect using steps 1 to 4 of the following "Tera Term Procedure".
To launch Tera Term, click the "Tera Term 5" icon on the desktop (Figure 2.2-3). Once launched, click "TeraA screen titled "Term: New Connection" will open.
Select "Serial" to choose a serial port , then from the list of "Ports," select the port corresponding to MCU-Link (① in Figure 1.3-1) and press "OK" (Figure 2.2-4). The list displays names like COM3: MCU-Link VCom Port (COM3) , where COM + number is used. The number varies depending on the PC. If you're unsure which one to choose, unplug and replug the board's USB cable, and select the port that disappears or reappears in the list (the list will update when you reopen the "New Connection" screen).
Set the baud rate (serial communication speed) to 115200. Select "Settings" → "Serial Port" from the menu, and the "Serial Port" tab of the "Tera Term: Other Settings" screen will open. Set "Speed" to 115200 and press "OK" (Figure 2.2-5). (Older versions of Tera) In Term, the screen names and buttons are different.
Set the character encoding to UTF-8 (this setting is not necessary on the venue's PCs). Open "Settings" → "Other Settings" from the menu and select the " Encoding " tab (you can also switch tabs while remaining on the screen from step 3). Set the receiving character encoding to UTF-8 and press "OK". This setting is necessary to correctly display ° in °C as shown in Chapter 3.
Figure 2.2-3: Tera Term icon on the desktop
Figure 2.2-4: Select a serial port in "New Connection"
Figure 2.2-5: Set the speed to 115200 in "Settings" → "Serial Port".
Once you've set it up, you can keep Tera Term open in subsequent chapters. You don't need to reconnect every time you write.
Step 4: Write
Once you're ready, return to PowerShell and write the following command:
# コマンド例2.2-3
west flash
Once the writing process is complete, the microcontroller will reset and the written program will be executed.
The following string will appear on the serial console (Figure 2.2-6):
*** Booting Zephyr OS build v4.x.x ***
Hello World! frdm_mcxn947/mcxn947/cpu0
The first line is the message that Zephyr always displays when it starts up, and the v4.x.x part is the Zephyr version. The second line is the string output by the program hello_world .
Figure 2.2-6: Screenshot of "Hello World" displayed in Tera Term
✔If you can do this, you're good to go: Hello World! frdm_mcxn947/mcxn947/cpu0 should be displayed in Tera Term.
When things don't go well
I forgot to open the serial console before writing and missed the output → With Tera Term connected, press the RESET button on the board (② in Figure 1.3-1). The program will run again from the beginning, and the string will be displayed again.
west flash If you get an error message such as "No probe found," check that the USB cable is plugged into port ① in Figure 1.3-1. Unplug and replug the cable, then run command example 2.2-3 again ( A.4 ).
If the writing was successful but nothing is displayed or the characters are garbled, check the port, baud rate, and character encoding settings in Tera Term ( A.5 ).
Explanation: Copying to a working folder (Command example 2.2-1)
The first line New-Item creates a working folder ~\handson (do nothing if it already exists; this line only needs to be written the first time). Copy-Item -Recurse copies the sample folders from zephyr\samples\ to the working folder, and cd moves you into that folder. In subsequent chapters, you should continue to copy the sample you want to work with to the working folder before starting.
Copy-Item If the destination folder already exists, this command will create another sample folder inside it (e.g., ~\handson\hello_world\hello_world ). If you want to redo the copy, first delete the old folder using Remove-Item -Recurse -Force ~\handson\hello_world before running the command again.
Explanation: -b and -p options (command example 2.2-2)
-b The argument that follows specifies the board to be built. Since the FRDM-MCXN947 has a dual-core Cortex-M33 configuration, you specify the "board name/SoC name/core name" as in frdm_mcxn947/mcxn947/cpu0 . For single-core boards like the FRDM-MCXA153, only the board name, frdm_mcxa153 , is needed.
You can also omit the SoC name and write it as frdm_mcxn947//cpu0 . This is because, on boards with only one SoC, such as the FRDM-MCXN947, the SoC name can be omitted, leaving only a slash, and the board will still be uniquely identified. In this article, we will use this abbreviation from section 2.3 onwards.
-p auto This is an abbreviation for --pristine=auto . It automatically determines whether to rebuild the build folder from a clean state (pristine build). More details will be explained in the following section.
The meaning of these options remains the same for west build and west flash , which will appear in subsequent chapters.
Explanation: Location of files created during the build process.
If the build is successful, a folder build/ will be created in the current directory. build/zephyr/zephyr.elf (an ELF file with debug information) will be used for writing, and west flash , which will be executed next, will also write this file to the board. In addition, the configuration contents can be checked in build/zephyr/.config , and the device tree after extraction can be checked in build/zephyr/zephyr.dts .
--pristine This option specifies whether to recreate this build folder. -p auto ( --pristine=auto ) will only recreate the build folder when necessary, based on changes to the source or configuration. Specify -p always ( --pristine=always ) if you want to explicitly perform a clean build, such as when the build process is abnormal.
If you want to try it on your own PC (using Tera Term)
If you save the settings from steps 3 and 4 in Tera Term by going to "Settings" → "Save Settings," you can connect using only step 2 from the next time onward.
Tera Term cannot be used on macOS or Linux. Please use CoolTerm or a similar application, select port /dev/tty.usbmodemXXXX (macOS) or /dev/ttyACM0 (Linux), and connect with a baud rate of 115200.
hello_world Let's take a look at the code.
hello_world The src/main.c is an astonishingly short piece of code. To open this file in VS Code, run code ~\handson\hello_world\src\main.c from PowerShell. (Please do not use VS Code's "Open Folder" to open a folder, as this will switch the contents of the window displaying the article.)
#include
int main(void)
{
printf("Hello World! %s\n", CONFIG_BOARD_TARGET);
return 0;
}
From what we can see, this is a perfectly ordinary C code Hello World . The only thing that seems special is that the macro CONFIG_BOARD_TARGET is probably defined within this build environment. Clock settings and peripheral initialization processes, which are commonly found in microcontroller programs, are nowhere to be found in this code.
This code also has a "non-RTOS-like" quality. There's no task (thread) creation or scheduler startup. It simply calls main() through printf() , making it look almost identical to a C program for a PC.
In many RTOSs, even for a simple "Hello World" program, you need to explicitly create a task and invoke the scheduler with a call like osKernelStart() . In Zephyr, main() itself already runs as a thread. The initialization before that is left to the build system and Kconfig settings. This "feel close to writing plain C programs" is one of the features that Zephyr presents to application developers.
Explanation: Files required in addition to main.c
The minimum requirements for a Zephyr application are src/main.c , as well as prj.conf and CMakeLists.txt .
prj.conf This is a configuration file that lists the Kconfig features used by the application. hello_world means there are no features that you particularly want to enable, so it is almost empty.
CMakeLists.txt This is the build definition file. find_package(Zephyr ...) loads the Zephyr build system, and target_sources() specifies the source files to build.
In fact, if you look inside zephyr/samples/hello_world/ , you'll only find files like CMakeLists.txt , prj.conf , src/main.c (and README.rst for explanation). The minimum configuration for a Zephyr application is this set of three files.
2.3 Write the blinky sample (LED blinking)
In this section, we will write the blinky sample to make the board's LED blink. The procedure is the same as for Hello World, only the sample we copy changes. From now on, we will use the abbreviation frdm_mcxn947//cpu0 mentioned in the explanation in section 2.2 to specify the board.
# コマンド例2.3-1
Copy-Item -Recurse ~\zephyrproject\zephyr\samples\basic\blinky ~\handson\blinky
cd ~\handson\blinky
Make sure the prompt is ...\handson\blinky> , then build.
Note: Build and write operations should be performed separately.
west build If you paste west flash at the same time, west flash will continue to run even if the build fails. In that case, the error on west flash will be displayed last, so the real cause (the build error) will be pushed to the top of the screen. If you follow the order of confirming that the build was successful before writing, you will be able to see where the failure occurred immediately.
# コマンド例2.3-2
west build -p auto -b frdm_mcxn947//cpu0 .
After confirming that the build was successful (that the memory usage table appears at the end), write the changes.
# コマンド例2.3-3
west flash
The RGB LED on the board (③ in Figure 1.3-1) blinks red every second (Figure 2.3-1). If you leave Tera Term connected, the following message will also be displayed along with the blinking.
Figure 2.3-1: RGB LED blinks red with blinky
*** Booting Zephyr OS build v4.x.x ***
LED state: OFF
LED state: ON
LED state: OFF
LED state: ON
✔This is the correct result: The RGB LED blinks red every second.
When things don't go well
If you executed west build while the prompt was still ...\hello_world> , hello_world will simply be rebuilt, which is harmless. Please start again from cd in command example 2.3-1.
Copy-Item If you run it twice, a nested folder called ~\handson\blinky\blinky will be created, but this will not affect the build in ~\handson\blinky . If this bothers you, delete it using the method explained in section 2.2 and then copy it again.
2.4 Let's take a peek inside the sample code
In this section, we will examine the code for blinky to determine where the LED's position is determined.
blinky src/main.c is a short piece of code that simply toggles (inverts the output of) a GPIO. Let's look at the whole thing. To open it in VS Code, run code ~\handson\blinky\src\main.c from PowerShell.
/*
* Copyright (c) 2016 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#include
#include
#include
/* 1000 msec = 1 sec */
#define SLEEP_TIME_MS 1000
/* The devicetree node identifier for the "led0" alias. */
#define LED0_NODE DT_ALIAS(led0)
/*
* A build error on this line means your board is unsupported.
* See the sample documentation for information on how to fix this.
*/
static const struct gpio_dt_spec led = GPIO_DT_SPEC_GET(LED0_NODE, gpios);
int main(void)
{
int ret;
bool led_state = true;
if (!gpio_is_ready_dt(&led)) {
return 0;
}
ret = gpio_pin_configure_dt(&led, GPIO_OUTPUT_ACTIVE);
if (ret < 0) {
return 0;
}
while (1) {
ret = gpio_pin_toggle_dt(&led);
if (ret < 0) {
return 0;
}
led_state = !led_state;
printf("LED state: %s\n", led_state ? "ON" : "OFF");
k_msleep(SLEEP_TIME_MS);
}
return 0;
}
Starting from the top, the following things are being done:
SLEEP_TIME_MS Then, the blinking interval (1000 milliseconds = 1 second) is determined.
DT_ALIAS(led0) The GPIO_DT_SPEC_GET() command retrieves information ( led ) indicating which GPIO pin the LED named led0 is connected to.
main() First, we check if the GPIO is available using gpio_is_ready_dt() , and then we set that pin as an output using gpio_pin_configure_dt() .
while (1) In this loop, the LED is inverted at gpio_pin_toggle_dt() , the status is displayed at printf() , and the program waits for 1 second at k_msleep() , and this process is repeated.
What's noteworthy here is that nowhere in the code is it written which pin the LED is connected to. The code only specifies an alias (another name) led0 . Which LED led0 actually refers to is defined in the Zephyr board's device tree (a file describing the hardware configuration, zephyr/boards/nxp/frdm_mcxn947/frdm_mcxn947.dtsi ) as follows:
aliases {
led0 = &red_led;
...
};
red_led: led_3 {
gpios = <&gpio0 10 GPIO_ACTIVE_LOW>;
label = "Red LED";
};
(excerpt)
The board has information written to it that " led0 is the red RGB LED (pin 10 of GPIO0)," so the application only needs to say led0 . The blinky folder does not contain any additional settings for the FRDM-MCXN947 (overlays placed in the boards/ folder. These are files that overlay differences onto the board's device tree, and are explained in section 3.3). It works as is with just the definitions on the board. This is why the same blinky works as is on any board that defines led0 .
The relationship between the application, device tree, Kconfig, and driver is illustrated in Figure 2.4-1. Kconfig is the mechanism for turning Zephyr's functions on and off (we will discuss this again in Chapter 3).
Figure 2.4-1: Relationship between applications, device trees, Kconfig, and drivers in blinky.
Column: MCX but called "kinetis"?
In the diagram, kinetis within compatible = "nxp,kinetis-gpio" is the name of NXP's previous microcontroller series (Kinetis). Since the MCX's GPIO uses the same circuitry as Kinetis, Zephyr does not create a new name, but uses the same name and driver ( gpio_mcux.c ).
The "device tree" introduced here will reappear in Chapter 3 when we explain the mechanism of temperature sensors. In Chapter 3, we will look at an example of adding parts that are not covered by the board-side definition using an application-side overlay.
▲ Return to Table of Contents
3. Try operating the temperature sensor.
3.1 Build and flash the sample
In this section, we will write the thermometer sample code that reads the temperature sensor on the board. As in Chapter 2, copy it to the working folder before building and writing it.
# コマンド例3.1-1
Copy-Item -Recurse ~\zephyrproject\zephyr\samples\sensor\thermometer ~\handson\thermometer
cd ~\handson\thermometer # コマンド例3.1-2
west build -p auto -b frdm_mcxn947//cpu0 .
Once the build is successful, make sure Tera Term is still connected before writing the files (if you have closed it, reconnect using the procedure in Section 2.2).
# コマンド例3.1-3
west flash
3.2 Check the value
The serial console displays the temperature value every second (Figure 3.2-1). If you touch the temperature sensor (④ in Figure 1.3-1 ) with your finger, you can see the value gradually increase.
*** Booting Zephyr OS build v4.x.x ***
Thermometer Example (arm)
Temperature device is 0x1000b23c, name is p3t1755@4800000236152a0090
Temperature is 25.9°C
Temperature is 25.8°C
Temperature is 25.8°C
The first few lines are sample startup messages. From the line marked name is p3t1755@4800000236152a0090 , we can see that the P3T1755 is being used as a temperature sensor, as defined in the device tree in Section 3.3. (The part marked 0x1000b23c may vary depending on the build.)
Figure 3.2-1: Screenshot showing temperature in Tera Term
✔If you can do this much, you're good to go: The temperature should be displayed in Tera Term every second, and the value should increase when you touch the sensor with your finger.
When things don't go well
If nothing is displayed, check if the COM port is displayed as COM3 - Tera Term VT in the Tera Term title bar (indicating a connection), and then press the RESET button on the board ( A.5 ).
°C The part may appear garbled → This is due to the character encoding settings in Tera Term, and does not affect its operation. If it bothers you, please set the receiving character encoding to UTF-8 in step 4 of Tera Term in section 2.2.
Device ... is not ready If you see a message like this → Sensor initialization failed. Check if you have written another sample (such as hello_world ) or if you built it while in the folder for this sample using cd ~\handson\thermometer , and then start again from command example 3.1-2.
3.3 Why did it move?
In this section, we will explain why the sensor values were displayed by looking at src/main.c and boards/*.overlay .
main.c On the other side, the sensor device is acquired as follows:
static const struct device *const temp_dev = DEVICE_DT_GET(DT_ALIAS(ambient_temp0));
boards/*.overlay determines which hardware (sensor type and connection bus) this alias ambient_temp0 actually refers to. The overlay is a file that overlays the differences for each application onto the device tree of the board itself.
In the FRDM-MCXN947, the temperature sensor is connected to the I3C bus. boards/frdm_mcxn947_mcxn947_cpu0.overlay is defined as follows (the actual file also includes specifications for the I3C bus clock speed, but only the essentials are extracted here).
/ {
aliases {
ambient-temp0 = &p3t1755;
};
};
&i3c1 {
status = "okay";
p3t1755: p3t1755@4800000236152a0090 {
compatible = "nxp,p3t1755";
reg = <0x48 0x0236 0x152a0090>;
status = "okay";
};
};
There are only two things I'm doing.
aliases In the block, connect ambient-temp0 to the p3t1755 node.
i3c1 Below the bus, add a sensor node that uses the nxp,p3t1755 driver.
main.c The side only says DT_ALIAS(ambient_temp0) . The application code has no idea that this sensor is connected via I3C (which is faster) instead of I2C, nor does it know the details of the register address.
The key point here is that "you can support different hardware configurations simply by changing the definition of the device tree, without writing a single line of code." For example, consider the case where you move the same sensor to an I2C-connected board or change to a different temperature sensor IC (assuming a compatible driver is available). Basically, only the contents of boards/*.overlay need to be changed, and the line DEVICE_DT_GET(DT_ALIAS(ambient_temp0)) in main.c can be reused as is. This relationship can be illustrated as shown in Figure 3.3-1.
Figure 3.3-1: Relationship between applications, device tree, Kconfig, and drivers in a thermometer.
Explanation: Where does the device tree actually exist?
The main component of the FRDM-MCXN947 board's device tree is zephyr/boards/nxp/frdm_mcxn947/frdm_mcxn947_mcxn947_cpu0.dts (and the common definition frdm_mcxn947.dtsi ) on the Zephyr board itself. This defines the complete set of peripherals that come standard on the board.
The device tree file on the board itself is not directly modified. Zephyr places a differential file (overlay, *.overlay ) on the application side to append to or overwrite the definition on the board itself. In Thermometer, it's samples/sensor/thermometer/boards/frdm_mcxn947_mcxn947_cpu0.overlay , and in the repository used in Chapter 5, it's boards/frdm_mcxn947_mcxn947_cpu0.overlay . The definition of the p3t1755 node shown in the main text is also part of this overlay. The advantage is that you can overlay only the differences necessary for each application while keeping the definition of the board itself the same.
When you build, the board's device tree and the application's overlay are merged, and the entire final device tree is written to build/zephyr/zephyr.dts . If you open this file, you can see that the p3t1755 node has been added to the board's definition.
In bare-metal development without an OS, and in many RTOSs that lack a device tree mechanism, it's common to directly write sensor I2C/I3C addresses and register operations into the application code. As a result, the application logic needs to be rewritten every time the sensor model or bus wiring changes. Zephyr moves the information of "which component" and "where" it's connected to a separate layer called the device tree. Therefore, even if the board changes, the application logic itself (in this case, the process of "reading and displaying the temperature") does not need to be touched.
If you're interested, try comparing the overlay files for other boards. You'll see that even though they're all samples/sensor/thermometer , each board has a different overlay with only the hardware connections differing.
▲ Return to Table of Contents
4. Try running the HTTP Server.
In this chapter, we connect the PC and the board with an Ethernet cable and access the HTTP Server running on the board from a browser (Figure 4.1-1). Up until now, everything has been self-contained on the board alone, but from here we take it a step further.
We will use the official Zephyr sample samples/net/sockets/http_server . Build and flash it as is, and you can turn the LED on/off from a browser and check the response of a simple endpoint (a window provided for each URL path, like /uptime ). In Chapter 5, we will use this mechanism as a foundation and extend it so that the temperature sensor values can be viewed in a browser.
The procedure for running the HTTP Server sample on the FRDM-MCXN947 has already been published as a separate blog post. For more detailed information, such as PC network settings and procedures for using DHCP instead of a static IP address, please refer to that post.
I tried running Zephyr HTTP Server on FRDM-MCXN947 (NXP Tech Blog, Japanese)
4.1 Build and flash the sample
In this section, we will rewrite the IP address of the http_server sample and write it down, then verify that a response is received from the PC at ping . This time, we will proceed using plain HTTP without TLS and a fixed IP address.
Figure 4.1-1: PC and board connection and IP address (USB cable and Ethernet cable)
Step 1: Copy the sample to your working folder.
# コマンド例4.1-1
Copy-Item -Recurse ~\zephyrproject\zephyr\samples\net\sockets\http_server ~\handson\http_server
cd ~\handson\http_server
Step 2: Rewrite the IP address of prj.conf
Running the following command will open prj.conf in VS Code.
# コマンド例4.1-2
code prj.conf
You may see a banner at the top of VSCode that says "Restricted Mode is intended for safe code browsing." (This is also visible at the top of Figure 4.1-2 later). This is a notification that the opened file is being displayed in a mode with restricted functionality for safety reasons. It does not affect editing or saving prj.conf , so you can proceed as is.
To give the board a fixed IP address, rewrite the line with CONFIG_NET_CONFIG_MY_IPV4_ADDR . Look below # Network address config in the middle of the file. In the original sample, it looks like this:
CONFIG_NET_CONFIG_MY_IPV4_ADDR="192.0.2.1"
CONFIG_NET_CONFIG_PEER_IPV4_ADDR="192.0.2.2"
CONFIG_NET_CONFIG_MY_IPV4_GW="192.0.2.2"
Replace the value enclosed in " on the first line (line 54 of the file) with the following. In VS Code, the line number is displayed on the left edge (Figure 4.1-2). Depending on the Zephyr version, the line number may be slightly off.
CONFIG_NET_CONFIG_MY_IPV4_ADDR="192.168.1.100"
CONFIG_NET_CONFIG_MY_IPV4_GW on the third line is the address of the Gateway (router). In this configuration, where the PC and the board are directly connected, it is not used, so you do not need to change it. If you do change it, change it to "192.168.1.1" (see the explanation at the end of this section). CONFIG_NET_CONFIG_PEER_IPV4_ADDR on the second line is similar but a different setting, so do not change it this time.
Note: Do not paste this line into PowerShell.
The line marked CONFIG_... above is not a command, but the content of the prj.conf file opened in VS Code. If you paste it into PowerShell, you will get an error saying "Not recognized" (it doesn't affect the file, so it's okay if you paste it by mistake).
Please rewrite the original line. If you add a line to the end while leaving the original line intact, the same setting will be written twice, making it difficult to determine which one is valid.
If you also need to rewrite the Gateway: The original value for both the PEER_IPV4_ADDR row and the MY_IPV4_GW row is "192.0.2.2" . Searching by value can easily lead to overwriting PEER row, so please check CONFIG_... name at the beginning of the row.
Do not remove " (double quotes) surrounding the value.
After editing, save with Ctrl + S . While ● is displayed next to the filename in the VSCode tab, it hasn't been saved yet. If you forget to save, the build will proceed with the original IP address.
Figure 4.1-2 shows the result after rewriting and saving the MY_IPV4_ADDR row (the MY_IPV4_GW row remains unchanged).
Figure 4.1-2: prj.conf has been rewritten to MY_IPV4_ADDR and saved.
The IP addresses of the PCs at the venue have already been configured to fall within the same subnet 192.168.1.0/24 as this board. You do not need to change any settings on your PCs.
Step 3: Build and flash
prj.conf After saving, return to the PowerShell window and build. Be careful not to paste commands directly into the VSCode window.
# コマンド例4.1-3
west build -p auto -b frdm_mcxn947//cpu0 .
I will write the data once the build is successful.
# コマンド例4.1-4
west flash
During the writing process, you may see a message like INFO: MCU-Link firmware update 'check': ... is running a firmware version which is older than the included firmware version . This indicates that the MCU-Link firmware on the board is older than the one included with the LinkServer. The writing process will proceed as is, so please do not worry and continue.
Step 4: Connect the Ethernet cable and check for a response.
Once the programming is complete, connect the PC and the board directly with an Ethernet cable. Insert the cable into the board's Ethernet connector (⑤ in Figure 1.3-1 ) (Figure 4.1-3).
Figure 4.1-3: Insert the Ethernet cable into the Ethernet connector on the board.
It will take a few seconds for the board to gain network access. Please wait a moment, then run the following command in PowerShell.
# コマンド例4.1-5
ping 192.168.1.100
It will be displayed as 192.168.1.100 からの応答 as shown below (Figure 4.1-4).
192.168.1.100 に ping を送信しています 32 バイトのデータ:
192.168.1.100 からの応答: バイト数 =32 時間 <1ms TTL=64
192.168.1.100 からの応答: バイト数 =32 時間 <1ms TTL=64
192.168.1.100 からの応答: バイト数 =32 時間 <1ms TTL=64
192.168.1.100 からの応答: バイト数 =32 時間 <1ms TTL=64
192.168.1.100 の ping 統計:
パケット数: 送信 = 4、受信 = 4、損失 = 0 (0% の損失)、
ラウンド トリップの概算時間 (ミリ秒):
最小 = 0ms、最大 = 0ms、平均 = 0ms
Figure 4.1-4: Execution result of ping
✔If you've reached this point, you're good to go: 192.168.1.100 からの応答 was displayed four times. Communication is working between the PC and the board.
When things don't go well
If you see the message "Request timed out," check the following in order:
Ensure the Ethernet cable is securely plugged into both the PC and the board. Also, check if the LED on the board's connector is lit.
prj.conf Check if the IP address is set to 192.168.1.100 and saved correctly . If you have saved it again, rebuild and write the file again starting from command example 4.1-3.
Check if the board's startup message or IP address is displayed on the serial console (Tera Term). If nothing is displayed, try pressing the RESET button.
If that still doesn't work, please refer to A.6 .
If you see the message "Destination host unreachable," it's possible that the PC's IP address is not set to 192.168.1.x ( A.6 ).
Explanation: Why use plain HTTP?
Plain HTTP is HTTP communication where the content of the communication is not encrypted. In practical use, it is recommended to use HTTPS, which is encrypted with TLS, to prevent eavesdropping and tampering. To use HTTPS, you need to prepare authentication-related files such as server certificates and private keys in advance.
Zephyr also supports these authentication mechanisms and communication encryption mechanisms. However, in this hands-on session, to avoid preparing authentication files within the limited time, and to focus on experiencing the HTTP Server mechanism itself, we will deliberately use plain HTTP.
Explanation: About Gateway Settings
The Gateway ( CONFIG_NET_CONFIG_MY_IPV4_GW ) is not strictly necessary for communication that does not go through a router. In this case, the PC and the board are directly connected with an Ethernet cable, and both are placed on the same subnet 192.168.1.0/24 . All communication is resolved by ARP within the same link, and routing through the Gateway does not occur. Therefore, in this case, it will work the same whether you leave the original value or change it to "192.168.1.1" .
If you connect the board to a router to communicate with another network, you will need to rewrite the router's address.
4.2 Trying to control an LED from a browser
In this section, you can turn the board's LEDs on and off from your browser.
Note: Enter the address starting with http://
Please enter the address in your browser's address bar as http://192.168.1.100/ , without omitting http:// .
Modern browsers automatically attempt to connect using encrypted communication https:// if you omit http:// or select an older history entry. This board runs on plain HTTP, so you cannot connect using https:// . If you see a message like "Your connection is not private" or "This site does not support secure connections," please check if the address bar is set to https:// .
Please note that when the page loads, "Not secure" will be displayed to the left of the address bar. This is because you are connecting via plain HTTP without encryption, and this is normal in this case.
Accessing http://192.168.1.100/ in your browser will display a page for controlling the LEDs (Figure 4.2-1).
Figure 4.2-1: LED control page opened in a browser
In addition to "LED Control," this page also displays "Uptime Counter" (the elapsed time since the board was started, the value of /uptime as seen in Section 4.3) and "Network Statistics" (statistics such as the amount of data sent and received by the board).
Pressing the "LED on" or "LED off" buttons on the page will turn the RGB LED on the board (③ in Figure 1.3-1 ) green on/off (Figure 4.2-2). The same RGB LED will be used in the LED blinking example in Section 2.3. The LED was blinking red before, but this time it's green.
Figure 4.2-2: RGB LED lights up green when the browser is operated.
✔This is the correct result: The RGB LED turns green on/off when you press the button.
At this time, lines like [00:00:25.684,000] ... are displayed one after another in Tera Term, and uart:~$ is also displayed. This is not an abnormality, as it is the log output by the HTTP Server sample and the display of the Zephyr shell (which accepts command input).
When things don't go well
Ping works but the page doesn't display in the browser → Check if the address is http:// . If a proxy is set up on your company PC, you need to configure it to bypass the proxy ( A.6 ).
The page displays but the LED doesn't react → It should light up green, not red, so please check the color. If it still doesn't react, refresh your browser ( F5 ) and try pressing the button again.
Column: On the "heaviness" of network functions
In typical embedded development, even running a single HTTP server often requires a lot of preparation. This includes tasks such as embedding and configuring the TCP/IP stack (e.g., lwIP), preparing a socket API, selecting and implementing an HTTP parser, and implementing a method for serving static files.
In this case, all of those options are simply changed from prj.conf to CONFIG_NET_* and CONFIG_HTTP_* to y . The only things written on the application side are the handler functions for each endpoint (functions that are called when a request arrives). The network stack and HTTP server can be handled consistently with a single build system and Kconfig. This is one of the reasons why Zephyr, despite being an RTOS for microcontrollers, is often discussed in the context of its relatively large amount of middleware.
Column: Is Zephyr's TCP/IP stack lwIP?
When it comes to TCP/IP stacks for embedded systems, many people might think of lwIP (lightweight IP). However, Zephyr doesn't import lwIP from an external source; instead, it uses its own proprietary TCP/IP stack implemented under subsys/net/ as standard. Features such as IPv4/IPv6, TCP/UDP, and socket APIs are built into the Zephyr core.
prj.conf The options CONFIG_NET_IPV4 , CONFIG_NET_TCP , and CONFIG_NET_SOCKETS that you enable also refer to the functionality of this stack. (Zephyr also supports configurations that combine external network stacks as modules, but this article uses the standard stack.)
4.3 Take a look at the /uptime endpoint
In this section, we will examine the behavior of the simplest endpoint.
Accessing http://192.168.1.100/uptime in your browser will display the elapsed time since the board was launched.
✔If you've reached this point, you're good to go: The browser should now display the elapsed time since the board was launched.
We will apply this endpoint structure, which "calculates a value in response to a GET request and returns it as text," directly to the next chapter, Chapter 5.
Explanation: HTTP Requests and Responses
When you access /uptime in your browser, a GET request is sent from the browser to the board, meaning "Please provide the contents of this path."
On the board side, the HTTP Server that receives the request calls the handler function associated with /uptime (the function that is called when a request arrives; in this case, uptime_handler ).
The handler calculates the elapsed time since the program was launched and sets that value as the response body.
The HTTP server adds a status line (such as 200 OK ) and headers to this body and returns it to the browser as an HTTP response.
The browser displays the body of the received response on the screen.
The /temperature endpoint, which will be added in Chapter 5, operates in exactly the same way: it receives a request, calculates a value, and returns it as the message body.
▲ Return to Table of Contents
5. Modify the HTTP Server to view the temperature sensor values in a browser.
5.1 What was added?
This section explains what has been added to the HTTP Server sample in Chapter 4.
We've added two more endpoints that return temperature, using the same structure as the /uptime endpoint seen in Section 4.3. The changes are only minor parts of src/main.c .
endpoint
Handler function
things to return
/temperature
temperature_handler
HTML page displaying temperature
/temperature.json
temperature_json_handler
Only the temperature value at that time (JSON)
The page that opens in your browser is page /temperature . This page has a small piece of JavaScript embedded in it that queries /temperature.json for a value every second and updates the display (Figure 5.1-1). This is the same mechanism that automatically updates the value of /uptime on the top page.
static int temperature_handler(struct http_client_ctx *client, enum http_transaction_status status,
const struct http_request_ctx *request_ctx,
struct http_response_ctx *response_ctx, void *user_data)
{
/* 3章の温度センサーと同じ sensor_sample_fetch_chan /
sensor_channel_get の流れで気温を取得し,HTMLとして返す */
...
}
static int temperature_json_handler(struct http_client_ctx *client, enum http_transaction_status status,
const struct http_request_ctx *request_ctx,
struct http_response_ctx *response_ctx, void *user_data)
{
/* 同じ方法で気温を取得し,数値だけを返す */
...
}
(excerpt)
I only added the following two things. The other parts (LED control, /uptime , static page delivery) remain unchanged from the original sample.
These two handler functions (the sensor reading part is combined into a common function)
Each is associated with the paths /temperature and /temperature.json , in the two lines HTTP_RESOURCE_DEFINE()
Figure 5.1-1: Flowchart showing how page /temperature displays the temperature and updates every second.
5.2 Let's actually view it in a browser
In this section, we will write the modified code and display the temperature in the browser.
The modified code is available in the GitHub repository teddokano/handson_http_server_temp . Clone it to your working folder and build and flash it using the same procedure as before.
# コマンド例5.2-1
cd ~\handson
git clone https://github.com/teddokano/handson_http_server_temp
cd handson_http_server_temp
[Confirm whether the venue PC has been cloned (i.e., whether internet access is available at the venue). If it has been cloned, only cd and above will be shown.]
prj.conf in this repository is already configured so that the board's IP address is the same as 192.168.1.100 in Chapter 4. There is no need to rewrite prj.conf .
# コマンド例5.2-2
west build -p auto -b frdm_mcxn947//cpu0 .
The program will be written once the build is successful. You can leave the Ethernet cable connected as it was in Chapter 4.
# コマンド例5.2-3
west flash
After writing the data, wait a few seconds, then access http://192.168.1.100/temperature in your browser, and the following page will be displayed (Figure 5.2-1).
Hello FRDM-MCXN947 temp sensor: P3T1755
Temperature: 24.312°C
← Back
The temperature value is automatically updated every second. Try touching the temperature sensor (④ in Figure 1.3-1 ) with your finger and see the value increase. If you open http://192.168.1.100/temperature.json directly, you can also see the numerical response (a value like 24.312 ) that is being queried on the back of the page.
Figure 5.2-1: Temperature displayed in the browser
✔If you can do this, you're good to go: The temperature is displayed in the browser, and the value increases when you touch the sensor with your finger.
When things don't go well
git clone If you get the message "already exists and is not an empty directory" → It has already been cloned. Just proceed by executing cd handson_http_server_temp .
git clone If you see a message like "Could not resolve host," it means your PC is not connected to the internet. Please connect to a network that can access the internet, such as Wi-Fi, and try again.
/temperature Opening it results in "404 Not Found" → The original sample from Chapter 4 is still written there. Check that the prompt is ...\handson_http_server_temp> and start again from command example 5.2-2.
If the page won't open, follow the same steps as in Sections 4.1 and 4.2, "When it doesn't work."
5.3 How are the contents of Chapters 3 and 4 combined?
The application created in this chapter does not use any new mechanisms. It is simply a combination of the components that were operated one by one in chapters 2 through 4. A table summarizing which component was used and where it was used is provided.
Things used in Chapter 5
Where in Chapter 5 is it?
Where did you see it?
Obtain temperature sensor data using an alias.
main.c of DEVICE_DT_GET(DT_ALIAS(ambient_temp0))
Section 3.3 (same line as thermometer)
Add a temperature sensor to the device tree.
boards/frdm_mcxn947_mcxn947_cpu0.overlay p3t1755 node
Section 3.3 (Same overlay as thermometer)
Enable the sensor function
prj.conf of CONFIG_SENSOR=y
Figure 3.3-1 in Section 3.3
Read the temperature
sensor_sample_fetch_chan() ・ sensor_channel_get()
Chapter 3 (thermometer)
Link the path and the handler function.
HTTP_RESOURCE_DEFINE() Register /temperature and /temperature.json
Section 4.3 (Same notation as /uptime )
Calculate the value and return it in the response.
temperature_handler ・ temperature_json_handler
Explanation of Section 4.3 (Same flow as uptime_handler )
Network and HTTP Server Functionality
prj.conf of CONFIG_NET_* ・ CONFIG_HTTP_*
Chapter 4 (as in the original sample)
By combining the components that were operated individually, we get an application that allows you to "view sensor values from a browser." The only new code we wrote was two handler functions and two lines of code to register them.
Explanation: Why main.c and CMakeLists.txt look a bit complicated
src/main.c When you open it, you'll find quite a few lines of code besides the /temperature handler. This is because the HTTP Server sample also provides the original endpoints such as the HTML and JavaScript for the top page, and the LED control /uptime . These are the "foundation for running as an HTTP server" and are not directly related to adding the temperature sensor, so for now, it's sufficient to focus only on the two handler functions in Section 5.1. The mechanism of this foundation is explained in Appendix G.
▲ Return to Table of Contents
6. Summary
6.1 Things I experienced today
I got a feel for the Zephyr development environment (west, device tree, Kconfig).
I ran an LED blinking program, a temperature sensor reading program, and an HTTP server.
I combined two samples to create an application that allows you to view sensor values in a browser.
6.2 Resources for trying it again yourself
Zephyr Project Official Documentation
The repository for the sample code used this time is (teddokano/handson_http_server_temp)
This blog post
For more helpful information, see → NXP's Zephyr OS - Summary Page (Japanese Blog)
6.3 How can AI be utilized?
When reading or modifying Zephyr's sample code, you can ask the AI assistant, "How can I add this functionality to this sample?" and it will suggest modifications that follow patterns in existing code. /temperature endpoint in this example was added with the same structure as the existing /uptime endpoint. If you encounter any parts you don't understand, we recommend first finding a similar section in the existing sample code and trying to decipher it together with the AI.
Another common issue is when an error occurs with west build . During a Zephyr build, a large number of messages appear at once, ranging from Kconfig warnings to CMake errors and linker errors. Initially, it can be difficult to pinpoint the real cause of the problem.
In such cases, it's recommended to start by pasting the entire error message into the AI and asking, "What kind of error is this?" The link error around sections-rom.ld mentioned in Appendix G was also identified with the help of the AI during the process of writing this article.
The information you should provide when asking a question is summarized in Section 0.4 , "When Asking a Question." The same applies when consulting with an AI.
6.4 Cleaning up
Those who attended the event
Please leave the boards and cables as they are. There is no need to put away your PC. Please follow the instructions of the venue staff.
Those who have tried it on their own PC
You can close PowerShell (or Terminal) as is. The virtual environment activation and ZEPHYR_BASE settings will disappear when you close the window. If you want to exit the virtual environment without closing the window, execute deactivate .
If you set your PC's Ethernet to a static IP address in Chapter 4, you should revert it back to its original setting. On the same screen as in column A.6 , change "IP assignment" back to "Automatic (DHCP)". If you don't, you won't be able to connect to the internet when you connect that Ethernet port to your company LAN or home router.
The board retains the last program written to it (the HTTP Server with temperature display from Chapter 5). This program runs every time the power is turned on, but it can be overwritten with a different program at any time using west flash .
Keep the working folder ~\handson so you can continue where you left off today. You can delete the entire folder when you no longer need it (but do not delete ~\zephyrproject ).
▲ Return to Table of Contents
Appendix A. When things don't work
This appendix summarizes common pitfalls when copying and pasting commands, and how to resolve them. Refer to the "What to do if it doesn't work" sections in each part of the main text.
A.1 First, check the following
If you encounter an error, please check the following three points before trying to find the cause. Most problems can be found by checking one of these.
If the prompt does not start with (.venv) or , the virtual environment is not enabled. This can happen if you have reopened PowerShell or are working in another window. Re-execute command example 2.1-1, or on the venue PC, execute zinit <作業中のサンプル名> ( command example 2.1-2 ).
Check if you are in the correct folder . The part of the prompt that looks like PS C:\Users\<ユーザー名>\handson\thermometer> should be the folder of the sample in the section you are currently working on. If not, re-execute cd in the first command example in that section.
Which error appeared first? When an error occurs, a large number of messages will appear afterward. Scroll up the screen and find the line where the first red text or error appeared. If you pasted multiple lines together, check which command caused the first error.
You can check the current status all at once with the following command.
# コマンド例A.1-1
Get-Location
$env:ZEPHYR_BASE
west topdir
If the first line displays your current folder, the second line displays C:\Users\<ユーザー名>\zephyrproject\zephyr , and the third line displays C:/Users/<ユーザー名>/zephyrproject , then your environment is set up correctly. If the second line is empty, run command example 2.1-1 again.
A.2 PowerShell Westbound
Symptoms
cause
Recovery method
west : 用語 'west' は,コマンドレット,関数,スクリプト ファイル,または操作可能なプログラムの名前として認識されません
The virtual environment is not enabled.
zinit <作業中のサンプル名> Execute the following (If your PC does not have zinit , execute command example 2.1-1 and return to the current working folder with cd ).
west: unknown command "build"
ZEPHYR_BASE This setting is not configured (west cannot find the workspace).
zinit <作業中のサンプル名> Execute the following (If your PC does not have zinit , execute command example 2.1-1 and return to the current working folder with cd ).
Activate.ps1 And "Script execution is disabled on this system."
PowerShell execution policy
Set-ExecutionPolicy -Scope CurrentUser RemoteSigned After executing this, repeat command example 2.1-1.
cd The error message is "Cannot be detected because the path does not exist" (e.g., Copy-Item .
Incorrect path entry, or missing source and destination folders.
Copy the command again instead of typing it manually. If ~\handson is not present, execute the first line of command example 2.2-1.
I pasted the command, but nothing happened, and the command remained after the prompt.
The newline character at the end of the line was not copied.
Enter Press
After pasting, a prompt saying >> appeared and the program stopped.
" Commands are cut off midway, such as forgetting to close a window.
Ctrl Interrupt with + C and copy the entire command again.
ping The error is not in the result of west , but in the Japanese text.
I accidentally pasted the entire article text and even the contents of prj.conf
This only copies the contents of the code block. Since it's executed within PowerShell, it doesn't affect any files.
A.3 Build errors
Symptoms
cause
Recovery method
Invalid BOARD , No board named ...
-b Typo in the board name
Copy the command example again, including // in frdm_mcxn947//cpu0 exactly.
source directory ... does not contain a CMakeLists.txt etc.
Built in a folder other than the sample folder (e.g., ~\handson or ~\zephyrproject ).
Execute the command cd in the example command for that section, then rebuild.
Build directory ... is for application ... It is said to be the build folder of another app.
The build folder from the previous build remains.
-p auto Change -p always and rebuild (see below).
The settings I changed aren't being reflected, and I keep getting unexplained errors.
Old information remains in the build folder.
-p always Then perform a clean build (see below).
prj.conf After rewriting it, a Kconfig error occurs.
I accidentally deleted " and = when rewriting.
prj.conf Review it. If you get confused, copy the sample again using the procedure in A.7.
A clean build is performed using the following command. It will delete the build folder and recreate it from scratch, so it will take time but is reliable.
# コマンド例A.3-1
west build -p always -b frdm_mcxn947//cpu0 .
If the error message is too long to read on the screen, you can save it to a file as follows. This is useful for opening the saved file build_log.txt in VS Code and searching for error , or for pasting the content into an AI for consultation.
# コマンド例A.3-2
west build -p auto -b frdm_mcxn947//cpu0 . 2>&1 | Out-File build_log.txt
code build_log.txt
When the build is slow (if you are trying it on your own PC)
Building Zephyr on Windows tends to be slower than building it on Linux on the same PC. For larger samples like http_server, a single build can take several minutes. The following three steps will significantly improve performance (the venue PCs are already configured).
Install ccache : This tool remembers the results of a compilation and reuses them for subsequent builds. Once installed, Zephyr will use it automatically. When rebuilding the same sample in the same folder, most of the compilation is skipped, making it faster (the first build will still take the usual time). In my environment, a clean build of http_server went from about -p always minutes to 73 seconds.
Windows Defender Exclusion Settings : Open "Windows Security" → "Virus & threat protection" → "Manage settings" → "Exclusions". Add ~\zephyrproject , working folder, Zephyr SDK folder, and ccache cache folder (usually %LOCALAPPDATA%\ccache ) to the exclusions. If you are using antivirus software other than Defender, exclude them in its settings. This will prevent a large number of files from being scanned with each build. If you are using a company PC, please check the IT department's policy.
Power settings : Connect the AC adapter to your laptop and set the power mode to "Optimal Performance".
# コマンド例A.3-3
winget install --id Ccache.Ccache -e
After installation, reopen PowerShell, configure the environment using zinit (or command example 2.1-1), and then rebuild using -p always . This is because the build folder created before installing ccache still has the settings configured not to use ccache.
If you are trying it on your own PC
If your Windows username contains Japanese characters or spaces, the build tool may not be able to handle the path correctly in some environments, resulting in an error. In that case, try using a short path with only alphanumeric characters, such as C:\handson instead of ~\handson , for your working folder.
A.4 Writing (west flash) error
Symptoms
cause
Recovery method
No probe found Errors such as "debug probe not found"
The USB cable is not plugged into the board's debug connector (MCU-Link side), or a USB cable designed for charging only is being used.
Check the connector you're plugging in, unplug it, plug it back in, and try again. Use a data communication compatible cable.
The probe is in use and cannot connect.
Debugging with another tool, such as MCUXpresso for VSC.
End the debugging session for the other tool and then run it again.
west flash It tries to restart the build and gets an error.
The previous build failed.
west flash Instead, resolve build errors first ( A.3 )
The writing process stopped midway, the board is unresponsive.
Temporary communication error
Unplug the USB cable, wait a few seconds, then plug it back in and run west flash again.
west flash You can run this command multiple times without any problems. If it fails, fix the cause and then run the same command again.
A.5 Nothing appears on the serial console.
Symptoms
cause
Recovery method
In Tera Term's "New Connection" menu, I can't select "Serial," and the board's port doesn't appear.
The USB cable is not plugged in, or it is a charging-only cable.
Check the cable, then reopen the screen by going to "File" → "New Connection" (the port list will be updated when you reopen it).
Unable to connect due to "Port in use" or "Serial port not open".
Another window, such as Tera Term or the VS Code serial monitor, is using the same port.
Close any other windowed applications or applications that are connected, then reconnect.
The whole thing becomes a meaningless string of symbols.
The baud rates are different.
Go to "Settings" → "Serial Port" and change it back to 115200.
Nothing is displayed even though it's connected.
I missed the timing for the output.
Press the RESET button on the board.
The display stopped working after I unplugged and replugged the USB cable.
The Tera Term connection was lost when I plugged it back in and out.
After going to "File" → "Disconnect," select "File" → "New Connection" and choose the port again. Note that the COM port number may have changed.
° Symbols such as these may appear as garbled characters.
The received character encoding is not UTF-8.
As per step 4 of Tera Term in Section 2.2 , set the receiving character encoding to UTF-8
A.6 Network and Browser-Related Features
You can check your PC's IP address by running the following command in PowerShell.
# コマンド例A.6-1
ipconfig
Please check the "IPv4 Address" in the "Ethernet Adapter" section.
Symptoms
cause
Recovery method
The IPv4 address is 169.254.x.x
The PC's Ethernet is not configured with a static IP address.
Set the PC side to 192.168.1.10 / 255.255.255.0 etc. (see below)
The IPv4 address is 192.168.1.100
The IP addresses of the PC and the board are overlapping.
Set the PC side to something other than 192.168.1.100 (e.g., 192.168.1.10 ).
The PC's Wi-Fi is also connected to network 192.168.1.x
The communication is routed to the Wi-Fi network and doesn't reach the board.
Disconnect Wi-Fi only during the practical training.
Ping works, but it won't open in the browser.
https:// You are trying to connect via a proxy, or through a proxy.
Re-enter the address as http://192.168.1.100/ . If you are using a proxy, add 192.168.1.100 to the proxy exceptions.
prj.conf I fixed it, but my IP address hasn't changed.
Not saved, or not rebuilt.
Save in VS Code with Ctrl + S and start again from command example 4.1-3.
If you are trying this on your own PC: Set a static IP address on your PC.
Open Windows "Settings" → "Network & Internet" → "Ethernet," and select "Manual" from "Edit" under "IP Assignment." Turn on IPv4, enter 192.168.1.10 for the IP address and 255.255.255.0 for the subnet mask, and save (you can leave the gateway field blank). For more details, please refer to the HTTP Server blog post introduced at the beginning of Chapter 4.
Figure A.6-1: Screenshot of setting a static IP address for Ethernet in Windows "Settings".
A.7 Reset procedure when the problem still cannot be fixed
When you're unsure what's causing the problem, the quickest solution is to start the section over from the beginning. Even if you delete the sample you copied to your working folder, the original sample in ~\zephyrproject remains, so you can try again as many times as you like.
Close the PowerShell window and open a new one.
Execute command example 2.1-1 ( zinit on the venue PC) to reconfigure the environment.
Delete the sample folder for the section you want to redo. For example, to redo Chapter 4, do the following: # コマンド例A.7-1
cd ~\handson
Remove-Item -Recurse -Force ~\handson\http_server Replace the folder name ( http_server ) with hello_world , blinky , thermometer , or handson_http_server_temp depending on the section you are redoing. Be careful not to delete ~\handson or ~\zephyrproject themselves.
Let's start again from the first command example in that section (copy and cd ).
If the board is not working properly, unplug both the USB cable and the Ethernet cable, wait a few seconds, plug them back in, and then try west flash again.
▲ Return to Table of Contents
Change history: [Published date]: First edition
=========================
We are currently unable to respond to comments left in the "Comment" section of this post. We apologize for the inconvenience, but please refer to "Technical Questions to NXP - How to Contact Us (Japanese Blog)" when making inquiries. (If you are already an NXP distributor or have a business relationship with NXP, you may contact your representative directly.) This article was written as a progress guide for the hands-on seminar " Zephyr Debut Session ." In the actual seminar, we will follow the steps outlined in this article.
Even if you didn't attend the seminar, you can reproduce the same content in your own environment by reading this article alone. To that end, I've included command examples and verification points without omitting any. Think of this not as a general explanatory article, but rather as a practical guide to get you to the point where it actually works.
(Estimated time: 90 minutes) *Assumes Zephyr OS is installed. Japanese Blog Introduction Sensor Ethernet Interface MCX
記事全体を表示