4967 views|33 replies

3386

Posts

0

Resources
The OP
 

MicroPython Hands-on (04) - Basic Examples of Learning MicroPython from Scratch [Copy link]

 
 

1、hello micropython

#MicroPython Hands-on (04) - Basic examples of learning MicroPython from scratch

#Program 1: hello micropython

#MicroPython动手做(04)——零基础学MaixPy之基本示例
#程序之一:hello micropython


import sys

for i in range(0, 2):

    print("hello micropython")

    print("hello ", end="micropython\n")


print("implementation:", sys.implementation)

print("platform:", sys.platform)

print("path:", sys.path)

print("Python version:", sys.version)


print("please input string, end with Enter")

r = sys.stdin.readline()

w_len = sys.stdout.write(r)



This content is originally created by eagler8 , a user of EEWORLD forum. If you want to reprint or use it for commercial purposes, you must obtain the author's consent and indicate the source

Latest reply

You can try it, the cost is lower   Details Published on 2020-4-4 11:29
 
 

3386

Posts

0

Resources
2
 

 
 
 

3386

Posts

0

Resources
3
 
This post was last edited by eagler8 on 2020-4-2 21:51

sys – system-specific function module (one of the standard libraries)

sys.implementation - an object containing information about the current Python implementation
System: micropythonFirmware
: V0.5.0

sys.platform——The platform running MicroPython
Platform: MaixPy

sys.path - a mutable list of directories to search for imported modules
Paths: ['', '.', '/flash']

sys.version - the Python version implemented, returns a string
Python version: 3.4.0

sys.stdin - standard input
sys.stdout - standard output

 
 
 

3386

Posts

0

Resources
4
 
This post was last edited by eagler8 on 2020-4-3 09:22

2. Query the flash directory

#MicroPython动手做(04)——零基础学MaixPy之基本示例
#程序之二:查询闪存目录

import uos

mount_points = uos.listdir("/")
for fs in mount_points:
    print("------------")
    print(" dir:", fs)
    uos.listdir("/"+fs)

 
 
 

3386

Posts

0

Resources
5
 
This post was last edited by eagler8 on 2020-4-3 09:22

 
 
 

3386

Posts

0

Resources
6
 
This post was last edited by eagler8 on 2020-4-3 09:23

uos – basic "operating system" service module (standard library)

uos.ilistdir([dir])
This function returns an iterator and then generates tuples corresponding to the entries in the listed directory. If no arguments are passed, it lists the current directory, otherwise it lists the directory given by dir.

dir: flash
['boot.py', 'main.py', 'freq.conf']

 
 
 

3386

Posts

0

Resources
7
 

3. JSON encoding and decoding

#MicroPython动手做(04)——零基础学MaixPy之基本示例
#程序之三:JSON编码和解码

import ujson

json_str = '''{

    "name": "sipeed",

    "babies": [

        {

            "name": "maixpy",

            "birthday": 2.9102,

            "sex": "unstable"

        }

    ]

}'''


obj = ujson.loads(json_str)

print(obj["name"])

print(obj["babies"])

 
 
 

3386

Posts

0

Resources
8
 

 
 
 

3386

Posts

0

Resources
9
 

ujson – Encoding and decoding module (standard library)
This module implements a subset of the corresponding CPython module, allowing conversion between Python objects and the JSON data format.

load
ujson.load(stream)
Parses the given stream, interpreting it as a JSON string and deserializing the data into Python objects. Returns the resulting object. Parsing continues until end-of-file is encountered. If the data in the stream is not correctly formed, a ValueError is raised.

loads
ujson.loads(str)
Parses JSON str and returns an object. Raises ValueError if the string format is wrong.

 
 
 

3386

Posts

0

Resources
10
 
This post was last edited by eagler8 on 2020-4-3 11:26

4. Thread multithreading

#MicroPython动手做(04)——零基础学MaixPy之基本示例
#程序之四:thread多线程


import _thread

import time


def func(name):

    while 1:

        print("hello {}".format(name))

        time.sleep(1)


_thread.start_new_thread(func,("1",))

_thread.start_new_thread(func,("2",))


while 1:

    pass

 
 
 

3386

Posts

0

Resources
11
 

 
 
 

3386

Posts

0

Resources
12
 

_thread Multithreading Support Module
This module provides low-level primitives for working with multiple threads (also called lightweight processes or tasks) - multiple threads of control that share their global data space. For synchronization, simple locks (also called mutexes or binary semaphores) are provided. The threading module provides easy-to-use functions and higher-level threading APIs are built on top of this module.

_thread.start_new_thread(函数,args [,kwargs ] )


Starts a new thread and returns its identifier. The thread executes function function with the argument list args (which must be a tuple). The optional kwargs argument specifies a dictionary of keyword arguments. The thread exits silently when the function returns. When the function terminates with an unhandled exception, a stack trace is printed and then the thread exits (but other threads continue to run).

 
 
 

