├── .gitattributes ├── .github └── workflows │ └── main.yml ├── .gitignore ├── LICENSE ├── README.md ├── application ├── camera │ ├── README.md │ └── cube_camera_shutter.py ├── capture_image_tool │ ├── README.md │ ├── assets │ │ └── capture.jpg │ └── boot.py ├── editor_pye.py ├── gimbal │ ├── Gimbal.py │ ├── README.md │ ├── gimbal.mp4 │ └── maixpy_gimbal.png └── uartTrans │ ├── README.md │ ├── demo_cmd.py │ ├── demo_data.py │ ├── demo_dual.py │ └── uart_protocol.py ├── basic ├── demo_crc16.py ├── demo_files.py ├── demo_fs_info.py ├── demo_globals.py ├── demo_json.py ├── demo_logging.py ├── demo_ram_fs.py ├── demo_repl_to_read.py ├── demo_set_gc_heap_size.py ├── demo_sha256.py ├── demo_sys_info.py ├── demo_thread.py ├── demo_time.py ├── demo_view_mem.py ├── demo_yield.py ├── demo_yield_task.py └── hello_wrold.py ├── board ├── board.py ├── config_maix_amigo.py ├── config_maix_amigo_ips.py ├── config_maix_bit.py ├── config_maix_cube.py ├── config_maix_dock.py ├── config_maix_duino.py ├── config_maix_go.py └── readme.md ├── hardware ├── demo_binocular.py ├── demo_camera.py ├── demo_cpu.py ├── demo_fft_spectrum.py ├── demo_fft_waterfall.py ├── demo_gpio_intr.py ├── demo_gpio_led.py ├── demo_i2c.py ├── demo_i2c_oled.py ├── demo_i2c_slave.py ├── demo_i2s.py ├── demo_lcd.py ├── demo_lcd_800x480.py ├── demo_mic_array.py ├── demo_onewire_ds18x20.py ├── demo_pwm.py ├── demo_spi_cs.py ├── demo_spi_soft.py ├── demo_switch_sensor.py ├── demo_timer.py ├── demo_touchscreen.py ├── demo_uart_loop.py ├── demo_uart_many.py ├── demo_wdt.py └── fpioa_manager.py ├── machine_vision ├── debug_kpu_yolov2.py ├── demo_affine.py ├── demo_find_green_blob.py ├── demo_fps_display.py ├── demo_image_deal.py ├── demo_scan_qr_code.py ├── face_find │ └── demo_find_face.py ├── face_recognization │ ├── README.md │ └── demo_face_recognization.py ├── fans_share │ ├── mask.kmodel │ │ ├── mask.kmodel │ │ └── mask.py │ ├── readme.md │ └── yolov2_apple,banana,orange │ │ ├── anchors.txt │ │ ├── classes.txt │ │ ├── main.py │ │ └── yolov2.kmodel ├── fmap │ ├── README.md │ └── fmap.py ├── load_big_model │ ├── README.md │ ├── README_ZH.md │ └── demo_load_big_model.py ├── mobilenet_1000_class │ ├── README.md │ ├── labels.txt │ └── mobilenetv1_1000class.py ├── model_le2be.py ├── models │ ├── face_model_at_0x300000.kfpkg │ ├── face_model_be_at_0x600000.kfpkg │ └── mnist.kmodel ├── self_learning_classifier │ ├── README.md │ ├── self_learning_classifier.py │ └── self_learning_classifier_load.py └── yolov2_20class.py ├── modules ├── grove │ ├── chainable_RGB_LED │ │ ├── README.md │ │ ├── RGB_LED.py │ │ ├── assets │ │ │ ├── grove_rgb_led.jpg │ │ │ └── grove_rgb_led2.jpg │ │ ├── breath.py │ │ └── fade_inout.py │ ├── ultrasonic │ │ ├── README.md │ │ ├── assets │ │ │ ├── ultrasonic.jpg │ │ │ └── ultrasonic2.jpg │ │ └── measure.py │ └── ws2812 │ │ └── ws2812.py ├── others │ ├── OLED │ │ └── ssd1306 │ │ │ ├── README.md │ │ │ ├── main.py │ │ │ ├── oled.png │ │ │ └── ssd1306k.py │ ├── Servo │ │ ├── Servo.png │ │ └── Servo.py │ ├── ads1115 │ │ └── ads1115.py │ ├── adxl345 │ │ └── adxl345.py │ ├── amg88xx │ │ ├── readme.md │ │ └── test_amg88xx.py │ ├── bmm150 │ │ └── bmm150.py │ ├── dht11 │ │ ├── DHT11-Technical-Data-Sheet.pdf │ │ ├── dht11.py │ │ ├── dht11_01.png │ │ └── readme.md │ ├── ds18x20 │ │ └── readme.md │ ├── es8374 │ │ ├── es8374.py │ │ └── sound.py │ ├── heimann_HTPA_32x32 │ │ ├── HTPA_32x32_demo.py │ │ ├── README.md │ │ └── Table.c │ ├── mlx90640 │ │ └── mlx90640.py │ └── pca9685 │ │ └── pca9685.py └── spmod │ ├── sp_bt │ └── demo_sp_bt.py │ ├── sp_eink │ └── demo_sp_eink.py │ ├── sp_ethernet │ ├── demo_ethernet_tcp.py │ └── demo_ethernet_udp.py │ ├── sp_lcd114 │ └── demo_sp_lcd114.py │ ├── sp_lora │ └── demo_sp_lora.py │ ├── sp_rfid │ └── demo_sp_rfid.py │ ├── sp_tof │ ├── demo_vl53l0x.py │ └── demo_vl53l1x.py │ └── sp_weather │ └── demo_sp_weather.py ├── multimedia ├── audio │ ├── 6.wav │ ├── play_wav.py │ ├── record_play.py │ └── record_wav.py ├── gui │ ├── image │ │ ├── anime.py │ │ ├── demo_draw_circle.py │ │ ├── demo_draw_font │ │ │ ├── image_draw_font.py │ │ │ ├── image_draw_string.py │ │ │ ├── readme.assets │ │ │ │ ├── image-20200902175614964.png │ │ │ │ ├── image-20200902175948599.png │ │ │ │ ├── image-20200902180153452.png │ │ │ │ ├── image-20200902180505263.png │ │ │ │ ├── image-20200902180913322.png │ │ │ │ ├── image-20200902181130459.png │ │ │ │ ├── image-20200902181311553.png │ │ │ │ ├── image-20200902181442677.png │ │ │ │ ├── image-20200902181645277.png │ │ │ │ └── view_image_font.jpg │ │ │ ├── readme.md │ │ │ ├── test_draw_font.py │ │ │ └── tools │ │ │ │ ├── 0xA00000_font_uincode_16_16_tblr.Dzk │ │ │ │ ├── FontGenerator.zip │ │ │ │ └── Pc2Lcd2002.zip │ │ ├── demo_rotation_corr.py │ │ └── demo_save_picture.py │ ├── lvgl │ │ ├── amigo_touchscreen │ │ │ ├── README.md │ │ │ ├── test_touch.py │ │ │ └── touch.py │ │ ├── images │ │ │ ├── blue_flower_32.bin │ │ │ └── png_decoder_test.png │ │ ├── lvgl_advanced.py │ │ ├── lvgl_button.py │ │ ├── lvgl_button2.py │ │ ├── lvgl_chart_anime.py │ │ ├── lvgl_image.Image.py │ │ ├── lvgl_img.py │ │ ├── lvgl_img_png.py │ │ ├── lvgl_multiple_screens.py │ │ └── lvgl_unicode.py │ └── maixui │ │ ├── bme280.py │ │ ├── button.py │ │ ├── msa301.py │ │ ├── pmu_axp173.py │ │ ├── qmcx983.py │ │ └── shtxx.py ├── nes │ ├── forward_keyboard.py │ ├── nes_amigo_handle_and_sound.py │ ├── nes_emulator.py │ ├── nes_ps2.py │ └── nes_py_input.py ├── speech_recognizer │ ├── demo_isolated_word_on_maixdock.py │ ├── isolated_word.py │ ├── maix_asr_2900k_0x500000.kmodel │ └── test_maix_asr.py └── video │ ├── amigo_play_video.py │ ├── demo_video_capture.py │ ├── demo_video_play.py │ └── demo_video_record.py └── network ├── README.md ├── demo_esp32_ap_scan.py ├── demo_esp32_ping.py ├── demo_esp32_read_adc.py ├── demo_espat_ap_scan.py ├── demo_espat_ap_test.py ├── demo_http_get_jpg.py ├── demo_socket_https.py ├── demo_socket_mqtt.py ├── demo_socket_pic_client.py ├── demo_socket_pic_server.py ├── demo_socket_tcp_client.py ├── demo_socket_tcp_server.py ├── demo_socket_udp_client.py ├── demo_socket_udp_server.py ├── espat_upgrade.py ├── network_esp32.py ├── network_espat.py └── network_wiznet5k.py /.gitattributes: -------------------------------------------------------------------------------- 1 | *.js linguist-language=python 2 | *.css linguist-language=python 3 | *.html linguist-language=python 4 | *.md linguist-language=python 5 | *.yml linguist-language=python 6 | *.py linguist-language=python 7 | *.c linguist-language=python 8 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | # This is a basic workflow to help you get started with Actions 2 | 3 | name: sync code to gitee 4 | 5 | # Controls when the action will run. Triggers the workflow on push or pull request 6 | # events but only for the master branch 7 | # on: 8 | # push: 9 | # branches: [ master ] 10 | # pull_request: 11 | # branches: [ master ] 12 | on: [push, pull_request] 13 | 14 | # A workflow run is made up of one or more jobs that can run sequentially or in parallel 15 | jobs: 16 | # This workflow contains a single job called "build" 17 | sync_gitee: 18 | name: sync repo to gitee 19 | # The type of runner that the job will run on 20 | runs-on: ubuntu-latest 21 | 22 | # Steps represent a sequence of tasks that will be executed as part of the job 23 | steps: 24 | # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it 25 | - name: checkout code from github 26 | uses: actions/checkout@v2 27 | 28 | # Runs a set of commands using the runners shell 29 | - name: sync shell cmd 30 | run: | 31 | GITEE_GIT_ADDR="git@gitee.com:Sipeed/maixpy-v1_scripts.git" 32 | git fetch --unshallow 33 | SSHPATH="$HOME/.ssh" 34 | rm -rf "$SSHPATH" 35 | mkdir -p "$SSHPATH" 36 | echo "${{ secrets.GITEE_SYNC_ACCESSS_KEY }}" > "$SSHPATH/id_rsa" 37 | chmod 600 "$SSHPATH/id_rsa" 38 | sudo sh -c "echo StrictHostKeyChecking no >>/etc/ssh/ssh_config" 39 | git remote add upstream $GITEE_GIT_ADDR 40 | git push upstream --all --force 41 | 42 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | .pytest_cache/ 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | local_settings.py 57 | db.sqlite3 58 | 59 | # Flask stuff: 60 | instance/ 61 | .webassets-cache 62 | 63 | # Scrapy stuff: 64 | .scrapy 65 | 66 | # Sphinx documentation 67 | docs/_build/ 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # Jupyter Notebook 73 | .ipynb_checkpoints 74 | 75 | # pyenv 76 | .python-version 77 | 78 | # celery beat schedule file 79 | celerybeat-schedule 80 | 81 | # SageMath parsed files 82 | *.sage.py 83 | 84 | # Environments 85 | .env 86 | .venv 87 | env/ 88 | venv/ 89 | ENV/ 90 | env.bak/ 91 | venv.bak/ 92 | 93 | # Spyder project settings 94 | .spyderproject 95 | .spyproject 96 | 97 | # Rope project settings 98 | .ropeproject 99 | 100 | # mkdocs documentation 101 | /site 102 | 103 | # mypy 104 | .mypy_cache/ 105 | 106 | .vscode 107 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 sipeed 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [MaixPy Scripts](https://github.com/sipeed/MaixPy_scripts) 2 | ==== 3 | 4 | 5 | Scripts for [MaixPy](https://github.com/sipeed/MaixPy) ~ have a good time~ 6 | 7 | Doc of MaixPy: [maixpy.sipeed.com](https://maixpy.sipeed.com) 8 | 9 | ## Directory Structure 10 | 11 | | directory | description | 12 | | --------- | ----------- | 13 | | application | Some complex applications | 14 | | basic | basic micropython usage | 15 | | board | run python code, config your sipeed hardware | 16 | | hardware | hardware API usage demo | 17 | | machine_vision | demo for vision related, including machine vision and AI processing related | 18 | | modules | external modules | 19 | | multimedia | normal multimedia processing, audio video game etc. | 20 | | network | network related | 21 | 22 | ------------------------------- 23 | 24 | 运行在 [MaixPy](https://github.com/sipeed/MaixPy) 上的脚本,玩得开心~ 25 | 26 | MaixPy 文档: [maixpy.sipeed.com](https://maixpy.sipeed.com) 27 | 28 | 另外,国内也可以在[gitee](https://gitee.com/Sipeed/maixpy_scripts)上查看,会实时同步, 对脚本有疑问请到[github](https://github.com/sipeed/MaixPy_scripts/issues)搜索问题或者提问, MaixPy 固件相关问题请到[MaixPy issue](https://github.com/sipeed/MaixPy_scripts/issues)提问 29 | 30 | 31 | 32 | ## 目录结构 33 | 34 | | 目录 | 描述 | 35 | | --------- | ----------- | 36 | | application | 一些复杂的应用 | 37 | | basic | 基本的 micropython 使用 | 38 | | board | 运行 Python 代码,配置你的 sipeed 硬件 | 39 | | hardware | 硬件 API 使用例程 | 40 | | machine_vision | 视觉处理相关,包括机器视觉以及AI处理 | 41 | | modules | 外部外设模块使用, 比如 Grove 模块, sp-mod 模块 | 42 | | multimedia | 普通的多媒体功能,比如音频、视频、GUI、游戏等 | 43 | | network | 网络相关例程 | 44 | 45 | -------------------------------------------------------------------------------- /application/camera/README.md: -------------------------------------------------------------------------------- 1 | simple camera program 2 | ====== 3 | 4 | * pull down IO10 to take photo 5 | * push boot key to exit to repl mode 6 | 7 | -------------------------------------------------------------------------------- /application/camera/cube_camera_shutter.py: -------------------------------------------------------------------------------- 1 | # simple_camera - By: chris - 周四 8月 6 2020 2 | 3 | import sensor, image, time, lcd 4 | from fpioa_manager import fm 5 | from board import board_info 6 | from Maix import GPIO 7 | import time 8 | 9 | 10 | num = 0 11 | switch_status = 0 12 | fm.register(board_info.BOOT_KEY, fm.fpioa.GPIO1, force=True) 13 | fm.register(board_info.ENTER,fm.fpioa.GPIOHS10,force=True) 14 | key_shot = GPIO(GPIO.GPIOHS10,GPIO.IN) 15 | repl_unlock = GPIO(GPIO.GPIO1, GPIO.IN) 16 | lcd.init(freq=15000000) 17 | sensor.reset() 18 | 19 | sensor.set_pixformat(sensor.YUV422) 20 | sensor.set_framesize(sensor.QVGA) 21 | sensor.skip_frames(time = 2000) 22 | clock = time.clock() 23 | 24 | while(repl_unlock.value() != 0): 25 | clock.tick() 26 | img = sensor.snapshot() 27 | if key_shot.value() == 0: 28 | path = "/flash/camera-" + str(num) + ".jpg" 29 | lcd.draw_string(80,40,"Saved :)",lcd.RED,lcd.WHITE) 30 | time.sleep(1) 31 | img.save(path) 32 | num += 1 33 | else: 34 | lcd.display(img) 35 | time.sleep(2) 36 | import lcd 37 | 38 | lcd.init() 39 | lcd.draw_string(60, 100, "REPL is unlocked!", lcd.RED, lcd.BLACK) 40 | time.sleep(4) 41 | -------------------------------------------------------------------------------- /application/capture_image_tool/README.md: -------------------------------------------------------------------------------- 1 | Tool: Capture iamges to SD card (工具: 采集图片到 SD 卡) 2 | ========= 3 | 4 | 5 | ![screenshot](assets/capture.jpg) 6 | 7 | 8 | Multiple classes supported 9 | 多分类支持 10 | --------------- 11 | 12 | Capture result example(采集结果示例): 13 | 14 | ``` 15 | ---cap_images_1 16 | | 17 | ----0 (class0) 18 | | | 19 | | ---0.jpg 20 | | | 21 | | ---1.jpg 22 | | | 23 | | ---2.jpg 24 | | 25 | ----1 (class1) 26 | | | 27 | | ---0.jpg 28 | | | 29 | | ---1.jpg 30 | | 31 | ----2 (class2) 32 | ---cap_images_2 33 | ``` 34 | 35 | 36 | 37 | ## Usage 38 | 39 | 1. Change camera and lcd configs according to your hardware like `lcd.rotation` 40 | 2. Prepare a `SD` card with `SPI` mode support, and format to `FAT32` with `MBR(msdos)` partition 41 | 3. Copy this `boot.py` to your `SD` card root directory 42 | 4. Power off board, then insert `SD` card to board 43 | 5. Power on, it will automatically create a directory like `cap_images_1`, 44 | the next time will be `cap_images_2` to avoid rewrite 45 | 6. Capture images for one class, 46 | push `boot` button on board and release to capture one image, 47 | this will save images as `cap_images_1/0/0.jpg`, 48 | the name of image will automaitcally increase, like `0.jpg` `1.jpg` ... 49 | 7. Long push `boot` botton on board to switch class, 50 | this will create a new directory like `cap_images_1/1/`, 51 | and later captured images will be saved to this directory like `cap_images_1/1/0.jpg` 52 | 8. Power off board, pop out SD card, mount on your PC, now you get your images in your file brower 53 | 54 | 55 | ## 使用方法 56 | 57 | 1. 根据你的开发板修改摄像头和屏幕配置, 比如`lcd.rotation` 58 | 2. 准备一张支持 `SPI` 模式的 `SD` 卡, 分区为 `MBR (msdos)`, 格式化为 `FAT32` 59 | 3. 将目录下的`boot.py`文件拷贝到 `SD` 卡根目录 60 | 4. 开发板断电, 将`SD`卡插入开发板 61 | 5. 开发板上电, 程序会自动创建一个目录`cap_images_1`, 下次上电会创建`cap_images_2`, 这样就避免了覆盖 62 | 6. 采集一个分类的图片 63 | 按开发板上的`boot`按键,然后松开按键来采集一张图片, 64 | 这会将图片保存到`cap_images_1/0/0.jpg`, 65 | 采集的图片的名字会自动增长, 比如`0.jpg` `1.jpg` ... 66 | 7. 长按`boot`按键切换类别目录 67 | 这会创建一个新目录,比如`cap_images_1/1/`, 68 | 后面采集的图片都会被保存到这个新的目录, 比如`cap_images_1/1/0.jpg` 69 | 8. 开发板断电,取出`SD`卡插到电脑, 打开文件管理器就可以看到采集的图片了 70 | 71 | 72 | 73 | 74 | 75 | -------------------------------------------------------------------------------- /application/capture_image_tool/assets/capture.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sipeed/MaixPy-v1_scripts/8d7c5f98ba654d226f433d31718d852674cab08d/application/capture_image_tool/assets/capture.jpg -------------------------------------------------------------------------------- /application/editor_pye.py: -------------------------------------------------------------------------------- 1 | # edit file by function pye("file_name_in_maixpy_fs") 2 | 3 | from pye_mp import pye 4 | 5 | pye("/sd/boot.py") 6 | 7 | -------------------------------------------------------------------------------- /application/gimbal/README.md: -------------------------------------------------------------------------------- 1 | A gimbal demo (Servo) 2 | ====== 3 | 4 | Two(/Tree) axies servo gimbal 5 | 6 | Servo parameters: 7 | 8 | * freq: 50 (Hz) 9 | * T: 1/50 = 0.02s = 20ms 10 | * duty: [0.5ms, 2.5ms] -> [0.025, 0.125] -> [2.5%, 12.5%] 11 | * pins: 12 | * IO24 <--> pitch 13 | * IO25 <--> roll 14 | 15 | Usage: 16 | 17 | * Use `face_model`([face_model_at_0x300000.kfpkg](https://dl.sipeed.com/MAIX/MaixPy/model)) to detect face 18 | * Change parameters according to your gimbal hardware( code at the start of the `main`), like direction of `camera` and `lcd`, and `PID` parameters 19 | * Run script 20 | 21 | demo video: 22 | 23 | [![](maixpy_gimbal.png)](https://wiki.sipeed.com/maixpy_gimbal.mp4) 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /application/gimbal/gimbal.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sipeed/MaixPy-v1_scripts/8d7c5f98ba654d226f433d31718d852674cab08d/application/gimbal/gimbal.mp4 -------------------------------------------------------------------------------- /application/gimbal/maixpy_gimbal.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sipeed/MaixPy-v1_scripts/8d7c5f98ba654d226f433d31718d852674cab08d/application/gimbal/maixpy_gimbal.png -------------------------------------------------------------------------------- /application/uartTrans/demo_cmd.py: -------------------------------------------------------------------------------- 1 | # 指令使用例程 2 | from fpioa_manager import fm 3 | import time 4 | from machine import UART 5 | import ustruct 6 | from uart_protocol import UartTrans 7 | 8 | def cus_cmd(uart, str): 9 | print("execute cus cmd {}".format(str)) 10 | uart.write("execute cus cmd {}".format(str)) 11 | 12 | # read cmd from uart and execute cmd fun 13 | if __name__ == "__main__": 14 | fm.register(22, fm.fpioa.UART1_TX, force=True) 15 | fm.register(21, fm.fpioa.UART1_RX, force=True) 16 | 17 | uart1 = UART(UART.UART1, 115200, 8, 1, 0, timeout=1000, read_buf_len=4096) 18 | 19 | uart_t = UartTrans(uart1) 20 | 21 | # pack cus cmd and send 22 | print("send the packed 'cus' cmd to uart1") 23 | uart_t.write('cus', 1) 24 | 25 | # register cus cmd 26 | uart_t.reg_cmd("cus", cus_cmd, uart1, "cus1") 27 | 28 | # start to parse the receive cmd 29 | while True: 30 | udatas = uart_t.read() 31 | if udatas: 32 | print(udatas) 33 | uart_t.parse(udatas) 34 | time.sleep_ms(100) 35 | 36 | '''output 37 | pc send: 38 | DD FF 01 00 03 63 75 73 E6 AB AA FF 39 | 40 | analysis: 41 | DD FF: head 42 | 01: cmd type 43 | 00 03: cmd len 44 | 63 75 73: 'cus' 45 | E6 AB: crc16 46 | AA FF: end 47 | output: 48 | >>> send the packed 'cus' cmd to uart1 49 | recv cmd: b'cus' 50 | execute cus cmd 1 51 | ''' 52 | -------------------------------------------------------------------------------- /application/uartTrans/demo_data.py: -------------------------------------------------------------------------------- 1 | # 收发数据例程 2 | from fpioa_manager import fm 3 | import time 4 | from machine import UART 5 | import ustruct 6 | from uart_protocol import UartTrans 7 | 8 | # read cmd from uart and execute cmd fun 9 | if __name__ == "__main__": 10 | fm.register(22, fm.fpioa.UART1_TX, force=True) 11 | fm.register(21, fm.fpioa.UART1_RX, force=True) 12 | uart1 = UART(UART.UART1, 115200, 8, 1, 0, timeout=1000, read_buf_len=4096) 13 | uart_t = UartTrans(uart1) 14 | 15 | # pack nums dat and send 16 | print("send the packed nums data to uart1") 17 | nums = uart_t.pack_num(3.1415, 'f') + uart_t.pack_num(16, 'H') + uart_t.pack_num(-8, 'b') 18 | uart_t.write(nums) 19 | uart_t.write("aaaaaaaaaaaaaaaaaaa") 20 | 21 | # start to parse the receive cmd 22 | while True: 23 | udatas = uart_t.read() 24 | d = uart_t.parse(udatas) 25 | if d: 26 | print(d) 27 | 28 | # send and reveive string 29 | '''log 30 | pc send: DD FF 00 00 13 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 CE 3A AA FF 31 | 32 | analysis: 33 | DD FF: head 34 | 00: data type 35 | 00 13: data len 36 | 61 ... 61: data 37 | CE 3A: crc16 38 | AA FF: end 39 | 40 | output: 41 | ['aaaaaaaaaaaaaaaaaaa'] 42 | 43 | pc send: 44 | DD FF 00 00 0A 66 40 49 0E 56 48 00 10 62 F8 4C E0 AA FF 45 | 46 | analysis: 47 | DD FF: head 48 | 00: data type 49 | 0A: data len 50 | 66: 'f' float 51 | 40 49 0e 56: 3.1415 52 | 48: 'H' uint16_t 53 | 00 10: 16 54 | 62: 'b' int8_t 55 | f8: -8 56 | 4c e0: crc16 57 | aa ff: end 58 | 59 | output: 60 | >>> send the packed nums data to uart1 61 | [3.1415, 16, -8] 62 | ''' -------------------------------------------------------------------------------- /application/uartTrans/demo_dual.py: -------------------------------------------------------------------------------- 1 | # 同时开启两个 uartTrans 例程 2 | from fpioa_manager import fm 3 | import time 4 | from machine import UART 5 | import ustruct 6 | from uart_protocol import UartTrans 7 | 8 | def cus_cmd(uart, str): 9 | print("execute cus cmd {}".format(str)) 10 | uart.write("execute cus cmd {}".format(str)) 11 | 12 | # read cmd from uart and execute cmd fun 13 | if __name__ == "__main__": 14 | fm.register(22, fm.fpioa.UART1_TX, force=True) 15 | fm.register(21, fm.fpioa.UART1_RX, force=True) 16 | 17 | fm.register(24, fm.fpioa.UART2_TX, force=True) 18 | fm.register(23, fm.fpioa.UART2_RX, force=True) 19 | 20 | uart1 = UART(UART.UART1, 115200, 8, 1, 0, timeout=1000, read_buf_len=4096) 21 | uart2 = UART(UART.UART2, 115200, 8, 1, 0, timeout=1000, read_buf_len=4096) 22 | 23 | uart_TA = UartTrans(uart1) 24 | uart_TB = UartTrans(uart2) 25 | 26 | # pack cus cmd and send 27 | print("send the packed 'cus' cmd to uart1") 28 | uart_TA.write('cus', 1) 29 | 30 | # register cus cmd 31 | uart_TA.reg_cmd("cus", cus_cmd, uart1, "cus1") 32 | uart_TB.reg_cmd("cus", cus_cmd, uart2, "cus2") 33 | 34 | # start to parse the receive cmd 35 | while True: 36 | uart_TA.parse(uart_TA.read()) 37 | uart_TB.parse(uart_TB.read()) 38 | time.sleep_ms(100) 39 | 40 | '''output 41 | pc send: 42 | DD FF 01 00 03 63 75 73 E6 AB AA FF 43 | 44 | analysis: 45 | DD FF: head 46 | 01: cmd type 47 | 00 03: cmd len 48 | 63 75 73: 'cus' 49 | E6 AB: crc16 50 | AA FF: end 51 | output: 52 | >>> send the packed 'cus' cmd to uart1 53 | recv cmd: b'cus' 54 | execute cus cmd 1 55 | ''' 56 | 57 | '''packed data: cmd: b'cus' 58 | 59 | ''' -------------------------------------------------------------------------------- /basic/demo_crc16.py: -------------------------------------------------------------------------------- 1 | CRC_LENGTH = 0x02 2 | 3 | CRC16_TABLE = ( 4 | 0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241, 0xC601, 5 | 0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440, 0xCC01, 0x0CC0, 6 | 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40, 0x0A00, 0xCAC1, 0xCB81, 7 | 0x0B40, 0xC901, 0x09C0, 0x0880, 0xC841, 0xD801, 0x18C0, 0x1980, 0xD941, 8 | 0x1B00, 0xDBC1, 0xDA81, 0x1A40, 0x1E00, 0xDEC1, 0xDF81, 0x1F40, 0xDD01, 9 | 0x1DC0, 0x1C80, 0xDC41, 0x1400, 0xD4C1, 0xD581, 0x1540, 0xD701, 0x17C0, 10 | 0x1680, 0xD641, 0xD201, 0x12C0, 0x1380, 0xD341, 0x1100, 0xD1C1, 0xD081, 11 | 0x1040, 0xF001, 0x30C0, 0x3180, 0xF141, 0x3300, 0xF3C1, 0xF281, 0x3240, 12 | 0x3600, 0xF6C1, 0xF781, 0x3740, 0xF501, 0x35C0, 0x3480, 0xF441, 0x3C00, 13 | 0xFCC1, 0xFD81, 0x3D40, 0xFF01, 0x3FC0, 0x3E80, 0xFE41, 0xFA01, 0x3AC0, 14 | 0x3B80, 0xFB41, 0x3900, 0xF9C1, 0xF881, 0x3840, 0x2800, 0xE8C1, 0xE981, 15 | 0x2940, 0xEB01, 0x2BC0, 0x2A80, 0xEA41, 0xEE01, 0x2EC0, 0x2F80, 0xEF41, 16 | 0x2D00, 0xEDC1, 0xEC81, 0x2C40, 0xE401, 0x24C0, 0x2580, 0xE541, 0x2700, 17 | 0xE7C1, 0xE681, 0x2640, 0x2200, 0xE2C1, 0xE381, 0x2340, 0xE101, 0x21C0, 18 | 0x2080, 0xE041, 0xA001, 0x60C0, 0x6180, 0xA141, 0x6300, 0xA3C1, 0xA281, 19 | 0x6240, 0x6600, 0xA6C1, 0xA781, 0x6740, 0xA501, 0x65C0, 0x6480, 0xA441, 20 | 0x6C00, 0xACC1, 0xAD81, 0x6D40, 0xAF01, 0x6FC0, 0x6E80, 0xAE41, 0xAA01, 21 | 0x6AC0, 0x6B80, 0xAB41, 0x6900, 0xA9C1, 0xA881, 0x6840, 0x7800, 0xB8C1, 22 | 0xB981, 0x7940, 0xBB01, 0x7BC0, 0x7A80, 0xBA41, 0xBE01, 0x7EC0, 0x7F80, 23 | 0xBF41, 0x7D00, 0xBDC1, 0xBC81, 0x7C40, 0xB401, 0x74C0, 0x7580, 0xB541, 24 | 0x7700, 0xB7C1, 0xB681, 0x7640, 0x7200, 0xB2C1, 0xB381, 0x7340, 0xB101, 25 | 0x71C0, 0x7080, 0xB041, 0x5000, 0x90C1, 0x9181, 0x5140, 0x9301, 0x53C0, 26 | 0x5280, 0x9241, 0x9601, 0x56C0, 0x5780, 0x9741, 0x5500, 0x95C1, 0x9481, 27 | 0x5440, 0x9C01, 0x5CC0, 0x5D80, 0x9D41, 0x5F00, 0x9FC1, 0x9E81, 0x5E40, 28 | 0x5A00, 0x9AC1, 0x9B81, 0x5B40, 0x9901, 0x59C0, 0x5880, 0x9841, 0x8801, 29 | 0x48C0, 0x4980, 0x8941, 0x4B00, 0x8BC1, 0x8A81, 0x4A40, 0x4E00, 0x8EC1, 30 | 0x8F81, 0x4F40, 0x8D01, 0x4DC0, 0x4C80, 0x8C41, 0x4400, 0x84C1, 0x8581, 31 | 0x4540, 0x8701, 0x47C0, 0x4680, 0x8641, 0x8201, 0x42C0, 0x4380, 0x8341, 32 | 0x4100, 0x81C1, 0x8081, 0x4040) 33 | """ Code to generate the CRC-16 lookup table: 34 | def generate_crc16_table(): 35 | crc_table = [] 36 | for byte in range(256): 37 | crc = 0x0000 38 | for _ in range(8): 39 | if (byte ^ crc) & 0x0001: 40 | crc = (crc >> 1) ^ 0xa001 41 | else: 42 | crc >>= 1 43 | byte >>= 1 44 | crc_table.append(crc) 45 | return crc_table 46 | """ 47 | 48 | import struct 49 | 50 | 51 | def crc16(data): 52 | crc = 0xFFFF 53 | for char in data: 54 | crc = (crc >> 8) ^ CRC16_TABLE[((crc) ^ char) & 0xFF] 55 | return struct.pack('= (self.level or _level) 54 | 55 | def log(self, level, msg, *args): 56 | if self.isEnabledFor(level): 57 | levelname = self._level_str(level) 58 | if args: 59 | msg = msg % args 60 | if self.handlers: 61 | d = self.record.__dict__ 62 | d["levelname"] = levelname 63 | d["levelno"] = level 64 | d["message"] = msg 65 | d["name"] = self.name 66 | for h in self.handlers: 67 | h.emit(self.record) 68 | else: 69 | print(levelname, ":", self.name, ":", msg, sep="", file=_stream) 70 | 71 | def debug(self, msg, *args): 72 | self.log(DEBUG, msg, *args) 73 | 74 | def info(self, msg, *args): 75 | self.log(INFO, msg, *args) 76 | 77 | def warning(self, msg, *args): 78 | self.log(WARNING, msg, *args) 79 | 80 | def error(self, msg, *args): 81 | self.log(ERROR, msg, *args) 82 | 83 | def critical(self, msg, *args): 84 | self.log(CRITICAL, msg, *args) 85 | 86 | def exc(self, e, msg, *args): 87 | self.log(ERROR, msg, *args) 88 | sys.print_exception(e, _stream) 89 | 90 | def addHandler(self, hndlr): 91 | self.handlers.append(hndlr) 92 | 93 | _level = INFO 94 | _loggers = {} 95 | 96 | def getLogger(name="root"): 97 | if name in _loggers: 98 | return _loggers[name] 99 | l = Logger(name) 100 | _loggers[name] = l 101 | return l 102 | 103 | def info(msg, *args): 104 | getLogger().info(msg, *args) 105 | 106 | def debug(msg, *args): 107 | getLogger().debug(msg, *args) 108 | 109 | def basicConfig(level=INFO, filename=None, stream=None, format=None): 110 | global _level, _stream 111 | _level = level 112 | if stream: 113 | _stream = stream 114 | if filename is not None: 115 | print("basicConfig: filename arg is not supported") 116 | if format is not None: 117 | print("basicConfig: format arg is not supported") 118 | 119 | if __name__ == "__main__": 120 | 121 | basicConfig(level=INFO) 122 | log = getLogger("test") 123 | log.debug("Test message: %d(%s)", 100, "foobar") 124 | log.info("Test message2: %d(%s)", 100, "foobar") 125 | log.warning("Test message3: %d(%s)") 126 | log.error("Test message4") 127 | log.critical("Test message5") 128 | info("Test message6") 129 | 130 | try: 131 | 1/0 132 | except Exception as e: 133 | log.exc(e, "Some trouble (%s)", "expected") 134 | 135 | class MyHandler(Handler): 136 | def emit(self, record): 137 | print("levelname=%(levelname)s name=%(name)s message=%(message)s" % record.__dict__) 138 | 139 | getLogger().addHandler(MyHandler()) 140 | info("Test message7") 141 | -------------------------------------------------------------------------------- /basic/demo_ram_fs.py: -------------------------------------------------------------------------------- 1 | import uos 2 | 3 | class RAMFlashDev: 4 | def __init__(self): 5 | self.fs_size = 256*1024 6 | self.fs_data = bytearray(256*1024) 7 | self.erase_block = 32*1024 8 | self.log_block_size = 64*1024 9 | self.log_page_size = 4*1024 10 | 11 | def read(self,buf,size,addr): 12 | for i in range(len(buf)): 13 | buf[i] = self.fs_data[addr+i] 14 | 15 | def write(self,buf,size,addr): 16 | for i in range(len(buf)): 17 | self.fs_data[addr+i] = buf[i] 18 | 19 | def erase(self,size,addr): 20 | for i in range(size): 21 | self.fs_data[addr+i] = 0xff 22 | 23 | 24 | blkdev = RAMFlashDev() 25 | vfs = uos.VfsSpiffs(blkdev) 26 | vfs.mkfs(vfs) 27 | uos.mount(vfs,'/ramdisk') 28 | 29 | text_str = "hello maixpy" 30 | f = open("/ramdisk/test.txt", "w") 31 | print("write:", text_str) 32 | f.write(text_str) 33 | f.close() 34 | 35 | f = open("/ramdisk/test.txt", "r") 36 | text = f.read() 37 | print("read:",text) 38 | f.close() 39 | 40 | 41 | -------------------------------------------------------------------------------- /basic/demo_repl_to_read.py: -------------------------------------------------------------------------------- 1 | 2 | import sys 3 | 4 | while True: 5 | tmp = sys.stdin.read(1) 6 | if tmp == 'e': 7 | break 8 | sys.stdout.write(tmp) 9 | -------------------------------------------------------------------------------- /basic/demo_set_gc_heap_size.py: -------------------------------------------------------------------------------- 1 | import machine 2 | import Maix 3 | 4 | gc_mem_size = 1024*1024 5 | 6 | print('config micropython gc stack 1M (1024KB) if not') 7 | if Maix.utils.gc_heap_size() != gc_mem_size: 8 | Maix.utils.gc_heap_size(gc_mem_size) 9 | print('updates take effect when you reboot the system. ') 10 | machine.reset() 11 | 12 | print('Current: ', Maix.utils.gc_heap_size()) 13 | 14 | ''' 15 | 16 | [MAIXPY] Pll0:freq:806000000 17 | [MAIXPY] Pll1:freq:398666666 18 | [MAIXPY] Pll2:freq:45066666 19 | [MAIXPY] cpu:freq:403000000 20 | [MAIXPY] kpu:freq:398666666 21 | [MAIXPY] Flash:0xef:0x17 22 | [MaixPy] gc heap=0x800cbc50-0x8014bc50(524288) 23 | [MaixPy] init end 24 | 25 | __ __ _____ __ __ _____ __ __ 26 | | \/ | /\ |_ _| \ \ / / | __ \ \ \ / / 27 | | \ / | / \ | | \ V / | |__) | \ \_/ / 28 | | |\/| | / /\ \ | | > < | ___/ \ / 29 | | | | | / ____ \ _| |_ / . \ | | | | 30 | |_| |_| /_/ \_\ |_____| /_/ \_\ |_| |_| 31 | 32 | Official Site : https://www.sipeed.com 33 | Wiki : https://maixpy.sipeed.com 34 | 35 | MicroPython v0.5.1-136-g039f72b6c-dirty on 2020-11-18; Sipeed_M1 with kendryte-k210 36 | Type "help()" for more information. 37 | >>> 38 | >>> 39 | >>> 40 | raw REPL; CTRL-B to exit 41 | >OK 42 | config micropython gc stack 1M (1024KB) if not 43 | updates take effect when you reboot the s 44 | [MAIXPY] Pll0:freq:806000000 45 | [MAIXPY] Pll1:freq:398666666 46 | [MAIXPY] Pll2:freq:45066666 47 | [MAIXPY] cpu:freq:403000000 48 | [MAIXPY] kpu:freq:398666666 49 | [MAIXPY] Flash:0xef:0x17 50 | [MaixPy] gc heap=0x800cbc50-0x801cbc50(1048576) 51 | [MaixPy] init end 52 | 53 | __ __ _____ __ __ _____ __ __ 54 | | \/ | /\ |_ _| \ \ / / | __ \ \ \ / / 55 | | \ / | / \ | | \ V / | |__) | \ \_/ / 56 | | |\/| | / /\ \ | | > < | ___/ \ / 57 | | | | | / ____ \ _| |_ / . \ | | | | 58 | |_| |_| /_/ \_\ |_____| /_/ \_\ |_| |_| 59 | 60 | Official Site : https://www.sipeed.com 61 | Wiki : https://maixpy.sipeed.com 62 | 63 | MicroPython v0.5.1-136-g039f72b6c-dirty on 2020-11-18; Sipeed_M1 with kendryte-k210 64 | Type "help()" for more information. 65 | >>> 66 | ''' 67 | -------------------------------------------------------------------------------- /basic/demo_sha256.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | 3 | a = bytes([0]*65) 4 | b = hashlib.sha256() 5 | b.update(a) 6 | b.update(a) 7 | c = b.digest() 8 | print(c) 9 | if c != b"\xe5Z\\'sj\x87a\xc8\xe9j\xce\xc0r\x10#%\xe0\x8c\xb2\xd0\xdb\xb4\xd4p,\xfe8\xf8\xab\x07\t": 10 | raise(Exception("error! {}".format(c))) 11 | 12 | a = bytes([0]*1024) 13 | b = hashlib.sha256(a) 14 | c = b.digest() 15 | print(c) 16 | if c != b'_p\xbf\x18\xa0\x86\x00p\x16\xe9H\xb0J\xed;\x82\x10:6\xbe\xa4\x17U\xb6\xcd\xdf\xaf\x10\xac\xe3\xc6\xef': 17 | raise(Exception("error! {}".format(c))) 18 | 19 | print(c == b.digest()) # False here 20 | -------------------------------------------------------------------------------- /basic/demo_sys_info.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | for i in range(0, 2): 4 | print("hello maixpy") 5 | print("hello ", end="maixpy\n") 6 | 7 | print("implementation:", sys.implementation) 8 | print("platform:", sys.platform) 9 | print("path:", sys.path) 10 | print("Python version:", sys.version) 11 | 12 | print("please input string, end with Enter") 13 | r = sys.stdin.readline() 14 | w_len = sys.stdout.write(r) 15 | 16 | 17 | -------------------------------------------------------------------------------- /basic/demo_thread.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | # doc refer to: http://docs.micropython.org/en/latest/library/_thread.html?highlight=_thread#module-_thread 5 | 6 | 7 | 8 | import _thread 9 | import time 10 | 11 | def func(name): 12 | while 1: 13 | print("hello {}".format(name)) 14 | time.sleep(1) 15 | 16 | _thread.start_new_thread(func,("1",)) 17 | _thread.start_new_thread(func,("2",)) 18 | 19 | while 1: 20 | pass 21 | 22 | -------------------------------------------------------------------------------- /basic/demo_time.py: -------------------------------------------------------------------------------- 1 | import time 2 | import machine 3 | 4 | print(time.time()) 5 | t1 = time.localtime(546450051) 6 | print('t1', t1) 7 | t2 = time.mktime(t1) 8 | print('t2', t2) 9 | print(time.time()) 10 | time.set_time(t1) 11 | print(time.time()) 12 | time.sleep(1) 13 | print(time.localtime(time.time())) 14 | 15 | ''' 16 | raw REPL; CTRL-B to exit 17 | >OK 18 | 74 19 | t1 (2017, 4, 25, 15, 40, 51, 1, 115) 20 | t2 546450051 21 | 546450065 22 | 546450051 23 | (2017, 4, 25, 15, 40, 52, 1, 115) 24 | > 25 | MicroPython v0.5.1-136-g039f72b6c-dirty on 2020-11-18; Sipeed_M1 with kendryte-k210 26 | Type "help()" for more information. 27 | >>> 28 | >>> 29 | ''' 30 | -------------------------------------------------------------------------------- /basic/demo_view_mem.py: -------------------------------------------------------------------------------- 1 | import gc 2 | 3 | print(gc.mem_free() / 1024) # stack mem 4 | 5 | import Maix 6 | 7 | print(Maix.utils.heap_free() / 1024) # heap mem 8 | 9 | ''' 10 | >>> 11 | raw REPL; CTRL-B to exit 12 | >OK 13 | 352.0937 14 | 4640.0 15 | > 16 | MicroPython v0.5.1-136-g039f72b6c-dirty on 2020-11-18; Sipeed_M1 with kendryte-k210 17 | Type "help()" for more information. 18 | >>> 19 | ''' -------------------------------------------------------------------------------- /basic/demo_yield.py: -------------------------------------------------------------------------------- 1 | def event(): 2 | print('start yield') 3 | # return next(task) and yield next(task.send('set_two')) 4 | one = yield 'get_one' 5 | assert(one == 'set_two') 6 | print(one) 7 | yield 'get_two' # return next(task) and yield next(task.send('set_two')) 8 | print('exit yield') 9 | yield # yield next() to exit or raise StopIteration 10 | 11 | 12 | task = event() 13 | run_one = next(task) # need next(task) init and next(task) == task.send(None) 14 | # so next(task) => yield 'get_one' => run_one = 'get_one' 15 | assert(run_one == 'get_one') 16 | run_two = task.send('set_two') 17 | assert(run_two == 'get_two') 18 | print('run : ', run_one, ' and ', run_two) 19 | 20 | try: 21 | next(task) 22 | print('run end') 23 | next(task) # will raise StopIteration 24 | except Exception as e: 25 | print('yield StopIteration') 26 | 27 | if __name__ == '__main__': 28 | 29 | def task(): 30 | while True: 31 | print('hello') 32 | yield 33 | 34 | tmp = task() 35 | while True: 36 | next(tmp) 37 | 38 | while True: 39 | print('hello') 40 | -------------------------------------------------------------------------------- /basic/demo_yield_task.py: -------------------------------------------------------------------------------- 1 | class Task: 2 | 3 | def __init__(self, event=(lambda: print('task running'))): 4 | self.event = event 5 | self.cb = self.pre() 6 | next(self.cb) 7 | print('task init') 8 | 9 | def pre(self): 10 | print('task start') 11 | flag = True 12 | while flag is True: 13 | flag = yield flag 14 | self.event() 15 | print('task exit') 16 | 17 | def run(self, flag=True): 18 | try: 19 | res = self.cb.send(flag) 20 | return res 21 | except StopIteration as e: 22 | return False 23 | 24 | 25 | if __name__ == "__main__": 26 | tmp = Task() 27 | 28 | assert(tmp.run()) 29 | assert(tmp.run()) 30 | assert(False == tmp.run(False)) 31 | 32 | print(tmp.run()) 33 | print(tmp.run(False)) 34 | 35 | class music: 36 | 37 | def __init__(self): 38 | self.task = Task(self.pre) 39 | self.args = None 40 | print('music init') 41 | 42 | def pre(self): 43 | print('pre ', self.args) 44 | 45 | def play(self, size=10): 46 | self.args = list(range(size)) 47 | print(self.task.run()) 48 | 49 | def stop(self): 50 | print(self.task.run(False)) 51 | self.__init__() 52 | 53 | def loop(self): 54 | self.alive = False 55 | while self.alive: 56 | self.play() 57 | stop() 58 | 59 | tmp = music() 60 | tmp.play() 61 | tmp.stop() 62 | tmp.play() 63 | -------------------------------------------------------------------------------- /basic/hello_wrold.py: -------------------------------------------------------------------------------- 1 | try: 2 | import gc, lcd, image 3 | gc.collect() 4 | lcd.init() 5 | loading = image.Image(size=(lcd.width(), lcd.height())) 6 | loading.draw_rectangle((0, 0, lcd.width(), lcd.height()), fill=True, color=(255, 0, 0)) 7 | info = "Welcome to MaixPy" 8 | loading.draw_string(int(lcd.width()//2 - len(info) * 5), (lcd.height())//4, info, color=(255, 255, 255), scale=2, mono_space=0) 9 | v = sys.implementation.version 10 | vers = 'V{}.{}.{} : maixpy.sipeed.com'.format(v[0],v[1],v[2]) 11 | loading.draw_string(int(lcd.width()//2 - len(info) * 6), (lcd.height())//3 + 20, vers, color=(255, 255, 255), scale=1, mono_space=1) 12 | lcd.display(loading) 13 | del loading, v, info, vers 14 | gc.collect() 15 | finally: 16 | gc.collect() -------------------------------------------------------------------------------- /board/board.py: -------------------------------------------------------------------------------- 1 | 2 | class board_info: 3 | def set(key, value=None): 4 | return setattr(__class__, key, value) 5 | def all(): 6 | return dir(__class__) 7 | def get(): 8 | return getattr(__class__, key) 9 | def load(__map__={}): 10 | for k, v in __map__.items(): 11 | __class__.set(k, v) 12 | 13 | from Maix import config 14 | tmp = config.get_value('board_info', None) 15 | if tmp != None: 16 | board_info.load(tmp) 17 | else: 18 | print('[Warning] Not loaded from /flash/config.json to board_info.') 19 | 20 | if __name__ == "__main__": 21 | def check_config_json(data): 22 | try: 23 | with open('/flash/config.json', 'rb') as f: 24 | tmp = json.loads(f.read()) 25 | if tmp["type"] != data["type"]: 26 | raise Exception('config.json no exist') 27 | except Exception as e: 28 | with open('/flash/config.json', "w") as f: 29 | f.write(cfg) 30 | import machine 31 | machine.reset() 32 | 33 | print(board_info.all()) 34 | board_info.set('test', 123) 35 | print(board_info.test) 36 | print(board_info.all()) 37 | 38 | import json 39 | test = { 40 | "type": "test", 41 | "board_info": { 42 | 'PIN10': 10, 43 | 'BOOT_KEY': 16, 44 | 'WIFI_TX': 6, 45 | 'WIFI_RX': 7, 46 | 'WIFI_EN': 8, 47 | } 48 | } 49 | cfg = json.dumps(test) 50 | check_config_json(test) 51 | from Maix import config 52 | tmp = config.get_value('board_info', None) 53 | if tmp != None: 54 | board_info.load(tmp) 55 | print(board_info.all()) 56 | print(board_info.PIN10) 57 | print(board_info.BOOT_KEY) 58 | print(board_info.WIFI_TX) 59 | print(board_info.WIFI_RX) 60 | print(board_info.WIFI_EN) 61 | -------------------------------------------------------------------------------- /board/config_maix_amigo.py: -------------------------------------------------------------------------------- 1 | 2 | import json 3 | 4 | config = { 5 | "type": "amigo", 6 | "lcd": { 7 | "height": 320, 8 | "width": 480, 9 | "invert": 0, 10 | "dir": 40, 11 | "lcd_type": 1 12 | }, 13 | "sdcard":{ 14 | "sclk":11, 15 | "mosi":10, 16 | "miso":6, 17 | "cs":26 18 | }, 19 | "board_info": { 20 | 'BOOT_KEY': 23, 21 | 'LED_R': 14, 22 | 'LED_G': 15, 23 | 'LED_B': 17, 24 | 'LED_W': 32, 25 | 'BACK': 31, 26 | 'ENTER': 23, 27 | 'NEXT': 20, 28 | 'WIFI_TX': 6, 29 | 'WIFI_RX': 7, 30 | 'WIFI_EN': 8, 31 | 'I2S0_MCLK': 13, 32 | 'I2S0_SCLK': 21, 33 | 'I2S0_WS': 18, 34 | 'I2S0_IN_D0': 35, 35 | 'I2S0_OUT_D2': 34, 36 | 'I2C_SDA': 27, 37 | 'I2C_SCL': 24, 38 | 'SPI_SCLK': 11, 39 | 'SPI_MOSI': 10, 40 | 'SPI_MISO': 6, 41 | 'SPI_CS': 12, 42 | } 43 | } 44 | 45 | cfg = json.dumps(config) 46 | print(cfg) 47 | 48 | # config sensor 49 | try: 50 | os.remove('boot.py') 51 | except: 52 | pass 53 | with open('boot.py', 'wb') as f: 54 | cfg_sensor = b'from machine import I2C\naxp173 = I2C(I2C.I2C0, freq=100000, scl=24, sda=27)\naxp173.writeto_mem(0x34, 0x27, 0x20)\naxp173.writeto_mem(0x34, 0x28, 0x0C)\naxp173.writeto_mem(0x34, 0x36, 0xCC, mem_size=8)' 55 | f.write(cfg_sensor) 56 | del cfg_sensor 57 | 58 | try: 59 | with open('config.json', 'rb') as f: 60 | tmp = json.loads(f.read()) 61 | print(tmp) 62 | if tmp["type"] != config["type"]: 63 | raise Exception('config.json no exist') 64 | except Exception as e: 65 | with open('config.json', "w") as f: 66 | f.write(cfg) 67 | import machine 68 | machine.reset() 69 | 70 | -------------------------------------------------------------------------------- /board/config_maix_amigo_ips.py: -------------------------------------------------------------------------------- 1 | 2 | import json 3 | 4 | config = { 5 | "type": "amigo", 6 | "lcd": { 7 | "height": 320, 8 | "width": 480, 9 | "invert": 1, 10 | "dir": 40, 11 | "lcd_type": 2 12 | }, 13 | "sdcard":{ 14 | "sclk":11, 15 | "mosi":10, 16 | "miso":6, 17 | "cs":26 18 | }, 19 | "board_info": { 20 | 'BOOT_KEY': 23, 21 | 'LED_R': 14, 22 | 'LED_G': 15, 23 | 'LED_B': 17, 24 | 'LED_W': 32, 25 | 'BACK': 23, 26 | 'ENTER': 16, 27 | 'NEXT': 20, 28 | 'WIFI_TX': 6, 29 | 'WIFI_RX': 7, 30 | 'WIFI_EN': 8, 31 | 'I2S0_MCLK': 13, 32 | 'I2S0_SCLK': 21, 33 | 'I2S0_WS': 18, 34 | 'I2S0_IN_D0': 35, 35 | 'I2S0_OUT_D2': 34, 36 | 'I2C_SDA': 27, 37 | 'I2C_SCL': 24, 38 | 'SPI_SCLK': 11, 39 | 'SPI_MOSI': 10, 40 | 'SPI_MISO': 6, 41 | 'SPI_CS': 12, 42 | } 43 | } 44 | 45 | cfg = json.dumps(config) 46 | print(cfg) 47 | 48 | # config sensor 49 | try: 50 | os.remove('/flash/boot.py') 51 | except: 52 | pass 53 | with open('/flash/boot.py', 'wb') as f: 54 | cfg_sensor = b'import lcd\nlcd.clear((99, 99, 99))\nlcd.register(0xD1, 0x00)\nlcd.init()\nfrom machine import I2C\naxp173 = I2C(I2C.I2C0, freq=100000, scl=24, sda=27)\naxp173.writeto_mem(0x34, 0x27, 0x20)\naxp173.writeto_mem(0x34, 0x28, 0x0C)\naxp173.writeto_mem(0x34, 0x36, 0xCC, mem_size=8)' 55 | f.write(cfg_sensor) 56 | del cfg_sensor 57 | 58 | try: 59 | with open('/flash/config.json', 'rb') as f: 60 | tmp = json.loads(f.read()) 61 | print(tmp) 62 | if tmp["type"] != config["type"]: 63 | raise Exception('config.json no exist') 64 | except Exception as e: 65 | with open('/flash/config.json', "w") as f: 66 | f.write(cfg) 67 | import machine 68 | machine.reset() 69 | -------------------------------------------------------------------------------- /board/config_maix_bit.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | config = { 4 | "type": "bit", 5 | "board_info": { 6 | 'BOOT_KEY': 16, 7 | 'LED_R': 13, 8 | 'LED_G': 12, 9 | 'LED_B': 14, 10 | 'MIC0_WS': 19, 11 | 'MIC0_DATA': 20, 12 | 'MIC0_BCK': 18, 13 | } 14 | } 15 | 16 | cfg = json.dumps(config) 17 | print(cfg) 18 | 19 | try: 20 | with open('/flash/config.json', 'rb') as f: 21 | tmp = json.loads(f.read()) 22 | print(tmp) 23 | if tmp["type"] != config["type"]: 24 | raise Exception('config.json no exist') 25 | except Exception as e: 26 | with open('/flash/config.json', "w") as f: 27 | f.write(cfg) 28 | import machine 29 | machine.reset() 30 | -------------------------------------------------------------------------------- /board/config_maix_cube.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | config = { 4 | "type": "cube", 5 | "lcd": { 6 | "height": 240, 7 | "width": 240, 8 | "invert": 1, 9 | "dir": 96 10 | }, 11 | "board_info": { 12 | 'BOOT_KEY': 16, 13 | 'LED_R': 13, 14 | 'LED_G': 12, 15 | 'LED_B': 14, 16 | 'LED_W': 32, 17 | 'BACK': 11, 18 | 'ENTER': 10, 19 | 'NEXT': 16, 20 | 'WIFI_TX': 6, 21 | 'WIFI_RX': 7, 22 | 'WIFI_EN': 8, 23 | 'I2S0_MCLK': 19, 24 | 'I2S0_SCLK': 35, 25 | 'I2S0_WS': 33, 26 | 'I2S0_IN_D0': 34, 27 | 'I2S0_OUT_D2': 18, 28 | 'I2C_SDA': 31, 29 | 'I2C_SCL': 30, 30 | 'SPI_SCLK': 21, 31 | 'SPI_MOSI': 8, 32 | 'SPI_MISO': 15, 33 | 'SPI_CS': 20, 34 | } 35 | } 36 | 37 | cfg = json.dumps(config) 38 | print(cfg) 39 | 40 | # config lcd back_light 41 | try: 42 | os.remove('/flash/boot.py') 43 | except: 44 | pass 45 | with open('/flash/boot.py', 'wb') as f: 46 | cfg_sensor = b'from fpioa_manager import fm\nfrom Maix import GPIO\nfm.register(17, fm.fpioa.GPIOHS28)\nlcd_en = GPIO(GPIO.GPIOHS28, GPIO.OUT)\nlcd_en.value(0)\n' 47 | f.write(cfg_sensor) 48 | del cfg_sensor 49 | 50 | try: 51 | with open('/flash/config.json', 'rb') as f: 52 | tmp = json.loads(f.read()) 53 | print(tmp) 54 | if tmp["type"] != config["type"]: 55 | raise Exception('config.json no exist') 56 | except Exception as e: 57 | with open('/flash/config.json', "w") as f: 58 | f.write(cfg) 59 | import machine 60 | machine.reset() 61 | -------------------------------------------------------------------------------- /board/config_maix_dock.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | config = { 4 | "type": "dock", 5 | "board_info": { 6 | 'BOOT_KEY': 16, 7 | 'LED_R': 14, 8 | 'LED_G': 13, 9 | 'LED_B': 12, 10 | 'WIFI_TX': 6, 11 | 'WIFI_RX': 7, 12 | 'WIFI_EN': 8, 13 | 'MIC0_WS': 30, 14 | 'MIC0_DATA': 20, 15 | 'MIC0_BCK': 32, 16 | 'I2S_WS': 33, 17 | 'I2S_DA': 34, 18 | 'I2S_BCK': 35, 19 | } 20 | } 21 | 22 | cfg = json.dumps(config) 23 | print(cfg) 24 | 25 | try: 26 | with open('/flash/config.json', 'rb') as f: 27 | tmp = json.loads(f.read()) 28 | print(tmp) 29 | if tmp["type"] != config["type"]: 30 | raise Exception('config.json no exist') 31 | except Exception as e: 32 | with open('/flash/config.json', "w") as f: 33 | f.write(cfg) 34 | import machine 35 | machine.reset() 36 | -------------------------------------------------------------------------------- /board/config_maix_duino.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | config = { 4 | "type": "duino", 5 | "board_info": { 6 | 'BOOT_KEY': 16, 7 | 'LED_R': 13, 8 | 'LED_G': 12, 9 | 'LED_B': 14, 10 | 'WIFI_TX': 6, 11 | 'WIFI_RX': 7, 12 | 'WIFI_EN': 8, 13 | 'MIC0_WS': 19, 14 | 'MIC0_DATA': 20, 15 | 'MIC0_BCK': 18, 16 | 'I2S_WS': 33, 17 | 'I2S_DA': 34, 18 | 'I2S_BCK': 35, 19 | 'ESP32_CS': 25, 20 | 'ESP32_RST': 8, 21 | 'ESP32_RDY': 9, 22 | 'ESP32_MOSI': 28, 23 | 'ESP32_MISO': 26, 24 | 'ESP32_SCLK': 27, 25 | 'PIN0':4, 26 | 'PIN1':5, 27 | 'PIN2':21, 28 | 'PIN3':22, 29 | 'PIN4':23, 30 | 'PIN5':24, 31 | 'PIN6':32, 32 | 'PIN7':15, 33 | 'PIN8':14, 34 | 'PIN9':13, 35 | 'PIN10':12, 36 | 'PIN11':11, 37 | 'PIN12':10, 38 | 'PIN13':3, 39 | } 40 | } 41 | 42 | cfg = json.dumps(config) 43 | print(cfg) 44 | 45 | try: 46 | with open('/flash/config.json', 'rb') as f: 47 | tmp = json.loads(f.read()) 48 | print(tmp) 49 | if tmp["type"] != config["type"]: 50 | raise Exception('config.json no exist') 51 | except Exception as e: 52 | with open('/flash/config.json', "w") as f: 53 | f.write(cfg) 54 | import machine 55 | machine.reset() 56 | -------------------------------------------------------------------------------- /board/config_maix_go.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | config = { 4 | "type": "Go", 5 | "board_info": { 6 | 'BOOT_KEY': 16, 7 | 'LED_R': 14, 8 | 'LED_G': 12, 9 | 'LED_B': 13, 10 | 'WIFI_TX': 6, 11 | 'WIFI_RX': 7, 12 | 'WIFI_EN': 8, 13 | 'MIC0_WS': 19, 14 | 'MIC0_DATA': 20, 15 | 'MIC0_BCK': 18, 16 | 'I2S_WS': 33, 17 | 'I2S_DA': 34, 18 | 'I2S_BCK': 35, 19 | } 20 | } 21 | 22 | cfg = json.dumps(config) 23 | print(cfg) 24 | 25 | try: 26 | with open('/flash/config.json', 'rb') as f: 27 | tmp = json.loads(f.read()) 28 | print(tmp) 29 | if tmp["type"] != config["type"]: 30 | raise Exception('config.json no exist') 31 | except Exception as e: 32 | with open('/flash/config.json', "w") as f: 33 | f.write(cfg) 34 | import machine 35 | machine.reset() 36 | -------------------------------------------------------------------------------- /board/readme.md: -------------------------------------------------------------------------------- 1 | ## Sipeed Typical hardware. 2 | 3 | 调用如下指定硬件的代码,完成对指定硬件配置项(config.json)的导入。 4 | 5 | Calls the code for the specified hardware below to complete the import of the specified hardware configuration item (config.json). 6 | 7 | 这可以为了让你在运行基础示例代码的时候减少不必要的麻烦。 8 | 9 | This will save you the hassle of running the basic sample code. 10 | 11 | 请确保 MaixPy 固件在 2020年10月12日 maixpy_v0.5.1_96_ga678dcd 以上的固件版本。 12 | 13 | Make sure the MaixPy firmware is in the firmware version above maixpy_v0.5.1_96_ga678dcd on October 12, 2020. 14 | 15 | ### Maix Cube 16 | 17 | [config_maix_cube.py](./config_maix_cube.py) 18 | 19 | ### Maix Dock 20 | 21 | [config_maix_dock.py](./config_maix_dock.py) 22 | 23 | ### Maix Duino 24 | 25 | [config_maix_duino.py](./config_maix_duino.py) 26 | 27 | ### Maix Amigo 28 | 29 | [config_maix_amigo.py](./config_maix_amigo.py) 30 | 31 | ### other hareware. 32 | 33 | 你可以借助该接口代码适配你的硬件。 34 | 35 | You can adapt your hardware with this interface code. -------------------------------------------------------------------------------- /hardware/demo_binocular.py: -------------------------------------------------------------------------------- 1 | # It need binocular sensor !!!!! 2 | 3 | import sensor 4 | import image 5 | import lcd 6 | import time 7 | lcd.init() 8 | lcd.freq(15000000) 9 | sensor.binocular_reset() 10 | sensor.shutdown(False) 11 | sensor.set_pixformat(sensor.RGB565) 12 | sensor.set_framesize(sensor.QVGA) 13 | sensor.shutdown(True) 14 | sensor.set_pixformat(sensor.RGB565) 15 | sensor.set_framesize(sensor.QVGA) 16 | sensor.run(1) 17 | while True: 18 | sensor.shutdown(False) 19 | img=sensor.snapshot() 20 | lcd.display(img) 21 | time.sleep_ms(100) 22 | sensor.shutdown(True) 23 | img=sensor.snapshot() 24 | lcd.display(img) 25 | time.sleep_ms(100) 26 | -------------------------------------------------------------------------------- /hardware/demo_camera.py: -------------------------------------------------------------------------------- 1 | import sensor, lcd 2 | 3 | try: 4 | sensor.reset() 5 | except Exception as e: 6 | raise Exception("sensor reset fail, please check hardware connection, or hardware damaged! err: {}".format(e)) 7 | sensor.set_pixformat(sensor.RGB565) 8 | sensor.set_framesize(sensor.QVGA) 9 | # sensor.set_hmirror(1) # cube & amigo 10 | # sensor.set_vflip(1) # cube & amigo 11 | sensor.run(1) 12 | sensor.skip_frames() 13 | lcd.init(freq=15000000) 14 | 15 | while(True): 16 | lcd.display(sensor.snapshot()) 17 | 18 | -------------------------------------------------------------------------------- /hardware/demo_cpu.py: -------------------------------------------------------------------------------- 1 | from Maix import freq 2 | 3 | cpu_freq, kpu_freq = freq.get() 4 | print(cpu_freq, kpu_freq) 5 | 6 | freq.set(cpu = 400, pll1=400, kpu_div = 1) 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /hardware/demo_fft_spectrum.py: -------------------------------------------------------------------------------- 1 | from Maix import GPIO, I2S, FFT 2 | import image, lcd, math 3 | 4 | from fpioa_manager import fm 5 | 6 | sample_rate = 38640 7 | sample_points = 1024 8 | fft_points = 512 9 | hist_x_num = 50 10 | 11 | 12 | lcd.init(freq=15000000) 13 | 14 | # close WiFi 15 | fm.register(8, fm.fpioa.GPIO0, force=True) 16 | wifi_en=GPIO(GPIO.GPIO0,GPIO.OUT) 17 | wifi_en.value(0) 18 | 19 | fm.register(20,fm.fpioa.I2S0_IN_D0, force=True) 20 | fm.register(30,fm.fpioa.I2S0_WS, force=True) # 19 on Go Board and Bit(new version) 21 | fm.register(32,fm.fpioa.I2S0_SCLK, force=True) # 18 on Go Board and Bit(new version) 22 | 23 | rx = I2S(I2S.DEVICE_0) 24 | rx.channel_config(rx.CHANNEL_0, rx.RECEIVER, align_mode = I2S.STANDARD_MODE) 25 | rx.set_sample_rate(sample_rate) 26 | img = image.Image() 27 | if hist_x_num > 320: 28 | hist_x_num = 320 29 | hist_width = int(320 / hist_x_num)#changeable 30 | x_shift = 0 31 | while True: 32 | audio = rx.record(sample_points) 33 | fft_res = FFT.run(audio.to_bytes(),fft_points) 34 | fft_amp = FFT.amplitude(fft_res) 35 | img = img.clear() 36 | x_shift = 0 37 | for i in range(hist_x_num): 38 | if fft_amp[i] > 240: 39 | hist_height = 240 40 | else: 41 | hist_height = fft_amp[i] 42 | img = img.draw_rectangle((x_shift,240-hist_height,hist_width,hist_height),[255,255,255],2,True) 43 | x_shift = x_shift + hist_width 44 | lcd.display(img) 45 | fft_amp.clear() 46 | 47 | -------------------------------------------------------------------------------- /hardware/demo_fft_waterfall.py: -------------------------------------------------------------------------------- 1 | from Maix import GPIO, I2S, FFT 2 | import image, lcd, math 3 | from fpioa_manager import fm 4 | import KPU as kpu 5 | 6 | sample_rate = 11025 7 | sample_points = 1024 8 | fft_points = 512 9 | hist_x_num = 128 10 | 11 | lcd.init() 12 | # close WiFi 13 | fm.register(8, fm.fpioa.GPIO0) 14 | wifi_en=GPIO(GPIO.GPIO0,GPIO.OUT) 15 | wifi_en.value(0) 16 | fm.register(20,fm.fpioa.I2S0_IN_D0) 17 | fm.register(30,fm.fpioa.I2S0_WS) # 30 on dock/bit Board 18 | fm.register(32,fm.fpioa.I2S0_SCLK) # 32 on dock/bit Board 19 | 20 | rx = I2S(I2S.DEVICE_0) 21 | rx.channel_config(rx.CHANNEL_0, rx.RECEIVER, align_mode = I2S.STANDARD_MODE) 22 | rx.set_sample_rate(sample_rate) 23 | img = image.Image(size=(128,128)) 24 | img=img.to_grayscale() 25 | 26 | while True: 27 | audio = rx.record(sample_points) 28 | fft_res = FFT.run(audio.to_bytes(),fft_points) 29 | fft_amp = FFT.amplitude(fft_res) 30 | img_tmp = img.cut(0,0,128,127) 31 | img.draw_image(img_tmp, 0,1) 32 | for i in range(hist_x_num): 33 | img[i] = fft_amp[i] 34 | del(img_tmp) 35 | imgc = img.to_rainbow(1) 36 | lcd.display(imgc) 37 | del(imgc) 38 | fft_amp.clear() -------------------------------------------------------------------------------- /hardware/demo_gpio_intr.py: -------------------------------------------------------------------------------- 1 | from board import board_info 2 | 3 | from fpioa_manager import fm 4 | fm.register(board_info.BOOT_KEY, fm.fpioa.GPIOHS0, force=True) 5 | 6 | from Maix import GPIO 7 | 8 | def test_irq(pin_num): 9 | print("key", pin_num) 10 | 11 | key=GPIO(GPIO.GPIOHS0, GPIO.IN, GPIO.PULL_NONE) 12 | key.irq(test_irq, GPIO.IRQ_BOTH, GPIO.WAKEUP_NOT_SUPPORT, 7) 13 | 14 | import time 15 | for i in range(20): 16 | #print('key.value(): ', key.value()) 17 | time.sleep_ms(500) 18 | 19 | key.disirq() 20 | fm.unregister(board_info.BOOT_KEY) 21 | 22 | -------------------------------------------------------------------------------- /hardware/demo_gpio_led.py: -------------------------------------------------------------------------------- 1 | 2 | import time 3 | from Maix import GPIO 4 | from fpioa_manager import fm 5 | from board import board_info 6 | 7 | # see board/readme.md to config your sipeed's hardware. 8 | print(board_info.LED_R) 9 | print(board_info.LED_G) 10 | print(board_info.LED_B) 11 | 12 | fm.register(board_info.LED_R, fm.fpioa.GPIO0, force=True) 13 | fm.register(board_info.LED_G, fm.fpioa.GPIOHS0, force=True) 14 | fm.register(board_info.LED_B, fm.fpioa.GPIO2, force=True) 15 | fm.register(board_info.BOOT_KEY, fm.fpioa.GPIO3, force=True) 16 | 17 | led_r = GPIO(GPIO.GPIO0, GPIO.OUT) 18 | led_g = GPIO(GPIO.GPIOHS0, GPIO.OUT) 19 | led_b = GPIO(GPIO.GPIO2, GPIO.OUT) 20 | key_input = GPIO(GPIO.GPIO3, GPIO.IN) 21 | 22 | status = 0 23 | for i in range(0, 20): 24 | led_r.value(status) 25 | time.sleep_ms(300) 26 | led_g.value(status) 27 | time.sleep_ms(300) 28 | led_b.value(status) 29 | time.sleep_ms(300) 30 | status = 0 if (status == 1) else 1 31 | time.sleep_ms(300) 32 | print("LED RGB(%d,%d,%d)" % (led_r.value(), led_g.value(), led_b.value())) 33 | time.sleep_ms(100) 34 | print("key_input:", key_input.value()) 35 | 36 | fm.unregister(board_info.LED_R) 37 | fm.unregister(board_info.LED_G) 38 | fm.unregister(board_info.LED_B) 39 | fm.unregister(board_info.BOOT_KEY) 40 | -------------------------------------------------------------------------------- /hardware/demo_i2c.py: -------------------------------------------------------------------------------- 1 | from machine import I2C 2 | from fpioa_manager import fm 3 | 4 | # i2c = I2C(I2C.I2C0, freq=100000, scl=28, sda=29) # hardware i2c 5 | i2c = I2C(I2C.I2C3, freq=100000, scl=28, sda=29) # software i2c 6 | #i2c = I2C(I2C.I2C_SOFT, freq=100000, scl=28, sda=29, 7 | #gscl = fm.fpioa.GPIOHS1, gsda = fm.fpioa.GPIOHS2) # software i2c for the latest firmware 8 | 9 | devices = i2c.scan() 10 | print(devices) 11 | 12 | for device in devices: 13 | i2c.writeto(device, b'123') 14 | i2c.readfrom(device, 3) 15 | # tmp = bytearray(6) 16 | # i2c.readfrom_into(device, tmp, True) 17 | 18 | -------------------------------------------------------------------------------- /hardware/demo_i2c_oled.py: -------------------------------------------------------------------------------- 1 | import time 2 | from machine import I2C 3 | 4 | SSD1306_CMD = 0 5 | SSD1306_DATA = 1 6 | SSD1306_ADDR = 0x3c 7 | 8 | def oled_init(i2c): 9 | i2c.writeto_mem(SSD1306_ADDR, 0x00, 0xAE, mem_size=8) 10 | i2c.writeto_mem(SSD1306_ADDR, 0x00, 0x20, mem_size=8) 11 | i2c.writeto_mem(SSD1306_ADDR, 0x00, 0x10, mem_size=8) 12 | i2c.writeto_mem(SSD1306_ADDR, 0x00, 0xb0, mem_size=8) 13 | i2c.writeto_mem(SSD1306_ADDR, 0x00, 0xc8, mem_size=8) 14 | i2c.writeto_mem(SSD1306_ADDR, 0x00, 0x00, mem_size=8) 15 | i2c.writeto_mem(SSD1306_ADDR, 0x00, 0x10, mem_size=8) 16 | i2c.writeto_mem(SSD1306_ADDR, 0x00, 0x40, mem_size=8) 17 | i2c.writeto_mem(SSD1306_ADDR, 0x00, 0x81, mem_size=8) 18 | i2c.writeto_mem(SSD1306_ADDR, 0x00, 0xff, mem_size=8) 19 | i2c.writeto_mem(SSD1306_ADDR, 0x00, 0xa1, mem_size=8) 20 | i2c.writeto_mem(SSD1306_ADDR, 0x00, 0xa6, mem_size=8) 21 | i2c.writeto_mem(SSD1306_ADDR, 0x00, 0xa8, mem_size=8) 22 | i2c.writeto_mem(SSD1306_ADDR, 0x00, 0x3F, mem_size=8) 23 | i2c.writeto_mem(SSD1306_ADDR, 0x00, 0xa4, mem_size=8) 24 | i2c.writeto_mem(SSD1306_ADDR, 0x00, 0xd3, mem_size=8) 25 | i2c.writeto_mem(SSD1306_ADDR, 0x00, 0x00, mem_size=8) 26 | i2c.writeto_mem(SSD1306_ADDR, 0x00, 0xd5, mem_size=8) 27 | i2c.writeto_mem(SSD1306_ADDR, 0x00, 0xf0, mem_size=8) 28 | i2c.writeto_mem(SSD1306_ADDR, 0x00, 0xd9, mem_size=8) 29 | i2c.writeto_mem(SSD1306_ADDR, 0x00, 0x22, mem_size=8) 30 | i2c.writeto_mem(SSD1306_ADDR, 0x00, 0xda, mem_size=8) 31 | i2c.writeto_mem(SSD1306_ADDR, 0x00, 0x12, mem_size=8) 32 | i2c.writeto_mem(SSD1306_ADDR, 0x00, 0xdb, mem_size=8) 33 | i2c.writeto_mem(SSD1306_ADDR, 0x00, 0x20, mem_size=8) 34 | i2c.writeto_mem(SSD1306_ADDR, 0x00, 0x8d, mem_size=8) 35 | i2c.writeto_mem(SSD1306_ADDR, 0x00, 0x14, mem_size=8) 36 | i2c.writeto_mem(SSD1306_ADDR, 0x00, 0xaf, mem_size=8) 37 | 38 | 39 | 40 | def oled_on(i2c): 41 | i2c.writeto_mem(SSD1306_ADDR, 0x00, 0X8D, mem_size=8) 42 | i2c.writeto_mem(SSD1306_ADDR, 0x00, 0X14, mem_size=8) 43 | i2c.writeto_mem(SSD1306_ADDR, 0x00, 0XAF, mem_size=8) 44 | 45 | def oled_off(i2c): 46 | i2c.writeto_mem(SSD1306_ADDR, 0x00, 0X8D, mem_size=8) 47 | i2c.writeto_mem(SSD1306_ADDR, 0x00, 0X10, mem_size=8) 48 | i2c.writeto_mem(SSD1306_ADDR, 0x00, 0XAE, mem_size=8) 49 | 50 | def oled_fill(i2c, data): 51 | for i in range(0,8): 52 | i2c.writeto_mem(SSD1306_ADDR, 0x00, 0xb0+i, mem_size=8) 53 | i2c.writeto_mem(SSD1306_ADDR, 0x00, 0x10, mem_size=8) 54 | i2c.writeto_mem(SSD1306_ADDR, 0x00, 0x01, mem_size=8) 55 | for j in range(0,128): 56 | i2c.writeto_mem(SSD1306_ADDR, 0x40, data, mem_size=8) 57 | 58 | i2c = I2C(I2C.I2C0, mode=I2C.MODE_MASTER, freq=400000, scl=28, sda=29, addr_size=7) 59 | 60 | time.sleep(1) 61 | oled_init(i2c) 62 | oled_fill(i2c, 0xff) 63 | 64 | -------------------------------------------------------------------------------- /hardware/demo_i2c_slave.py: -------------------------------------------------------------------------------- 1 | from machine import I2C 2 | 3 | count = 0 4 | 5 | def on_receive(data): 6 | print("on_receive:",data) 7 | 8 | def on_transmit(): 9 | global count 10 | count = count+1 11 | print("on_transmit, send:",count) 12 | return count 13 | 14 | def on_event(event): 15 | print("on_event:",event) 16 | 17 | i2c = I2C(I2C.I2C0, mode=I2C.MODE_SLAVE, scl=28, sda=29, addr=0x24, addr_size=7, on_receive=on_receive, on_transmit=on_transmit, on_event=on_event) 18 | 19 | -------------------------------------------------------------------------------- /hardware/demo_i2s.py: -------------------------------------------------------------------------------- 1 | from Maix import GPIO, I2S 2 | import image, lcd, math, audio 3 | from fpioa_manager import fm 4 | 5 | sample_rate = 22050 6 | sample_points = 1024 7 | 8 | rx = I2S(I2S.DEVICE_0) 9 | rx.channel_config(I2S.CHANNEL_0, rx.RECEIVER, resolution = I2S.RESOLUTION_16_BIT, cycles = I2S.SCLK_CYCLES_32, align_mode = I2S.STANDARD_MODE) 10 | rx.set_sample_rate(sample_rate) 11 | 12 | fm.fpioa.set_function(pin=20, func=fm.fpioa.I2S0_IN_D0) 13 | fm.fpioa.set_function(pin=19, func=fm.fpioa.I2S0_WS) 14 | fm.fpioa.set_function(pin=18, func=fm.fpioa.I2S0_SCLK) 15 | 16 | tx = I2S(I2S.DEVICE_2) 17 | 18 | tx.channel_config(I2S.CHANNEL_1, I2S.TRANSMITTER, resolution = I2S.RESOLUTION_16_BIT, cycles = I2S.SCLK_CYCLES_32, align_mode = I2S.RIGHT_JUSTIFYING_MODE) 19 | tx.set_sample_rate(sample_rate) 20 | 21 | fm.fpioa.set_function(pin=34, func=fm.fpioa.I2S2_OUT_D1) 22 | fm.fpioa.set_function(pin=35, func=fm.fpioa.I2S2_SCLK) 23 | fm.fpioa.set_function(pin=33, func=fm.fpioa.I2S2_WS) 24 | 25 | while True: 26 | tx.play(rx.record(sample_points)) 27 | -------------------------------------------------------------------------------- /hardware/demo_lcd.py: -------------------------------------------------------------------------------- 1 | 2 | import lcd, time 3 | 4 | lcd.init() 5 | #lcd.direction(lcd.XY_RLDU) 6 | 7 | #lcd.init(type=2, invert=True) # cube ips 8 | #lcd.init(width=320, height=240, invert=True, freq=20000000) 9 | 10 | # see lcd datasheet (such as amigo ips) 11 | #lcd.register(0x36, 0b01101000) # BGR2RGB Mode 12 | #lcd.register(0x21, None) # invert=True 13 | #lcd.register(0x20, None) # invert=False 14 | #lcd.register(0x36, [0b01101000, ]) # invert=True 15 | 16 | lcd.clear(lcd.RED) 17 | 18 | lcd.rotation(0) 19 | lcd.draw_string(30, 30, "hello maixpy", lcd.WHITE, lcd.RED) 20 | time.sleep(1) 21 | lcd.rotation(1) 22 | lcd.draw_string(60, 60, "hello maixpy", lcd.WHITE, lcd.RED) 23 | time.sleep(1) 24 | lcd.rotation(2) 25 | lcd.draw_string(120, 60, "hello maixpy", lcd.WHITE, lcd.RED) 26 | time.sleep(1) 27 | lcd.rotation(3) 28 | lcd.draw_string(120, 120, "hello maixpy", lcd.WHITE, lcd.RED) 29 | time.sleep(1) 30 | -------------------------------------------------------------------------------- /hardware/demo_lcd_800x480.py: -------------------------------------------------------------------------------- 1 | import time 2 | import lcd 3 | 4 | lcd.init(type=5, lcd_type=3) 5 | while True: 6 | lcd.clear(0xff00) 7 | lcd.rotation(0) 8 | lcd.draw_string(30, 30, "hello maixpy", lcd.WHITE, 0xff00) 9 | time.sleep(1) 10 | 11 | lcd.clear(0x00ff) 12 | lcd.rotation(1) 13 | lcd.draw_string(60, 60, "hello maixpy", lcd.WHITE, 0X00FF) 14 | time.sleep(1) 15 | 16 | lcd.clear(0x0ff0) 17 | lcd.rotation(2) 18 | lcd.draw_string(120, 60, "hello maixpy", lcd.WHITE, 0x0ff0) 19 | time.sleep(1) 20 | 21 | lcd.clear(0x0f0f) 22 | lcd.rotation(3) 23 | lcd.draw_string(120, 120, "hello maixpy", lcd.WHITE, 0x0f0f) 24 | time.sleep(1) 25 | -------------------------------------------------------------------------------- /hardware/demo_mic_array.py: -------------------------------------------------------------------------------- 1 | from Maix import MIC_ARRAY as mic 2 | import lcd 3 | 4 | lcd.init() 5 | mic.init() 6 | #mic.init(i2s_d0=23, i2s_d1=22, i2s_d2=21, i2s_d3=20, i2s_ws=19, i2s_sclk=18, sk9822_dat=24, sk9822_clk=25) 7 | 8 | #mic.init(i2s_d0=20, i2s_d1=21, i2s_d2=15, i2s_d3=8, i2s_ws=7, i2s_sclk=6, sk9822_dat=25, sk9822_clk=24)# for maix cube 9 | 10 | while True: 11 | imga = mic.get_map() 12 | b = mic.get_dir(imga) 13 | a = mic.set_led(b,(0,0,255)) 14 | imgb = imga.resize(160,160) 15 | imgc = imgb.to_rainbow(1) 16 | a = lcd.display(imgc) 17 | mic.deinit() 18 | -------------------------------------------------------------------------------- /hardware/demo_onewire_ds18x20.py: -------------------------------------------------------------------------------- 1 | from fpioa_manager import * 2 | from modules import onewire 3 | from micropython import const 4 | from board import board_info 5 | import time 6 | 7 | class DS18X20: 8 | _CONVERT = const(0x44) 9 | _RD_SCRATCH = const(0xBE) 10 | _WR_SCRATCH = const(0x4E) 11 | _SKIP_ROM = const(0xCC) 12 | def __init__(self, pin): 13 | self.device = onewire(pin) 14 | self.buf = bytearray(9) 15 | 16 | def scan(self): 17 | return self.device.search(65) 18 | 19 | def convert_temp(self): 20 | self.device.reset() 21 | self.device.writebyte(_SKIP_ROM) 22 | self.device.writebyte(_CONVERT) 23 | 24 | def read_scratch(self, rom): 25 | self.device.reset() 26 | self.convert_temp() 27 | self.device.select(rom) 28 | self.device.writebyte(_RD_SCRATCH) 29 | self.buf = self.device.readbuffer(len(self.buf)) 30 | if self.device.crc8(self.buf): 31 | raise Exception("CRC error") 32 | return self.buf 33 | 34 | def write_scratch(self, rom, buf): 35 | self.device.reset() 36 | self.device.select(rom) 37 | self.device.writebyte(_WR_SCRATCH) 38 | self.device.writebuffer(buf) 39 | 40 | def read_temp(self, rom): 41 | temp = [] 42 | for _rom in rom: 43 | buf = self.read_scratch(_rom) 44 | if _rom[0] == 0x10: 45 | if buf[1]: 46 | t = buf[0] >> 1 | 0x80 47 | t = -((~t + 1) & 0xFF) 48 | else: 49 | t = buf[0] >> 1 50 | temp.append(t - 0.25 + (buf[7] - buf[6]) / buf[7]) 51 | else: 52 | t = buf[1] << 8 | buf[0] 53 | if t & 0x8000: # sign bit set 54 | t = -((t ^ 0xFFFF) + 1) 55 | temp.append(t / 16) 56 | if len(temp) < 1: 57 | return -1 58 | if len(temp) < 2: 59 | return temp[0] 60 | return tuple(temp) 61 | 62 | 63 | fm.register(14, fm.fpioa.GPIOHS2, force=True) 64 | ds18b20_2 = DS18X20(fm.fpioa.GPIOHS2) 65 | while True: 66 | print(ds18b20_2.read_temp(rom_2)) 67 | time.sleep_ms(100) 68 | -------------------------------------------------------------------------------- /hardware/demo_pwm.py: -------------------------------------------------------------------------------- 1 | from machine import Timer,PWM 2 | import time 3 | from board import board_info 4 | from fpioa_manager import fm 5 | 6 | tim = Timer(Timer.TIMER0, Timer.CHANNEL0, mode=Timer.MODE_PWM) 7 | ch = PWM(tim, freq=500000, duty=50, pin=board_info.LED_G) 8 | duty=0 9 | dir = True 10 | while True: 11 | if dir: 12 | duty += 10 13 | else: 14 | duty -= 10 15 | if duty>100: 16 | duty = 100 17 | dir = False 18 | elif duty<0: 19 | duty = 0 20 | dir = True 21 | time.sleep(0.05) 22 | ch.duty(duty) -------------------------------------------------------------------------------- /hardware/demo_spi_cs.py: -------------------------------------------------------------------------------- 1 | import time 2 | from machine import SPI 3 | from fpioa_manager import fm 4 | 5 | fm.register(25,fm.fpioa.GPIOHS10, force=True)#cs 6 | 7 | from Maix import GPIO 8 | 9 | cs = GPIO(GPIO.GPIOHS10, GPIO.OUT) 10 | 11 | fm.register(28,fm.fpioa.SPI1_D0, force=True)#mosi 12 | fm.register(26,fm.fpioa.SPI1_D1, force=True)#miso 13 | fm.register(27,fm.fpioa.SPI1_SCLK, force=True)#sclk 14 | spi1 = SPI(SPI.SPI1, mode=SPI.MODE_MASTER, baudrate=10000000, polarity=0, phase=0, bits=8, firstbit=SPI.MSB) 15 | 16 | while True: 17 | w = b'\xFF' 18 | r = bytearray(1) 19 | cs.value(0) 20 | print(spi1.write_readinto(w, r)) 21 | cs.value(1) 22 | print(w, r) 23 | time.sleep(0.1) 24 | 25 | ''' 26 | from machine import SPI 27 | spi1 = SPI(SPI.SPI1, mode=SPI.MODE_MASTER, baudrate=10000000, polarity=0, phase=0, bits=8, firstbit=SPI.MSB, sck=28, mosi=29, miso=30) 28 | w = b'1234' 29 | r = bytearray(4) 30 | spi1.write(w) 31 | spi1.write_readinto(w, r) 32 | spi1.read(5, write=0x00) 33 | spi1.readinto(r, write=0x00) 34 | ''' 35 | -------------------------------------------------------------------------------- /hardware/demo_spi_soft.py: -------------------------------------------------------------------------------- 1 | from machine import SPI 2 | from Maix import GPIO 3 | from fpioa_manager import fm 4 | 5 | mosi=8 6 | miso=15 7 | cs=20 8 | clk=21 9 | 10 | spi = SPI(SPI.SPI_SOFT, mode=SPI.MODE_MASTER, baudrate=400*1000, polarity=0, phase=0, bits=8, firstbit=SPI.MSB, sck=clk, mosi=mosi, miso=miso) 11 | fm.register(cs, fm.fpioa.GPIO6, force=True) 12 | cs = GPIO(GPIO.GPIO6, GPIO.OUT) 13 | 14 | # read spi flash id 15 | while True: 16 | cs.value(0) 17 | write_data = bytearray([0x90, 0x00, 0x00, 0x00]) 18 | spi.write(write_data) 19 | id_buf = bytearray(2) 20 | spi.readinto(id_buf, write=0xff) 21 | work_data = id_buf 22 | cs.value(1) 23 | print(work_data) 24 | -------------------------------------------------------------------------------- /hardware/demo_switch_sensor.py: -------------------------------------------------------------------------------- 1 | 2 | from machine import I2C 3 | axp173 = I2C(I2C.I2C3, freq=100000, scl=24, sda=27) 4 | axp173.writeto_mem(0x34, 0x27, 0x20) 5 | axp173.writeto_mem(0x34, 0x28, 0x0C) 6 | 7 | import sensor, image, time, lcd 8 | lcd.init() 9 | 10 | while True: 11 | 12 | #time.sleep(2) 13 | 14 | try: 15 | sensor.reset(choice=1) 16 | sensor.set_pixformat(sensor.YUV422) 17 | sensor.set_framesize(sensor.QVGA) 18 | # sensor.set_hmirror(1) 19 | sensor.set_vflip(1) 20 | sensor.skip_frames(time=2000) 21 | for i in range(50): 22 | img = sensor.snapshot() 23 | lcd.display(img) 24 | except Exception as e: 25 | print(e) 26 | 27 | try: 28 | sensor.reset(choice=2) 29 | sensor.set_pixformat(sensor.YUV422) 30 | sensor.set_framesize(sensor.QVGA) 31 | sensor.set_hmirror(1) 32 | sensor.set_vflip(1) 33 | sensor.skip_frames(time=2000) 34 | for i in range(50): 35 | img = sensor.snapshot().rotation_corr(z_rotation = +90) 36 | lcd.display(img) 37 | except Exception as e: 38 | print(e) 39 | -------------------------------------------------------------------------------- /hardware/demo_timer.py: -------------------------------------------------------------------------------- 1 | from machine import Timer 2 | import time 3 | 4 | def on_timer(timer): 5 | print("time up:",timer) 6 | print("param:",timer.callback_arg()) 7 | 8 | tim = Timer(Timer.TIMER0, Timer.CHANNEL0, mode=Timer.MODE_ONE_SHOT, period=3000, callback=on_timer, arg=on_timer) 9 | # tim = Timer(Timer.TIMER0, Timer.CHANNEL0, mode=Timer.MODE_PERIODIC, period=1, unit=Timer.UNIT_S, callback=on_timer, arg=on_timer, start=False, priority=1, div=0) 10 | 11 | print("period:",tim.period()) 12 | 13 | tim.start() 14 | time.sleep(5) 15 | tim.stop() 16 | time.sleep(5) 17 | tim.restart() 18 | time.sleep(5) 19 | tim.stop() 20 | del tim 21 | 22 | -------------------------------------------------------------------------------- /hardware/demo_touchscreen.py: -------------------------------------------------------------------------------- 1 | import touchscreen as ts 2 | from machine import I2C 3 | import lcd, image 4 | from board import board_info 5 | from fpioa_manager import fm 6 | from Maix import GPIO 7 | 8 | fm.register(board_info.BOOT_KEY, fm.fpioa.GPIO1, force=True) 9 | btn_clear = GPIO(GPIO.GPIO1, GPIO.IN) 10 | 11 | lcd.init() 12 | i2c = I2C(I2C.I2C0, freq=400000, scl=30, sda=31) 13 | ts.init(i2c) 14 | #ts.calibrate() 15 | lcd.clear() 16 | img = image.Image() 17 | status_last = ts.STATUS_IDLE 18 | x_last = 0 19 | y_last = 0 20 | draw = False 21 | while True: 22 | (status,x,y) = ts.read() 23 | print(status, x, y) 24 | if draw: 25 | img.draw_line((x_last, y_last, x, y)) 26 | if status_last!=status: 27 | if (status==ts.STATUS_PRESS or status == ts.STATUS_MOVE): 28 | draw = True 29 | else: 30 | draw = False 31 | status_last = status 32 | lcd.display(img) 33 | x_last = x 34 | y_last = y 35 | if btn_clear.value() == 0: 36 | img.clear() 37 | 38 | 39 | -------------------------------------------------------------------------------- /hardware/demo_uart_loop.py: -------------------------------------------------------------------------------- 1 | from fpioa_manager import fm 2 | 3 | # maixduino board_info PIN10/PIN11 4 | # from board import board_info 5 | # fm.register(board_info.PIN10, fm.fpioa.UART1_TX, force=True) 6 | # fm.register(board_info.PIN11, fm.fpioa.UART1_RX, force=True) 7 | 8 | # need your connect hardware IO 10/11 to loopback 9 | fm.register(10, fm.fpioa.UART1_TX, force=True) 10 | fm.register(11, fm.fpioa.UART1_RX, force=True) 11 | 12 | from machine import UART 13 | 14 | uart_A = UART(UART.UART1, 115200, 8, 1, 0, timeout=1000, read_buf_len=4096) 15 | 16 | import time 17 | 18 | time.sleep_ms(100) # wait uart ready 19 | uart_A.write(b'hello world') 20 | 21 | while True: 22 | if uart_A.any(): 23 | while uart_A.any(): 24 | read_data = uart_A.read() 25 | print("recv = ", read_data) # recv = b'hello world' 26 | break 27 | time.sleep_ms(10) # ohter event 28 | 29 | uart_A.deinit() 30 | del uart_A 31 | -------------------------------------------------------------------------------- /hardware/demo_uart_many.py: -------------------------------------------------------------------------------- 1 | from fpioa_manager import fm 2 | from machine import UART 3 | from board import board_info 4 | from fpioa_manager import fm 5 | 6 | # maixduino board_info PIN10/PIN11/PIN12/PIN13 or other hardware IO 12/11/10/3 7 | fm.register(board_info.PIN10, fm.fpioa.UART1_TX, force=True) 8 | fm.register(board_info.PIN11, fm.fpioa.UART1_RX, force=True) 9 | fm.register(board_info.PIN12, fm.fpioa.UART2_TX, force=True) 10 | fm.register(board_info.PIN13, fm.fpioa.UART2_RX, force=True) 11 | 12 | uart_A = UART(UART.UART1, 115200, 8, 0, 0, timeout=1000, read_buf_len=4096) 13 | uart_B = UART(UART.UART2, 115200, 8, 0, 0, timeout=1000, read_buf_len=4096) 14 | 15 | write_bytes = b'hello world' 16 | for i in range(20): 17 | uart_A.write(write_str) 18 | if uart_A.any(): 19 | read_data = uart_B.read() 20 | if read_data: 21 | print("write_bytes = ", write_bytes) 22 | if read_data == write_bytes: 23 | print("baudrate:115200 bits:8 parity:0 stop:0 ---check Successfully") 24 | 25 | uart_A.deinit() 26 | uart_B.deinit() 27 | del uart_A 28 | del uart_B 29 | -------------------------------------------------------------------------------- /hardware/demo_wdt.py: -------------------------------------------------------------------------------- 1 | import time 2 | from machine import WDT 3 | 4 | # ''' 5 | # test default wdt 6 | wdt0 = WDT(id=0, timeout=3000) 7 | print('into', wdt0) 8 | time.sleep(2) 9 | print(time.ticks_ms()) 10 | # 1.test wdt feed 11 | wdt0.feed() 12 | time.sleep(2) 13 | print(time.ticks_ms()) 14 | # 2.test wdt stop 15 | wdt0.stop() 16 | print('stop', wdt0) 17 | # 3.wait wdt work 18 | #while True: 19 | #print('idle', time.ticks_ms()) 20 | #time.sleep(1) 21 | # ''' 22 | 23 | # ''' 24 | def on_wdt(self): 25 | print(self.context(), self) 26 | #self.feed() 27 | ## release WDT 28 | #self.stop() 29 | 30 | # test callback wdt 31 | wdt1 = WDT(id=1, timeout=4000, callback=on_wdt, context={}) 32 | print('into', wdt1) 33 | time.sleep(2) 34 | print(time.ticks_ms()) 35 | # 1.test wdt feed 36 | wdt1.feed() 37 | time.sleep(2) 38 | print(time.ticks_ms()) 39 | # 2.test wdt stop 40 | wdt1.stop() 41 | print('stop', wdt1) 42 | # 3.wait wdt work 43 | #while True: 44 | #print('idle', time.ticks_ms()) 45 | #time.sleep(1) 46 | # ''' 47 | 48 | #''' 49 | ## test default and callback wdt 50 | def on_wdt(self): 51 | print(self.context(), self) 52 | #self.feed() 53 | ## release WDT 54 | #self.stop() 55 | 56 | wdt0 = WDT(id=0, timeout=3000, callback=on_wdt, context=[]) 57 | wdt1 = WDT(id=1, timeout=4000, callback=on_wdt, context={}) 58 | ## 3.wait wdt work 59 | while True: 60 | #wdt0.feed() 61 | print('idle', time.ticks_ms()) 62 | time.sleep(1) 63 | #''' -------------------------------------------------------------------------------- /hardware/fpioa_manager.py: -------------------------------------------------------------------------------- 1 | from Maix import FPIOA 2 | 3 | class fm: 4 | fpioa = FPIOA() 5 | 6 | def help(): 7 | __class__.fpioa.help() 8 | 9 | def get_pin_by_function(function): 10 | return __class__.fpioa.get_Pin_num(function) 11 | 12 | def register(pin, function, force=False): 13 | pin_used = __class__.get_pin_by_function(function) 14 | if pin_used == pin: 15 | return 16 | if None != pin_used: 17 | info = "[Warning] function is used by %s(pin:%d)" % ( 18 | fm.str_function(function), pin_used) 19 | if force == False: 20 | raise Exception(info) 21 | else: 22 | print(info) 23 | __class__.fpioa.set_function(pin, function) 24 | 25 | def unregister(pin): 26 | __class__.fpioa.set_function(pin, fm.fpioa.RESV0) 27 | 28 | def str_function(function): 29 | if fm.fpioa.GPIOHS0 <= function and function <= fm.fpioa.GPIO7: 30 | if fm.fpioa.GPIO0 <= function: 31 | return 'fm.fpioa.GPIO%d' % (function - fm.fpioa.GPIO0) 32 | return 'fm.fpioa.GPIOHS%d' % (function - fm.fpioa.GPIOHS0) 33 | return 'unknown' 34 | 35 | def get_gpio_used(): 36 | return [(__class__.str_function(f), __class__.get_pin_by_function(f)) for f in range(fm.fpioa.GPIOHS0, fm.fpioa.GPIO7 + 1)] 37 | 38 | 39 | if __name__ == "__main__": 40 | import time 41 | print('check register') 42 | for item in fm.get_gpio_used(): 43 | print(item) 44 | print('test unregister') 45 | for pin in range(8, 48): 46 | fm.unregister(pin) 47 | print('check register') 48 | for item in fm.get_gpio_used(): 49 | print(item) 50 | # gpio test 51 | from Maix import GPIO 52 | 53 | def gpio_test(): 54 | for i in range(5): 55 | led_b.value(1) 56 | led_g.value(1) 57 | time.sleep_ms(100) 58 | print('woking...') 59 | led_b.value(0) 60 | led_g.value(0) 61 | time.sleep_ms(100) 62 | print('woking...') 63 | print('register...') 64 | fm.register(12, fm.fpioa.GPIO0) 65 | fm.register(13, fm.fpioa.GPIOHS0) 66 | led_b = GPIO(GPIO.GPIO0, GPIO.OUT) 67 | led_g = GPIO(GPIO.GPIOHS0, GPIO.OUT) 68 | gpio_test() 69 | print('unregister...') 70 | fm.unregister(12) 71 | fm.unregister(13) 72 | gpio_test() 73 | print('register...') 74 | fm.register(12, fm.fpioa.GPIO0) 75 | fm.register(13, fm.fpioa.GPIOHS0) 76 | gpio_test() 77 | fm.unregister(12) 78 | fm.unregister(13) 79 | # register Coverage test 80 | fm.register(12, fm.fpioa.GPIO0) 81 | time.sleep_ms(500) 82 | try: 83 | fm.register(13, fm.fpioa.GPIO0) # fail 84 | except Exception as e: 85 | print('Exception') 86 | print(e) 87 | time.sleep_ms(500) 88 | fm.register(12, fm.fpioa.GPIOHS0) # pass 89 | time.sleep_ms(500) 90 | print('Warning') 91 | fm.register(13, fm.fpioa.GPIOHS0, force=True) # pass 92 | time.sleep_ms(500) 93 | fm.unregister(12) 94 | fm.unregister(13) 95 | -------------------------------------------------------------------------------- /machine_vision/debug_kpu_yolov2.py: -------------------------------------------------------------------------------- 1 | 2 | import sys, time, sensor, lcd 3 | 4 | class camera: 5 | 6 | is_init = False 7 | is_dual_buff = False 8 | 9 | def init(): 10 | sensor.reset(dual_buff=__class__.is_dual_buff) 11 | sensor.set_pixformat(sensor.RGB565) 12 | sensor.set_framesize(sensor.QVGA) 13 | sensor.set_windowing((320, 224)) 14 | sensor.set_hmirror(1) 15 | sensor.set_vflip(1) 16 | sensor.run(1) 17 | sensor.skip_frames() 18 | 19 | def get_image(): 20 | if __class__.is_init == False: 21 | __class__.init() 22 | __class__.is_init = True 23 | return sensor.snapshot() 24 | 25 | 26 | import KPU as kpu 27 | 28 | import lcd 29 | lcd.init() 30 | 31 | if __name__ == "__main__": 32 | 33 | with open("anchors.txt","r") as f: 34 | anchor_txt=f.read() 35 | #print(anchor_txt) 36 | anchor=tuple([float(i) for i in anchor_txt.split(",")]) 37 | #print(anchor) 38 | 39 | with open("classes.txt","r") as f: 40 | labels_txt=f.read() 41 | #print(labels_txt) 42 | labels=tuple([str(i) for i in labels_txt.split(",")]) 43 | #print(labels) 44 | 45 | import time 46 | last = time.ticks_ms() 47 | while True: 48 | try: 49 | #KpuTask = kpu.load(0x5C0000) 50 | KpuTask = kpu.load("/sd/yolov2.kmodel") 51 | kpu.init_yolo2(KpuTask, 0.6, 0.3, 5, anchor) 52 | while True: 53 | #print(time.ticks_ms() - last) 54 | last = time.ticks_ms() 55 | img = camera.get_image() 56 | things = kpu.run_yolo2(KpuTask, img) 57 | if things: 58 | 59 | for pos in range(len(things)): 60 | i = things[pos] 61 | img.draw_rectangle(320 - (i.x() + i.w()), i.y(), i.w(), i.h()) 62 | img.draw_string(320 - (i.x() + i.w()), i.y(), '%.2f:%s' % (i.value(), labels[i.classid()]), color=(0, 255, 0)) 63 | 64 | ## gc.collect() # have bug when reply 3 65 | lcd.display(img) 66 | except KeyboardInterrupt as e: 67 | pass 68 | finally: 69 | kpu.deinit(KpuTask) 70 | #break 71 | -------------------------------------------------------------------------------- /machine_vision/demo_affine.py: -------------------------------------------------------------------------------- 1 | import image 2 | import lcd, sensor 3 | import time 4 | 5 | lcd.init() 6 | # lcd.init(type=2, freq=20000000) 7 | 8 | sensor.reset(freq=24000000) 9 | sensor.set_pixformat(sensor.RGB565) 10 | sensor.set_framesize(sensor.QVGA) 11 | 12 | 13 | matrix = image.get_affine_transform([(0,0), (240, 0), (240, 240)], [(60,60), (240, 0), (220, 200)]) 14 | print("matrix:") 15 | print("[{:.02f}, {:.02f}, {:.02f}]".format(matrix[0], matrix[1], matrix[2])) 16 | print("[{:.02f}, {:.02f}, {:.02f}]".format(matrix[3], matrix[4], matrix[5])) 17 | print("[{:.02f}, {:.02f}, {:.02f}]".format(matrix[6], matrix[7], matrix[8])) 18 | 19 | 20 | try: 21 | del img 22 | del img2 23 | except Exception: 24 | pass 25 | 26 | img2 = image.Image(size=(320, 240)) 27 | img2.pix_to_ai() 28 | flag = False 29 | while 1: 30 | img = sensor.snapshot() 31 | 32 | image.warp_affine_ai(img, img2, matrix) 33 | 34 | img2.ai_to_pix() 35 | if flag: 36 | lcd.display(img2) 37 | else: 38 | lcd.display(img) 39 | flag = not flag 40 | time.sleep_ms(500) 41 | 42 | -------------------------------------------------------------------------------- /machine_vision/demo_find_green_blob.py: -------------------------------------------------------------------------------- 1 | import sensor 2 | import image 3 | import lcd 4 | import time 5 | 6 | lcd.init(freq=15000000) 7 | sensor.reset() 8 | sensor.set_pixformat(sensor.RGB565) 9 | sensor.set_framesize(sensor.QVGA) 10 | sensor.run(1) 11 | green_threshold = (0, 80, -70, -10, -0, 30) 12 | while True: 13 | img=sensor.snapshot() 14 | blobs = img.find_blobs([green_threshold]) 15 | if blobs: 16 | for b in blobs: 17 | tmp=img.draw_rectangle(b[0:4]) 18 | tmp=img.draw_cross(b[5], b[6]) 19 | c=img.get_pixel(b[5], b[6]) 20 | lcd.display(img) 21 | -------------------------------------------------------------------------------- /machine_vision/demo_fps_display.py: -------------------------------------------------------------------------------- 1 | import sensor 2 | import image 3 | import lcd 4 | import time 5 | 6 | clock = time.clock() 7 | lcd.init() 8 | sensor.reset() 9 | sensor.set_pixformat(sensor.RGB565) 10 | sensor.set_framesize(sensor.QVGA) 11 | sensor.run(1) 12 | sensor.skip_frames(30) 13 | while True: 14 | clock.tick() 15 | img = sensor.snapshot() 16 | fps =clock.fps() 17 | img.draw_string(2,2, ("%2.1ffps" %(fps)), color=(0,128,0), scale=2) 18 | lcd.display(img) 19 | 20 | 21 | -------------------------------------------------------------------------------- /machine_vision/demo_image_deal.py: -------------------------------------------------------------------------------- 1 | import sensor 2 | import image 3 | import lcd 4 | import time 5 | 6 | lcd.init(freq=15000000) 7 | sensor.reset() 8 | sensor.set_pixformat(sensor.RGB565) 9 | sensor.set_framesize(sensor.QVGA) 10 | sensor.run(1) 11 | origin = (0,0,0, 0,1,0, 0,0,0) 12 | edge = (-1,-1,-1,-1,8,-1,-1,-1,-1) 13 | sharp = (-1,-1,-1,-1,9,-1,-1,-1,-1) 14 | relievo = (2,0,0,0,-1,0,0,0,-1) 15 | 16 | tim = time.time() 17 | while True: 18 | img=sensor.snapshot() 19 | img.conv3(edge) 20 | lcd.display(img) 21 | if time.time() -tim >10: 22 | break 23 | tim = time.time() 24 | while True: 25 | img=sensor.snapshot() 26 | img.conv3(sharp) 27 | lcd.display(img) 28 | if time.time() -tim >10: 29 | break 30 | tim = time.time() 31 | while True: 32 | img=sensor.snapshot() 33 | img.conv3(relievo) 34 | lcd.display(img) 35 | if time.time() -tim >10: 36 | break 37 | 38 | lcd.clear() 39 | 40 | -------------------------------------------------------------------------------- /machine_vision/demo_scan_qr_code.py: -------------------------------------------------------------------------------- 1 | import sensor 2 | import image 3 | import lcd 4 | import time 5 | 6 | clock = time.clock() 7 | lcd.init() 8 | sensor.reset() 9 | sensor.set_pixformat(sensor.RGB565) 10 | sensor.set_framesize(sensor.QVGA) 11 | sensor.set_vflip(1) 12 | sensor.set_hmirror(1) # set hmirror if can not recognize qr code 13 | sensor.skip_frames(30) 14 | while True: 15 | clock.tick() 16 | img = sensor.snapshot() 17 | res = img.find_qrcodes() 18 | fps =clock.fps() 19 | if len(res) > 0: 20 | img.draw_string(2,2, res[0].payload(), color=(0,128,0), scale=2) 21 | print(res[0].payload()) 22 | lcd.display(img) 23 | 24 | -------------------------------------------------------------------------------- /machine_vision/face_find/demo_find_face.py: -------------------------------------------------------------------------------- 1 | 2 | import sensor, image, lcd, time 3 | import KPU as kpu 4 | import gc, sys 5 | 6 | def lcd_show_except(e): 7 | import uio 8 | err_str = uio.StringIO() 9 | sys.print_exception(e, err_str) 10 | err_str = err_str.getvalue() 11 | img = image.Image(size=(224,224)) 12 | img.draw_string(0, 10, err_str, scale=1, color=(0xff,0x00,0x00)) 13 | lcd.display(img) 14 | 15 | def main(model_addr=0x300000, lcd_rotation=0, sensor_hmirror=False, sensor_vflip=False): 16 | try: 17 | sensor.reset() 18 | except Exception as e: 19 | raise Exception("sensor reset fail, please check hardware connection, or hardware damaged! err: {}".format(e)) 20 | sensor.set_pixformat(sensor.RGB565) 21 | sensor.set_framesize(sensor.QVGA) 22 | sensor.set_hmirror(sensor_hmirror) 23 | sensor.set_vflip(sensor_vflip) 24 | sensor.run(1) 25 | 26 | lcd.init(type=1) 27 | lcd.rotation(lcd_rotation) 28 | lcd.clear(lcd.WHITE) 29 | 30 | anchors = (1.889, 2.5245, 2.9465, 3.94056, 3.99987, 5.3658, 5.155437, 6.92275, 6.718375, 9.01025) 31 | try: 32 | task = None 33 | task = kpu.load(model_addr) 34 | kpu.init_yolo2(task, 0.5, 0.3, 5, anchors) # threshold:[0,1], nms_value: [0, 1] 35 | while(True): 36 | img = sensor.snapshot() 37 | t = time.ticks_ms() 38 | objects = kpu.run_yolo2(task, img) 39 | t = time.ticks_ms() - t 40 | if objects: 41 | for obj in objects: 42 | img.draw_rectangle(obj.rect()) 43 | img.draw_string(0, 200, "t:%dms" %(t), scale=2) 44 | lcd.display(img) 45 | except Exception as e: 46 | raise e 47 | finally: 48 | if not task is None: 49 | kpu.deinit(task) 50 | 51 | 52 | if __name__ == "__main__": 53 | try: 54 | main( model_addr=0x300000, lcd_rotation=0, sensor_hmirror=False, sensor_vflip=False) 55 | # main(model_addr="/sd/m.kmodel") 56 | except Exception as e: 57 | sys.print_exception(e) 58 | lcd_show_except(e) 59 | finally: 60 | gc.collect() 61 | -------------------------------------------------------------------------------- /machine_vision/face_recognization/README.md: -------------------------------------------------------------------------------- 1 | face recognization 2 | ============ 3 | 4 | video demo [youtube](https://www.youtube.com/embed/hS_mcGptXeo) or [bilibili](https://www.bilibili.com/video/BV1bJ411Q7L6) 5 | 6 | ## Usage 7 | 8 | * Download model from [maixhub](https://www.maixhub.com/index/index/detail/id/235.html) 9 | * Download model to board 10 | * run [script](./demo_face_recognization.py) 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /machine_vision/fans_share/mask.kmodel/mask.kmodel: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sipeed/MaixPy-v1_scripts/8d7c5f98ba654d226f433d31718d852674cab08d/machine_vision/fans_share/mask.kmodel/mask.kmodel -------------------------------------------------------------------------------- /machine_vision/fans_share/mask.kmodel/mask.py: -------------------------------------------------------------------------------- 1 | import sensor, image, lcd, time 2 | import KPU as kpu 3 | 4 | color_R = (255, 0, 0) 5 | color_G = (0, 255, 0) 6 | color_B = (0, 0, 255) 7 | 8 | 9 | class_IDs = ['no_mask', 'mask'] 10 | 11 | 12 | def drawConfidenceText(image, rol, classid, value): 13 | text = "" 14 | _confidence = int(value * 100) 15 | 16 | if classid == 1: 17 | text = 'mask: ' + str(_confidence) + '%' 18 | else: 19 | text = 'no_mask: ' + str(_confidence) + '%' 20 | 21 | image.draw_string(rol[0], rol[1], text, color=color_R, scale=2.5) 22 | 23 | 24 | 25 | lcd.init() 26 | sensor.reset(dual_buff=True) 27 | sensor.set_pixformat(sensor.RGB565) 28 | sensor.set_framesize(sensor.QVGA) 29 | sensor.set_hmirror(0) 30 | sensor.run(1) 31 | 32 | 33 | task = kpu.load(0x500000) 34 | 35 | 36 | anchor = (0.1606, 0.3562, 0.4712, 0.9568, 0.9877, 1.9108, 1.8761, 3.5310, 3.4423, 5.6823) 37 | _ = kpu.init_yolo2(task, 0.5, 0.3, 5, anchor) 38 | img_lcd = image.Image() 39 | 40 | clock = time.clock() 41 | while (True): 42 | clock.tick() 43 | img = sensor.snapshot() 44 | code = kpu.run_yolo2(task, img) 45 | if code: 46 | totalRes = len(code) 47 | 48 | for item in code: 49 | confidence = float(item.value()) 50 | itemROL = item.rect() 51 | classID = int(item.classid()) 52 | 53 | if confidence < 0.52: 54 | _ = img.draw_rectangle(itemROL, color=color_B, tickness=5) 55 | continue 56 | 57 | if classID == 1 and confidence > 0.65: 58 | _ = img.draw_rectangle(itemROL, color_G, tickness=5) 59 | if totalRes == 1: 60 | drawConfidenceText(img, (0, 0), 1, confidence) 61 | else: 62 | _ = img.draw_rectangle(itemROL, color=color_R, tickness=5) 63 | if totalRes == 1: 64 | drawConfidenceText(img, (0, 0), 0, confidence) 65 | 66 | _ = lcd.display(img) 67 | 68 | print(clock.fps()) 69 | 70 | _ = kpu.deinit(task) 71 | -------------------------------------------------------------------------------- /machine_vision/fans_share/readme.md: -------------------------------------------------------------------------------- 1 | # This is the code and public model that some of our fans share 2 | 3 | 这是我们的爱好者们分享的代码(.py)和公开模型(.kmodel)。 4 | -------------------------------------------------------------------------------- /machine_vision/fans_share/yolov2_apple,banana,orange/anchors.txt: -------------------------------------------------------------------------------- 1 | 0.32,0.68,0.7,0.73,0.75,0.75,0.8,0.96,1.1,1.63 -------------------------------------------------------------------------------- /machine_vision/fans_share/yolov2_apple,banana,orange/classes.txt: -------------------------------------------------------------------------------- 1 | apple,banana,orange -------------------------------------------------------------------------------- /machine_vision/fans_share/yolov2_apple,banana,orange/main.py: -------------------------------------------------------------------------------- 1 | import sensor 2 | import image 3 | import lcd 4 | import KPU as kpu 5 | 6 | lcd.init() 7 | sensor.reset() 8 | sensor.set_pixformat(sensor.RGB565) 9 | sensor.set_framesize(sensor.QVGA) 10 | sensor.set_windowing((224, 224)) 11 | sensor.set_hmirror(0) 12 | sensor.run(1) 13 | task = kpu.load("/sd/yolov2.kmodel") 14 | f=open("anchors.txt","r") 15 | anchor_txt=f.read() 16 | L=[] 17 | for i in anchor_txt.split(","): 18 | L.append(float(i)) 19 | anchor=tuple(L) 20 | f.close() 21 | a = kpu.init_yolo2(task, 0.6, 0.3, 5, anchor) 22 | f=open("classes.txt","r") 23 | labels_txt=f.read() 24 | labels = labels_txt.split(",") 25 | f.close() 26 | while(True): 27 | img = sensor.snapshot() 28 | code = kpu.run_yolo2(task, img) 29 | if code: 30 | for i in code: 31 | a=img.draw_rectangle(i.rect(),(0,255,0),2) 32 | a = lcd.display(img) 33 | for i in code: 34 | lcd.draw_string(i.x()+45, i.y()-5, labels[i.classid()]+" "+'%.2f'%i.value(), lcd.WHITE,lcd.GREEN) 35 | else: 36 | a = lcd.display(img) 37 | a = kpu.deinit(task) -------------------------------------------------------------------------------- /machine_vision/fans_share/yolov2_apple,banana,orange/yolov2.kmodel: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sipeed/MaixPy-v1_scripts/8d7c5f98ba654d226f433d31718d852674cab08d/machine_vision/fans_share/yolov2_apple,banana,orange/yolov2.kmodel -------------------------------------------------------------------------------- /machine_vision/fmap/README.md: -------------------------------------------------------------------------------- 1 | feature map 2 | ====== 3 | 4 | * use [mnist.kmodel](../models/mnist.kmodel) 5 | * run fmap.py on maixpy 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /machine_vision/fmap/fmap.py: -------------------------------------------------------------------------------- 1 | import sensor,lcd,image 2 | import KPU as kpu 3 | lcd.init() 4 | sensor.reset() 5 | sensor.set_pixformat(sensor.RGB565) 6 | sensor.set_framesize(sensor.QVGA) 7 | sensor.set_windowing((224, 224)) #set to 224x224 input 8 | sensor.set_hmirror(0) #flip camera 9 | task = kpu.load(0x300000) #load model from flash address 0x200000 10 | 11 | img_lcd=image.Image() 12 | img_lcd = img_lcd.to_grayscale() 13 | while True: 14 | img2 = sensor.snapshot() 15 | #lcd.display(img,oft=(0,0)) #display large picture 16 | img2=img2.to_grayscale() #convert to gray 17 | img2=img2.resize(28,28) #resize to mnist input 28x28 18 | a=img2.invert() #invert picture as mnist need 19 | # a=img2.strech_char(1) #preprocessing pictures, eliminate dark corner 20 | img2x2=img2.resize(28*2,28*2) #scale to display 21 | a = img_lcd.draw_image(img2x2,0,0)#display small 28x28 picture 22 | a=img2.pix_to_ai(); #generate data for ai 23 | #watch conv0 24 | a=kpu.set_layers(task, 1) 25 | fmap=kpu.forward(task,img2) #run neural network model 26 | for i in range(0,16): 27 | tmp=kpu.fmap(fmap,i) 28 | tmpx2=tmp.resize(14*2,14*2) #scale to display 29 | a=img_lcd.draw_image(tmpx2,(i%8)*14*2,28*2+14*2*int(i/8)) 30 | #watch conv1 31 | a=kpu.set_layers(task, 2) 32 | fmap=kpu.forward(task,img2) #run neural network model 33 | for i in range(0,32): 34 | tmp=kpu.fmap(fmap,i) 35 | tmpx2=tmp.resize(7*2,7*2) #scale to display 36 | a=img_lcd.draw_image(tmpx2,(i%16)*7*2,28*2+14*2*2+7*2*int(i/16)) 37 | #watch conv2 38 | a=kpu.set_layers(task, 8) 39 | fmap=kpu.forward(task,img2) #run neural network model 40 | for i in range(0,10): 41 | tmp=kpu.fmap(fmap,i) 42 | tmpx2=tmp.resize(4*2,4*2) #scale to display 43 | a=img_lcd.draw_image(tmpx2,i*4*2,28*2+14*2*2+7*2*2) 44 | #watch softmax 45 | a=kpu.set_layers(task, 11) 46 | fmap=kpu.forward(task,img2) 47 | plist=fmap[:] 48 | for i in range(0,10): 49 | cc = int(plist[i]*256) 50 | lcd.display(img_lcd) 51 | -------------------------------------------------------------------------------- /machine_vision/load_big_model/README.md: -------------------------------------------------------------------------------- 1 | load big kmodel 2 | ======== 3 | 4 | If your model is too big(size), you can use this way to load it dynamically from flash 5 | 6 | Limitations: 7 | * Slower than normal run 8 | * Only support load from flash, from file system is not supported 9 | 10 | ## Example usage 11 | 12 | * Burn [preprocessed kmodel](../models/face_model_be_at_0x600000.kfpkg) (or download [here](https://dl.sipeed.com/MAIX/MaixPy/model)) to flash by kflash_gui 13 | * Run [demo_load_big_model.py](./demo_load_big_model.py) on MaixPy 14 | * The difference from [demo_find_face.py](../demo_find_face.py) is `kpu.load()` changed to `kpu.load_flash`, the parameters: 15 | * `model_addr`: flash addr store your model, note, you need flip the model endian(step 1). 16 | * `is_dual_buf`: `0`, single buf, use less ram and slower speed; `1`, dual buf, more ram and faster speed. 17 | * `batch_size`: when set `is_dual_buf` to 1, you need set load batch_size, suggestion value is `0x4000`~`0x10000`, you can test out best value for your model. set to 0 if `is_dual_buf` is 0 18 | * `spi_speed`: when use flash runner, we will temporary set flash to high speed mode, set the spi speed you want. the value should <= 80000000 (actual frequency, value set may not equal to actual freq.) 19 | 20 | 21 | ## Run your model 22 | 23 | * Preprocess kmodel on PC 24 | ``` 25 | cd MaixPy_scripts/machine_vision 26 | python3 model_le2be.py your_kmodel_path.kmodel 27 | ``` 28 | this command will generate a kmodel ends with `_be.kmodel`(`be` means `big edian`), 29 | you **MUST** use this model if you use `kpu.load_flash()` API 30 | 31 | * Burn this kmodel to flash, and run your script 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /machine_vision/load_big_model/README_ZH.md: -------------------------------------------------------------------------------- 1 | # 从 SPI FLASH 中加载并运行大模型 2 | ======== 3 | 4 | 由于 K210 的 RAM 的运行机制,当需要加载大模型文件时,可以通过直接 Flash 中动态加载并运行 5 | 6 | 局限性: 7 | * 从 flash 加载运行的速度,比正常运行慢 8 | * 仅支持从内部 flash 加载,不支持从文件系统加载 9 | 10 | ## 用法示例 11 | 12 | * 烧录[预处理的 kmodel 示例文件](../models/face_model_be_at_0x600000.kfpkg)(或者从[这里下载](https://dl.sipeed.com/MAIX/MaixPy/model)),然后使用 kflash_gui 烧录到 flash 中 13 | 14 | * 在 MaixPy 上运行示例程序[demo_load_big_model.py](./demo_load_big_model.py) 15 | 16 | * 与 [demo_find_face.py](../demo_find_face.py) 的区别是将 `kpu.load()` 更改为 `kpu.load_flash`, 相关参数如下: 17 | * `model_addr`: Flash addr 经过预处理的模型烧录到 flash 中的偏移地址。注意,这里需要预处理模型文件(第1步)。 18 | * `is_dual_buf`:`0`,单一缓冲区加载,使用较少的 RAM 和较慢的速度动态加载该模型文件;`1`,开启双缓冲加载,需要更大的 RAM, 运行速度相对较快。 19 | * `batch_size`:将`is_dual_buf`设置为 1 时,需要设置 load batch_size,建议值为`0x4000`~`0x10000`,可以测试出模型的最佳值。如果 is_dual_buf 为 0 则设置为 0 20 | * `spi_speed`:使用 SPI flash 加载模型文件时,我们会暂时将 flash 设置为高速模式,并设置所需的 spi 时钟频率。该值应 <= 80000000(实际频率,设置的值可能不等于实际频率。) 21 | 22 | 23 | ## 预处理模型文件 24 | 25 | * 在 PC 上对 kmodel 模型文件进行预处理(对模型字节序进行翻转) 26 | 27 | ```shell 28 | cd MaixPy_scripts/machine_vision 29 | python3 model_le2be.py your_kmodel_path.kmodel #进行预处理 30 | ``` 31 | 32 | 如果需要从 flash 中动态加载模型文件时必须,使用预处理之后的`_be.kmodel` 模型文件,该命令将生成以`_be.kmodel`(`be`表示`big edian`) 结尾的 kmodel 33 | * 烧录该预处理的模型文件,然后运行示例脚本 34 | -------------------------------------------------------------------------------- /machine_vision/load_big_model/demo_load_big_model.py: -------------------------------------------------------------------------------- 1 | 2 | import sensor 3 | import image 4 | import lcd 5 | import KPU as kpu 6 | 7 | lcd.init() 8 | sensor.reset() 9 | sensor.set_hmirror(1) 10 | sensor.set_pixformat(sensor.RGB565) 11 | sensor.set_framesize(sensor.QVGA) 12 | sensor.run(1) 13 | task = kpu.load_flash(0x600000, 1, 0xC000, 60000000) 14 | print("load end") 15 | anchor = (1.889, 2.5245, 2.9465, 3.94056, 3.99987, 5.3658, 5.155437, 6.92275, 6.718375, 9.01025) 16 | a = kpu.init_yolo2(task, 0.5, 0.3, 5, anchor) 17 | print("init yolo2 end") 18 | while(True): 19 | img = sensor.snapshot() 20 | t = time.ticks_ms() 21 | code = kpu.run_yolo2(task, img) 22 | print(time.ticks_ms() - t) 23 | if code: 24 | for i in code: 25 | print(i) 26 | a = img.draw_rectangle(i.rect()) 27 | lcd.display(img) 28 | a = kpu.deinit(task) 29 | 30 | 31 | -------------------------------------------------------------------------------- /machine_vision/mobilenet_1000_class/README.md: -------------------------------------------------------------------------------- 1 | Mobilenet V1 1000 classes classifier 2 | ========== 3 | 4 | 5 | * Download model from https://dl.sipeed.com/MAIX/MaixPy/model , download `mobilenet_0x300000.kfpkg` 6 | * And [labels.txt](./labels.txt) 7 | * To make sure have enough memory for this `4.2MiB` model, so use `minimum` version firmware 8 | * Reduce GC heap size by 9 | ```python 10 | from Maix import utils 11 | import machine 12 | 13 | utils.gc_heap_size(256*1024) 14 | machine.reset() 15 | ``` 16 | * Run [script](.mobilenetv1_1000class.py) 17 | 18 | More doc see[doc](maixpy.sipeed.com) 19 | 20 | -------------------------------------------------------------------------------- /machine_vision/mobilenet_1000_class/mobilenetv1_1000class.py: -------------------------------------------------------------------------------- 1 | # refer to http://blog.sipeed.com/p/680.html 2 | 3 | import sensor, image, lcd, time 4 | import KPU as kpu 5 | import gc, sys 6 | 7 | 8 | def main(labels = None, model_addr="/sd/m.kmodel", lcd_rotation=0, sensor_hmirror=False, sensor_vflip=False): 9 | gc.collect() 10 | 11 | sensor.reset() 12 | sensor.set_pixformat(sensor.RGB565) 13 | sensor.set_framesize(sensor.QVGA) 14 | sensor.set_windowing((224, 224)) 15 | sensor.set_hmirror(sensor_hmirror) 16 | sensor.set_vflip(sensor_vflip) 17 | sensor.run(1) 18 | 19 | lcd.init(type=1) 20 | lcd.rotation(lcd_rotation) 21 | lcd.clear(lcd.WHITE) 22 | 23 | if not labels: 24 | raise Exception("no labels.txt") 25 | 26 | task = kpu.load(model_addr) 27 | 28 | try: 29 | while(True): 30 | img = sensor.snapshot() 31 | t = time.ticks_ms() 32 | fmap = kpu.forward(task, img) 33 | t = time.ticks_ms() - t 34 | plist=fmap[:] 35 | pmax=max(plist) 36 | max_index=plist.index(pmax) 37 | img.draw_string(0,0, "%.2f\n%s" %(pmax, labels[max_index].strip()), scale=2, color=(255, 0, 0)) 38 | img.draw_string(0, 200, "t:%dms" %(t), scale=2, color=(255, 0, 0)) 39 | lcd.display(img) 40 | except Exception as e: 41 | sys.print_exception(e) 42 | finally: 43 | kpu.deinit(task) 44 | 45 | 46 | if __name__ == "__main__": 47 | try: 48 | with open("labels.txt") as f: 49 | labels = f.readlines() 50 | main(labels=labels, model_addr=0x300000, lcd_rotation=0, sensor_hmirror=False, sensor_vflip=False) 51 | # main(labels=labels, model_addr="/sd/m.kmodel") 52 | except Exception as e: 53 | sys.print_exception(e) 54 | finally: 55 | gc.collect() 56 | -------------------------------------------------------------------------------- /machine_vision/model_le2be.py: -------------------------------------------------------------------------------- 1 | ################################# 2 | # model_le2be.py 3 | # 4 | # run python3 on pc not maixpy 5 | # 6 | # not maixpy !!!!!!!! 7 | ################################# 8 | 9 | import struct 10 | import sys 11 | import os 12 | 13 | # main body 14 | if sys.argv.__len__() > 1: 15 | # 参数获取 16 | src_file = sys.argv[1] 17 | else: 18 | # 文本输入 19 | src_file = input("Source Bin Path: ") 20 | 21 | if not os.path.exists(src_file): 22 | print('File Path Invalid! Exiting...') 23 | exit(1) 24 | 25 | dst_file = src_file.split(".") 26 | ext = dst_file.pop() 27 | dst_file = ".".join(dst_file) 28 | dst_file = "{}_be.{}".format(dst_file, ext) 29 | print("Source file: {0}\nTarget File: {1}".format( 30 | src_file, dst_file)) 31 | 32 | try: 33 | sf = open(src_file, "rb") 34 | df = open(dst_file, "wb") 35 | 36 | buf_tmp = [b'0' for x in range(0, 4)] 37 | contents = sf.read() 38 | buf_size = contents.__len__() 39 | # 不足4个字节,自动补0 40 | extra_size = (buf_size % 4) 41 | if extra_size > 0: 42 | buf_size += (4 - extra_size) 43 | contents = contents + b'0000' 44 | 45 | for i in range(0, buf_size, 4): 46 | buf_tmp[3] = contents[i] 47 | buf_tmp[2] = contents[i+1] 48 | buf_tmp[1] = contents[i+2] 49 | buf_tmp[0] = contents[i+3] 50 | 51 | # pack into bytes flow 52 | tmp_bytes = struct.pack("4B", buf_tmp[0], buf_tmp[1], buf_tmp[2], buf_tmp[3]) 53 | df.write(tmp_bytes) 54 | finally: 55 | if sf: 56 | sf.close() 57 | if df: 58 | df.close() 59 | 60 | print("Convert Completed!") 61 | 62 | -------------------------------------------------------------------------------- /machine_vision/models/face_model_at_0x300000.kfpkg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sipeed/MaixPy-v1_scripts/8d7c5f98ba654d226f433d31718d852674cab08d/machine_vision/models/face_model_at_0x300000.kfpkg -------------------------------------------------------------------------------- /machine_vision/models/face_model_be_at_0x600000.kfpkg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sipeed/MaixPy-v1_scripts/8d7c5f98ba654d226f433d31718d852674cab08d/machine_vision/models/face_model_be_at_0x600000.kfpkg -------------------------------------------------------------------------------- /machine_vision/models/mnist.kmodel: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sipeed/MaixPy-v1_scripts/8d7c5f98ba654d226f433d31718d852674cab08d/machine_vision/models/mnist.kmodel -------------------------------------------------------------------------------- /machine_vision/self_learning_classifier/README.md: -------------------------------------------------------------------------------- 1 | self learning classifier 2 | ===== 3 | 4 | 5 | * Download firnware >= v0.5.0-33 [here](https://dl.sipeed.com/MAIX/MaixPy/release/master/maixpy_v0.5.0_33_gfcd6d8a) 6 | * Download kmodel [here](https://www.maixhub.com/index.php/index/index/detail/id/225.html) 7 | * Flash kmodel and firmware by [kflash_gui](https://github.com/sipeed/kflash_gui) 8 | * Connect board to PC, open terminal tool like minicom, or use MaixPyIDE 9 | * Run [demo script](self_learning_classifier.py) 10 | 11 | Then you capture train image 12 | 13 | * Push `boot button` to capture 3 classes like `phone`, `car`, `keyboard`, every one class only capture once 14 | * Then capture 15 sample images, no cap order needed, you can capture 5 `phone`, 5 `car` and 5 `keyboard` 15 | * Then it will automatically train the 15 sample images 16 | * The image type will be displayed on the left top of screen 17 | 18 | video on [youtube](https://www.youtube.com/watch?v=aLW1YQrT-2A) or [bilibili](https://www.bilibili.com/video/BV1Ck4y1d7tx) 19 | 20 | ## save/load 21 | 22 | * Use `classifier.save(path)` to save trained data 23 | * load by `KPU.classifier.load()`, refer to [self_learning_classifier_load.py](self_learning_classifier_load.py) 24 | 25 | -------------------------------------------------------------------------------- /machine_vision/self_learning_classifier/self_learning_classifier_load.py: -------------------------------------------------------------------------------- 1 | import KPU as kpu 2 | import sensor 3 | import lcd 4 | import gc 5 | 6 | ############### config ################# 7 | saved_path = "3_classes.classifier" 8 | THRESHOLD = 11 9 | class_names = ['class1', 'class2', 'class3'] 10 | ######################################## 11 | 12 | def draw_string(img, x, y, text, color, scale, bg=None ): 13 | if bg: 14 | img.draw_rectangle(x-2,y-2, len(text)*8*scale+4 , 16*scale, fill=True, color=bg) 15 | img = img.draw_string(x, y, text, color=color,scale=scale) 16 | return img 17 | 18 | 19 | lcd.init() 20 | sensor.reset() 21 | sensor.set_pixformat(sensor.RGB565) 22 | sensor.set_framesize(sensor.QVGA) 23 | sensor.set_windowing((224, 224)) 24 | 25 | try: 26 | del model 27 | except Exception: 28 | pass 29 | try: 30 | del classifier 31 | except Exception: 32 | pass 33 | gc.collect() 34 | model = kpu.load(0x300000) 35 | classifier, class_num, sample_num = kpu.classifier.load(model, saved_path) 36 | 37 | while 1: 38 | img = sensor.snapshot() 39 | res_index = -1 40 | try: 41 | res_index, min_dist = classifier.predict(img) 42 | print("{:.2f}".format(min_dist)) 43 | except Exception as e: 44 | print("predict err:", e) 45 | if res_index >= 0 and min_dist < THRESHOLD : 46 | print("predict result:", class_names[res_index]) 47 | img = draw_string(img, 2, 2, class_names[res_index], color=lcd.WHITE,scale=2, bg=lcd.RED) 48 | else: 49 | print("unknown, maybe:", class_names[res_index]) 50 | img = draw_string(img, 2, 2, 'maybe {}'.format(class_names[res_index]), color=lcd.WHITE,scale=2, bg=lcd.RED) 51 | lcd.display(img) 52 | -------------------------------------------------------------------------------- /machine_vision/yolov2_20class.py: -------------------------------------------------------------------------------- 1 | #refer to http://blog.sipeed.com/p/677.html 2 | import sensor,image,lcd,time 3 | import KPU as kpu 4 | 5 | lcd.init(freq=15000000) 6 | sensor.reset() 7 | sensor.set_pixformat(sensor.RGB565) 8 | sensor.set_framesize(sensor.QVGA) 9 | sensor.set_vflip(1) 10 | sensor.run(1) 11 | clock = time.clock() 12 | classes = ['aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor'] 13 | task = kpu.load(0x500000) 14 | anchor = (1.08, 1.19, 3.42, 4.41, 6.63, 11.38, 9.42, 5.11, 16.62, 10.52) 15 | a = kpu.init_yolo2(task, 0.5, 0.3, 5, anchor) 16 | while(True): 17 | clock.tick() 18 | img = sensor.snapshot() 19 | code = kpu.run_yolo2(task, img) 20 | print(clock.fps()) 21 | if code: 22 | for i in code: 23 | a=img.draw_rectangle(i.rect()) 24 | img.draw_string(i.x(), i.y(), classes[i.classid()], color=(255, 0, 0), scale=2) 25 | img.draw_string(i.x(), i.y()+24, '%.3f'%i.value(), color=(255, 0, 0), scale=2) 26 | a = lcd.display(img) 27 | else: 28 | a = lcd.display(img) 29 | a = kpu.deinit(task) 30 | -------------------------------------------------------------------------------- /modules/grove/chainable_RGB_LED/README.md: -------------------------------------------------------------------------------- 1 | Grove chainable RGB LED 2 | ============ 3 | 4 | 5 | 6 | 7 | More info see :[seeed studio wiki](http://wiki.seeedstudio.com/Grove-Chainable_RGB_LED/) 8 | 9 | ## Examples 10 | 11 | 12 | Send `RGB_LED.py` to board by `MaixPy IDE` or `upyloader` first, or just merge `RGB_LED.py` and example file to one file 13 | 14 | * [breath](breath.py) 15 | * [fade_inout](fade_inout.py) 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /modules/grove/chainable_RGB_LED/RGB_LED.py: -------------------------------------------------------------------------------- 1 | 2 | from fpioa_manager import * 3 | from Maix import GPIO 4 | import time 5 | 6 | class RGB_LED: 7 | def __init__(self, clk, data, number_leds, clk_gpiohs=fm.fpioa.GPIOHS0, data_gpiohs=fm.fpioa.GPIOHS1, force_register_io = False ): 8 | if force_register_io: 9 | fm.register(clk, clk_gpiohs, force=True) 10 | fm.register(data, data_gpiohs, force=True) 11 | else: 12 | ret = fm.register(clk, clk_gpiohs, force=False) 13 | if ret != 1: 14 | raise ValueError("pin %d has been registered to func %d" %(ret[0], ret[1])) 15 | ret = fm.register(data, data_gpiohs, force=False) 16 | if ret != 1: 17 | raise ValueError("pin %d has been registered to func %d" %(ret[0], ret[1])) 18 | self.clk = GPIO(GPIO.GPIOHS0+clk_gpiohs-fm.fpioa.GPIOHS0, GPIO.OUT) 19 | self.data = GPIO(GPIO.GPIOHS0+data_gpiohs-fm.fpioa.GPIOHS0, GPIO.OUT) 20 | self.clk.value(1) 21 | self.data.value(0) 22 | self.status = [] 23 | for i in range(number_leds): 24 | self.status.append([0,0,0]) 25 | 26 | def check_RGB(self, value): 27 | if not value in range(0,256): 28 | raise ValueError("value: [0, 255]") 29 | 30 | def check_HSB(self, value): 31 | if not value in range(0.0,1.0): 32 | raise ValueError("value: [0, 1]") 33 | 34 | # red, green, blue 35 | def set_RGB(self, led, r, g, b): 36 | self.check_RGB(r) 37 | self.check_RGB(g) 38 | self.check_RGB(b) 39 | 40 | self.send_byte(0x00) 41 | self.send_byte(0x00) 42 | self.send_byte(0x00) 43 | self.send_byte(0x00) 44 | for i in range(len(self.status)): 45 | if i == led: 46 | self.status[i]=[r, g, b] 47 | self.send_color(self.status[i][0], self.status[i][1], self.status[i][2]) 48 | self.send_byte(0x00) 49 | self.send_byte(0x00) 50 | self.send_byte(0x00) 51 | self.send_byte(0x00) 52 | 53 | # hue, saturation, brightness 54 | def set_HSB(self, led, h, s, b): 55 | self.check_HSB(h) 56 | self.check_HSB(s) 57 | self.check_HSB(b) 58 | if s == 0: 59 | r = b 60 | g = b 61 | b = b 62 | else: 63 | q = b*(1.0+s) if b<0.5 else b+s-b*s 64 | p = 2.0 * b -q 65 | r = int(self.hue_to_rgb(p, q, h + 1/3)) & 0xFF 66 | g = int(self.hue_to_rgb(p, q, hue)) & 0xFF 67 | b = int(self.hue_to_rgb(p, q, hue - 1/3)) & 0xFF 68 | 69 | self.set_RGB(led, r, g, b) 70 | 71 | def send_byte(self, data): 72 | for i in range(8): 73 | if data & 0x80: 74 | self.data.value(1) 75 | else: 76 | self.data.value(0) 77 | self.write_clk() 78 | data <<= 1 79 | 80 | def write_clk(self): 81 | self.clk.value(0) 82 | time.sleep_us(20) 83 | self.clk.value(1) 84 | time.sleep_us(20) 85 | 86 | def send_color(self, r, g, b): 87 | prefix = 0xC0 88 | if (b & 0x80) == 0: 89 | prefix |= 0x20 90 | if (b & 0x40) == 0: 91 | prefix |= 0x10 92 | if (g & 0x80) == 0: 93 | prefix |= 0x08 94 | if (g & 0x40) == 0: 95 | prefix |= 0x04 96 | if (r & 0x80) == 0: 97 | prefix |= 0x02 98 | if (r & 0x40) == 0: 99 | prefix |= 0x01 100 | self.send_byte(prefix) 101 | self.send_byte(b) 102 | self.send_byte(g) 103 | self.send_byte(r) 104 | 105 | def hue_to_rgb(self, p, q, t): 106 | if t < 0: 107 | t += 1 108 | if t > 1: 109 | t -= 1 110 | if t < 1/6: 111 | return p + (q - p) * 6.0 * t 112 | if t < 1/2: 113 | return q 114 | if t < 2/3: 115 | return p + (q - p) * (2/3 - t) * 6 116 | return p 117 | 118 | 119 | 120 | -------------------------------------------------------------------------------- /modules/grove/chainable_RGB_LED/assets/grove_rgb_led.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sipeed/MaixPy-v1_scripts/8d7c5f98ba654d226f433d31718d852674cab08d/modules/grove/chainable_RGB_LED/assets/grove_rgb_led.jpg -------------------------------------------------------------------------------- /modules/grove/chainable_RGB_LED/assets/grove_rgb_led2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sipeed/MaixPy-v1_scripts/8d7c5f98ba654d226f433d31718d852674cab08d/modules/grove/chainable_RGB_LED/assets/grove_rgb_led2.jpg -------------------------------------------------------------------------------- /modules/grove/chainable_RGB_LED/breath.py: -------------------------------------------------------------------------------- 1 | 2 | from fpioa_manager import * 3 | from Maix import GPIO 4 | import time 5 | from RGB_LED import RGB_LED 6 | 7 | 8 | led_num = 1 # LED number 9 | clk_pin = 21 # board_info.D[2] # Maixduino D2 10 | data_pin = 22 # board_info.D[3] # Maixduino D3 11 | 12 | clk_gpiohs_num = fm.fpioa.GPIOHS0 13 | data_gpiohs_num = fm.fpioa.GPIOHS1 14 | 15 | led = RGB_LED(clk_pin, data_pin, led_num, clk_gpiohs_num, data_gpiohs_num, True) 16 | 17 | 18 | r = 0 19 | g = 0 20 | b = 0 21 | dir = 0 22 | while True: 23 | if dir == 0: 24 | if r < 255: 25 | r += 1 26 | elif g < 255: 27 | g += 1 28 | elif b < 255: 29 | b += 1 30 | else: 31 | dir = 1 32 | else: 33 | if b > 0: 34 | b -= 1 35 | elif g > 0: 36 | g -= 1 37 | elif r > 0: 38 | r -= 1 39 | else: 40 | dir = 0 41 | 42 | for i in range(led_num): 43 | led.set_RGB(i, r, g, b) 44 | time.sleep_ms(1) 45 | 46 | 47 | -------------------------------------------------------------------------------- /modules/grove/chainable_RGB_LED/fade_inout.py: -------------------------------------------------------------------------------- 1 | 2 | from fpioa_manager import * 3 | from Maix import GPIO 4 | import time 5 | from RGB_LED import RGB_LED 6 | 7 | 8 | led_num = 5 # LED number 9 | clk_pin = 21 # borad_info.D[2] # Maixduino D2 10 | data_pin = 22 # borad_info.D[3] # Maixduino D3 11 | 12 | clk_gpiohs_num = 0 13 | data_gpiohs_num = 1 14 | 15 | led = RGB_LED(clk_pin, data_pin, led_num, clk_gpiohs_num, data_gpiohs_num, force_register_io=True) 16 | 17 | r = 0 18 | g = 0 19 | b = 0 20 | power = 0 21 | while True: 22 | 23 | 24 | for i in range(led_num): 25 | if i%2 == 0: 26 | r = power 27 | g = 0 28 | b = 0 29 | else: 30 | r = 0 31 | g = 255 - power 32 | b = 0 33 | led.set_RGB(i, r, g, b) 34 | power = (power + 10) & 0xFF 35 | time.sleep_ms(10) 36 | 37 | -------------------------------------------------------------------------------- /modules/grove/ultrasonic/README.md: -------------------------------------------------------------------------------- 1 | Grove Ultrasonic Ranger 2 | ======= 3 | 4 | 5 | 6 | 7 | More info see [Seeed Studio Wiki](http://wiki.seeedstudio.com/Grove-Ultrasonic_Ranger/) 8 | 9 | ## Examples 10 | 11 | * [measure](./measure.py) 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /modules/grove/ultrasonic/assets/ultrasonic.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sipeed/MaixPy-v1_scripts/8d7c5f98ba654d226f433d31718d852674cab08d/modules/grove/ultrasonic/assets/ultrasonic.jpg -------------------------------------------------------------------------------- /modules/grove/ultrasonic/assets/ultrasonic2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sipeed/MaixPy-v1_scripts/8d7c5f98ba654d226f433d31718d852674cab08d/modules/grove/ultrasonic/assets/ultrasonic2.jpg -------------------------------------------------------------------------------- /modules/grove/ultrasonic/measure.py: -------------------------------------------------------------------------------- 1 | 2 | from fpioa_manager import * 3 | from modules import ultrasonic 4 | import time 5 | from board import board_info 6 | 7 | fm.register(board_info.D[6], fm.fpioa.GPIOHS0, force = True) 8 | 9 | device = ultrasonic(fm.fpioa.GPIOHS0) 10 | 11 | while True: 12 | distance = device.measure(unit = ultrasonic.UNIT_CM, timeout = 3000000) 13 | print(distance) 14 | time.sleep_ms(100) 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /modules/grove/ws2812/ws2812.py: -------------------------------------------------------------------------------- 1 | from modules import ws2812 2 | 3 | # test maix cube grove ws2813 24 4 | led_io, led_num = 24, 24 5 | 6 | ws = ws2812(led_io, led_num) 7 | 8 | for i in range(led_num): 9 | ws.set_led(i, (0, 0, 0)) 10 | ws.display() 11 | 12 | import time, math 13 | value = 0 14 | while True: 15 | value += 1 16 | for i in range(value, value + led_num): 17 | ws.set_led(i % led_num, (value + i, value + i, value + i)) 18 | ws.display() 19 | time.sleep_ms(10) 20 | -------------------------------------------------------------------------------- /modules/others/OLED/ssd1306/README.md: -------------------------------------------------------------------------------- 1 | SSD 1306 OLED 2 | ======= 3 | 4 | 5 | ![](oled.png) 6 | 7 | 8 | -------------------------------------------------------------------------------- /modules/others/OLED/ssd1306/main.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 实验名称:I2C总线(OLED显示屏) 3 | 版本:v1.0 4 | 日期:2019.12 5 | 作者:01Studio 6 | 实验内容:学习使用MicroPython的I2C总线通讯编程和OLED显示屏的使用。 7 | ''' 8 | 9 | from machine import I2C 10 | from ssd1306k import SSD1306 11 | 12 | #定义I2C接口和OLED对象 13 | i2c = I2C(I2C.I2C0, mode=I2C.MODE_MASTER,scl=27, sda=28) 14 | oled = SSD1306(i2c, addr=0x3c) 15 | 16 | #清屏,0x00(白屏),0xff(黑屏) 17 | oled.fill(0) 18 | 19 | 20 | #显示字符。参数格式为(str,x,y),其中x范围是0-127,y范围是0-7(共8行) 21 | oled.text("Hello World!", 0, 0) #写入第 0 行内容 22 | oled.text("MicroPython", 0, 2) #写入第 2 行内容 23 | oled.text("By 01Studio", 0, 5) #写入第 5 行内容 24 | -------------------------------------------------------------------------------- /modules/others/OLED/ssd1306/oled.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sipeed/MaixPy-v1_scripts/8d7c5f98ba654d226f433d31718d852674cab08d/modules/others/OLED/ssd1306/oled.png -------------------------------------------------------------------------------- /modules/others/Servo/Servo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sipeed/MaixPy-v1_scripts/8d7c5f98ba654d226f433d31718d852674cab08d/modules/others/Servo/Servo.png -------------------------------------------------------------------------------- /modules/others/Servo/Servo.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 实验名称:舵机控制(Servo Control) 3 | 版本:v1.0 4 | 日期:2019.12 5 | 作者:01Studio 【www.01Studio.org】 6 | 说明:通过编程控制舵机旋转到不同角度 7 | ''' 8 | 9 | from machine import Timer,PWM 10 | import time 11 | 12 | #PWM通过定时器配置,接到IO17引脚(Pin IO17) 13 | tim = Timer(Timer.TIMER0, Timer.CHANNEL0, mode=Timer.MODE_PWM) 14 | S1 = PWM(tim, freq=50, duty=0, pin=17) 15 | 16 | ''' 17 | 说明:舵机控制函数 18 | 功能:180度舵机:angle:-90至90 表示相应的角度 19 | 360连续旋转度舵机:angle:-90至90 旋转方向和速度值。 20 | 【duty】占空比值:0-100 21 | ''' 22 | 23 | def Servo(servo,angle): 24 | S1.duty((angle+90)/180*10+2.5) 25 | 26 | 27 | while True: 28 | #-90度 29 | Servo(S1,-90) 30 | time.sleep(1) 31 | 32 | #-45度 33 | Servo(S1,-45) 34 | time.sleep(1) 35 | 36 | #0度 37 | Servo(S1,0) 38 | time.sleep(1) 39 | 40 | #45度 41 | Servo(S1,45) 42 | time.sleep(1) 43 | 44 | #90度 45 | Servo(S1,90) 46 | time.sleep(1) 47 | -------------------------------------------------------------------------------- /modules/others/adxl345/adxl345.py: -------------------------------------------------------------------------------- 1 | # ADXL345 Python library for Raspberry Pi 2 | # 3 | # author: Jonathan Williamson 4 | # license: BSD, see LICENSE.txt included in this package 5 | # 6 | # This is a Raspberry Pi Python implementation to help you get started with 7 | # the Adafruit Triple Axis ADXL345 breakout board: 8 | # http://shop.pimoroni.com/products/adafruit-triple-axis-accelerometer 9 | 10 | from time import sleep 11 | import ustruct 12 | # ADXL345 constants 13 | EARTH_GRAVITY_MS2 = 9.80665 14 | SCALE_MULTIPLIER = 0.004 15 | 16 | DATA_FORMAT = 0x31 17 | BW_RATE = 0x2C 18 | POWER_CTL = 0x2D 19 | 20 | BW_RATE_1600HZ = 0x0F 21 | BW_RATE_800HZ = 0x0E 22 | BW_RATE_400HZ = 0x0D 23 | BW_RATE_200HZ = 0x0C 24 | BW_RATE_100HZ = 0x0B 25 | BW_RATE_50HZ = 0x0A 26 | BW_RATE_25HZ = 0x09 27 | 28 | RANGE_2G = 0x00 29 | RANGE_4G = 0x01 30 | RANGE_8G = 0x02 31 | RANGE_16G = 0x03 32 | 33 | MEASURE = 0x08 34 | AXES_DATA = 0x32 35 | 36 | class ADXL345: 37 | 38 | address = None 39 | 40 | def __init__(self, i2c = None, address = 0x53): 41 | self.address = address 42 | self.bus = i2c 43 | self.setBandwidthRate(BW_RATE_100HZ) 44 | self.setRange(RANGE_8G) 45 | self.enableMeasurement() 46 | 47 | def enableMeasurement(self): 48 | self.bus.writeto_mem(self.address, POWER_CTL, MEASURE) 49 | 50 | def setBandwidthRate(self, rate_flag): 51 | self.bus.writeto_mem(self.address, BW_RATE, rate_flag) 52 | 53 | # set the measurement range for 10-bit readings 54 | def setRange(self, range_flag): 55 | bs = self.bus.readfrom_mem(self.address, DATA_FORMAT, 1) 56 | value = ustruct.unpack('= lcd_w/2: 55 | x = max_temp_pos[0] - 80 56 | else: 57 | x = max_temp_pos[0] + 4 58 | img2 = img2.draw_rectangle(x, max_temp_pos[1], 80, 22, color=(0xff,112,0xff), fill=True) 59 | img2 = img2.draw_string(x, max_temp_pos[1], "%.2f" %(max/100.0), color=(0xff,0xff,0xff), scale=2) 60 | img2 = img2.draw_cross(max_temp_pos[0], max_temp_pos[1], color=(0xff,0xff,0xff), thickness=3) 61 | lcd.display(img2) 62 | del img2 63 | print(clock.fps()) 64 | except Exception as e: 65 | print(e) 66 | -------------------------------------------------------------------------------- /modules/others/heimann_HTPA_32x32/README.md: -------------------------------------------------------------------------------- 1 | # Heimann HTPA32x32d 2 | 3 | Notice: the official firmware is matching for `HTPA32x32dR1L7_0HiSi_Gain3k3` sensor model, if you are using other different type of sensor, just replace the table in `htpa_table_32x32d.c` [file](https://github.com/sipeed/MaixPy/blob/master/components/drivers/htpa/src/htpa_table_32x32d.c) and rebuild the firmware. 4 | 5 | The other type of HTPA sensor's table [here](modules\heimann_HTPA_32x32\Table.c). 6 | -------------------------------------------------------------------------------- /modules/others/pca9685/pca9685.py: -------------------------------------------------------------------------------- 1 | import utime 2 | from machine import I2C 3 | 4 | i2c = I2C(I2C.I2C0,freq=100000, scl=28, sda=29) 5 | #scl和sda看自己具体插哪里而更改的 6 | 7 | def pca_setfreq(freqs): 8 | freqs *= 0.92 9 | prescaleval = 25000000 10 | prescaleval /= 4096 11 | prescaleval /= freqs 12 | prescaleval -= 1 13 | prescale =int(prescaleval + 0.5) 14 | 15 | oldmode = i2c.readfrom_mem(0x40,0x00,8) 16 | 17 | newmode = (oldmode[0]&0x7F) | 0x10 #sleep 18 | 19 | i2c.writeto_mem(0x40,0x00,newmode) #go to sleep 20 | 21 | i2c.writeto_mem(0x40,0xFE, prescale) #set the prescaler 22 | 23 | i2c.writeto_mem(0x40,0x00, oldmode) 24 | utime.sleep_ms(2) 25 | 26 | i2c.writeto_mem(0x40,0x00, oldmode[0]|0xa1) 27 | 28 | def pca_setpwm(num,on,off): 29 | i2c.writeto_mem(0x40,0x06+4*num,on) 30 | i2c.writeto_mem(0x40,0x07+4*num,on>>8) 31 | i2c.writeto_mem(0x40,0x08+4*num,off) 32 | i2c.writeto_mem(0x40,0x09+4*num,off>>8) 33 | 34 | def pca_init(hz,angle): #初始化函数 35 | off = 0 36 | i2c.writeto_mem(0x40,0x00,0x0) 37 | pca_setfreq(hz) 38 | off = int(145+angle*2.4) 39 | pca_setpwm(0,0,off) 40 | #pca_setpwm(1,0,off) 41 | #pca_setpwm(2,0,off) 42 | #pca_setpwm(3,0,off) 43 | #pca_setpwm(4,0,off) 44 | #pca_setpwm(5,0,off) 45 | #pca_setpwm(6,0,off) 46 | #pca_setpwm(7,0,off) 47 | #pca_setpwm(8,0,off) 48 | #pca_setpwm(9,0,off) 49 | #pca_setpwm(10,0,off) 50 | #pca_setpwm(11,0,off) 51 | #pca_setpwm(12,0,off) 52 | #pca_setpwm(13,0,off) 53 | #pca_setpwm(14,0,off) 54 | #pca_setpwm(15,0,off) 55 | utime.sleep_ms(500) 56 | 57 | def pca_mg90(num,start_angle,end_angle,mode,speed): 58 | off = 0 59 | if mode==0: 60 | off=int(158+end_angle*2.2) 61 | pca_setpwm(num,0,off) 62 | elif mode==1: 63 | off=int(158+end_angle*2.2) 64 | pca_setpwm(num,0,off) 65 | #未完待续 66 | 67 | pca_init(50,60) 68 | -------------------------------------------------------------------------------- /modules/spmod/sp_bt/demo_sp_bt.py: -------------------------------------------------------------------------------- 1 | # Phenomenon: Send back received data 2 | # DATE: 2020-12-3 3 | 4 | from machine import UART 5 | from fpioa_manager import fm 6 | import time 7 | 8 | name = "MAIXCUBE" 9 | 10 | def set_name(uart, name): 11 | for i in range(200): 12 | # change the name to MAIXCUBE 13 | uart.write("AT+NAME{}\r\n".format(name)) 14 | time.sleep_ms(200) 15 | read_data = uart.read() 16 | if read_data: 17 | read_str = read_data.decode('utf-8') 18 | count = read_str.count("OK") 19 | if count != 0: 20 | print("set success") 21 | break 22 | 23 | if __name__ == "__main__": 24 | ############# config ############### 25 | TX = 7 26 | RX = 6 27 | ################################### 28 | 29 | # set uart rx/tx func to io_6/7 30 | fm.register(TX, fm.fpioa.UART1_TX) 31 | fm.register(RX, fm.fpioa.UART1_RX) 32 | # init uart 33 | uart = UART(UART.UART1, 9600, 8, 1, 0, timeout=1000, read_buf_len=4096) 34 | 35 | set_name(uart, name) 36 | print("wait data: ") 37 | while True: 38 | read_data = uart.read() 39 | if read_data: 40 | print("recv:", read_data) 41 | uart.write(read_data) # send data back 42 | print("wait data: ") 43 | 44 | -------------------------------------------------------------------------------- /modules/spmod/sp_ethernet/demo_ethernet_tcp.py: -------------------------------------------------------------------------------- 1 | import network, socket, time 2 | from machine import SPI 3 | from Maix import GPIO 4 | from fpioa_manager import fm 5 | 6 | ################ config ################ 7 | server_ip = "192.168.0.141" 8 | server_port = 8000 9 | 10 | WIZNET5K_SPI_SCK = 21 11 | WIZNET5K_SPI_MOSI = 8 12 | WIZNET5K_SPI_MISO = 15 13 | WIZNET5K_SPI_CS = 20 14 | ####################################### 15 | 16 | addr = (server_ip, server_port) 17 | spi1 = SPI(4, mode=SPI.MODE_MASTER, baudrate=600 * 1000, 18 | polarity=0, phase=0, bits=8, firstbit=SPI.MSB, sck=WIZNET5K_SPI_SCK, mosi=WIZNET5K_SPI_MOSI, miso = WIZNET5K_SPI_MISO) 19 | 20 | # create wiznet5k nic 21 | nic = network.WIZNET5K(spi = spi1, cs = WIZNET5K_SPI_CS) 22 | print("Static IP: ", nic.ifconfig()) 23 | 24 | 25 | ############################## TCP Test ############################## 26 | # The TCP server needs to be pre-started 27 | sock = socket.socket() 28 | sock.connect(addr) 29 | while 1: 30 | sock.send("Client send: Hello TCP\n") 31 | try: 32 | data = sock.recv(10) 33 | print("Recv from Server: ", data) 34 | except Exception as e: 35 | print(e) 36 | time.sleep(500) 37 | sock.close() 38 | ############################ TCP Test end ############################ -------------------------------------------------------------------------------- /modules/spmod/sp_ethernet/demo_ethernet_udp.py: -------------------------------------------------------------------------------- 1 | import network, socket, time 2 | from machine import SPI 3 | from Maix import GPIO 4 | from fpioa_manager import fm 5 | 6 | ################ config ################ 7 | server_ip = "192.168.0.141" 8 | server_port = 8000 9 | 10 | WIZNET5K_SPI_SCK = 21 11 | WIZNET5K_SPI_MOSI = 8 12 | WIZNET5K_SPI_MISO = 15 13 | WIZNET5K_SPI_CS = 20 14 | ####################################### 15 | 16 | addr = (server_ip, server_port) 17 | spi1 = SPI(4, mode=SPI.MODE_MASTER, baudrate=600 * 1000, 18 | polarity=0, phase=0, bits=8, firstbit=SPI.MSB, sck=WIZNET5K_SPI_SCK, mosi=WIZNET5K_SPI_MOSI, miso = WIZNET5K_SPI_MISO) 19 | 20 | # create wiznet5k nic 21 | nic = network.WIZNET5K(spi = spi1, cs = WIZNET5K_SPI_CS) 22 | print("Static IP: ", nic.ifconfig()) 23 | 24 | ############################# UDP Test ############################## 25 | # The server must first know the client's IP and port number through the message sent by the client before it send the message to the client 26 | sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 27 | sock.settimeout(5) 28 | 29 | while True: 30 | sock.sendto("Client send: hello UDP\n".encode(),addr) 31 | try: 32 | data, addr1 = sock.recvfrom(10) 33 | print("Recv from server: ", data) 34 | except Exception as e: 35 | pass 36 | time.sleep_ms(500) 37 | sock.close() 38 | ########################### UDP Test end ############################ -------------------------------------------------------------------------------- /multimedia/audio/6.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sipeed/MaixPy-v1_scripts/8d7c5f98ba654d226f433d31718d852674cab08d/multimedia/audio/6.wav -------------------------------------------------------------------------------- /multimedia/audio/play_wav.py: -------------------------------------------------------------------------------- 1 | from fpioa_manager import * 2 | from Maix import I2S, GPIO 3 | import audio 4 | 5 | ########### settings ############ 6 | WIFI_EN_PIN = 8 7 | # AUDIO_PA_EN_PIN = None # Bit Dock and old MaixGo 8 | AUDIO_PA_EN_PIN = 32 # Maix Go(version 2.20) 9 | # AUDIO_PA_EN_PIN = 2 # Maixduino 10 | 11 | 12 | # disable wifi 13 | fm.register(WIFI_EN_PIN, fm.fpioa.GPIO0, force=True) 14 | wifi_en = GPIO(GPIO.GPIO0, GPIO.OUT) 15 | wifi_en.value(0) 16 | 17 | # open audio PA 18 | if AUDIO_PA_EN_PIN: 19 | fm.register(AUDIO_PA_EN_PIN, fm.fpioa.GPIO1, force=True) 20 | wifi_en = GPIO(GPIO.GPIO1, GPIO.OUT) 21 | wifi_en.value(1) 22 | 23 | # register i2s(i2s0) pin 24 | fm.register(34, fm.fpioa.I2S0_OUT_D1, force=True) 25 | fm.register(35, fm.fpioa.I2S0_SCLK, force=True) 26 | fm.register(33, fm.fpioa.I2S0_WS, force=True) 27 | 28 | # init i2s(i2s0) 29 | wav_dev = I2S(I2S.DEVICE_0) 30 | 31 | # init audio 32 | player = audio.Audio(path="/sd/6.wav") 33 | player.volume(40) 34 | 35 | # read audio info 36 | wav_info = player.play_process(wav_dev) 37 | print("wav file head information: ", wav_info) 38 | 39 | # config i2s according to audio info 40 | wav_dev.channel_config(wav_dev.CHANNEL_1, I2S.TRANSMITTER, resolution=I2S.RESOLUTION_16_BIT, 41 | cycles=I2S.SCLK_CYCLES_32, align_mode=I2S.RIGHT_JUSTIFYING_MODE) 42 | wav_dev.set_sample_rate(wav_info[1]) 43 | 44 | # loop to play audio 45 | while True: 46 | ret = player.play() 47 | if ret == None: 48 | print("format error") 49 | break 50 | elif ret == 0: 51 | print("end") 52 | break 53 | player.finish() 54 | -------------------------------------------------------------------------------- /multimedia/audio/record_play.py: -------------------------------------------------------------------------------- 1 | from Maix import GPIO, I2S 2 | import image, lcd, math 3 | import audio 4 | from fpioa_manager import fm 5 | 6 | # maixduino: 7 | maixduino = True 8 | if maixduino: 9 | fm.fpioa.set_function(2, fm.fpioa.GPIO0) 10 | pa=GPIO(GPIO.GPIO0,GPIO.OUT) 11 | pa.value(1) 12 | 13 | sample_rate = 22050 14 | sample_points = 1024 15 | 16 | rx = I2S(I2S.DEVICE_0) 17 | rx.channel_config(I2S.CHANNEL_0, rx.RECEIVER, resolution = I2S.RESOLUTION_16_BIT, cycles = I2S.SCLK_CYCLES_32, align_mode = I2S.STANDARD_MODE) 18 | rx.set_sample_rate(sample_rate) 19 | 20 | fm.fpioa.set_function(pin=20, func=fm.fpioa.I2S0_IN_D0) 21 | fm.fpioa.set_function(pin=19, func=fm.fpioa.I2S0_WS) 22 | fm.fpioa.set_function(pin=18, func=fm.fpioa.I2S0_SCLK) 23 | 24 | tx = I2S(I2S.DEVICE_2) 25 | 26 | tx.channel_config(I2S.CHANNEL_1, I2S.TRANSMITTER, resolution = I2S.RESOLUTION_16_BIT, cycles = I2S.SCLK_CYCLES_32, align_mode = I2S.RIGHT_JUSTIFYING_MODE) 27 | tx.set_sample_rate(sample_rate) 28 | 29 | fm.fpioa.set_function(pin=34, func=fm.fpioa.I2S2_OUT_D1) 30 | fm.fpioa.set_function(pin=35, func=fm.fpioa.I2S2_SCLK) 31 | fm.fpioa.set_function(pin=33, func=fm.fpioa.I2S2_WS) 32 | 33 | while True: 34 | tx.play(rx.record(sample_points)) 35 | -------------------------------------------------------------------------------- /multimedia/audio/record_wav.py: -------------------------------------------------------------------------------- 1 | import image, lcd, time 2 | import audio 3 | from Maix import GPIO, I2S 4 | from fpioa_manager import fm 5 | 6 | # user setting 7 | sample_rate = 16000 8 | record_time = 4 #s 9 | # default seting 10 | sample_points = 2048 11 | wav_ch = 2 12 | 13 | fm.register(8, fm.fpioa.GPIO0, force=True) 14 | wifi_en = GPIO(GPIO.GPIO0, GPIO.OUT) 15 | wifi_en.value(0) 16 | 17 | fm.register(20,fm.fpioa.I2S0_IN_D0, force=True) 18 | fm.register(19,fm.fpioa.I2S0_WS, force=True) # 19 on Go Board and Bit(new version) 19 | fm.register(18,fm.fpioa.I2S0_SCLK, force=True) # 18 on Go Board and Bit(new version) 20 | 21 | rx = I2S(I2S.DEVICE_0) 22 | rx.channel_config(rx.CHANNEL_0, rx.RECEIVER, align_mode=I2S.STANDARD_MODE) 23 | rx.set_sample_rate(sample_rate) 24 | print(rx) 25 | 26 | #import time 27 | # init audio 28 | recorder = audio.Audio(path="/sd/record.wav", is_create=True, samplerate=sample_rate) 29 | 30 | queue = [] 31 | 32 | frame_cnt = record_time*sample_rate//sample_points 33 | 34 | for i in range(frame_cnt): 35 | tmp = rx.record(sample_points*wav_ch) 36 | if len(queue) > 0: 37 | ret = recorder.record(queue[0]) 38 | queue.pop(0) 39 | rx.wait_record() 40 | queue.append(tmp) 41 | print(str(i) + ":" + str(time.ticks())) 42 | 43 | recorder.finish() -------------------------------------------------------------------------------- /multimedia/gui/image/anime.py: -------------------------------------------------------------------------------- 1 | 2 | import image 3 | import lcd 4 | 5 | lcd.init(freq=20000000) 6 | 7 | i = 0 8 | dir = 1 9 | 10 | while(True): 11 | img = image.Image(copy_to_fb=1) 12 | img.clear() 13 | img.draw_rectangle(i, 50, 50, 50) 14 | lcd.display(img) 15 | 16 | if dir: 17 | i += 5 18 | if i == 270: 19 | dir = 0 20 | else: 21 | i -= 5 22 | if i == 0: 23 | dir = 1 24 | -------------------------------------------------------------------------------- /multimedia/gui/image/demo_draw_circle.py: -------------------------------------------------------------------------------- 1 | import lcd 2 | import time 3 | import image 4 | 5 | bg = (236, 36, 36) 6 | lcd.init(freq=15000000) 7 | lcd.direction(lcd.YX_RLDU) 8 | 9 | img = image.Image() 10 | img.draw_string(60, 100, "hello maixpy", scale=2) 11 | img.draw_rectangle((120, 120, 30, 30)) 12 | img.draw_circle((150, 140, 80)) 13 | img.draw_cross((250, 40)) 14 | img.draw_arrow((250, 200, 20, 200), color=(236, 36, 36)) 15 | lcd.display(img) 16 | -------------------------------------------------------------------------------- /multimedia/gui/image/demo_draw_font/image_draw_font.py: -------------------------------------------------------------------------------- 1 | import lcd, time 2 | import image 3 | 4 | lcd.init(freq=15000000) 5 | ##lcd.direction(lcd.YX_RLDU) 6 | 7 | ##img = image.Image("ts.bmp") 8 | img = image.Image() 9 | # img.draw_rectangle((0,0,240,240), fill=True, color=(30,30,30)) 10 | #img.draw_string(60, 100, "hello \nmaixpy", scale=4) 11 | #img.draw_rectangle((120,120,30,30)) 12 | #img.draw_circle((150,140, 80)) 13 | #img.draw_cross((200,40)) 14 | #img.draw_arrow((200,200,20,200), color=(236,36,36)) 15 | #img.draw_image(image.Image("test.bmp"), 20, 30) 16 | 17 | # 8 * 8 18 | 19 | tmp = b'\x20\xFC\xFC\x2C\xAC\x4C\x4D\xA3' 20 | 21 | img.draw_font(10, 20, 8, 8, tmp, scale=1, color=(255, 255, 255)) 22 | img.draw_font(60, 15, 8, 8, tmp, scale=2, color=(255,0,0)) 23 | img.draw_font(110, 10, 8, 8, tmp, scale=3, color=(0,255,0)) 24 | img.draw_font(180, 2, 8, 8, tmp, scale=4, color=(0,255,0)) 25 | 26 | # It has now been removed 20200828. 27 | #img.draw_font(150, 10, 16, 8, b'\x00\x00\x00\x00\x7F\x01\x01\xFF\x00\x00\x00\x78\x80\x00\x04\xFE', scale=2, color=(0,0,255)) 28 | #img.draw_font(160, 10, 8, 16, b'\x00\x00\x00\x00\x7F\x01\x01\xFF\x01\x01\x01\x01\x01\x01\x01\x01', scale=2, color=(0,0,255)) 29 | #img.draw_font(200, 10, 8, 10, b'\x01\x02\x04\x08\x10\x20\x40\x80', scale=4, color=(0,0,255)) 30 | 31 | # 16 * 16 32 | 33 | qian = b'\x00\x00\x00\x00\x7F\x01\x01\xFF\x01\x01\x01\x01\x01\x01\x01\x01\x00\x00\x00\x78\x80\x00\x04\xFE\x00\x00\x00\x00\x00\x00\x00\x00' 34 | 35 | img.draw_font(10, 40, 16, 16, qian, scale=1, color=(255, 255, 255)) 36 | img.draw_font(10, 60, 16, 16, qian, scale=2, color=(255, 255, 255)) 37 | #img.draw_font(10, 90, 16, 16, qian, scale=3, color=(255, 255, 255)) 38 | 39 | li = b'\x00\x00\x00\x1F\x11\x11\x1F\x11\x1F\x11\x01\x01\x3F\x01\x01\xFF\x00\x00\x08\xF8\x08\x08\xF8\x08\xF8\x08\x00\x08\xFC\x00\x00\xFE' 40 | 41 | img.draw_font(60, 40, 16, 16, li, scale=1, color=(255,0,0)) 42 | img.draw_font(60, 60, 16, 16, li, scale=2, color=(255,0,0)) 43 | #img.draw_font(60, 90, 16, 16, li, scale=3, color=(255,0,0)) 44 | 45 | zhi = b'\x00\x00\x02\x01\x01\x7F\x00\x00\x00\x00\x01\x06\x08\x30\x4C\x03\x00\x00\x00\x00\x08\xFC\x10\x20\x40\x80\x00\x00\x00\x00\x00\xFE' 46 | 47 | img.draw_font(120, 40, 16, 16, zhi, scale=1, color=(0,255,0)) 48 | img.draw_font(120, 60, 16, 16, zhi, scale=2, color=(0,255,0)) 49 | #img.draw_font(120, 90, 16, 16, zhi, scale=3, color=(0,255,0)) 50 | 51 | wai = b'\x00\x00\x04\x08\x08\x0F\x11\x11\x29\x26\x42\x04\x04\x08\x10\x20\x00\x00\x20\x20\x20\xA0\x20\x38\x24\x22\x20\x20\x20\x20\x20\x20' 52 | 53 | img.draw_font(180, 40, 16, 16, wai, scale=1, color=(0,0,255)) 54 | img.draw_font(180, 60, 16, 16, wai, scale=2, color=(0,0,255)) 55 | #img.draw_font(180, 90, 16, 16, wai, scale=3, color=(0,0,255)) 56 | 57 | # 32 * 32 58 | 59 | zhi = b'\x00\x00\x00\x00\x00\x03\xFF\x38\x1C\xFF\x00\x7F\x60\x7F\x60\x7F\x61\x00\x30\xFE\x4C\xFE\x00\xFE\xFE\xC6\xFE\xC6\xFC\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFE\x38\x60\xFE\x00\xFC\x0C\xFC\x0C\xFC\xF8\xC0\xFE\xC0\xFC\xFD\xC4\xFC\xC0\xFC\xFE\xC6\xFC\x00\x00\x00\x00\x00\x00\x00\x00\xC0\xFF\xC0\xFF\xFF\xC0\xFF\xC0\xFF\xC0\xFF\x7F\x20\x30\xFC\xCC\xFE\x00\xFC\xFC\x8C\xFC\x8C\xBC\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFC\x00\xF8\xF8\x00\xF8\x00\xF8\x0C\xFC\xF8\x80\xFC\x80\xFC\xFC\x80\xFC\x80\xFC\xFE\x86\xFC\x00\x00\x00' 60 | 61 | img.draw_font(20, 100, 32, 32, zhi, scale=1, color=(0,255,0)) 62 | img.draw_font(60, 90, 32, 32, zhi, scale=2, color=(0,255,0)) 63 | img.draw_font(20, 140, 32, 32, zhi, scale=3, color=(0,255,0)) 64 | 65 | wai = b'\x00\x00\x00\x00\x00\x03\x0F\x3C\xF0\x8C\x47\xC7\x7E\xF8\xEC\x8E\x06\x1F\xFB\xC3\x03\x0F\x3D\xF1\xC1\x01\x03\x7F\x7E\x00\x00\x00\x00\x00\x00\x00\x00\x00\x3F\x30\x3F\x30\xFF\xB0\x3F\x30\x0E\x1F\x38\x7F\x78\x1F\x98\x9F\x98\x9F\x87\x81\x00\xFF\x7C\x00\x00\x00\x00\x00\x00\x00\x00\x00\xE7\x66\xE7\x66\xE7\x66\xE7\x7E\x0C\xFF\x0C\xFF\x0C\xFF\x0C\xFF\x00\xFF\x00\xE3\x7E\xE7\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFC\x0C\xFC\x0C\xFC\x0C\xFC\x0C\x00\xFC\x00\xF8\x00\xF8\x00\xFE\x00\xF0\x70\xC0\x00\xFE\x1E\x00\x00\x00' 66 | 67 | img.draw_font(130, 100, 32, 32, wai, scale=1, color=(0,0,255)) 68 | img.draw_font(170, 90, 32, 32, wai, scale=2, color=(0,0,255)) 69 | img.draw_font(130, 140, 32, 32, wai, scale=3, color=(0,0,255)) 70 | 71 | # 64 * 64 give up 72 | 73 | lcd.display(img) 74 | -------------------------------------------------------------------------------- /multimedia/gui/image/demo_draw_font/image_draw_string.py: -------------------------------------------------------------------------------- 1 | import lcd, image 2 | 3 | img = image.Image() 4 | 5 | #image.font_load(image.UTF8, 16, 16, '/sd/0xA00000_font_uincode_16_16_tblr.Dzk') 6 | image.font_load(image.UTF8, 16, 16, 0xA00000) 7 | 8 | img.draw_string(20, 30, b'hello world!', scale=1, color=(255,255,255), x_spacing=2, mono_space=0) 9 | 10 | img.draw_string(20, 60, b'你好,世界', scale=1, color=(0,0,255), x_spacing=2, mono_space=1) 11 | 12 | img.draw_string(20, 160, b'簡繁轉換互換', scale=2, color=(0,255,255), x_spacing=2, mono_space=1) 13 | 14 | img.draw_string(20, 90, b'こんにちは、世界', scale=1, color=(255,255,255), x_spacing=2, mono_space=1) 15 | 16 | img.draw_string(20, 120, b'안녕,세상이야.', scale=1, color=(255,0,0), x_spacing=2, mono_space=1) 17 | 18 | image.font_free() 19 | 20 | lcd.display(img) 21 | -------------------------------------------------------------------------------- /multimedia/gui/image/demo_draw_font/readme.assets/image-20200902175614964.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sipeed/MaixPy-v1_scripts/8d7c5f98ba654d226f433d31718d852674cab08d/multimedia/gui/image/demo_draw_font/readme.assets/image-20200902175614964.png -------------------------------------------------------------------------------- /multimedia/gui/image/demo_draw_font/readme.assets/image-20200902175948599.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sipeed/MaixPy-v1_scripts/8d7c5f98ba654d226f433d31718d852674cab08d/multimedia/gui/image/demo_draw_font/readme.assets/image-20200902175948599.png -------------------------------------------------------------------------------- /multimedia/gui/image/demo_draw_font/readme.assets/image-20200902180153452.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sipeed/MaixPy-v1_scripts/8d7c5f98ba654d226f433d31718d852674cab08d/multimedia/gui/image/demo_draw_font/readme.assets/image-20200902180153452.png -------------------------------------------------------------------------------- /multimedia/gui/image/demo_draw_font/readme.assets/image-20200902180505263.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sipeed/MaixPy-v1_scripts/8d7c5f98ba654d226f433d31718d852674cab08d/multimedia/gui/image/demo_draw_font/readme.assets/image-20200902180505263.png -------------------------------------------------------------------------------- /multimedia/gui/image/demo_draw_font/readme.assets/image-20200902180913322.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sipeed/MaixPy-v1_scripts/8d7c5f98ba654d226f433d31718d852674cab08d/multimedia/gui/image/demo_draw_font/readme.assets/image-20200902180913322.png -------------------------------------------------------------------------------- /multimedia/gui/image/demo_draw_font/readme.assets/image-20200902181130459.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sipeed/MaixPy-v1_scripts/8d7c5f98ba654d226f433d31718d852674cab08d/multimedia/gui/image/demo_draw_font/readme.assets/image-20200902181130459.png -------------------------------------------------------------------------------- /multimedia/gui/image/demo_draw_font/readme.assets/image-20200902181311553.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sipeed/MaixPy-v1_scripts/8d7c5f98ba654d226f433d31718d852674cab08d/multimedia/gui/image/demo_draw_font/readme.assets/image-20200902181311553.png -------------------------------------------------------------------------------- /multimedia/gui/image/demo_draw_font/readme.assets/image-20200902181442677.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sipeed/MaixPy-v1_scripts/8d7c5f98ba654d226f433d31718d852674cab08d/multimedia/gui/image/demo_draw_font/readme.assets/image-20200902181442677.png -------------------------------------------------------------------------------- /multimedia/gui/image/demo_draw_font/readme.assets/image-20200902181645277.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sipeed/MaixPy-v1_scripts/8d7c5f98ba654d226f433d31718d852674cab08d/multimedia/gui/image/demo_draw_font/readme.assets/image-20200902181645277.png -------------------------------------------------------------------------------- /multimedia/gui/image/demo_draw_font/readme.assets/view_image_font.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sipeed/MaixPy-v1_scripts/8d7c5f98ba654d226f433d31718d852674cab08d/multimedia/gui/image/demo_draw_font/readme.assets/view_image_font.jpg -------------------------------------------------------------------------------- /multimedia/gui/image/demo_draw_font/readme.md: -------------------------------------------------------------------------------- 1 | ## 如何使用 2 | 3 | 该功能接口均使用 `image.Image()` 对象完成,MaixPy 固件请使用最新版本 2020年9月2日。 4 | 5 | ### 字模接口 6 | 7 | 使用 draw_font 打印字模字符串,类似 `img.draw_font(10, 20, 8, 8, b'/x20/xFC/xFC/x2C/xAC/x4C/x4D/xA3')`。 8 | 9 | ```python 10 | import lcd, image 11 | lcd.init() 12 | img = image.Image() 13 | tmp = b'/x20/xFC/xFC/x2C/xAC/x4C/x4D/xA3' 14 | img.draw_font(10, 20, 8, 8, tmp, scale=1, color=(255, 255, 255)) 15 | lcd.display(img) 16 | ``` 17 | 18 | 范例参考 [image_draw_font.py](image_draw_font.py) 。 19 | 20 | ### 字库接口 21 | 22 | 请先使用 font_load / font_free 加载或释放字库,这将提升 draw_string 的功能,支持从 `xx.Dzk` 文件 与 Flash 地址加载,这之后后 draw_string 将通过字库打印字符串,目前只支持 `ASCII` / `UTF-8` 编码 。 23 | 24 | > 附带字库文件 [0xA00000_font_uincode_16_16_tblr.Dzk](./tools/0xA00000_font_uincode_16_16_tblr.Dzk) 25 | 26 | ```python 27 | import lcd, image 28 | lcd.init() 29 | img = image.Image() 30 | # image.font_load(image.UTF8, 16, 16, 0xA00000) 31 | image.font_load(image.UTF8, 16, 16, '/sd/0xA00000_font_uincode_16_16_tblr.Dzk') 32 | img.draw_string(20, 90, b'こんにちは、世界', x_spacing=2, mono_space=1) 33 | image.font_free() 34 | lcd.display(img) 35 | ``` 36 | 37 | 范例参考 [image_draw_string.py](image_draw_string.py) 。 38 | 39 | ### 显示效果 40 | 41 | ![view_image_font](./readme.assets/view_image_font.jpg) 42 | 43 | ### 字库工具 44 | 45 | 我们将使用根目录下的 [FontGenerator.zip](./tools/FontGenerator.zip) 导出字体对应的字库,请看下图完成导出操作。 46 | 47 | 1. 选择字库编码类型为 Unicode 编码,这将支持绝大多数国家的语言。 48 | 49 | ![image-20200902180913322](./readme.assets/image-20200902180913322.png) 50 | 51 | 2. 选择扫描模式,为 5 横向、先上下后左右的字模的扫描打印方向。 52 | 53 | ![image-20200902181130459](./readme.assets/image-20200902181130459.png) 54 | 55 | 3. 如下图配置所需要的字体样式后创建字库。 56 | 57 | ![image-20200902181311553](./readme.assets/image-20200902181311553.png) 58 | 59 | 4. 保存成 DZK 格式即可,字模数据访问方法如图文字说明 60 | 61 | ![image-20200902181442677](./readme.assets/image-20200902181442677.png) 62 | 63 | ### 字模工具 64 | 65 | > 警告:不推荐使用字模工具,不了解的人请不要使用。 66 | 67 | 使用目录下的 [Pc2Lcd2002.zip](./tools/Pc2Lcd2002.zip) 获取字模的字符串。 68 | 69 | 1. 确认软件为字符模式。 70 | 71 | ![image-20200902175614964](./readme.assets/image-20200902175614964.png) 72 | 73 | 74 | 75 | 2. 设置如图即可导出想要的字符串。 76 | 77 | ​ ![image-20200902180153452](./readme.assets/image-20200902180153452.png) 78 | 79 | 3. 填入文字后点击生成字模。 80 | 81 | ![image-20200902175948599](./readme.assets/image-20200902175948599.png) 82 | 83 | 4. 提取字模字符串即可使用。 84 | 85 | ![image-20200902180505263](./readme.assets/image-20200902180505263.png) 86 | 87 | ``` 88 | 这(0) 是(1) 测(2) 试(3) 89 | 90 | /x00/x20/x10/x17/x00/x02/xF1/x10/x10/x10/x11/x12/x14/x28/x47/x00/x80/x40/x40/xFC/x10/x10/x20/xA0/x40/xA0/x10/x08/x08/x00/xFE/x00这0 91 | /x1F/x10/x10/x1F/x10/x10/x1F/x00/xFF/x01/x11/x11/x11/x29/x45/x83/xF0/x10/x10/xF0/x10/x10/xF0/x00/xFE/x00/x00/xF8/x00/x00/x00/xFE是1 92 | /x00/x27/x14/x14/x85/x45/x45/x15/x15/x25/xE5/x21/x22/x22/x24/x08/x04/xC4/x44/x54/x54/x54/x54/x54/x54/x54/x54/x04/x84/x44/x14/x08测2 93 | /x00/x20/x10/x10/x07/x00/xF0/x17/x11/x11/x11/x15/x19/x17/x02/x00/x28/x24/x24/x20/xFE/x20/x20/xE0/x20/x10/x10/x10/xCA/x0A/x06/x02试3 94 | ``` 95 | 96 | > 可以使用图形模式绘制自己喜欢的字模图形,支持 32 * 32 的图形。 97 | > 98 | > ![image-20200902181645277](./readme.assets/image-20200902181645277.png) -------------------------------------------------------------------------------- /multimedia/gui/image/demo_draw_font/tools/0xA00000_font_uincode_16_16_tblr.Dzk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sipeed/MaixPy-v1_scripts/8d7c5f98ba654d226f433d31718d852674cab08d/multimedia/gui/image/demo_draw_font/tools/0xA00000_font_uincode_16_16_tblr.Dzk -------------------------------------------------------------------------------- /multimedia/gui/image/demo_draw_font/tools/FontGenerator.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sipeed/MaixPy-v1_scripts/8d7c5f98ba654d226f433d31718d852674cab08d/multimedia/gui/image/demo_draw_font/tools/FontGenerator.zip -------------------------------------------------------------------------------- /multimedia/gui/image/demo_draw_font/tools/Pc2Lcd2002.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sipeed/MaixPy-v1_scripts/8d7c5f98ba654d226f433d31718d852674cab08d/multimedia/gui/image/demo_draw_font/tools/Pc2Lcd2002.zip -------------------------------------------------------------------------------- /multimedia/gui/image/demo_rotation_corr.py: -------------------------------------------------------------------------------- 1 | import lcd 2 | import image 3 | 4 | bg = (236, 36, 36) 5 | lcd.init(freq=15000000) 6 | 7 | 8 | img = image.Image() 9 | img.draw_circle((150, 140, 80)) 10 | img.draw_rectangle(100,100,60,60) 11 | img.draw_cross((250, 40)) 12 | img.draw_arrow((250, 200, 20, 200), color=(236, 36, 36)) 13 | 14 | #img.rotation_corr(x_rotation=180) 15 | img.rotation_corr(x_rotation=180, fov=2) # The FOV parameter is required otherwise strange errors will occur 16 | 17 | lcd.display(img) 18 | -------------------------------------------------------------------------------- /multimedia/gui/image/demo_save_picture.py: -------------------------------------------------------------------------------- 1 | import sensor 2 | import lcd 3 | import image 4 | 5 | print("init") 6 | lcd.init(freq=15000000) 7 | sensor.reset() 8 | sensor.set_pixformat(sensor.RGB565) 9 | sensor.set_framesize(sensor.QVGA) 10 | sensor.run(1) 11 | sensor.skip_frames(40) 12 | print("init ok") 13 | 14 | path = "/sd/image.jpg" 15 | img = sensor.snapshot() 16 | print("save image") 17 | img.save(path) 18 | 19 | print("read image") 20 | img_read = image.Image(path) 21 | lcd.display(img_read) 22 | print("ok") 23 | 24 | -------------------------------------------------------------------------------- /multimedia/gui/lvgl/amigo_touchscreen/README.md: -------------------------------------------------------------------------------- 1 | LVGL Touchscreen demo for Maix Amigo 2 | 3 | Place touch.py in the device SPIFFS memory (using uPyLoader or MaixPy IDE), restart device and then run test_touch.py 4 | 5 | -------------------------------------------------------------------------------- /multimedia/gui/lvgl/amigo_touchscreen/test_touch.py: -------------------------------------------------------------------------------- 1 | import lvgl as lv 2 | import lvgl_helper as lv_h 3 | import lcd 4 | import time 5 | from machine import Timer 6 | from machine import I2C 7 | from touch import Touch, TouchLow 8 | import KPU as kpu 9 | import gc 10 | 11 | config_touchscreen_support = True 12 | board_m1n = False 13 | 14 | lcd.init() 15 | 16 | TOUCH = None 17 | DEBUG = False 18 | 19 | def read_cb(drv, ptr): 20 | # print(ptr, b) 21 | data = lv.indev_data_t.cast(ptr) 22 | TOUCH.event() 23 | if DEBUG: 24 | print(TOUCH.state, TOUCH.points) 25 | data.point = lv.point_t({'x': TOUCH.points[1][0], 'y': TOUCH.points[1][1]}) 26 | data.state = lv.INDEV_STATE.PR if TOUCH.state == 1 else lv.INDEV_STATE.REL 27 | return False 28 | 29 | if config_touchscreen_support: 30 | i2c = I2C(I2C.I2C0, freq=1000*1000, scl=24, sda=27) # 24 27) 31 | devices = i2c.scan() 32 | print("devs", devices) # devs 0 [16, 38, 52, 56] 33 | TouchLow.config(i2c) 34 | TOUCH = Touch(480, 320, 200) 35 | 36 | lv.init() 37 | 38 | disp_buf1 = lv.disp_buf_t() 39 | buf1_1 = bytearray(320*10) 40 | lv.disp_buf_init(disp_buf1,buf1_1, None, len(buf1_1)//4) 41 | disp_drv = lv.disp_drv_t() 42 | lv.disp_drv_init(disp_drv) 43 | disp_drv.buffer = disp_buf1 44 | 45 | disp_drv.flush_cb = lv_h.flush 46 | if board_m1n: 47 | disp_drv.hor_res = 240 48 | disp_drv.ver_res = 240 49 | else: 50 | disp_drv.hor_res = 480 51 | disp_drv.ver_res = 320 52 | lv.disp_drv_register(disp_drv) 53 | 54 | if config_touchscreen_support: 55 | indev_drv = lv.indev_drv_t() 56 | lv.indev_drv_init(indev_drv) 57 | indev_drv.type = lv.INDEV_TYPE.POINTER 58 | indev_drv.read_cb = read_cb 59 | lv.indev_drv_register(indev_drv) 60 | 61 | lv.log_register_print_cb(lambda level,path,line,msg: print('%s(%d): %s' % (path, line, msg))) 62 | 63 | def event_handler(obj, event): 64 | global btn, box, bg 65 | 66 | if event == lv.EVENT.CLICKED: 67 | if obj == btn: 68 | box.set_hidden(0) 69 | bg.set_hidden(0) 70 | elif obj == box: 71 | box.set_hidden(1) 72 | bg.set_hidden(1) 73 | 74 | #create screen object 75 | scr = lv.obj() 76 | 77 | #create button in center with callback 78 | btn = lv.btn(scr) 79 | btn.align(scr, lv.ALIGN.CENTER, 0, 0) 80 | btn.set_event_cb(event_handler) 81 | label = lv.label(btn) 82 | label.set_text("Press me") 83 | label.set_size(20,20) 84 | 85 | #create semi-transparrent background and set it to hidden 86 | bg = lv.obj(scr) 87 | bg.set_pos(0, 0) 88 | bg.set_size(scr.get_width(), scr.get_height()) 89 | modal_style = lv.style_t() 90 | lv.style_copy(modal_style, lv.style_plain_color) 91 | modal_style.body.main_color = modal_style.body.grad_color = lv.color_make(0,0,50) 92 | modal_style.body.opa = 75 93 | bg.set_style(modal_style) 94 | bg.set_hidden(1) 95 | 96 | #create message box and set it to hidden 97 | box = lv.mbox(scr) 98 | box.set_text("Congratulations, you pressed the button! Now do it again, here"); 99 | box.add_btns(["OK", ""]) 100 | box.set_width(200) 101 | box.set_event_cb(event_handler) 102 | box.align(None, lv.ALIGN.CENTER, 0, 0) 103 | box.set_hidden(1) 104 | 105 | lv.scr_load(scr) 106 | 107 | def on_timer(timer): 108 | lv.tick_inc(5) 109 | lv.task_handler() 110 | gc.collect() 111 | 112 | timer = Timer(Timer.TIMER0, Timer.CHANNEL0, mode=Timer.MODE_PERIODIC, period=5, unit=Timer.UNIT_MS, callback=on_timer, arg=None) 113 | 114 | while True: 115 | pass 116 | -------------------------------------------------------------------------------- /multimedia/gui/lvgl/amigo_touchscreen/touch.py: -------------------------------------------------------------------------------- 1 | # This file is part of MaixUI 2 | # Copyright (c) sipeed.com 3 | # 4 | # Licensed under the MIT license: 5 | # http://www.opensource.org/licenses/mit-license.php 6 | # 7 | 8 | import time 9 | 10 | FT_DEVIDE_MODE = 0x00 11 | FT_ID_G_MODE = 0xA4 12 | FT_ID_G_THGROUP = 0x80 13 | FT_ID_G_PERIODACTIVE = 0x88 14 | 15 | FT6X36_ADDR = 0x38 16 | 17 | class TouchLow: 18 | i2c3 = None 19 | addr = 0x0 20 | 21 | def config(i2c3, addr=FT6X36_ADDR): 22 | TouchLow.i2c3 = i2c3 23 | TouchLow.addr = addr 24 | 25 | def write_reg(reg_addr, buf): 26 | TouchLow.i2c3.writeto_mem(TouchLow.addr, reg_addr, buf, mem_size=8) 27 | 28 | def read_reg(reg_addr, buf_len): 29 | return TouchLow.i2c3.readfrom_mem(TouchLow.addr, reg_addr, buf_len, mem_size=8) 30 | 31 | def config_ft6x36(): 32 | TouchLow.write_reg(FT_DEVIDE_MODE, 0); # 进入正常操作模式 33 | TouchLow.write_reg(FT_ID_G_THGROUP, 12); # 设置触摸有效值,触摸有效值,12,越小越灵敏 34 | TouchLow.write_reg(FT_DEVIDE_MODE, 14); # 激活周期,不能小于12,最大14 35 | 36 | def get_point(): 37 | if TouchLow.i2c3 != None: 38 | #data = self.read_reg(0x01, 1) 39 | #print("get_gesture:" + str(data)) 40 | data = TouchLow.read_reg(0x02, 1) 41 | #print("get_points:" + str(data)) 42 | if (data != None and data[0] == 0x1): 43 | data_buf = TouchLow.read_reg(0x03, 4) 44 | y = ((data_buf[0] & 0x0f) << 8) | (data_buf[1]) 45 | x = ((data_buf[2] & 0x0f) << 8) | (data_buf[3]) 46 | #print("1 point[{}:{}]".format(x,y)) 47 | if ((data_buf[0] & 0xc0) == 0x80): 48 | #print("2 point[({},{}):({},{})]".format( 49 | #x, y, self.width - x, self.height - y)) 50 | return (x, y) 51 | return None 52 | 53 | class Touch: 54 | 55 | idle, press, release = 0, 1, 2 56 | 57 | def __init__(self, w, h, cycle=1000, invert_y=False): 58 | self.cycle = cycle 59 | self.last_time = 0 60 | self.points = [(0, 0, 0), (0, 0, 0)] 61 | self.state = Touch.idle 62 | self.width, self.height = w, h 63 | self.invert_y = invert_y 64 | 65 | def event(self): 66 | tmp = TouchLow.get_point() 67 | if tmp != None: 68 | x, y = tmp 69 | 70 | if self.invert_y: 71 | y = self.height - y 72 | if x < 0: x = 0 73 | if y < 0: y = 0 74 | 75 | self.last_time = time.ticks_ms() 76 | if self.state != Touch.press: 77 | self.state = Touch.press 78 | self.points[0] = (x, y, time.ticks_ms()) 79 | self.points[1] = (x, y, time.ticks_ms()) 80 | 81 | # timeout return ilde. 82 | if time.ticks_ms() > self.last_time + self.cycle: 83 | if self.state == Touch.release: 84 | self.state = Touch.idle 85 | self.points = [(0, 0, 0), (0, 0, 0)] 86 | return 87 | if self.state == Touch.press: 88 | self.state = Touch.release 89 | return 90 | 91 | if __name__ == "__main__": 92 | 93 | import lcd 94 | from machine import I2C 95 | 96 | i2c = I2C(I2C.I2C3, freq=1000*1000, scl=24, sda=27) # amigo 97 | devices = i2c.scan() 98 | print(devices) 99 | TouchLow.config(i2c) 100 | tmp = Touch(480, 320, 200) 101 | while 1: 102 | tmp.event() 103 | print(tmp.state, tmp.points) 104 | -------------------------------------------------------------------------------- /multimedia/gui/lvgl/images/blue_flower_32.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sipeed/MaixPy-v1_scripts/8d7c5f98ba654d226f433d31718d852674cab08d/multimedia/gui/lvgl/images/blue_flower_32.bin -------------------------------------------------------------------------------- /multimedia/gui/lvgl/images/png_decoder_test.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sipeed/MaixPy-v1_scripts/8d7c5f98ba654d226f433d31718d852674cab08d/multimedia/gui/lvgl/images/png_decoder_test.png -------------------------------------------------------------------------------- /multimedia/gui/lvgl/lvgl_button.py: -------------------------------------------------------------------------------- 1 | import lvgl as lv 2 | import lvgl_helper as lv_h 3 | import lcd 4 | import time 5 | from machine import Timer 6 | from machine import I2C 7 | 8 | config_touchscreen_support = True 9 | board_m1n = False 10 | 11 | i2c = I2C(I2C.I2C0, freq=400000, scl=30, sda=31) 12 | if not board_m1n: 13 | lcd.init() 14 | else: 15 | lcd.init(type=2, freq=20000000) 16 | if config_touchscreen_support: 17 | import touchscreen as ts 18 | ts.init(i2c) 19 | lv.init() 20 | 21 | disp_buf1 = lv.disp_buf_t() 22 | buf1_1 = bytearray(320*10) 23 | lv.disp_buf_init(disp_buf1,buf1_1, None, len(buf1_1)//4) 24 | disp_drv = lv.disp_drv_t() 25 | lv.disp_drv_init(disp_drv) 26 | disp_drv.buffer = disp_buf1 27 | disp_drv.flush_cb = lv_h.flush 28 | if board_m1n: 29 | disp_drv.hor_res = 240 30 | disp_drv.ver_res = 240 31 | else: 32 | disp_drv.hor_res = 320 33 | disp_drv.ver_res = 240 34 | lv.disp_drv_register(disp_drv) 35 | 36 | if config_touchscreen_support: 37 | indev_drv = lv.indev_drv_t() 38 | lv.indev_drv_init(indev_drv) 39 | indev_drv.type = lv.INDEV_TYPE.POINTER 40 | indev_drv.read_cb = lv_h.read 41 | lv.indev_drv_register(indev_drv) 42 | 43 | # lv.log_register_print_cb(lv_h.log) 44 | lv.log_register_print_cb(lambda level,path,line,msg: print('%s(%d): %s' % (path, line, msg))) 45 | 46 | scr = lv.obj() 47 | btn = lv.btn(scr) 48 | btn.align(lv.scr_act(), lv.ALIGN.CENTER, 0, 0) 49 | label = lv.label(btn) 50 | label.set_text("Button") 51 | label.set_size(20,20) 52 | lv.scr_load(scr) 53 | 54 | def on_timer(timer): 55 | lv.tick_inc(5) 56 | 57 | timer = Timer(Timer.TIMER0, Timer.CHANNEL0, mode=Timer.MODE_PERIODIC, period=5, unit=Timer.UNIT_MS, callback=on_timer, arg=None) 58 | 59 | while True: 60 | tim = time.ticks_ms() 61 | lv.task_handler() 62 | while time.ticks_ms()-tim < 5: 63 | pass 64 | 65 | 66 | -------------------------------------------------------------------------------- /multimedia/gui/lvgl/lvgl_button2.py: -------------------------------------------------------------------------------- 1 | import lvgl as lv 2 | import lvgl_helper as lv_h 3 | import lcd 4 | import time 5 | from machine import Timer 6 | from machine import I2C 7 | 8 | config_touchscreen_support = True 9 | board_m1n = False 10 | 11 | i2c = I2C(I2C.I2C0, freq=400000, scl=30, sda=31) 12 | if not board_m1n: 13 | lcd.init() 14 | else: 15 | lcd.init(type=2, freq=20000000) 16 | if config_touchscreen_support: 17 | import touchscreen as ts 18 | ts.init(i2c) 19 | lv.init() 20 | 21 | disp_buf1 = lv.disp_buf_t() 22 | buf1_1 = bytearray(320*10) 23 | lv.disp_buf_init(disp_buf1,buf1_1, None, len(buf1_1)//4) 24 | disp_drv = lv.disp_drv_t() 25 | lv.disp_drv_init(disp_drv) 26 | disp_drv.buffer = disp_buf1 27 | disp_drv.flush_cb = lv_h.flush 28 | if board_m1n: 29 | disp_drv.hor_res = 240 30 | disp_drv.ver_res = 240 31 | else: 32 | disp_drv.hor_res = 320 33 | disp_drv.ver_res = 240 34 | lv.disp_drv_register(disp_drv) 35 | 36 | if config_touchscreen_support: 37 | indev_drv = lv.indev_drv_t() 38 | lv.indev_drv_init(indev_drv) 39 | indev_drv.type = lv.INDEV_TYPE.POINTER 40 | indev_drv.read_cb = lv_h.read 41 | lv.indev_drv_register(indev_drv) 42 | 43 | # lv.log_register_print_cb(lv_h.log) 44 | lv.log_register_print_cb(lambda level,path,line,msg: print('%s(%d): %s' % (path, line, msg))) 45 | 46 | scr = lv.obj() 47 | btn = lv.btn(scr) 48 | btn.align(lv.scr_act(), lv.ALIGN.IN_TOP_LEFT, 0, 0) 49 | label = lv.label(btn) 50 | label.set_text("Button") 51 | label.set_size(20,20) 52 | lv.scr_load(scr) 53 | 54 | while True: 55 | tim = time.ticks_ms() 56 | lv.tick_inc(5) 57 | lv.task_handler() 58 | while time.ticks_ms()-tim < 5: 59 | pass 60 | 61 | 62 | -------------------------------------------------------------------------------- /multimedia/gui/lvgl/lvgl_image.Image.py: -------------------------------------------------------------------------------- 1 | 2 | # init 3 | 4 | 5 | import lvgl as lv 6 | import lvgl_helper as lv_h 7 | import lodepng as png 8 | import lcd 9 | import time 10 | import ustruct as struct 11 | from machine import Timer 12 | from machine import I2C 13 | import sensor 14 | 15 | config_touchscreen_support = True 16 | 17 | 18 | def init_sensor(): 19 | sensor.reset(freq=22000000) 20 | sensor.set_pixformat(sensor.RGB565) 21 | sensor.set_framesize(sensor.QQVGA) 22 | 23 | init_sensor() 24 | 25 | i2c = I2C(I2C.I2C0, freq=400000, scl=30, sda=31) 26 | lcd.init() 27 | if config_touchscreen_support: 28 | import touchscreen as ts 29 | ts.init(i2c) 30 | lv.init() 31 | 32 | disp_buf1 = lv.disp_buf_t() 33 | buf1_1 = bytearray(320*10) 34 | lv.disp_buf_init(disp_buf1,buf1_1, None, len(buf1_1)//4) 35 | disp_drv = lv.disp_drv_t() 36 | lv.disp_drv_init(disp_drv) 37 | disp_drv.buffer = disp_buf1 38 | disp_drv.flush_cb = lv_h.flush 39 | disp_drv.hor_res = 320 40 | disp_drv.ver_res = 240 41 | lv.disp_drv_register(disp_drv) 42 | 43 | indev_drv = lv.indev_drv_t() 44 | lv.indev_drv_init(indev_drv) 45 | indev_drv.type = lv.INDEV_TYPE.POINTER 46 | indev_drv.read_cb = lv_h.read 47 | lv.indev_drv_register(indev_drv) 48 | 49 | 50 | # lv.log_register_print_cb(lv_h.log) 51 | lv.log_register_print_cb(lambda level,path,line,msg: print('%s(%d): %s' % (path, line, msg))) 52 | 53 | snapshot = sensor.snapshot() 54 | 55 | # Create a screen with a draggable image 56 | 57 | scr = lv.obj() 58 | img = lv.img(scr) 59 | img_data = snapshot.to_bytes() 60 | img.align(scr, lv.ALIGN.CENTER, 0, 0) 61 | img_dsc = lv.img_dsc_t({ 62 | 'header':{ 63 | 'always_zero': 0, 64 | 'w':snapshot.width(), 65 | 'h':snapshot.height(), 66 | 'cf':lv.img.CF.TRUE_COLOR 67 | }, 68 | 'data_size': len(img_data), 69 | 'data': img_data 70 | }) 71 | 72 | img.set_src(img_dsc) 73 | img.set_drag(True) 74 | 75 | # Load the screen and display image 76 | 77 | 78 | lv.scr_load(scr) 79 | 80 | def on_timer(timer): 81 | lv.tick_inc(5) 82 | lv.task_handler() 83 | 84 | timer = Timer(Timer.TIMER0, Timer.CHANNEL0, mode=Timer.MODE_PERIODIC, period=5, unit=Timer.UNIT_MS, callback=on_timer, arg=None) 85 | 86 | update_tim = time.ticks_ms() 87 | while True: 88 | snapshot = sensor.snapshot() 89 | img_data = snapshot.to_bytes() 90 | w = snapshot.width() 91 | h = snapshot.height() 92 | # snapshot.draw_rectangle((0,0,100,100), fill=True, color=lcd.RED) 93 | #img_data = snapshot.to_bytes() 94 | img_dsc = lv.img_dsc_t({ 95 | 'header':{ 96 | 'always_zero': 0, 97 | 'w': w, 98 | 'h': h, 99 | 'cf':lv.img.CF.TRUE_COLOR 100 | }, 101 | 'data_size': w*h*2, 102 | 'data': img_data 103 | }) 104 | 105 | img.set_src(img_dsc) 106 | img.set_drag(True) 107 | 108 | -------------------------------------------------------------------------------- /multimedia/gui/lvgl/lvgl_img.py: -------------------------------------------------------------------------------- 1 | import lvgl as lv 2 | import lvgl_helper as lv_h 3 | import lcd 4 | import time 5 | from machine import Timer 6 | from machine import I2C 7 | import touchscreen as ts 8 | 9 | i2c = I2C(I2C.I2C0, freq=400000, scl=30, sda=31) 10 | lcd.init() 11 | ts.init(i2c) 12 | lv.init() 13 | 14 | disp_buf1 = lv.disp_buf_t() 15 | buf1_1 = bytearray(320*10) 16 | lv.disp_buf_init(disp_buf1,buf1_1, None, len(buf1_1)//4) 17 | disp_drv = lv.disp_drv_t() 18 | lv.disp_drv_init(disp_drv) 19 | disp_drv.buffer = disp_buf1 20 | disp_drv.flush_cb = lv_h.flush 21 | disp_drv.hor_res = 320 22 | disp_drv.ver_res = 240 23 | lv.disp_drv_register(disp_drv) 24 | 25 | indev_drv = lv.indev_drv_t() 26 | lv.indev_drv_init(indev_drv) 27 | indev_drv.type = lv.INDEV_TYPE.POINTER 28 | indev_drv.read_cb = lv_h.read 29 | lv.indev_drv_register(indev_drv) 30 | 31 | 32 | # lv.log_register_print_cb(lv_h.log) 33 | lv.log_register_print_cb(lambda level,path,line,msg: print('%s(%d): %s' % (path, line, msg))) 34 | 35 | # Image data 36 | 37 | with open('/flash/blue_flower_32.bin','rb') as f: 38 | img_data = f.read() 39 | 40 | # Pixel format: Fix 0xFF: 8 bit, Red: 8 bit, Green: 8 bit, Blue: 8 bit 41 | 42 | # Create a screen with a draggable image 43 | 44 | scr = lv.obj() 45 | img = lv.img(scr) 46 | img.align(scr, lv.ALIGN.CENTER, 0, 0) 47 | img_dsc = lv.img_dsc_t({ 48 | 'header':{ 49 | 'always_zero': 0, 50 | 'w':100, 51 | 'h':75, 52 | 'cf':lv.img.CF.TRUE_COLOR 53 | }, 54 | 'data_size': len(img_data), 55 | 'data': img_data 56 | }) 57 | 58 | img.set_src(img_dsc) 59 | img.set_drag(False) 60 | 61 | # Load the screen and display image 62 | 63 | 64 | lv.scr_load(scr) 65 | 66 | def on_timer(timer): 67 | lv.tick_inc(5) 68 | 69 | timer = Timer(Timer.TIMER0, Timer.CHANNEL0, mode=Timer.MODE_PERIODIC, period=5, unit=Timer.UNIT_MS, callback=on_timer, arg=None) 70 | 71 | while True: 72 | tim = time.ticks_ms() 73 | lv.task_handler() 74 | while time.ticks_ms()-tim < 5: 75 | pass 76 | 77 | -------------------------------------------------------------------------------- /multimedia/gui/lvgl/lvgl_multiple_screens.py: -------------------------------------------------------------------------------- 1 | #this demo shows how to create multiple screens, load and unload them properly without causing memory leak 2 | 3 | import lvgl as lv 4 | import lvgl_helper as lv_h 5 | import lcd 6 | import time 7 | from machine import Timer 8 | from machine import I2C 9 | from touch import Touch, TouchLow 10 | import KPU as kpu 11 | import gc 12 | 13 | config_touchscreen_support = True 14 | board_m1n = False 15 | 16 | lcd.init() 17 | 18 | 19 | TOUCH = None 20 | 21 | def read_cb(drv, ptr): 22 | data = lv.indev_data_t.cast(ptr) 23 | TOUCH.event() 24 | data.point = lv.point_t({'x': TOUCH.points[1][0], 'y': TOUCH.points[1][1]}) 25 | data.state = lv.INDEV_STATE.PR if TOUCH.state == 1 else lv.INDEV_STATE.REL 26 | return False 27 | 28 | 29 | if config_touchscreen_support: 30 | i2c = I2C(I2C.I2C0, freq=1000*1000, scl=24, sda=27) # 24 27) 31 | devices = i2c.scan() 32 | print("devs", devices) # devs 0 [16, 38, 52, 56] 33 | TouchLow.config(i2c) 34 | TOUCH = Touch(480, 320, 200) 35 | 36 | lv.init() 37 | 38 | disp_buf1 = lv.disp_buf_t() 39 | buf1_1 = bytearray(320*10) 40 | lv.disp_buf_init(disp_buf1,buf1_1, None, len(buf1_1)//4) 41 | disp_drv = lv.disp_drv_t() 42 | lv.disp_drv_init(disp_drv) 43 | disp_drv.buffer = disp_buf1 44 | 45 | disp_drv.flush_cb = lv_h.flush 46 | if board_m1n: 47 | disp_drv.hor_res = 240 48 | disp_drv.ver_res = 240 49 | else: 50 | disp_drv.hor_res = 480 51 | disp_drv.ver_res = 320 52 | lv.disp_drv_register(disp_drv) 53 | 54 | if config_touchscreen_support: 55 | indev_drv = lv.indev_drv_t() 56 | lv.indev_drv_init(indev_drv) 57 | indev_drv.type = lv.INDEV_TYPE.POINTER 58 | indev_drv.read_cb = read_cb 59 | lv.indev_drv_register(indev_drv) 60 | 61 | 62 | lv.log_register_print_cb(lambda level,path,line,msg: print('%s(%d): %s' % (path, line, msg))) 63 | 64 | class UI: 65 | 66 | def __init__(self): 67 | self.scr1 = self.create_scr1() 68 | self.scr2 = self.create_scr2() 69 | 70 | def create_scr1(self): 71 | scr1 = lv.obj() 72 | btn1 = lv.btn(scr1) 73 | btn1.align(scr1, lv.ALIGN.CENTER, 0, 0) 74 | label1 = lv.label(btn1) 75 | label1.set_text("Button 1") 76 | label1.set_size(20,20) 77 | return scr1 78 | 79 | def create_scr2(self): 80 | scr2 = lv.obj() 81 | btn2 = lv.btn(scr2) 82 | btn2.align(scr2, lv.ALIGN.CENTER, 0, 0) 83 | label2 = lv.label(btn2) 84 | label2.set_text("Button 2") 85 | label2.set_size(20,20) 86 | return scr2 87 | 88 | ui = UI() 89 | kpu.memtest() 90 | 91 | def on_timer(timer): 92 | lv.tick_inc(5) 93 | lv.task_handler() 94 | gc.collect() 95 | 96 | timer = Timer(Timer.TIMER0, Timer.CHANNEL0, mode=Timer.MODE_PERIODIC, period=5, unit=Timer.UNIT_MS, callback=on_timer, arg=None) 97 | 98 | while True: 99 | tim = time.ticks_ms() 100 | while time.ticks_ms()-tim < 500: 101 | pass 102 | 103 | lv.scr_load(ui.scr1) 104 | kpu.memtest() 105 | 106 | tim = time.ticks_ms() 107 | while time.ticks_ms()-tim < 500: 108 | pass 109 | 110 | lv.scr_load(ui.scr2) 111 | kpu.memtest() 112 | -------------------------------------------------------------------------------- /multimedia/gui/maixui/qmcx983.py: -------------------------------------------------------------------------------- 1 | from machine import I2C 2 | import lcd 3 | import time 4 | from ustruct import unpack, unpack_from 5 | from array import array 6 | 7 | #I2C devices:[44, 118] 8 | # i2c_bus = I2C(I2C.I2C0, freq=100*1000, scl=6, sda=7) 9 | # i2c_devs_list = i2c_bus.scan() 10 | # print("I2C devices:" + str(i2c_devs_list)) 11 | 12 | QMC6983_A1_D1 = 0 13 | QMC6983_E1 = 1 14 | QMC7983 = 2 15 | QMC7983_LOW_SETRESET= 3 16 | QMC6983_E1_Metal = 4 17 | QMC7983_Vertical = 5 18 | QMC7983_Slope = 6 19 | 20 | # QMCX983 default address. 21 | QMCX983_I2CADDR = 0x2C 22 | 23 | class QMCX983: 24 | 25 | def __init__(self, i2c=None, 26 | address=QMCX983_I2CADDR, 27 | **kwargs): 28 | self.address = address 29 | if i2c is None: 30 | raise ValueError('An I2C object is required.') 31 | self.i2c = i2c 32 | self.mag_chip_id = 0 33 | 34 | self.i2c.writeto_mem(self.address, 0x09, 35 | bytearray([0x1d])) 36 | chip = self.i2c.readfrom_mem(self.address, 0x0d, 1) 37 | #print("chip id: " + str(chip)) 38 | print(hex(chip[0])) 39 | if 0x31 == chip[0]: 40 | self.mag_chip_id = QMC6983_E1 41 | elif 0x32 == chip[0]: 42 | self.i2c.writeto_mem(self.address, 0x2e, bytearray([0x01])) 43 | chip = self.i2c.readfrom_mem(self.address, 0x2f, 1) 44 | if ((chip[0]&0x04) >>2) != 0: 45 | self.mag_chip_id = QMC6983_E1_Metal 46 | else: 47 | self.i2c.writeto_mem(self.address, 0x2e, bytearray([0x0f])) 48 | chip = self.i2c.readfrom_mem(self.address, 0x2f, 1) 49 | if (0x02 == ((chip[0]&0x3C)>>2)): 50 | self.mag_chip_id = QMC7983_Vertical 51 | if (0x03 == ((chip[0]&0x3C)>>2)): 52 | self.mag_chip_id = QMC7983_Slope 53 | else: 54 | return 55 | print(self.mag_chip_id) 56 | self.i2c.writeto_mem(self.address, 0x21, bytearray([0x01])) 57 | self.i2c.writeto_mem(self.address, 0x20, bytearray([0x40])) 58 | if (self.mag_chip_id != QMC6983_A1_D1): 59 | self.i2c.writeto_mem(self.address, 0x29, bytearray([0x80])) 60 | self.i2c.writeto_mem(self.address, 0x0a, bytearray([0x0c])) 61 | if (self.mag_chip_id == QMC6983_E1_Metal or self.mag_chip_id == QMC7983_Slope ): 62 | self.i2c.writeto_mem(self.address, 0x1b, bytearray([0x80])) 63 | self.i2c.writeto_mem(self.address, 0x0b, bytearray([0x01])) 64 | self.i2c.writeto_mem(self.address, 0x09, bytearray([0x1d])) 65 | 66 | def read_xyz(self): 67 | read_data = self.i2c.readfrom_mem(self.address, 0x00, 6) 68 | #if (self.mag_chip_id >= 3) 69 | raw = bytearray(3) 70 | raw[0] = (read_data[1]<<8) | read_data[0] 71 | raw[1] = (read_data[3]<<8) | read_data[2] 72 | raw[2] = (read_data[5]<<8) | read_data[4] 73 | return (raw[0], raw[1], raw[2]) 74 | # return "({:.1f}|{:.1f}|{:.1f})".format(raw[0]/25.0, raw[1]/25.0, raw[2]/25.0) 75 | 76 | if __name__ == "__main__": 77 | 78 | from machine import I2C 79 | import lcd, time 80 | import micropython, gc 81 | 82 | i2c_bus = I2C(I2C.I2C0, freq=100*1000, scl=6, sda=7) 83 | i2c_devs_list = i2c_bus.scan() 84 | print("I2C devices:" + str(i2c_devs_list)) 85 | 86 | bme=QMCX983(i2c=i2c_bus) 87 | lcd.init() 88 | while 1: 89 | time.sleep_ms(500) 90 | data = bme.read_xyz() 91 | print(data) 92 | -------------------------------------------------------------------------------- /multimedia/gui/maixui/shtxx.py: -------------------------------------------------------------------------------- 1 | 2 | import sys 3 | import time 4 | from machine import I2C 5 | 6 | SHT3x_ADDR = 0x45 7 | SHT31_ADDR = 0x44 8 | 9 | class SHT3x: 10 | 11 | def __init__(self, i2c, addr = SHT31_ADDR): 12 | self.i2c = i2c 13 | #addrs = self.i2c.scan() 14 | #print(addrs) 15 | #if SHT3x_ADDR not in addrs or SHT31_ADDR not in addrs: 16 | #raise Exception('no SHT3X found at bus on %s' % (str(self.i2c))) 17 | self.addr = addr 18 | self.last = 0 19 | self.cache = [0, 0] 20 | 21 | def read_temp_humd(self): 22 | if self.last == 0: 23 | status = self.i2c.writeto(self.addr, b'\x24\x00') 24 | self.last = time.ticks_ms() + 2000 25 | elif time.ticks_ms() > self.last: 26 | self.last = 0 27 | ## delay (20 slow) 28 | #utime.sleep_ms(20) 29 | # read 6 bytes 30 | databytes = self.i2c.readfrom(self.addr, 6) 31 | dataset = [databytes[0], databytes[1]] 32 | dataset = [databytes[3], databytes[4]] 33 | temperature_raw = databytes[0] << 8 | databytes[1] 34 | temperature = (175.0 * float(temperature_raw) / 65535.0) - 45 35 | # fahreheit 36 | # temperature = (315.0 * float(temperature_raw) / 65535.0) - 49 37 | humidity_raw = databytes[3] << 8 | databytes[4] 38 | humidity = (100.0 * float(humidity_raw) / 65535.0) 39 | self.cache = [temperature, humidity] 40 | return self.cache 41 | 42 | 43 | if __name__ == "__main__": 44 | 45 | #sht3x = SHT3x(I2C(I2C.I2C0, freq=100*1000, scl=24, sda=25)) 46 | sht3x = SHT3x(I2C(I2C.I2C0, freq=100*1000, scl=24, sda=27)) 47 | #sht3x = SHT3x(I2C(I2C.I2C0, freq=100*1000, scl=23, sda=20)) 48 | #sht3x = SHT3x(I2C(I2C.I2C0, freq=100*1000, scl=9, sda=7)) 49 | while True: 50 | try: 51 | print(sht3x.read_temp_humd()) 52 | time.sleep(1) 53 | except Exception as e: 54 | print(e) 55 | -------------------------------------------------------------------------------- /multimedia/nes/nes_amigo_handle_and_sound.py: -------------------------------------------------------------------------------- 1 | from machine import I2C 2 | import nes, lcd 3 | from sound import CubeAudio 4 | import sys, time 5 | from fpioa_manager import fm 6 | from Maix import FPIOA, GPIO 7 | 8 | i2c = I2C(I2C.I2C3, freq=500*1000, sda=27, scl=24) 9 | CubeAudio.init(i2c) 10 | tmp = CubeAudio.check() 11 | print(tmp) 12 | 13 | CubeAudio.ready(volume=100) 14 | 15 | fm.fpioa.set_function(13,fm.fpioa.I2S0_MCLK) 16 | fm.fpioa.set_function(21,fm.fpioa.I2S0_SCLK) 17 | fm.fpioa.set_function(18,fm.fpioa.I2S0_WS) 18 | fm.fpioa.set_function(35,fm.fpioa.I2S0_IN_D0) 19 | fm.fpioa.set_function(34,fm.fpioa.I2S0_OUT_D2) 20 | 21 | CubeAudio.i2s.set_sample_rate(44100) 22 | 23 | lcd.init(freq=15000000) 24 | lcd.register(0x36, 0x20) 25 | 26 | # B A SEL START UP DOWN LEFT RIGHT 27 | # 1 2 4 8 16 32 64 128 28 | state = 0 29 | 30 | try: 31 | nes.init(nes.INPUT) 32 | nes.load("sd/game/mario.nes") 33 | for i in range(20000): 34 | nes.loop() 35 | for i in range(500): 36 | nes.loop() 37 | nes.input(8, 0, 0) 38 | nes.loop() 39 | nes.input(0, 0, 0) 40 | while True: 41 | tmp = i2c.readfrom(66, 1) 42 | for i in range(10): 43 | nes.loop() 44 | nes.input(tmp[0], 0, 0) 45 | for i in range(10): 46 | nes.loop() 47 | finally: 48 | nes.free() 49 | 50 | #import time 51 | #i = 0 52 | #while True: 53 | ##dev = i2c.scan() 54 | ##print(dev) 55 | ##time.sleep(0.5) 56 | #try: 57 | ##i2c.writeto(66, b'0') 58 | #tmp = (i2c.readfrom(66, 1)) 59 | #print('{:08b}'.format(tmp[0])) 60 | #except Exception as e: 61 | #print(e) 62 | -------------------------------------------------------------------------------- /multimedia/nes/nes_emulator.py: -------------------------------------------------------------------------------- 1 | import nes, lcd 2 | 3 | lcd.init(freq=15000000) 4 | 5 | # B A SEL START UP DOWN LEFT RIGHT 6 | # 1 2 4 8 16 32 64 128 7 | # nes.input(8, 0, 0) # press START 8 | # nes.input(1P, 2P, SYS) 9 | 10 | try: 11 | nes.init(nes.INPUT) 12 | nes.load("mario.nes") 13 | # nes.run("/sd/mario.nes") 14 | for i in range(20000): # wait 15 | nes.loop() 16 | for i in range(500): 17 | nes.loop() 18 | nes.input(8, 0, 0) # input enter 19 | nes.loop() 20 | nes.input(0, 0, 0) 21 | nes.loop() 22 | while True: 23 | nes.loop() # run 24 | finally: 25 | nes.free() 26 | 27 | '''python 28 | try: 29 | nes.init(nes.INPUT) # input 30 | nes.load("mario.nes") # load 31 | while True: 32 | nes.loop() # run 33 | finally: 34 | nes.free() # exit 35 | ''' 36 | 37 | -------------------------------------------------------------------------------- /multimedia/nes/nes_ps2.py: -------------------------------------------------------------------------------- 1 | import nes, lcd 2 | from fpioa_manager import * 3 | 4 | # AUDIO_PA_EN_PIN = None # Bit Dock and old MaixGo 5 | AUDIO_PA_EN_PIN = 32 # Maix Go(version 2.20) 6 | # AUDIO_PA_EN_PIN = 2 # Maixduino 7 | 8 | # open audio PA 9 | if AUDIO_PA_EN_PIN: 10 | fm.register(AUDIO_PA_EN_PIN, fm.fpioa.GPIO1, force=True) 11 | wifi_en=GPIO(GPIO.GPIO1, GPIO.OUT) 12 | wifi_en.value(1) 13 | 14 | 15 | fm.register(19, fm.fpioa.GPIOHS0, force=True) 16 | fm.register(18, fm.fpioa.GPIOHS1, force=True) 17 | fm.register(21, fm.fpioa.GPIOHS2, force=True) 18 | fm.register(20, fm.fpioa.GPIOHS3, force=True) 19 | 20 | lcd.init(freq=15000000) 21 | nes.init(1, cs=fm.fpioa.GPIOHS0, clk=fm.fpioa.GPIOHS1, mosi=fm.fpioa.GPIOHS2, miso=fm.fpioa.GPIOHS3) 22 | nes.run("/sd/mario.nes") 23 | 24 | -------------------------------------------------------------------------------- /multimedia/nes/nes_py_input.py: -------------------------------------------------------------------------------- 1 | from machine import I2C 2 | import nes, lcd 3 | from sound import CubeAudio 4 | import sys, time 5 | from fpioa_manager import fm 6 | from Maix import FPIOA, GPIO 7 | 8 | from machine import I2C 9 | #i2c = I2C(I2C.I2C1, freq=100*1000, sda=31, scl=30) # cube 10 | i2c = I2C(I2C.I2C3, freq=100*1000, sda=27, scl=24) # amigo 11 | CubeAudio.init(i2c) 12 | tmp = CubeAudio.check() 13 | print(tmp) 14 | 15 | CubeAudio.ready(volume=100) 16 | 17 | # amigo 18 | fm.fpioa.set_function(13,fm.fpioa.I2S0_MCLK) 19 | fm.fpioa.set_function(21,fm.fpioa.I2S0_SCLK) 20 | fm.fpioa.set_function(18,fm.fpioa.I2S0_WS) 21 | fm.fpioa.set_function(35,fm.fpioa.I2S0_IN_D0) 22 | fm.fpioa.set_function(34,fm.fpioa.I2S0_OUT_D2) 23 | 24 | # cube 25 | #fm.fpioa.set_function(19,fm.fpioa.I2S0_MCLK) 26 | #fm.fpioa.set_function(35,fm.fpioa.I2S0_SCLK) 27 | #fm.fpioa.set_function(33,fm.fpioa.I2S0_WS) 28 | #fm.fpioa.set_function(34,fm.fpioa.I2S0_IN_D0) 29 | #fm.fpioa.set_function(18,fm.fpioa.I2S0_OUT_D2) 30 | 31 | CubeAudio.i2s.set_sample_rate(44100) 32 | 33 | i2c = I2C(I2C.I2C0, freq=400*1000, sda=27, scl=24) 34 | 35 | lcd.init(freq=15000000) 36 | lcd.register(0x36, 0x20) # amigo 37 | # lcd.register(0x36, 0x68) # cube 38 | 39 | # B A SEL START UP DOWN LEFT RIGHT 40 | # 1 2 4 8 16 32 64 128 41 | state = 0 42 | 43 | try: 44 | nes.init(nes.INPUT) 45 | nes.load("mario.nes") 46 | for i in range(20000): 47 | nes.loop() 48 | for i in range(500): 49 | nes.loop() 50 | nes.input(8, 0, 0) 51 | nes.loop() 52 | nes.input(0, 0, 0) 53 | nes.loop() 54 | while True: 55 | # tmp = i2c.readfrom(66, 1) # handle i2c addr 56 | # tmp = i2c.readfrom(74, 1) # handle i2c addr 57 | # nes.input(tmp[0], 0, 0) 58 | # for i in range(100): 59 | # nes.loop() 60 | nes.loop() 61 | finally: 62 | nes.free() 63 | 64 | #import time 65 | #i = 0 66 | #while True: 67 | ##dev = i2c.scan() 68 | ##print(dev) 69 | ##time.sleep(0.5) 70 | #try: 71 | ##i2c.writeto(66, b'0') 72 | #tmp = (i2c.readfrom(66, 1)) 73 | #print('{:08b}'.format(tmp[0])) 74 | #except Exception as e: 75 | #print(e) 76 | -------------------------------------------------------------------------------- /multimedia/speech_recognizer/isolated_word.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) sipeed.com 2 | # 3 | # Licensed under the MIT license: 4 | # http://www.opensource.org/licenses/mit-license.php 5 | # 6 | 7 | import time 8 | from Maix import GPIO, I2S 9 | from fpioa_manager import fm 10 | 11 | # user setting 12 | sample_rate = 16000 13 | record_time = 4 #s 14 | 15 | #fm.register(8, fm.fpioa.GPIO0, force=True) 16 | #wifi_en = GPIO(GPIO.GPIO0, GPIO.OUT) 17 | #wifi_en.value(0) 18 | 19 | fm.register(20,fm.fpioa.I2S0_IN_D0, force=True) 20 | fm.register(18,fm.fpioa.I2S0_SCLK, force=True) 21 | fm.register(19,fm.fpioa.I2S0_WS, force=True) 22 | 23 | # fm.register(32,fm.fpioa.I2S0_SCLK, force=True) # dock 24 | # fm.register(30,fm.fpioa.I2S0_WS, force=True) # dock 25 | 26 | rx = I2S(I2S.DEVICE_0) 27 | rx.channel_config(rx.CHANNEL_0, rx.RECEIVER, align_mode=I2S.STANDARD_MODE) 28 | rx.set_sample_rate(sample_rate) 29 | print(rx) 30 | 31 | from speech_recognizer import isolated_word 32 | 33 | # default: maix dock / maix duino set shift=0 34 | sr = isolated_word(dmac=2, i2s=I2S.DEVICE_0, size=10, shift=0) # maix bit set shift=1 35 | print(sr.size()) 36 | print(sr) 37 | 38 | ## threshold 39 | sr.set_threshold(0, 0, 10000) 40 | 41 | ## record and get & set 42 | 43 | while True: 44 | time.sleep_ms(100) 45 | print(sr.state()) 46 | if sr.Done == sr.record(0): 47 | data = sr.get(0) 48 | print(data) 49 | break 50 | if sr.Speak == sr.state(): 51 | print('speak A') 52 | 53 | #sr.set(1, data) 54 | 55 | while True: 56 | time.sleep_ms(100) 57 | print(sr.state()) 58 | if sr.Done == sr.record(2): 59 | data = sr.get(2) 60 | print(data) 61 | break 62 | if sr.Speak == sr.state(): 63 | print('speak B') 64 | 65 | #sr.set(3, data) 66 | 67 | ## recognizer 68 | #sr.stop() 69 | #sr.run() 70 | 71 | print('recognizer') 72 | while True: 73 | time.sleep_ms(200) 74 | #print(sr.state()) 75 | #print(sr.dtw(data)) 76 | if sr.Done == sr.recognize(): 77 | res = sr.result() 78 | print(res) 79 | -------------------------------------------------------------------------------- /multimedia/speech_recognizer/maix_asr_2900k_0x500000.kmodel: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sipeed/MaixPy-v1_scripts/8d7c5f98ba654d226f433d31718d852674cab08d/multimedia/speech_recognizer/maix_asr_2900k_0x500000.kmodel -------------------------------------------------------------------------------- /multimedia/video/amigo_play_video.py: -------------------------------------------------------------------------------- 1 | from machine import I2C 2 | import nes, lcd, sys, time 3 | from sound import CubeAudio # see ../modules/es8374 put sound.py and es8374.py 4 | from fpioa_manager import fm 5 | from Maix import FPIOA, GPIO 6 | 7 | i2c = I2C(I2C.I2C3, freq=500*1000, sda=27, scl=24) 8 | CubeAudio.init(i2c) 9 | tmp = CubeAudio.check() 10 | print(tmp) 11 | 12 | CubeAudio.ready(volume=100) 13 | 14 | fm.fpioa.set_function(13,fm.fpioa.I2S0_MCLK) 15 | fm.fpioa.set_function(21,fm.fpioa.I2S0_SCLK) 16 | fm.fpioa.set_function(18,fm.fpioa.I2S0_WS) 17 | fm.fpioa.set_function(35,fm.fpioa.I2S0_IN_D0) 18 | fm.fpioa.set_function(34,fm.fpioa.I2S0_OUT_D2) 19 | 20 | import video 21 | v = video.open("/sd/badapple.avi") 22 | print(v) 23 | v.volume(90) 24 | while True: 25 | if v.play() == 0: 26 | print("play end") 27 | break 28 | -------------------------------------------------------------------------------- /multimedia/video/demo_video_capture.py: -------------------------------------------------------------------------------- 1 | import lcd 2 | import video 3 | import image 4 | 5 | lcd.init() 6 | v = video.open("/sd/badapple_320_240_15fps.avi") 7 | print(v) 8 | img = image.Image() 9 | while True: 10 | status = v.capture(img) 11 | if status != 0: 12 | lcd.display(img) 13 | else: 14 | print("end") 15 | break; 16 | v.__del__() -------------------------------------------------------------------------------- /multimedia/video/demo_video_play.py: -------------------------------------------------------------------------------- 1 | from Maix import GPIO, I2S 2 | 3 | from fpioa_manager import fm 4 | import lcd 5 | import video 6 | import time 7 | 8 | lcd.init() 9 | 10 | # AUDIO_PA_EN_PIN = None # Bit Dock and old MaixGo 11 | AUDIO_PA_EN_PIN = 32 # Maix Go(version 2.20) 12 | # AUDIO_PA_EN_PIN = 2 # Maixduino 13 | 14 | # init i2s(i2s0) 15 | i2s = I2S(I2S.DEVICE_0) 16 | 17 | # config i2s according to audio info 18 | i2s.channel_config(i2s.CHANNEL_1, I2S.TRANSMITTER, resolution=I2S.RESOLUTION_16_BIT, 19 | cycles=I2S.SCLK_CYCLES_32, align_mode=I2S.RIGHT_JUSTIFYING_MODE) 20 | 21 | # open audio PA 22 | if AUDIO_PA_EN_PIN: 23 | fm.register(AUDIO_PA_EN_PIN, fm.fpioa.GPIO1, force=True) 24 | wifi_en = GPIO(GPIO.GPIO1, GPIO.OUT) 25 | wifi_en.value(1) 26 | 27 | fm.register(34, fm.fpioa.I2S0_OUT_D1, force=True) 28 | fm.register(35, fm.fpioa.I2S0_SCLK, force=True) 29 | fm.register(33, fm.fpioa.I2S0_WS, force=True) 30 | 31 | v = video.open("/sd/badapple.avi") 32 | print(v) 33 | v.volume(50) 34 | while True: 35 | if v.play() == 0: 36 | print("play end") 37 | break 38 | v.__del__() 39 | -------------------------------------------------------------------------------- /multimedia/video/demo_video_record.py: -------------------------------------------------------------------------------- 1 | import sensor, image, lcd, time 2 | 3 | lcd.init(freq=15000000) 4 | sensor.reset() 5 | sensor.set_pixformat(sensor.RGB565) 6 | sensor.set_framesize(sensor.QVGA) 7 | 8 | sensor.set_hmirror(1) 9 | sensor.set_vflip(1) 10 | 11 | sensor.run(1) 12 | sensor.skip_frames(30) 13 | 14 | import video 15 | 16 | v = video.open("/sd/capture.avi", audio = False, record=1, interval=200000, quality=50) 17 | 18 | tim = time.ticks_ms() 19 | for i in range(50): 20 | tim = time.ticks_ms() 21 | img = sensor.snapshot() 22 | lcd.display(img) 23 | img_len = v.record(img) 24 | # print("record",time.ticks_ms() - tim) 25 | 26 | print("record_finish") 27 | v.record_finish() 28 | v.__del__() 29 | 30 | # play your record 31 | v = video.open("/sd/capture.avi") 32 | print(v) 33 | v.volume(50) 34 | while True: 35 | if v.play() == 0: 36 | print("play end") 37 | break 38 | 39 | print("play finish") 40 | v.__del__() 41 | 42 | lcd.clear() 43 | 44 | -------------------------------------------------------------------------------- /network/README.md: -------------------------------------------------------------------------------- 1 | # Usage 2 | 3 | ## network 4 | 5 | - [network_esp32.py](./network_esp32.py) 6 | - [network_espat.py](./network_espat.py) 7 | - [network_wiznet5k.py](./network_wiznet5k.py) 8 | 9 | > 使用 MaixPy IDE 的菜单功能【发送文件到板子】即可作为一个类库使用。 10 | 11 | Use the MaixPy IDE's menu functionality [send files to the board] as a class library. 12 | 13 | ```python 14 | from network_esp32 import wifi 15 | 16 | from network_espat import wifi 17 | 18 | from network_wiznet5k import lan 19 | ``` 20 | 21 | ## example 22 | 23 | > 使用网卡连接到网络后才能进行以下操作。 24 | 25 | Using the network card to connect to the network to make the following operation. 26 | 27 | - [demo_esp32_ap_scan.py](./demo_esp32_ap_scan.py) 28 | - [demo_esp32_ping.py](./demo_esp32_ping.py) 29 | 30 | - [demo_espat_ap_scan.py](./demo_espat_ap_scan.py) 31 | 32 | - [demo_socket_tcp_client.py](./demo_socket_tcp_client.py) 33 | - (run your pc python3 not maixpy)[demo_socket_tcp_server.py](./demo_socket_tcp_server.py) 34 | 35 | - [demo_socket_udp_client.py](./demo_socket_udp_client.py) 36 | - (run your pc python3 not maixpy)[demo_socket_udp_server.py](./demo_socket_udp_server.py) 37 | 38 | - [demo_socket_mqtt.py](./demo_socket_mqtt.py) 39 | 40 | - [demo_http_get_jpg.py](./demo_http_get_jpg.py) 41 | - [demo_socket_https.py](./demo_socket_https.py) 42 | 43 | - [demo_socket_send_pic.py](./demo_socket_send_pic.py) 44 | - (run your pc python3 not maixpy)[demo_socket_pic_server.py](./demo_socket_pic_server.py) 45 | 46 | ## other 47 | 48 | - [demo_espat_ap_test.py](./demo_espat_ap_test.py) 49 | - [espat_upgrade.py](./espat_upgrade.py) 50 | 51 | - [demo_esp32_read_adc.py](./demo_esp32_read_adc.py) 52 | -------------------------------------------------------------------------------- /network/demo_esp32_ap_scan.py: -------------------------------------------------------------------------------- 1 | # This file is part of MaixPY 2 | # Copyright (c) sipeed.com 3 | # 4 | # Licensed under the MIT license: 5 | # http://www.opensource.org/licenses/mit-license.php 6 | # 7 | 8 | # Uasge see readme.md 9 | from network_esp32 import wifi 10 | 11 | wifi.reset() 12 | enc_str = ["OPEN", "", "WPA PSK", "WPA2 PSK", "WPA/WPA2 PSK", "", "", ""] 13 | aps = wifi.nic.scan() 14 | for ap in aps: 15 | print("SSID:{:^20}, ENC:{:>5} , RSSI:{:^20}".format(ap[0], enc_str[ap[1]], ap[2])) 16 | 17 | ''' 18 | >>> 19 | raw REPL; CTRL-B to exit 20 | >OK 21 | SSID: Sipeed_2.4G , ENC:WPA/WPA2 PSK , RSSI: -57 22 | SSID: ChinaNet-Ffdj , ENC:WPA/WPA2 PSK , RSSI: -58 23 | SSID: wea_615 , ENC:WPA/WPA2 PSK , RSSI: -67 24 | SSID: ChinaNet-PnAN , ENC:WPA/WPA2 PSK , RSSI: -70 25 | SSID: wea_613 , ENC:WPA/WPA2 PSK , RSSI: -73 26 | SSID: ChinaNet-TnSG , ENC:WPA/WPA2 PSK , RSSI: -82 27 | SSID: chipshine_GUEST , ENC:WPA/WPA2 PSK , RSSI: -83 28 | SSID: ASUS , ENC:WPA/WPA2 PSK , RSSI: -86 29 | SSID: gta888 , ENC:WPA/WPA2 PSK , RSSI: -87 30 | SSID: huahua , ENC:WPA/WPA2 PSK , RSSI: -88 31 | > 32 | MicroPython v0.5.1-136-g039f72b6c-dirty on 2020-11-18; Sipeed_M1 with kendryte-k210 33 | Type "help()" for more information. 34 | >>> 35 | ''' 36 | -------------------------------------------------------------------------------- /network/demo_esp32_ping.py: -------------------------------------------------------------------------------- 1 | # This file is part of MaixPY 2 | # Copyright (c) sipeed.com 3 | # 4 | # Licensed under the MIT license: 5 | # http://www.opensource.org/licenses/mit-license.php 6 | # 7 | 8 | # Uasge see readme.md 9 | from network_esp32 import wifi 10 | 11 | SSID = "Sipeed_2.4G" 12 | PASW = "XXXXXXXX" 13 | 14 | if wifi.isconnected() == False: 15 | for i in range(5): 16 | try: 17 | wifi.reset() 18 | print('try AT connect wifi...') 19 | wifi.connect(SSID, PASW) 20 | if wifi.isconnected(): 21 | break 22 | except Exception as e: 23 | print(e) 24 | print('network state:', wifi.isconnected(), wifi.ifconfig()) 25 | 26 | print("ping baidu.com:", wifi.nic.ping("baidu.com"), "ms") 27 | wifi.nic.disconnect() 28 | 29 | ''' 30 | ESP32_SPI firmware version: 1.4.0 31 | try AT connect wifi... 32 | network state: True ('192.168.0.180', '255.255.255.0', '192.168.0.1') 33 | ping baidu.com: 40 ms 34 | > 35 | MicroPython v0.5.1-136-g039f72b6c-dirty on 2020-11-18; Sipeed_M1 with kendryte-k210 36 | Type "help()" for more information. 37 | >>> 38 | ''' 39 | -------------------------------------------------------------------------------- /network/demo_esp32_read_adc.py: -------------------------------------------------------------------------------- 1 | # This file is part of MaixPY 2 | # Copyright (c) sipeed.com 3 | # 4 | # Licensed under the MIT license: 5 | # http://www.opensource.org/licenses/mit-license.php 6 | # 7 | 8 | # Uasge see readme.md 9 | # from network_esp32 import wifi 10 | 11 | import time, network 12 | from Maix import GPIO 13 | from fpioa_manager import fm 14 | 15 | class wifi(): 16 | # IO map for ESP32 on Maixduino 17 | fm.register(25,fm.fpioa.GPIOHS10)#cs 18 | fm.register(8,fm.fpioa.GPIOHS11)#rst 19 | fm.register(9,fm.fpioa.GPIOHS12)#rdy 20 | print("Use Hareware SPI for other maixduino") 21 | fm.register(28,fm.fpioa.SPI1_D0, force=True)#mosi 22 | fm.register(26,fm.fpioa.SPI1_D1, force=True)#miso 23 | fm.register(27,fm.fpioa.SPI1_SCLK, force=True)#sclk 24 | nic = network.ESP32_SPI(cs=fm.fpioa.GPIOHS10, rst=fm.fpioa.GPIOHS11, rdy=fm.fpioa.GPIOHS12, spi=1) 25 | 26 | print("ESP32_SPI firmware version:", wifi.nic.version()) 27 | 28 | # get ADC0 ADC1 ADC2 29 | adc = wifi.nic.adc((0,1,2)) 30 | print(adc) 31 | 32 | while True: 33 | try: 34 | # get ADC0~5 35 | adc = wifi.nic.adc() 36 | except Exception as e: 37 | print(e) 38 | continue 39 | for v in adc: 40 | print("%04d" %(v), end=" ") 41 | print(' : adc') 42 | 43 | ''' 44 | MicroPython v0.5.1-136-g039f72b6c-dirty on 2020-11-18; Sipeed_M1 with kendryte-k210 45 | Type "help()" for more information. 46 | >>> 47 | raw REPL; CTRL-B to exit 48 | >OK 49 | (2370, 3102, 3071) 50 | 2017 2753 0977 2709 0963 0855 : adc 51 | 0617 0757 0150 0095 0133 0153 : adc 52 | 1319 1478 0955 0939 0698 0619 : adc 53 | 2403 3231 3299 3298 1483 0779 : adc 54 | 1119 1815 1274 1315 0230 0255 : adc 55 | 0951 0951 0295 0283 0319 0399 : adc 56 | 2175 2769 2576 2579 1487 1104 : adc 57 | 1995 2846 2647 2699 0839 0441 : adc 58 | ''' 59 | -------------------------------------------------------------------------------- /network/demo_espat_ap_scan.py: -------------------------------------------------------------------------------- 1 | # This file is part of MaixPY 2 | # Copyright (c) sipeed.com 3 | # 4 | # Licensed under the MIT license: 5 | # http://www.opensource.org/licenses/mit-license.php 6 | # 7 | 8 | #from board import board_info 9 | #from Maix import config 10 | #tmp = config.get_value('board_info', None) 11 | #board_info.load(tmp) 12 | 13 | from network_espat import wifi 14 | wifi.reset() 15 | 16 | print(wifi.at_cmd("AT\r\n")) 17 | 18 | ap_info = [] 19 | 20 | import time 21 | while True: 22 | time.sleep(1) 23 | print('ap-scan...') 24 | try: 25 | tmp = wifi.at_cmd('AT+CWLAP\r\n') 26 | #ap_info = wifi.nic.scan() 27 | if tmp != None and len(tmp) > 64: 28 | #print(tmp[len('+CWLAP:'):].split(b"\r\n")) 29 | aps = tmp.replace(b'+CWLAP:', b'').replace(b'\r\n\r\nOK\r\n', b'') 30 | #print(aps) 31 | ap_info = aps.split(b"\r\n") 32 | #print(ap_info) 33 | break 34 | except Exception as e: 35 | print('error', e) 36 | 37 | def wifi_deal_ap_info(info): 38 | res = [] 39 | for ap_str in info: 40 | ap_str = ap_str.split(b",") 41 | #print(ap_str) 42 | info_one = [] 43 | for node in ap_str[1:-1]: 44 | if node.startswith(b'"'): 45 | info_one.append(node[1:-1]) 46 | else: 47 | info_one.append(int(node)) 48 | res.append(info_one) 49 | return res 50 | 51 | #print(ap_info) 52 | 53 | ap_info = wifi_deal_ap_info(ap_info) 54 | 55 | ap_info.sort(key=lambda x:x[2], reverse=True) # sort by rssi 56 | for ap in ap_info: 57 | print("SSID:{:^20}, RSSI:{:>5} , MAC:{:^20}".format(ap[0], ap[1], ap[2]) ) 58 | 59 | ''' 60 | MicroPython fa51290 on 2020-12-07; Sipeed_M1 with kendryte-k210 61 | Type "help()" for more information.>>> 62 | >>> 63 | >>> 64 | raw REPL; CTRL-B to exit 65 | >OK 66 | reset... 67 | b'\r\n\r\nOK\r\n' 68 | ap-scan... 69 | ap-scan... 70 | ap-scan... 71 | ap-scan... 72 | SSID: webduino.io , RSSI: -50 , MAC: b6:e4:2f:f9:2f:1f 73 | SSID: Sipeed_2.4G , RSSI: -73 , MAC: b0:b9:8a:5b:be:7f 74 | SSID: ChinaNet-Ffdj , RSSI: -91 , MAC: a4:29:40:cc:51:f4 75 | SSID: wea_615 , RSSI: -91 , MAC: 64:6e:97:e1:86:e5 76 | SSID: OpenWrt , RSSI: -88 , MAC: 20:76:93:40:15:9c 77 | > 78 | ''' 79 | -------------------------------------------------------------------------------- /network/demo_espat_ap_test.py: -------------------------------------------------------------------------------- 1 | # This file is part of MaixPY 2 | # Copyright (c) sipeed.com 3 | # 4 | # Licensed under the MIT license: 5 | # http://www.opensource.org/licenses/mit-license.php 6 | # 7 | 8 | from network_espat import wifi 9 | wifi.reset() 10 | 11 | print(wifi.at_cmd("AT\r\n")) 12 | print(wifi.at_cmd("AT+GMR\r\n")) 13 | 14 | ''' 15 | >>> reset... 16 | b'\r\n\r\nOK\r\n' 17 | b'AT version:1.1.0.0(May 11 2016 18:09:56)\r\nSDK version:1.5.4(baaeaebb)\r\ncompile time:May 20 2016 15:06:44\r\nOK\r\n' 18 | MicroPython v0.5.1-136-g039f72b6c-dirty on 2020-11-18; Sipeed_M1 with kendryte-k210 19 | Type "help()" for more information. 20 | >>> 21 | ''' 22 | -------------------------------------------------------------------------------- /network/demo_socket_https.py: -------------------------------------------------------------------------------- 1 | # This file is part of MaixPY 2 | # Copyright (c) sipeed.com 3 | # 4 | # Licensed under the MIT license: 5 | # http://www.opensource.org/licenses/mit-license.php 6 | # 7 | 8 | SSID = "Sipeed_2.4G" 9 | PASW = "xxxxxxxx" 10 | 11 | def enable_esp32(): 12 | from network_esp32 import wifi 13 | if wifi.isconnected() == False: 14 | for i in range(5): 15 | try: 16 | # Running within 3 seconds of power-up can cause an SD load error 17 | # wifi.reset(is_hard=False) 18 | wifi.reset(is_hard=True) 19 | print('try AT connect wifi...') 20 | wifi.connect(SSID, PASW) 21 | if wifi.isconnected(): 22 | break 23 | except Exception as e: 24 | print(e) 25 | print('network state:', wifi.isconnected(), wifi.ifconfig()) 26 | 27 | enable_esp32() 28 | 29 | def enable_espat(): 30 | from network_espat import wifi 31 | if wifi.isconnected() == False: 32 | for i in range(5): 33 | try: 34 | # Running within 3 seconds of power-up can cause an SD load error 35 | # wifi.reset(is_hard=False) 36 | wifi.reset() 37 | print('try AT connect wifi...') 38 | wifi.connect(SSID, PASW) 39 | if wifi.isconnected(): 40 | break 41 | except Exception as e: 42 | print(e) 43 | print('network state:', wifi.isconnected(), wifi.ifconfig()) 44 | 45 | #enable_espat() 46 | 47 | def network_wiznet5k(): 48 | from network_wiznet5k import lan 49 | from machine import SPI 50 | from Maix import GPIO 51 | if lan.isconnected() == False: 52 | WIZNET5K_SPI_SCK = 21 53 | WIZNET5K_SPI_MOSI = 8 54 | WIZNET5K_SPI_MISO = 15 55 | WIZNET5K_SPI_CS = 20 56 | spi1 = SPI(4, mode=SPI.MODE_MASTER, baudrate=600 * 1000, 57 | polarity=0, phase=0, bits=8, firstbit=SPI.MSB, sck=WIZNET5K_SPI_SCK, mosi=WIZNET5K_SPI_MOSI, miso=WIZNET5K_SPI_MISO) 58 | for i in range(5): 59 | try: 60 | lan.reset(spi1, WIZNET5K_SPI_CS) 61 | print('try connect lan...') 62 | if lan.isconnected(): 63 | break 64 | except Exception as e: 65 | print(e) 66 | print('network state:', lan.isconnected(), lan.ifconfig()) 67 | 68 | # network_wiznet5k() 69 | 70 | try: 71 | import usocket as socket 72 | except: 73 | import socket 74 | 75 | TestHttps = False 76 | 77 | def main(use_stream=True): 78 | s = socket.socket() 79 | s.settimeout(1) 80 | host = "www.baidu.com" 81 | if TestHttps: 82 | ai = socket.getaddrinfo(host, 443) 83 | else: 84 | ai = socket.getaddrinfo(host, 80) 85 | print("Address infos:", ai) 86 | addr = ai[0][-1] 87 | for i in range(5): 88 | try: 89 | print("Connect address:", addr) 90 | s.connect(addr) 91 | 92 | if TestHttps: # ssl 93 | try: 94 | import ussl as ssl 95 | except: 96 | import ssl 97 | tmp = ssl.wrapsocket(s, server_hostname=host) 98 | tmp.write(b"GET / HTTP/1.1\r\n\r\n") 99 | else: 100 | s.write(b"GET / HTTP/1.1\r\n\r\n") 101 | data = (s.readline('\r\n')) 102 | print(data) 103 | with open('test.txt', 'wb') as f: 104 | f.write(data) 105 | 106 | except Exception as e: 107 | print(e) 108 | 109 | s.close() 110 | 111 | main() 112 | 113 | 114 | -------------------------------------------------------------------------------- /network/demo_socket_mqtt.py: -------------------------------------------------------------------------------- 1 | 2 | # Refer to https://github.com/daq-tools/umqtt-example 3 | -------------------------------------------------------------------------------- /network/demo_socket_pic_server.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | #!/usr/bin/env python2 3 | # 4 | # This file is part of MaixPY 5 | # Copyright (c) sipeed.com 6 | # 7 | # Licensed under the MIT license: 8 | # http://www.opensource.org/licenses/mit-license.php 9 | # 10 | 11 | ''' 12 | # Network tools srcipt 13 | 14 | ## pic_server.py 15 | 16 | LAN map transmission server 17 | 18 | - Installation dependency 19 | 20 | update pip 21 | 22 | ```shell 23 | # python -m pip install --upgrade pip 24 | python -m pip install --upgrade pip -i https://pypi.tuna.tsinghua.edu.cn/simple # Domestic Tsinghua source 25 | ``` 26 | 27 | update pygame 28 | 29 | ```shell 30 | # pip3 install pygame 31 | pip3 install pygame -i https://pypi.tuna.tsinghua.edu.cn/simple # Domestic Tsinghua source 32 | ``` 33 | 34 | - run server 35 | 36 | ```shell 37 | python3 demo_socket_pic_server.py 38 | ``` 39 | ''' 40 | 41 | import socket 42 | import time 43 | import threading 44 | import datetime 45 | import pygame 46 | from pygame.locals import QUIT, KEYDOWN, K_f, K_F11, FULLSCREEN 47 | 48 | local_ip = "" 49 | local_port = 3456 50 | width = 320 51 | height = 240 52 | 53 | # jpeg 20 fps 54 | # esp32 spi dma temp buffer MAX Len: 4k 55 | 56 | 57 | def receiveThread(conn): 58 | conn.settimeout(10) 59 | conn_end = False 60 | pack_size = 1024*5 61 | while True: 62 | if conn_end: 63 | break 64 | img = b"" 65 | tmp = b'' 66 | while True: 67 | try: 68 | client_data = conn.recv(1) 69 | except socket.timeout: 70 | conn_end = True 71 | break 72 | if tmp == b'\xFF' and client_data == b'\xD8': 73 | img = b'\xFF\xD8' 74 | break 75 | tmp = client_data 76 | while True: 77 | try: 78 | client_data = conn.recv(4096) 79 | except socket.timeout: 80 | client_data = None 81 | conn_end = True 82 | if not client_data: 83 | break 84 | # print("received data,len:",len(client_data) ) 85 | img += client_data 86 | if img[-2:] == b'\xFF\xD9': 87 | break 88 | if len(client_data) > pack_size: 89 | break 90 | print("recive end, pic len:", len(img)) 91 | 92 | if not img.startswith(b'\xFF\xD8') or not img.endswith(b'\xFF\xD9'): 93 | print("image error") 94 | continue 95 | f = open("tmp.jpg", "wb") 96 | f.write(img) 97 | f.close() 98 | try: 99 | surface = pygame.image.load("tmp.jpg").convert() 100 | screen.blit(surface, (0, 0)) 101 | pygame.display.update() 102 | print("recieve ok") 103 | except Exception as e: 104 | print(e) 105 | conn.close() 106 | print("receive thread end") 107 | 108 | 109 | pygame.init() 110 | screen = pygame.display.set_mode((width, height), 0, 32) 111 | pygame.display.set_caption("pic from client") 112 | 113 | ip_port = (local_ip, local_port) 114 | sk = socket.socket() 115 | sk.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 116 | sk.bind(ip_port) 117 | sk.listen(50) 118 | print("accept now,wait for client") 119 | 120 | 121 | def server(): 122 | while True: 123 | conn, addr = sk.accept() 124 | print("hello client,ip:") 125 | print(addr) 126 | t = threading.Thread(target=receiveThread, args=(conn,)) 127 | t.setDaemon(True) 128 | t.start() 129 | 130 | 131 | tmp = threading.Thread(target=server, args=()) 132 | tmp.setDaemon(True) 133 | tmp.start() 134 | 135 | while True: 136 | 137 | for event in pygame.event.get(): 138 | if event.type == pygame.QUIT: 139 | exit() 140 | -------------------------------------------------------------------------------- /network/demo_socket_tcp_client.py: -------------------------------------------------------------------------------- 1 | # This file is part of MaixPY 2 | # Copyright (c) sipeed.com 3 | # 4 | # Licensed under the MIT license: 5 | # http://www.opensource.org/licenses/mit-license.php 6 | # 7 | 8 | #network_wiznet5k() 9 | 10 | SSID = "Sipeed_2.4G" 11 | PASW = "xxxxxxxx" 12 | 13 | def enable_esp32(): 14 | from network_esp32 import wifi 15 | if wifi.isconnected() == False: 16 | for i in range(5): 17 | try: 18 | # Running within 3 seconds of power-up can cause an SD load error 19 | # wifi.reset(is_hard=False) 20 | wifi.reset(is_hard=True) 21 | print('try AT connect wifi...') 22 | wifi.connect(SSID, PASW) 23 | if wifi.isconnected(): 24 | break 25 | except Exception as e: 26 | print(e) 27 | print('network state:', wifi.isconnected(), wifi.ifconfig()) 28 | 29 | enable_esp32() 30 | 31 | def enable_espat(): 32 | from network_espat import wifi 33 | if wifi.isconnected() == False: 34 | for i in range(5): 35 | try: 36 | # Running within 3 seconds of power-up can cause an SD load error 37 | # wifi.reset(is_hard=False) 38 | wifi.reset() 39 | print('try AT connect wifi...') 40 | wifi.connect(SSID, PASW) 41 | if wifi.isconnected(): 42 | break 43 | except Exception as e: 44 | print(e) 45 | print('network state:', wifi.isconnected(), wifi.ifconfig()) 46 | 47 | #enable_espat() 48 | 49 | def network_wiznet5k(): 50 | from network_wiznet5k import lan 51 | from machine import SPI 52 | from Maix import GPIO 53 | if lan.isconnected() == False: 54 | WIZNET5K_SPI_SCK = 21 55 | WIZNET5K_SPI_MOSI = 8 56 | WIZNET5K_SPI_MISO = 15 57 | WIZNET5K_SPI_CS = 20 58 | spi1 = SPI(4, mode=SPI.MODE_MASTER, baudrate=600 * 1000, 59 | polarity=0, phase=0, bits=8, firstbit=SPI.MSB, sck=WIZNET5K_SPI_SCK, mosi=WIZNET5K_SPI_MOSI, miso=WIZNET5K_SPI_MISO) 60 | for i in range(5): 61 | try: 62 | lan.reset(spi1, WIZNET5K_SPI_CS) 63 | print('try connect lan...') 64 | if lan.isconnected(): 65 | break 66 | except Exception as e: 67 | print(e) 68 | print('network state:', lan.isconnected(), lan.ifconfig()) 69 | 70 | # network_wiznet5k() 71 | 72 | import socket 73 | 74 | ADDR = ("192.168.0.107", 60000) 75 | 76 | sock = socket.socket() 77 | sock.connect(ADDR) 78 | 79 | sock.settimeout(1) 80 | while 1: 81 | sock.send("hello\n") 82 | #data = sock.recv(10) # old maxipy have bug (recv timeout no return last data) 83 | #print(data) # fix 84 | try: 85 | data = b"" 86 | while True: 87 | tmp = sock.recv(1) 88 | print(tmp) 89 | if len(tmp) == 0: 90 | raise Exception('timeout or disconnected') 91 | data += tmp 92 | except Exception as e: 93 | print("rcv:", len(data), data) 94 | #time.sleep(2) 95 | 96 | sock.close() 97 | -------------------------------------------------------------------------------- /network/demo_socket_tcp_server.py: -------------------------------------------------------------------------------- 1 | ''' 2 | This is a testing program 3 | the program is used to start server 4 | ''' 5 | import socket 6 | import sys 7 | import time 8 | 9 | def start_tcp_server(ip, port): 10 | #create socket 11 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 12 | server_address = (ip, port) 13 | #bind port 14 | print('starting listen on ip %s, port %s' % server_address) 15 | sock.bind(server_address) 16 | #starting listening, allow only one connection 17 | try: 18 | sock.listen(1) 19 | except socket.error as e: 20 | print("fail to listen on port %s" % e) 21 | sys.exit(1) 22 | while True: 23 | print("waiting for connection") 24 | client, addr = sock.accept() 25 | print('having a connection') 26 | for i in range(5): 27 | print('send message') 28 | client.send(b'I am server') 29 | print(client.recv(6)) 30 | print('send OSError: [Errno 128(32)] ENOTCONN') 31 | client.close() 32 | 33 | if __name__ == '__main__': 34 | start_tcp_server('0.0.0.0', 60000) 35 | -------------------------------------------------------------------------------- /network/demo_socket_udp_client.py: -------------------------------------------------------------------------------- 1 | # This file is part of MaixPY 2 | # Copyright (c) sipeed.com 3 | # 4 | # Licensed under the MIT license: 5 | # http://www.opensource.org/licenses/mit-license.php 6 | # 7 | 8 | #network_wiznet5k() 9 | 10 | SSID = "Sipeed_2.4G" 11 | PASW = "xxxxxxxx" 12 | 13 | def enable_esp32(): 14 | from network_esp32 import wifi 15 | if wifi.isconnected() == False: 16 | for i in range(5): 17 | try: 18 | # Running within 3 seconds of power-up can cause an SD load error 19 | # wifi.reset(is_hard=False) 20 | wifi.reset(is_hard=True) 21 | print('try AT connect wifi...') 22 | wifi.connect(SSID, PASW) 23 | if wifi.isconnected(): 24 | break 25 | except Exception as e: 26 | print(e) 27 | print('network state:', wifi.isconnected(), wifi.ifconfig()) 28 | 29 | #enable_esp32() 30 | 31 | # UDP not support enable_espat 32 | 33 | def network_wiznet5k(): 34 | from network_wiznet5k import lan 35 | from machine import SPI 36 | from Maix import GPIO 37 | if lan.isconnected() == False: 38 | WIZNET5K_SPI_SCK = 21 39 | WIZNET5K_SPI_MOSI = 8 40 | WIZNET5K_SPI_MISO = 15 41 | WIZNET5K_SPI_CS = 20 42 | spi1 = SPI(4, mode=SPI.MODE_MASTER, baudrate=600 * 1000, 43 | polarity=0, phase=0, bits=8, firstbit=SPI.MSB, sck=WIZNET5K_SPI_SCK, mosi=WIZNET5K_SPI_MOSI, miso=WIZNET5K_SPI_MISO) 44 | for i in range(5): 45 | try: 46 | lan.reset(spi1, WIZNET5K_SPI_CS) 47 | print('try connect lan...') 48 | if lan.isconnected(): 49 | break 50 | except Exception as e: 51 | print(e) 52 | print('network state:', lan.isconnected(), lan.ifconfig()) 53 | 54 | # network_wiznet5k() 55 | 56 | import socket 57 | 58 | ADDR = ("192.168.0.107", 60000) 59 | 60 | sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 61 | sock.settimeout(1) 62 | 63 | while 1: 64 | try: 65 | sock.sendto("hello\n", ADDR) 66 | data, addr = sock.recvfrom(1024) 67 | except Exception as e: 68 | print("receive error:", e) 69 | continue 70 | print("addr:", addr, "data:", data) 71 | time.sleep(2) 72 | 73 | sock.close() 74 | 75 | ''' 76 | >>> 77 | raw REPL; CTRL-B to exit 78 | >OK 79 | network state: True ('192.168.0.186', '255.255.255.0', '192.168.0.1') 80 | addr: ('192.168.0.107', 60000) data: b'HELLO\n' 81 | addr: ('192.168.0.107', 60000) data: b'HELLO\n' 82 | addr: ('192.168.0.107', 60000) data: b'HELLO\n' 83 | ''' 84 | -------------------------------------------------------------------------------- /network/demo_socket_udp_server.py: -------------------------------------------------------------------------------- 1 | import socket 2 | BUFSIZE = 1024 3 | ip_port = ('0.0.0.0', 60000) 4 | server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # udp 5 | server.bind(ip_port) 6 | while True: 7 | data,client_addr = server.recvfrom(BUFSIZE) 8 | print('server recv', data) 9 | server.sendto(data.upper(),client_addr) 10 | server.close() 11 | 12 | ''' 13 | ('server recv', 'hello\n') 14 | ('server recv', 'hello\n') 15 | ('server recv', 'hello\n') 16 | ('server recv', 'hello\n') 17 | ('server recv', 'hello\n') 18 | ('server recv', 'hello\n') 19 | ''' 20 | -------------------------------------------------------------------------------- /network/network_wiznet5k.py: -------------------------------------------------------------------------------- 1 | import network 2 | 3 | class lan: 4 | 5 | nic = None 6 | 7 | def reset(spi1, cs, force=False, reply=5): 8 | if force == False and __class__.isconnected(): 9 | return True 10 | try: 11 | # create wiznet5k nic 12 | __class__.nic = network.WIZNET5K(spi=spi1, cs=cs) 13 | # time.sleep_ms(500) # wait at ready to connect 14 | except Exception as e: 15 | print(e) 16 | return False 17 | return True 18 | 19 | def ifconfig(): # should check ip != 0.0.0.0 20 | if __class__.nic != None: 21 | return __class__.nic.ifconfig() 22 | 23 | def isconnected(): 24 | if __class__.nic != None: 25 | return __class__.nic.isconnected() 26 | return False 27 | 28 | if __name__ == '__main__': 29 | 30 | from machine import SPI 31 | from Maix import GPIO 32 | import socket, time 33 | from fpioa_manager import fm 34 | 35 | ################ config ################ 36 | local_ip = "192.168.0.117" 37 | local_netmask = "255.255.255.0" 38 | local_gateway = "255.255.255.0" 39 | local_dns_server = "8.8.8.8" 40 | 41 | server_ip = "192.168.0.141" 42 | server_port = 8000 43 | addr = (server_ip, server_port) 44 | ####################################### 45 | 46 | def network_wiznet5k(): 47 | if lan.isconnected() == False: 48 | WIZNET5K_SPI_SCK = 21 49 | WIZNET5K_SPI_MOSI = 8 50 | WIZNET5K_SPI_MISO = 15 51 | WIZNET5K_SPI_CS = 20 52 | spi1 = SPI(4, mode=SPI.MODE_MASTER, baudrate=600 * 1000, 53 | polarity=0, phase=0, bits=8, firstbit=SPI.MSB, sck=WIZNET5K_SPI_SCK, mosi=WIZNET5K_SPI_MOSI, miso=WIZNET5K_SPI_MISO) 54 | 55 | for i in range(5): 56 | try: 57 | lan.reset(spi1, WIZNET5K_SPI_CS) 58 | print('try connect lan...') 59 | if lan.isconnected(): 60 | break 61 | except Exception as e: 62 | print(e) 63 | print('network state:', lan.isconnected(), lan.ifconfig()) 64 | 65 | network_wiznet5k() 66 | 67 | if lan.isconnected(): 68 | is_dhcp = False 69 | if is_dhcp: 70 | # #dhcp: Dynamic IP acquisition, It's not necessary 71 | while True: 72 | if(lan.nic.dhclient()): 73 | print("DHCP IP:", lan.ifconfig()) 74 | break 75 | else: 76 | lan.ifconfig() 77 | 78 | ############################## UDP Test ############################## 79 | # # The server must first know the client's IP and port number through the message sent by the client before it send the message to the client 80 | sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 81 | sock.settimeout(5) 82 | 83 | while True: 84 | sock.sendto("Client send: hello UDP\n".encode(), addr) 85 | try: 86 | data, addr1 = sock.recvfrom(10) 87 | print("Recv from server: ", data) 88 | except Exception as e: 89 | pass 90 | time.sleep_ms(500) 91 | sock.close() 92 | ############################ UDP Test end ############################ 93 | 94 | ############################## TCP Test ############################## 95 | # The TCP server needs to be pre-started 96 | # sock = socket.socket() 97 | # sock.connect(addr) 98 | # while 1: 99 | # sock.send("Client send: Hello TCP\n") 100 | # try: 101 | # data = sock.recv(10) 102 | # print("Recv from Server: ", data) 103 | # except Exception as e: 104 | # print(e) 105 | # time.sleep(500) 106 | # sock.close() 107 | ############################ TCP Test end ############################ 108 | --------------------------------------------------------------------------------