The leftover old man hummed "Golden Cooper" and brought HarmonyOS Device development experience

The leftover old man hummed "Golden Cooper" and brought HarmonyOS Device development experience

HarmonyOS Device development experience based on Hi3861 platform

Hello everyone, I am a non-famous Copy Siege Lion who is not doing my job properly. This article should be the last "Hello, World" of Copy Siege Lion in 2020-the actual development of IoT applications based on the Hi3861 development board of Harmony OS. Copy siege "Hello World" Lion of the road is never easy, try to open the (copy) hair (Tony) networking applications are also quite a few detours, and finally ran through the buzzer version of "Jingle Bells", I wish you all a happy new year!

Environment Setup

There is a "rule" that has been handed down for decades in the programming world-the entry starts with the environment setup. Sometimes the environment setup is relatively simple, such as learning HTML programming and having a browser; sometimes it is more cumbersome, such as React Native development. , You need to install NodeJS, Python, Java, Android SDK... and HarmonyOS Device development belongs to the latter, and the environment is more cumbersome. For example, you need a Linux system to compile, and you need to use Windows when burning to the device. If you want to experience other functions such as Wifi module or "touch", you also need to provide hotspots and other equipment. HarmonyOS officially provides a detailed environment building document and an introduction to the Hi3861 development board . In theory, you can run "Hello, HarmonyOS Device" after walking through the document.

Despite this, everyone's development habits or tool tastes are different, so when the environment is actually set up, there will still be some differences from the official documentation. Since I have some beggar version of the cloud host resources, I chose to use them, using the Linux cloud host as the compiler, and install SFTP Drive on the local Window 10 computer to mount the Linux cloud host to the local computer to make it burn When recording, you can directly read files on Linux; use VSCode's Remote SSH extension and HUAWEI DevEco Device Tool extension to develop debugging code, and use the sscom serial port debugging tool shared by a big guy for more convenient debugging. If you happen to be in the same situation as me, or you want to try my construction ideas, then let's get started!

1. Windows environment (development, debugging, burning)

On Windows, because it involves development and debugging, we need to install VS Code and extensions (that is, plug-ins), SFTP Drive (used to directly access files on Linux when burning), CH341SER.EXE (USB to serial port driver), sscom (optional, connect to serial port for debugging). I have already installed VS Code locally, so I won t go into too much detail. I believe everyone has installed it. I recommend installing VS Code from several software and hardware development tutorials that I have contacted.

1.1 Remote-SSH and SFTP Drive

You may have questions. Both of these things access files on the remote host. Just install one, right? I had the same idea at the beginning, but in practice, I found out: If only Remote-SSSH is installed, remote files cannot be read when programming configuration; if only SFTP Drive is installed, access to remote files when editing code is very slow; If you have a good plan for a big boss, you must teach it. What I installed here is Remote-SSH. If you want to experience more functions, you can install Remote Development directly. The Remote series is an extension developed by the giant company for remote development. After installing Remote-SSH, in order to avoid password login to Linux (there is a risk, be cautious), we need to operate the SSH key configuration.

In VSCode's Remote extension and SFTP Drive, first access the remote host through the account password to ensure that the code and files in the Linux host can be accessed normally.

When SSH key configuration, we can generate the key on the remote host, or generate the key on the local machine, and finally associate the configuration. What we use here is the Windows machine using PowerShell to execute the ssh-keygengeneration of the key to the file C:\Users/\.ssh\id_rsa(private key), and the file C:\Users/\.ssh\id_rsa.pub(public key) will be generated at the same time , copy the public key to the ~/.sshdirectory of the remote host through SFTP Drive , and connect to the remote host to execute the command cat id_rsa.pub >> authorized_keysappend In authorized_keys, since my machine already has a public key and private key, just use it directly. The things to note at this step are:

cd ~/.ssh
cat id_rsa.pub >> authorized_keys # 
sudo chmod 600 authorized_keys
sudo chmod 700 ~/.ssh # 
sudo vim/etc/ssh/sshd_config # sshd 
# PubkeyAuthentication yes  
sudo service sshd restart # sshd
 

After finishing the work, close VSCode and open it again. If you connect to the remote host without accident, you don't need to enter the access password. Say goodbye to the trouble of entering the password every time you connect.