3386

Posts

0

Resources
13
 

5. Update frequency demonstration

#MicroPython动手做(04)——零基础学MaixPy之基本示例
#程序之五:更新频率演示

from Maix import freq
 
cpu_freq, kpu_freq = freq.get()
print(cpu_freq, kpu_freq)
 
freq.set(cpu = 400, pll1=400, kpu_div = 1)

 
 
 

3386

Posts

0

Resources
14
 

 
 
 

3386

Posts

0

Resources
15
 

6. Pin Index

#MicroPython动手做(04)——零基础学MaixPy之基本示例
#程序之六:引脚索引

from board import board_info

wifi_en_pin = board_info.WIFI_EN
print(wifi_en_pin)#输出为8
board_info.pin_map()#打印所有
board_info.pin_map(8)#只打印8号引脚的信息

 
 
 

3386

Posts

0

Resources
16
 

 
 
 

3386

Posts

0

Resources
17
 

board_info built-in library
Mainly used to facilitate users to use the development board pin configuration, which has built-in human-friendly naming and interfaces, allowing users to reduce their dependence on electrical connection schematics. It is an internally defined Board_Info global variable, written in MicroPython syntax.

Pin index
It mainly converts numbers into human-friendly strings to facilitate programming. Enter the following, be careful not to ignore the ., and then press the tab key to complete, you can see the board-level pin functions
board_info.

For example
, if you enter the following code, the number 8 will be returned, which represents the 8th pin of the development board, and its electrical connection is the enable pin of the wifi module
board_info.WIFI_EN

Search method
When the user is not sure about the pin electrical connection, this method can be used to search
board_info.pin_map(pin_num)

Parameters
This method takes no parameters or takes one parameter
pin_num: pin number, range [6,47]
When no parameters are passed, the board-level electrical connection information of all pins will be printed. When parameters are passed, only the board-level electrical connection information of the specified pin will be printed.

 
 
 

3386

Posts

0

Resources
18
 

7. Print information after 3 seconds

#MicroPython动手做(04)——零基础学MaixPy之基本示例
#程序之七:定时3秒后打印信息

from machine import Timer

def on_timer(timer):
    print("time up:",timer)
    print("param:",timer.callback_arg())

tim = Timer(Timer.TIMER0, Timer.CHANNEL0, mode=Timer.MODE_ONE_SHOT, period=3000, callback=on_timer, arg=on_timer)
print("period:",tim.period())

 
 
 

3386

Posts

0

Resources
19
 

 
 
 

3386

Posts

0

Resources
20
 

machine.Timer function
Hardware timer can be used to trigger tasks or process tasks at a fixed time. When the set time is reached, it can trigger an interrupt (call a callback function). It has higher accuracy than software timer. It should be noted that the timer may behave differently in different hardware.

The MicroPython Timer class defines the basic operation of executing a callback at a given time period (or executing a callback after a delay), and allows for more non-standard behavior to be defined for specific hardware (and therefore not portable to other boards).

There are 3 timers in total, each timer has 4 channels available.

Parameters
id: Timer ID, [0~2] (Timer.TIMER0~TIMER2)
channel: Timer channel, [Timer.CHANNEL0~Timer.CHANNEL3]
mode: Timer mode, MODE_ONE_SHOT or MODE_PERIODIC or MODE_PWM
period: Timer period, after starting the timer, the callback function will be called, (0,~)
unit: Set the unit of the period, the default is milliseconds (ms), Timer.UNIT_S or Timer.UNIT_MS or Timer.UNIT_US or Timer.UNIT_NS
callback: Timer callback function, two parameters are defined, one is the timer object Timer, the second is the parameter arg that you want to pass in the definition object, please see the arg parameter explanation for more information
Note: The callback function is called in the interrupt, so please do not take up too much time in the callback function and do actions such as dynamically allocating switch interrupts, etc.

arg: the parameter you want to pass to the callback function, as the second parameter of the callback function
start: whether to start the timer immediately after the object is successfully constructed, True: start immediately, False: do not start immediately, you need to call the start() function to start the timer
priority: hardware timer interrupt priority, related to the specific CPU, in K210, the value range is [1,7], the smaller the value, the higher the priority
div: hardware timer divider, the value range is [0,255], the default is 0, clk_timer (timer clock frequency) = clk_pll0 (phase-locked loop 0 frequency)/2^(div+1)
clk_timer*period(unit:s) should be < 2^32 and >=1

 
 
 

Just looking around
Find a datasheet?

EEWorld Datasheet Technical Support

EEWorld
subscription
account

EEWorld
service
account

Automotive
development
circle

Copyright © 2005-2024 EEWORLD.com.cn, Inc. All rights reserved 京B2-20211791 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号
快速回复 返回顶部 Return list