Chat freely about anything...

User avatar
By mialee
#65790 We take blink and breathing light as examples to learn the use of micropython on ameba. However, currently ameba doesn’t support Timer, and there is no breathing light demo.

Blink Program
Code: Select all   from machine import Pin
   import time
   led = Pin('PC_1',Pin.OUT)
   while True:
    led.value(1)
    time.sleep(0.5)
    led.value(0)
    time.sleep(0.5)

Using micropython on ameba for the first time, we must burn micropython onto ameba board. The burning method is very simple. Download the following link and then unpack it. We will get a ram_all.bin file (if there is problem of unpacking under windows, think about unpacking under linux or virtual machine). Burn the file onto ameba board, and then we can use micropython on ameba. Of course we need a terminal (putty) to write micropython
Link: https://github.com/cwyark/micropython/releases/download/v1.8.3/ram_all.tar
Image
After ameba is linked to PC, we need to install a driver. At the completion of installation, we can see MBED (a mobile device) in my computer. https://developer.mbed.org/media/downlo ... _16466.exe.


Then right-click->my computer->management->device manager->port. We can see the port number of ameba. Here you can see my port no. is COM7.
烧录方法:
Burning method:


After completing driver installation, you can see a mobile device MBED in my computer. Double click to open it. Copy the unpacked ram_all.bin file to MBED. Meanwhile you can see that the green light is flashing, which reflects burning. When it stops flashing, burning is completed.

After finishing preparation, open putty terminal. The following interface will appear. Follow the arrow to modify selection.
Image
After finishing preparation, open putty terminal. The following interface will appear. Follow the arrow to modify selection.
Image
These are default selection of 115200 8 1 None None.
Image
After finishing setting, click open. Then click enter key several times. There will be an interface as follows.
Image
Press Ctrl+E in the terminal. There will be a paste command line as follows
Image
Copy the blink program and then right-click in the terminal to finish the copy as shown below. Press Ctrl+D for completing copy. Press Ctrl+C to cancel copy.
Image
It is very simple. Led light is flashing. Press Ctrl+C for exit after completion (currently, ameba doesn’t support the command).

Use of micropython on esp32

esp32
Temporarily, esp32 doesn’t support Timer, therefore there is no breathing light demo.


Blink Program

Code: Select allfrom machine import Pin
   import time
   led = Pin(13,Pin.OUT)
   try:
     whileTrue:
       led.value(1)
       time.sleep(0.5)
       led.value(0)
       time.sleep(0.5)
   except:
     led.value(0)


Method for burning micropython firmware


Use the official programming tools to burn. Before burning, we need to compile micropython firmware first. Refer to the official compiling method. You can directly use my compiled firware: micropython firmware to save the trouble. Note that flash initial address of each firmware cannot be changed. Address of official firmware compiling method is:
[url=https://github.com/micropython/micropython-esp32/tree/esp32/esp32
]https://github.com/micropython/micropython-esp32/tree/esp32/esp32
[/url]

After downloading the official burning tool, double click the burning tool, as shown below:
Image
There will be two interfaces after opening:
Image
Click ESP32DownloadTool on the right interface. We can see the interface of burning firmware. Now we are not far from success. Keep going! At this time, import the three compiled or downloaded bin files of micropython into burning tool. Check the port no. in my computer. Right-click->my computer->management->device manager->port. Note: be sure the address is right, otherwise burning may not be successful or it cannot work normally after burning.
Image

After burning, close burning tool. Open and operate terminal putty of micropython. Select port No. (COM12), connection type(Serial).
Image

Other settings are as follows. Click Open after setting.
Image
Press enter key several times after Open. We can enter micropython language at putty terminal.
Image

Press Ctrl+E to enter paste mode. Right-click in the mode to paste program. Press Ctrl+D to complete pasting. Micropython will execute the program of pasting.
Image

Now led light is flashing. Isn’t it quite simple to light blink! After completion, press Ctrl+C to exit executing program. Led light stops flashing.