1.2 HUAWEI DevEco Device Tool and dependent installation

HUAWEI DevEco Device Tool can be understood as a development tool for HarmonyOS Device, "HarmonyOS one-stop integrated development environment for smart devices, which supports on-demand customization of HarmonyOS components, one-click compilation and burning, visual debugging, and integration of distributed capabilities, etc., to help development Develop and innovate new hardware efficiently".

Official website: device.harmonyos.com/cn/ide , currently only supports Windows , which is why we need to use Windows native! In addition HUAWEI DevEco Device Tool VSCode no shelves to expand the market, only through the installation VSIX install way, that we need to extract the installation package downloaded from the official website, in addition to the .vsixfile suffix changed to .zipunpacked surprise for you - in DevEcoDeviceTool\extension\deveco\toolyour If you can get it HiBurn.exe, this program can be used for burning (equivalent to directly burning without using the VSCode extension to configure the burning parameters in the program).

According to the guidelines of the official document, we also need:

  • Install Node.js (try not to install the latest)
  • Install JDK
  • Install hpm
  • Install VSCode C/C++ extension
  • Install CH341SER.EXE
  • Install Jlink tool (optional, V6.54c and above)
  • Install hcc_riscv32 (I didn't install this successfully, so debugging depends on hand type)

In view of the fact that I have run "Hello, HarmonyOS" in the early stage (the development board I only obtained), I have most of the environments, but I got stuck for a long time when installing the Jlink tool, mainly due to network problems, which caused the downloaded files to be incomplete. Fortunately I tried every means to finally download it, and I got stuck when installing hcc_riscv32. Fortunately, it was not the key, so I simply gave up! ......After a lot of effort, I finally completed the Windows part of the environment setup, and you can directly burn the programs compiled by others!

2. Linux environment (compiled)

Compared with the Windows environment, the environment of HarmonyOS Device Linux is trivial. Just follow the document and it's done. However, after practical operation, if you are Ubuntu 18.04, I would recommend Mr. Runhe Xu's document- Harmony OS Development Guide-source code download and compilation . If you are like me and want to try to build an environment on CentOS, then I recommend the article of Hongmeng Community- Install Hongmeng LiteOS Compilation Environment in CentOS-HiSilicon Hi3861 , the same also only take what I need-I only need Build the environment for the compilation part. My cloud host operating system is CentOS 7.6 64-bit, which is similar to the blogger. Just follow the command line in the article and type them one by one before compiling.

The old saying goes well: "If I have seen further, it is by standing upon the shoulders of giants", so I combined Mr. Xu and the community article to complete the build environment of HarmonyOS on CentOS.

2.1 Source code acquisition (can be obtained by yourself)

#  repo 
mkdir ~/bin/
# sudo apt install curl #  curl 
curl https://gitee.com/oschina/repo/raw/fork_flow/repo-py3 > ~/bin/repo
chmod +x ~/bin/repo
echo 'export PATH=~/bin:$PATH'  >> ~/.bashrc
source ~/.bashrc
 


#  Harmony OS 
mkdir -p ~/harmonyos/openharmony && cd ~/harmonyos/openharmony
sudo apt install --no-install-recommends git python # repo python git 
#  `user.name` `user.email` 
# git config --global user.name "yourname"
# git config --global user.email "your-email-address"
repo init -u https://gitee.com/openharmony/manifest.git -b master --no-repo-verify
repo sync -c  #  
 

2.2 Install and compile the basic environment

Relying on Python 3.7+ and SCons installation, I compiled and installed Python 3.9.0 by myself here.

#  Python 
wget https://www.python.org/ftp/python/3.9.0/Python-3.9.0.tgz
#  
tar -xzvf Python-3.9.0.tgz
#  
yum groupinstall -y "Development tools"
yum install -y openssl-devel
yum install -y libffi libffi-devel
yum install -y bzip2-devel
yum install -y sqlite-devel
yum install -y readline-devel
yum install -y libuuid-devel
yum install -y uuid-devel
yum install -y xz-devel
yum install -y gdbm-devel
yum install -y tk-devel
#  
cd Python-3.9.0
./configure --prefix=/usr/local/python3
#  Python
make -j8 && make install
#  
ln -s/usr/local/python3/bin/python3/usr/bin/python3
ln -s/usr/local/python3/bin/pip3/usr/bin/pip3
#  
python3 --version
pip3 --version
#  Python 3 
pip3 install setuptools
pip3 install kconfiglib
pip3 install pycryptodome
pip3 install six --upgrade --ignore-installed six
pip3 install ecdsa
 


#  SCons 
wget http://prdownloads.sourceforge.net/scons/scons-4.0.1.tar.gz
#  
tar -xzvf scons-4.0.1.tar.gz
#  
cd SCons-4.0.1/
python3 setup.py install
#  
ln -s/usr/local/python3/bin/scons/usr/bin/scons
 

2.3 Install the compilation tool environment

The compilation tools we need to use are the cross-compiler gcc_riscv32, the gn that generates the ninja compilation script, and the ninja that executes the ninja compilation script. Although I don't know how they work, I firmly believe in "Just Do IT"!

#  
wget https://repo.huaweicloud.com/harmonyos/compiler/gcc_riscv32/7.3.0/linux/gcc_riscv32-linux-7.3.0.tar.gz
#  
tar -xvf gcc_riscv32-linux-7.3.0.tar.gz
#  
mv gcc_riscv32/usr/local/ #  
vi/etc/profile #  export PATH=/usr/local/gcc_riscv32/bin:$PATH
#  PATH :/usr/local/gcc_riscv32/bin:$PATH  PATH
source/etc/profile
#   vim ~/.bashrc  
#  
cd
riscv32-unknown-elf-gcc --version
 


#  gn 
wget https://repo.huaweicloud.com/harmonyos/compiler/gn/1523/linux/gn.1523.tar
#  
tar -xvf gn.1523.tar
#  
mv gn/usr/local/
ln -s/usr/local/gn/gn/usr/bin/gn
#  
gn --version
 


#  ninja
wget https://repo.huaweicloud.com/harmonyos/compiler/ninja/1.9.0/linux/ninja.1.9.0.tar
#  
tar -xvf ninja.1.9.0.tar
#  
mv ninja/usr/local/
ln -s/usr/local/ninja/ninja/usr/bin/ninja
#  
 ninja --version
 

2.4 Compile and test

Through simple and cumbersome Ctrl C and Ctrl V, we finally completed the Linux environment for HarmonyOS Device compilation. I can't wait to compile and try:

cd/root/harmonyos/openharmony
python3 build.py wifiiot
 

At this point, the complete HarmonyOS Device environment is set up, and we can start to write our own programs to compile and burn. Next, we try to understand the development and debugging of HarmonyOS Device from some basic functions of the Hi3861 kit.

Development and debugging

For specific documents and tutorials, please refer to official HarmonyOS documents and open source tutorials from vendors, such as HiHope's "Harmony OS Internet of Things Application Development Practical Combat" supporting video and code repository, BearPi's "HM Nano Hongmeng Season Release" supporting video and code repository. We are using the WI-FI IoT Hi3861 kit produced by HiHope, which covers a core board (Hi3861 WLAN module) and seven expansion modules (traffic light board, colorful light board, OLED board, NFC board, robot expansion board) , Contains a wealth of peripheral interfaces such as I2C (The Inter Integrated Circuit), PWM (Pulse Width Modulation), GPIO (General Purpose Input/Output) and multi-channel ADC (Analog to Digital Converter), etc., with very high playability . There are also many great people in Hongmeng community who have created a lot of creative gameplay, such as playing music through buzzer, playing video through OLED, Tetris mini game, controlling DJI drones... Do you also want to have a set? Next, please Follow Copy Siege Lion to explore the development and debugging of HarmonyOS Devic!

3.1 Start from lighting

If you have noticed the Hi3861 sample program in the official HarmonyOS Device documentation, in addition to "Hello, World" and WLAN module networking, a demo of LED peripheral control is also provided in the device development chapter, which can be realized by calling the NDK interface of HarmonyOS Control GPIO to achieve the effect of LED blinking, which is what we often call "lighting". We downloaded the source code directory: harmonyos/openharmony/applications/sample/wifi-iot/app/iothardware/led_example.c. Before copying the code, roughly understand the source directory:

.
  applications          #  wifi-iot camera 
      sample
      camera          #  
      wifi-iot        # WIFI 
  base                  #  & 
  build                 #  
      lite
  build.py              #  
  device                # qemu 
  docs                  # OpenHarmony 
  domains               #  
      iot
  drivers               #  
      hdf
      liteos
  foundation            #  
  kernel                #  
  out                   #  
      wifiiot           # python3 build.py wifiiot 
  prebuilts             #  
  test                  #  
  third_party           #  
  utils                 #  
  vendor                #  
      hisi
      huawei
 

Take a look at our development directory applications/sample/wifi-iot:

  app
      BUILD.gn                            #  
      demolink                            # Hello,World
          BUILD.gn
          helloworld.c
      iothardware                         #  Demo
          BUILD.gn
          led_example.c
      samgr                               #  
          bootstrap_example.c
          broadcast_example.c
          BUILD.gn
          example.h
          feature_example.c
          maintenance_example.c
          service_example.c
          service_recovery_example.c
          specified_task_example.c
          task_example.c
      startup                             #  
          BUILD.gn
  LICENSE                                 #  
 

According to the existing code, in order to complete the "lighting" practice, we only need to modify the entry file in VSCode Remote BUILD.gn:

import("//build/lite/config/component/lite_component.gni")
lite_component("app") {
    features = [
        "iothardware:led_example"
    ]
}
 

Then open a new VSCode window to configure and burn the DevEco Device Tool. After burning, you can view the output of the development board through the serial port tool. After resetting the development board, the LED lights flash and flash with the rhythm sound. Hurry up, the prompt flashes when you press the left button.

In order to simplify the operation, I installed the serial port debugging tool sscom, so I close the serial port in sscom before each programming. After the programming is completed, I open the serial port in sscom. The convenient point is that there is no need to input the serial port every time. , It is also faster when sending operation instructions. It is worth noting that the occupied serial port must be closed when programming, otherwise it will prompt that the serial port is busy and cannot be programmed normally.

The lighting demo here is realized through GPIO (General-purpose input/output), and the same can also realize the operation of the "red, yellow, green" LED and buzzer on the traffic light board. We realize the buzzer version "Jingle Bells" is also based on GPIO.

3.2 The Road to Copy

In the world of Internet of Everything, sensors are responsible for most of the data collection work. The colorful light board in the WIFI-IoTHi3861 kit includes photosensitive and human infrared, and the environment detection board includes temperature and humidity sensors and gas sensors. This part mainly involves ADC and I2C, so when we are developing sensor applications, we need to pay special attention to the wifiiot_adc.hsum in the public basic library, and the wifiiot_i2c.hfiles are located in the [openharmony/base/iot_hardware/interfaces/kits/wifiiot_lite](https://gitee.com/openharmony/iothardware_interfaces_kits_wifiiot_lite "openharmony/base/iot_hardware/interfaces/kits/wifiiot_lite")directory. In addition, if you use the peripheral interface to compile, you should pay attention to the corresponding Whether the configuration has been set up normally, for example, if I use I2C, then in the compile configuration file vendor\hisi\hi3861\hi3861\build\config\usr_config.mk, I need to # CONFIG_I2C_SUPPORT is not setmodify it to CONFIG_I2C_SUPPORT=y... Of course I didn t know these doorways at the beginning, until I moved forward again in the development of HarmonyOS Device The road to Copy, this road may never be able to turn back. I am like these sensors, collecting "knowledge" in a predetermined program...

With a learning attitude, I directly clone the HiHope warehouse to my harmonyos/openharmonycatalog. Of course, since it is Copy, I will LICENSEuse it according to the rules . Right. Please start Copy:

cd/root/harmonyos/openharmony/applications/sample/wifi-iot
git clone https://gitee.com/hihopeorg/HarmonyOS-IoT-Application-Development.git
mv HarmonyOS-IoT-Application-Development/* ./
 

Since then, the copy siege lion developed at the front-end of the company has more development trends in the Internet of Things, "the layman sees the excitement, the insider sees the joke", but ask myself, I am still very happy to try such a copy-zero It's great to be able to play with the basics! After the copy operation, I began to try to compile and burn each Demo. Although the code looks difficult (I am too white), some key codes can be reluctantly modified, such as "1 to 2"... In general , I experienced the fun of hands-on practice. Especially when I saw the buzzer version of "Two Tigers", I instantly thought of Christmas Eve that year. After working overtime late at night in a strange city, my shadow under the street lamp was stretched long, and I swept as usual. I took a shared bicycle, and the moment the lock was unlocked, the music rang...

Practical application

Back to our main task today-the buzzer version of "Jingle Bells". When we were young, we learned that "sound is a kind of wave. The sound that can be recognized by the human ear (the frequency is between 20 Hz and 20000 Hz), we call it a sound." What does the frequency of the sound have to do with the pitch we hear? I just found it- music theory that everyone should know . From the table, we can see that the frequency of the sound in the direction of "ji" gradually increases, and the "Duo Mi" we hear is almost the "in the table". 1046.50, 1174.66, 1318.51".

If the buzzer in the WIFI-IoT kit I use wants to output the same frequency, it needs to be controlled by a PWM interface. According to the actual measurement of the community leaders, hi_pwm_set_clock(PWM_CLK_XTAL);the clock source can be set to the crystal clock and the clock frequency is 40MHz. According to the formula of the square wave frequency of PWM output:

f = Fcs/freq
 

Among them, Fcs is the PWM clock source frequency, freq is the frequency division multiple, the value is [1~65535];

We can get the audio needed in the notation of "Jingle Bells" I used by simple conversion:

static const uint16_t g_tuneFreqs[] = {
    0, //40M Hz  
    38223, //1046.50  1
    34052, //1174.66  2
    30338, //1318.51  3
    28635, //1396.91  4
    25510, //1567.99  5
    22727, //1760.00  6
    40495, //987.77   7-
    36077, //1108.73  1+
    51021, //783.99   5-
    45455  //880.00   6-
};
 

The index starts from 0. For example, "1,2,3,4,5,6" correspond to "Do Lei Mi Shou La", so the corresponding notes in the numbered musical notation are as shown in the following figure:

Of course, in order to perform well, we also need to master a certain rhythm, otherwise it is all a beat, and there is no feeling of ups and downs. How do we reflect the life course of our Copy Siege Lion? Regarding the beats, I briefly summarized. The common beats in the notation are the following, which is the pause time when applied to the code:

After understanding this, I began to compile (kao) process (bei), and its core practices are as follows:

#  
static void *BeeperMusicTask(const char *arg)
{
    (void)arg;

    printf("BeeperMusicTask start!\r\n");

    hi_pwm_set_clock(PWM_CLK_XTAL); // 40MHz 160MHz 

    for (size_t i = 0; i < sizeof(g_scoreNotes)/sizeof(g_scoreNotes[0]); i++) {
        uint32_t tune = g_scoreNotes[i]; // 
        uint16_t freqDivisor = g_tuneFreqs[tune];
        uint32_t tuneInterval = g_scoreDurations[i] * (125*1000); // 
        printf("%d %d %d %d\r\n", tune, (40*1000*1000)/freqDivisor, freqDivisor, tuneInterval);
        PwmStart(WIFI_IOT_PWM_PORT_PWM0, freqDivisor/2, freqDivisor);
        usleep(tuneInterval);
        PwmStop(WIFI_IOT_PWM_PORT_PWM0);
    }

    return NULL;
}
 

The whole thing is to compile and burn. After a set of releases is pressed, the familiar voice bursts out: "Jingle bells, jingle bells,ingle all the way......"

Suddenly another thought came up: "Music Box" can be adjusted? The server provides music data, Hi3861 obtains the data through the request network, the buzzer plays, and then the OLED screen displays the current playback, and then adds functions to the buttons of the traffic light board, is it all alive~

postscript

XinXinNian finally finished this article. I thought it could be done in a few hours, but it turned out to be a weekend. Recently I found that the efficiency is too low. There are many articles and topics that I want to write, and there are many things to be done, but I always find that there is no time. Where does the time go? I didn't build this environment on CentOS before. I found out that the same is Linux when I wrote the article. There are still some differences between CentOS and Ubuntu. Fortunately, some pits have also emerged. The key lies in the experience sharing of the predecessors. Therefore, I hope this article can inspire newcomers to HarmonyOS.

Blessing not counting eggs: Happy leftover eggs and happy new year!

Link to station B: www.bilibili.com/video/BV1X6...