Use of micropython on esp8266

Blink and breathing light are supported on esp8266. Let’s learn how to operate blink and breathing light on esp8266 by using micropython!


Blink program
Code: Select all  from machineimport Pin
   import time
   led = Pin(14,Pin.OUT)
   try:
    while True:
     led.value(1)
     time.sleep(0.5)
     led.value(0)
     time.sleep(0.5)
   except:
     led.value(0)


Breathing light program:

Code: Select all   from machineimport Pin,Timer,PWM
   pwm =PWM(Pin(14),100)
   polar = 0
   duty = 0
   def setLed(t):
    global duty,polar
    if(polar == 0):
      duty+=16
      if(duty >= 1008):
        polar = 1
    else:
      duty -= 16
      if(duty <= 0):
        polar = 0
        pwm.duty(duty)
        tim = Timer(1)
        tim.init(period=10,mode=Timer.PERIODIC, callback=setLed)
   try:
    while True:
      pass
   except:
    tim.deinit()
    pwm.deinit()


Firstly, we need to link esp8266 to PC, and then find the port no. of esp8266 in the same method as that of esp32 and ameba. My port no. here is COM9 (you need to find your own).
To use micropython on esp8266, we must burn the micropython firmware of esp8266 to board. There is compiled firmware on micropython official website for downloading. Address is: http://micropython.org/download.


Open and run terminal putty of micropython. Select port no. (COM9), connection type(Serial).
Image
Other settings are shown below. Click Open after setting.
Image
Press enter key several times after Open. We can enter micropython language at putty terminal.
Image
Image
Breathing light
Image
After that we can realize blink in the same method as that of esp32 and ameba. There is a led light installed on esp8266 board, and is no need of external connection of led light. Method of finishing breathing light is also the same. I will save the trouble of introduction here.



IO port reading on esp32 platform


IO port reading program

Code: Select all from machineimport Pin
  import time
  button =Pin(34,Pin.IN)
  while True:
   print(button.value())
   time.sleep(1)

Enter the read program of IO port to terminal for running. IO34 pin is connected to nothing, so what it read is low level, output 0. When we connect IO34 pin to 3.3V pin, what it read is high level, output 1.

Reference ESP8266 micropython- Tutorial 2: Micropython GPIO
User avatar
By mialee
#65792 Timer

Using timer in micropython is also simple. To use timer, we need to import Timer library first from machine importTimer



Basic usage:

Define Timer
tim=Timer(n)

Timer 3 is reserved for internal use. Timer 5 controls the servo drive. Timer 6 is used to signaling ADC / DAC read/write. It is recommended to use other timer in your program.
tim=Timer(1, freq=100)
tim=Timer(4, freq=200, callback=f)


Set frequency: tim.freq(100)

Define callback function (interrupt): tim.callback(f)

Disable callback function: tim.callback(None)


Introduction of Timer library
timer.counter([value])



Obtain or set timer counter
timer.freq([value]



Obtained or (if setting changes prescaler and period) set frequency timer
timer.init(*, freq, prescaler, period) initialize timer. Initialization must have frequency (Hz) or prescaler tim.init(freq=100), tim.init(prescaler=83, period=999) keyword parameter:


freq — Frequency with specified time period
Prescaler—Prescaler, [0-0xffff]. Timer frequency is system clock
(prescaler + 1). The highest frequency of timer 2-7 and 12-14 is 84MHz, that of timer 1, 8-11 is 168MHz
Period—Period value(ARR). Timer 1/3/4/6-15 is [0-0xffff]. Timer 2 and 5 is [0-0x3fffffff]
Check port no. from my computer. Right-click->my computer->management->device manager->port. Port No. is COM9.

Open and run terminal putty of micropython. Select port no. (COM9), connection type (Serial)
Image

Other settings are shown below.
Image

Press enter key several times after Open. We can enter micropython language at putty terminal
Image

Press Ctrl+E to access paste mode, and right-click in the mode to paste program. Press Ctrl+D to complete pasting. Micropython will execute pasting program

Example of Timer
Code: Select allTiming period output 1

from machine import Timer

tim = Timer(-1)

def func(t):

    print (1)

tim.init(period=2000, mode=Timer.PERIODIC, callback=func)

Image
Timing one-time output 2
Code: Select allfrom machine import Timer

tim = Timer(-1)

def func(t):

    print(2)

tim.init(period=2000, mode=Timer.ONE_SHOT, callback=func)

Image

Breathing Light
Code: Select allfrom machine import Pin,Timer,PWM

pwm = PWM(Pin(14),100)

polar = 0

duty = 0

def setLed(t):

   global duty,polar

  if(polar == 0):

     duty+=16

     if(duty >= 1008):

       polar = 1

   else:

     duty -= 16

     if(duty <= 0):

       polar = 0

   pwm.duty(duty) 

   tim = Timer(1)

   tim.init(period=10,mode=Timer.PERIODIC, callback=setLed)

try:

   while True:

     pass

except:

   tim.deinit()

   pwm.deinit()

Image

I2C

I2C is two-wire communication protocol between devices. It only needs two signal lines in the physical layer: SCL and SDA, which is clock and data line respectively.

I2C communication program between esp8266 and EEPROM Data Storage Module For Arduino
Code: Select allfrom machine import Pin, I2C   

  i2c =I2C(scl=Pin(5), sda=Pin(4), freq=100000)

b=bytearray(4)

b[0]=97

b[1]=98

b[2]=99

i2c.writeto_mem(0x50,0,b)

i2c.readfrom_mem(0x50,0,4)

I2C.init(scl, sda, *, freq=400000)
初始化 I2C:
Initialize I2C:

scl represents pin of SCL

sda represents pin of SDA

freq represents clock rate of SCL



Standard Bus Operation

I2C master mode read-write operation

I2C.readfrom(addr, nbytes) 


Read data from device at specified address, and return to the read object

I2C.readfrom_into(addr, buf)


Read data from device at specified address to the buffer. The read number is the length of buf

I2C.writeto(addr, buf, )


Enter data to device



Original I2C operation

The following methods perform the original I2C main operation. They can be combined to produce various I2C transactions. Providing these methods is to better control bus, otherwise using

standard method is sufficient.
I2C.start()


Send start bit from the bus (SDA goes low when SCL is high)
I2C.stop()


Send stop bit (SCL goes high when SCL is high)
I2C.readinto(buf)


Read data from the bus and store it on buf. The read number is the length of buf. ACK signal is sent when the penultimate data is received. NACK signal is transmitted when all the data has been received.
I2C.write(buf)


Enter the buffer data to the bus. Check whether ACK is received every time of sending a byte. If not, it will cause OSError abnormity.

We used esp8266 and EEPROM Data Storage Module For Arduino to do a simple I2C communication.

We find its I2C address from the display code. I will not say much here. Open the said web page. From its code we find the address is 0x50. Then we connect the corresponding GND VCC SDASCL of DFR0117 to GND VCC SDA SCL of esp8266. Finally we connect esp8266 to PC.

Check port no. from my computer. Right-click->my computer->management->device manager->port. Port no. is COM9.

Open and run terminal putty of micropython. Select port no. (COM9), connection type (Serial)

Other settings are show below. Click Open after setting.
Image
Press enter key several times after Open. We can enter micropython language at putty terminal.
Image
Enter our program. Executing result is shown below. I2C communication between two devices is completed.
Reference link:ESP8266 micro python - Tutorial 3: Micropython Timer I2C
User avatar
By mialee
#65795 mode:Pin.IN input
Pin.OUT output

value:output value

Pin.value ([value]) It means reading input level when it’s without parameter, and setting output level when it’s with parameter, which is 1/0.
Pin.irq(*,trigger, handler=None)



INTERRUPT

trigger
Pin.IRQ_FALLING, falling
Pin.IRQ_RISING, rising
Pin.IN, rising and falling
handler, callback

Interrupt function program

Copy code
Code: Select all"from machine import Pin[/align]value=1
counter=0
def func(v):
     global value,counter
     counter+=1
    led.value(value)
     if(value == 0):
     value = 1
    else:
    value = 0
    print("IRQ ",counter)
led = Pin(14, Pin.OUT)
led.value(0)
button = Pin(0, Pin.IN)
button.irq(trigger=Pin.IRQ_FALLING, handler=func)
while True:
    pass"

I don’t need the compiling environment of how to find port no. and how to enter esp8266 micropython. Refer to the previously published documents if you don’t understand. As shown below, after entering the compiling environment, paste our interrupt program according to the said method.

Press Ctrl+d to complete pasting and then run the program. Now it output <IRQ>, which means our program is good and is under execution. At this time, we can see that led light is in extinguished state on our esp8266 development board.
Image
We connect a DuPont line to GPIO0 port of the board. Touch other pins with the other end of the DuPont line. There will be result as shown below. Every time of touch, led light will flash for one time, and counter number will increase. Therefore, we realize the effect of interruption.
Image
Reference link: ESP8266 Micropython Tutorial 4: How To Interrupt Micropython
User avatar
By mialee
#66236 Micropython UDP on ESP8266

TCP is to establish reliable connection, and both sides of communication can send data in the form of flow. Compared to TCP, UDP aims at connectionless protocol. When using UDP, you don’t need to establish connection and only need to know the IP address and port no. of the other part. Then you can send data packets directly.


Here we will use serial/network debugging assistant. Download address is: http://www.daxia.com/sscom/sscom5.12.1.rar

Program is as follows:
Code: Select allimport socket
port = 10086
s=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(('192.168.0.110',port)) #绑定端口binding the port
print('waiting...')
while True:   #接收数据receiving data
 data,addr=s.recvfrom(1024)
print('received:',data,'from',addr)


Connect esp8266 with burnt micropython to PC. Open our putty terminal in the said methods. Before doing udp, we must finish some necessary preparation. Firstly, connect esp8266 to wireless network, and then we are able to get the needed ip address.


Enter the following command in the terminal until esp8266 is successfully connected to wifi. We can use wlan.isconnected to check whether it is connected. wlan.scan() is used to scan nearby wireless networks. Use wlan.connect(‘ssid’,’password’) to connect our wireless network (ssid: our wifi name. password: password of wireless network).
Image
After entering command of connecting wifi, appearance of condition as shown below means successful connection to wifi. At the same time, we can see the needed ip address. Remember the ip address, which we will use in the following udpserver program.
Image
Operate our program in the terminal in the said methods. Correct running result is shown below:
Image
Open the downloaded serial debugging assistant.Now we can use the recorded ip address. Select udp at our port no. Enter the recorded ip address at remote. Fill the port no. of our program in the port behind remote.


Click link. You can see whether connect is successful at the bottom line.
Image


Enter nihao in the blank next to the send button, and then click send. We will receive the sent message and sent address at putty terminal as shown below:



Then our udp connection and receiving and sending message are completed.


There is a direct method to realize the function. Code is as follows:
Code: Select allimport network[/align]import socket
import time
port=10086
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect('dfyanfa', 'df123456')
while(wlan.isconnected() == False):
  time.sleep(1)
ip = wlan.ifconfig()[0]
print(ip)
s=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
s.bind((ip,port))
print('waiting....')
while True:
  data,addr=s.recvfrom(1024)
  s.sendto(data,addr)
  print('received:',data,'from',addr)

Directly entering the said code is ok. Use serial/network debugging assistant as UDP client to establish connection with server. Operating method is the same as the said. Try it if you are interested or for the sake of convenience.


Reference link: https://www.dfrobot.com/blog-608.html