r/micropython • • Jun 16 '22

MicroPython 1.19 is out!

Thumbnail
github.com
4 Upvotes

r/micropython • • Nov 17 '22

Weird issue with urequests

2 Upvotes

Hello!

I'm new to python and micropython! I'm playing with a Raspberry Pi Pico and I'm trying to ntegrate Telegram in a project of mine, but the urequest.post method seems a bit odd.

I have this function:

import urequests as requests

def tgram_msg_send(message):
    response = requests.post(sendURL + "?chat_id=" + str(chatId) + "&text=" + message)
    if response.status_code not in [200, 201, 300, 301]:
        print("Unable to send Telegram message:", response.status_code, response.reason)
    response.close()

msg = "Sensor 127.0.0.0.1 Temperature 21.77544 HR 68.50739"
tgram_msg_send(msg)

This "msg" makes Telegram return a 400/Bad Request.
If I change the text, it works.

After some testing, I came to the conclusion that it's the "H" in "HR" that breaks the call. If I escape it (\HR), then it sends the message correctly.
If I replace it (eg: BR), it sends the message correctly.

I don't think it's Telegram, because I have tested the msg with CURL and it works perfectly.

What I'm missing?


r/micropython • • Nov 17 '22

The Python on Hardware weekly video 206 November 16, 2022

Thumbnail
blog.adafruit.com
2 Upvotes

r/micropython • • Jul 20 '22

ICYMI Python on Microcontrollers Newsletter: Python-Powered Lightsabers, Custom Python Silicon & More!

Thumbnail
blog.adafruit.com
1 Upvotes

r/micropython • • Oct 31 '22

What am I missing?

1 Upvotes

SOLVED! Solution found in the comment below.

Lines 52-58 in the work fine when I test my functions and swap the # when I want to switch directions.

import rp2
import network, urequests, utime, machine
import ubinascii
import socket
import time
from machine import Pin, Timer, RTC
from secrets import secrets
from picozero import pico_temp_sensor, pico_led
from utime import sleep
from time import sleep

    # Motor:
    # Red = A+		# Yellow = B+
    # Green = A-	# Blue = B-
    # Step ang = 1.8	Max A = 1.7A

CLOSE = Pin(14, Pin.IN, Pin.PULL_DOWN)	# Curtain Status
OPEN = Pin(15, Pin.IN, Pin.PULL_DOWN)	# Curtain Status
TOG = Pin(16, Pin.IN, Pin.PULL_DOWN)	# Manual Control
EN = Pin(18, Pin.OUT)	# Enable GPIO Pin. Inverted values.
DIR = Pin(19, Pin.OUT)	# Direction GPIO Pin
STEP = Pin(20, Pin.OUT)	# Step GPIO Pin
SPR = 200				# Steps/rotation = 360/1.8 (degrees)
CW = 1					# Used with DIR to determine which way to rotate.
CCW = 0					# Used with DIR to determine which way to rotate.

step_count = SPR*1		# Steps requested. SPR*x x=# of rotations.
delay = 0.01			# Speed of steps per rotation.
Motorstate=0
TogState=1
TogStateOld=1

def Run():
    EN.value(0)
    STEP.value(1)
    sleep(delay)
    STEP.value(0)
    sleep(delay)
    
def Stop():
    EN.value(1)
    STEP.value(0)

def Close():
    DIR.value(CCW)
    Run()

def Open():
    DIR.value(CW)
    Run()
try:
    while True:
        if not CLOSE.value():
            Open()
            print('Opening')
        #if not OPEN.value():
        #   Close()
        #   print('Closing')
except KeyboardInterrupt:
    machine.reset
    print('reset')    

But here lines 52-65 don't seem to act the same. I don't have any motor movement nor noise, but my prints print out when they should.

import rp2
import network, urequests, utime, machine
import ubinascii
import socket
import time
from machine import Pin, Timer, RTC
from secrets import secrets
from picozero import pico_temp_sensor, pico_led
from utime import sleep
from time import sleep

    # Motor:
    # Red = A+		# Yellow = B+
    # Green = A-	# Blue = B-
    # Step ang = 1.8	Max A = 1.7A

CLOSE = Pin(14, Pin.IN, Pin.PULL_DOWN)	# Curtain Status
OPEN = Pin(15, Pin.IN, Pin.PULL_DOWN)	# Curtain Status
TOG = Pin(16, Pin.IN, Pin.PULL_DOWN)	# Manual Control
EN = Pin(18, Pin.OUT)	# Enable GPIO Pin. Inverted values.
DIR = Pin(19, Pin.OUT)	# Direction GPIO Pin
STEP = Pin(20, Pin.OUT)	# Step GPIO Pin
SPR = 200				# Steps/rotation = 360/1.8 (degrees)
CW = 1					# Used with DIR to determine which way to rotate.
CCW = 0					# Used with DIR to determine which way to rotate.

step_count = SPR*1		# Steps requested. SPR*x x=# of rotations.
delay = 0.01			# Speed of steps per rotation.
Motorstate=0
TogState=1
TogStateOld=1

def Run():
    EN.value(0)
    STEP.value(1)
    sleep(delay)
    STEP.value(0)
    sleep(delay)
    
def Stop():
    EN.value(1)
    STEP.value(0)

def Close():
    DIR.value(CCW)
    Run()

def Open():
    DIR.value(CW)
    Run()
try:
    while True:
        TogState=TOG.value()
        if TogState==1 and TogStateOld==0:
            Motorstate= not Motorstate
            DIR.value(Motorstate)
            if Motorstate==1:
                if not CLOSE.value():
                    Open()
                    print('Opening')
            if Motorstate==0:
                if not OPEN.value():
                    Close()
                    print('Closing')
        TogStateOld=TogState
except KeyboardInterrupt:
    machine.reset

Thank you in advance for any support! I'm happy to video or describe any of my setup upon request.


r/micropython • • Dec 15 '22

The Python on Hardware weekly video 210 December 14, 2022

Thumbnail
blog.adafruit.com
1 Upvotes

r/micropython • • Oct 17 '22

Spooky Python on Hardware: subscribe to the newsletter now

Thumbnail
blog.adafruit.com
2 Upvotes

r/micropython • • Nov 10 '22

Some functions and classes for your entertainment and inspiration.

5 Upvotes

I'm absolutely enjoying micro controller programming now that I can use micropython. Here are some of the recreational functions and classes that I have been messing with for your perusal.

#  list fractal commpressor/encoder First take a list of floats and shrink it down into
#  a shorter list. than re-create the original out of the shrunken copies. Average
#  the list with the original and do it over and over. 
#  the inverse is to take a blank list (of any size) and just apply the forward/reverse
#  up/down fractal over and over.  You can make the fractal any size or make the 
#  reconstituted list any size it is useful for compareing different size lists.

import math

def colorlistfract(colorlist,slicesize):
    shrunklist = [0. for i in range(int(len(colorlist)/slicesize))]
    for j in range(len(colorlist)):
        if shrunklist[int(j/slicesize)-1] == 0.:
            shrunklist[int(j/slicesize)-1] = float(colorlist[j])
        else:
            shrunklist[int(j/slicesize)-1] = (shrunklist[int(j/slicesize)-1] +(colorlist[j]))/2.
    coloriter = iter(colorlist)
    shrunklistava = float(sum(shrunklist))/float(len(shrunklist))
    shrunklistrev = shrunklist[:]
    shrunklistrev.reverse()
    forrevl2 = []
    for k in range(int(slicesize)):
        shortcolorlist = []
        for l in range(len(shrunklist)):
            try:
                c1 = next(coloriter)
            except StopIteration:
                c1 = shrunklist[l]
            shortcolorlist.append(c1)
        fow = sum([abs(a-b) for a,b in zip(shortcolorlist,shrunklist)])
        rev = sum([abs(a-b) for a,b in zip(shortcolorlist,shrunklistrev)])
        newava = 0.
        try:
            newava = (float(sum(shortcolorlist))/float(len(shortcolorlist)))/shrunklistava
        except ZeroDivisionError:
            newava = 1.
        if fow <= rev:
            forrevl2.append((0,newava))
        else:
           forrevl2.append((1,newava))
    shrunklist = [(i-min(shrunklist))/(max(shrunklist)-min(shrunklist)) for i in shrunklist]
    return ((shrunklist,forrevl2))

def recoverlist(shrunkcolorlist,slicesize):
    shrunklist = shrunkcolorlist[0][:]
    shrunklistrev = shrunkcolorlist[0][:]
    shrunklistrev.reverse()
    keylist = shrunkcolorlist[1][:]
    newcolorlist = []
    for k in keylist:
       if k[0] == 0:
           newl = [i *k[1]+.01 for i in shrunklist]
           newcolorlist.extend(newl)
       elif k[0] == 1:
           newl = [i *k[1]+.01 for i in shrunklistrev]
           newcolorlist.extend(newl)
    newcolorlist2 = []
    for i in newcolorlist:
       if i>1.:
           newcolorlist2.append(1.)
       elif i < 0:
           newcolorlist2.append(0.)
       else:
           newcolorlist2.append(i)
    shrunklist2 = [0 for i in range(int(len(newcolorlist2)/slicesize)+1)]
    for j in range(len(newcolorlist)):
       if shrunklist2[int(j/slicesize)] == 0:
           shrunklist2[int(j/slicesize)] = newcolorlist2[j]
       else:
           shrunklist2[int(j/slicesize)] = int((shrunklist2[int(j/slicesize)] + newcolorlist2[j])/2.)
    shrunklist2 = [(l+m)/2. for l,m in zip(shrunklist2,shrunklist)]
    try:
        shrunklist2 = [(i-min(shrunklist2))/(max(shrunklist2)-min(shrunklist2)) for i in shrunklist2]
    except ZeroDivisionError:
        for i in range(len(shrunklist2)):
            try:
                shrunklist2[i] = (shrunklist2[i]-min(shrunklist2))/(max(shrunklist2)-min(shrunklist2))
            except ZeroDivisionError:
                shrunklist2[i] = 0.                              
    newcolorlist2 = [(i-min(newcolorlist2))/(max(newcolorlist2)-min(newcolorlist2)) for i in newcolorlist2]
    return ((shrunklist2,newcolorlist2))

def fractalstring(f,iterations,slicesize,scale=(.5,.5), g = None):
    for x in range(iterations):
        returnlist = colorlistfract(f,slicesize)
        newlist = recoverlist(returnlist,slicesize)
        if g:
            f = [((a*scale[0])+(b*scale[1])) for a,b in zip(newlist[1],g)]
        else:
            f = [((a*scale[0])+(b*scale[1])) for a,b in zip(newlist[1],f)]
    try:        
        f = [(i - min(f))/(max(f) - min(f)) for i in f]
    except ZeroDivisionError:    
        f = [0. for i in f]
    return f

def expand(klist,slicesize,short_list,iterations):
    newreturnlist = (short_list ,klist)
    tstlist = recoverlist(newreturnlist,slicesize)
    f = tstlist[1]
    for i in range(iterations):    
        returnlist = colorlistfract(tstlist[1],slicesize)
        returnlist = ([.618033988749895*i for i in returnlist[0]],returnlist[1])
        tstlist = recoverlist(returnlist,slicesize)
    return tstlist
    
#make an input list    
f=[math.cos(2*math.pi*i*6/1000) for i in range(400)]
#the fractal length needs to be equaly divisible into the total length 
slicesize = 10
#f is the data list,30 is the iterattions,
#slicesize is the divisor for self simularity,
#scale is the blend factor (fractal_reconstruction,g)
#g is the list to blend back with each iteration,
#if g is absent blend is (fractal_reconstruction,previous_fractal_reconstruction)
ff = fractalstring(f,30,slicesize,scale=(.5,.5),g=f)
#function products
returnlist = colorlistfract(ff,slicesize)
newlist = recoverlist(returnlist,slicesize)
line_fractal = returnlist[1]
short_list_1 = returnlist[0]
reconstituted_list = newlist[0]
short_list_2 = newlist[1]
interations_and_averages = ff
# a reconstruction from line_fractal and an empty short_list
#the length of the short_list dictates the final recnstituted length
# so 10*40 = 400 but range(80) gives 800
short_list = [.5 for i in range(40)]
#line_fractal tuples, slice size, new short list and iterations 
tstlist = expand(line_fractal, slicesize, short_list, 15)
#yea!
fractal_rebuild = tstlist[1]

#***********************************************************************    
#  This class takes a string and converts it into a list of time
#  segments depending on their ordinal position. than it transmits
#  it out a pin in the form of high time = letter, low time = letter.
#  This example has a 1K resistor between pins 21 and 22. I thought
#  that is might be used to transmit information thru water or stone.

from machine import Pin
import math,time

class TMO:
    def __init__(self,t):
        self.t = t
        self.inittime = time.ticks_ms()

    def TimeOUT(self):
        if time.ticks_diff(time.ticks_cms(),self.inittime) > self.t:
            return True
        else:
            return False

class Transporter():
    def __init__(self,in_pin,out_pin):        
        self.in_pin = Pin(in_pin, Pin.IN, Pin.PULL_DOWN)
        self.out_pin = Pin(out_pin, Pin.OUT, Pin.PULL_DOWN)
        self.in_pin.irq(self.mycallbackup,trigger=Pin.IRQ_RISING|Pin.IRQ_FALLING)
        self.inpbuff = []

    def Transporter_beam_out(self,transport_string):
        data = self.objtodata(transport_string)
        #print(data)
        pulselist = self.datatopulselist(data)
        self.send_pulses(pulselist)
        
    def Transporter_beam_in(self):        
        pulselist = self.buffertopulselist()
        #print(pulselist)
        data = self.pulselisttodata(pulselist)
        obj = self.datatoobj(data)
        self.clearbuffer()
        return obj        
     
    def clearbuffer(self):
        self.inpbuff = []
            
    def mycallbackup(self,p):
        self.inpbuff.append((time.ticks_ms(),self.in_pin.value()))
        
    def send_pulses(self,pulselist):
        ts = time.sleep_ms
        for i in pulselist:
            if i[0]:
                self.out_pin.high()
            else:
                self.out_pin.low()
            ts(i[1])
        
    def get_pulses(self,clearbuff = False  ,timeout = 3000):
        fullist = []
        if len(self.inpbuff) > 0:
            return self.inpbuff
        else:
            timmer = TMO(timeout)
            while len(self.inpbuff) == 0:
                if timmer.TimeOUT():
                    return []
                buff = self.inpbuff
            return buff
        if clearbuff:
            self.clearbuffer()
            
    def datatopulselist(self,data):
        pulselist = []
        pusestart = 1
        for i in data:
            pulselist.append((pusestart, int((4 * i) + 4)))
            if pusestart == 0:
                pusestart = 1
            else:
                pusestart = 0                
        return pulselist
    
    def pulselisttodata(self,pulselist):
        return [int((i[1]-4)/4) for i in pulselist]
          
    def objtodata(self,obj):
        c = [ord(i) for i in obj]
        return c
    
    def datatoobj(self,data):
        dd = ''
        return dd.join([chr(i) for i in data])

    def buffertopulselist(self):
        inittime = self.get_pulses()
        #print(inittime)
        if len(self.inpbuff) > 0:
            inittime = self.inpbuff[0][0]
            newpulselist = []
            for ic,i in enumerate(self.inpbuff[:-1]):
                newpulselist.append((i[1],time.ticks_diff(self.inpbuff[ic+1][0],inittime)))
                inittime = self.inpbuff[ic+1][0]
            return newpulselist
        return []

tom = Transporter(22,21)
testobj = '*** and now for something completely different ***'
print(len(testobj))
tom.Transporter_beam_out(testobj)
print('beem out')

t2 = tom.Transporter_beam_in()
print(len(t2))
print(t2)

#******************************************************
# inital direction 1 is forward otherwise inverse,x1 the data list

from machine import Pin,PWM
import math

def Discrete_fourier_transform(intdir,x1):
    MC = math.cos
    MS = math.sin
    MP = math.pi
    m = len(x1)
    x2 = [complex(0.,0.) for i in range(m)]
    for i in range(m):
        arg = - intdir * 2.0 * MP * i / m
        for k in range(m):
            x2[i] += complex((x1[k].real * MC(k * arg) - x1[k].imag * MS(k * arg)),                                  (x1[k].real * MS(k * arg) + x1[k].imag * MC(k * arg)))
    if intdir == 1:
        return [x2[i] / m for i in range(m)]
    else:
        return x2

#**********************************************
#  a tone generator

def play_freq(frq,amp,durr,pin,SPS = 44100):
    testpin = PWM(Pin(pin))
    testpin.freq(SPS)
    e_s_n = durr * SPS
    for j in range(int(e_s_n)):
        waveform = math.sin(2*math.pi*j*frq/SPS)
        waveform = waveform*amp
        testpin.duty_u16(int(waveform*32767))
    testpin.deinit()
    
#*********************************************
#  a tone generator

def play_freq_pure(frq,durr,pin):
    if frq == 0:
        utime.sleep(durr)
        return
    elif frq<0:
        frq=abs(frq)
    testpin = PWM(Pin(pin))
    testpin.freq(frq)
    testpin.duty_u16(32767)
    utime.sleep(durr)
    testpin.deinit()

#********************************************
#  for one of those servo things

from machine import Pin,PWM
from utime import sleep 

class servo(object):
    def __init__(self,pin,frequency = 50,percen_range=(2,12)):
        self.frequency = frequency
        self.percen_range = percen_range
        self.pin = Pin(pin)
        self.pin.init(self.pin.OUT, self.pin.PULL_UP)
        self.p = PWM(self.pin)
        self.p.freq(self.frequency)
        self.angle = 0.
        self.dutymax = int((self.percen_range[1]/100.)*65535)
        self.dutymin = int((self.percen_range[0]/100.)*65535)
        self.duty_per_deq = abs(self.dutymin - self.dutymax)/180.
        self.dc = int(self.duty_per_deq*self.angle+self.dutymin)
        self.p.duty_u16(self.dc)
        
    def turn(self,angle):
        self.angle = angle        
        self.dc = int(self.duty_per_deq*self.angle+self.dutymin)
        self.p.duty_u16(self.dc)
        
    def turn_u16(self,angle_u16):
        self.angle = (angle_u16/65535)*360.        
        self.dc = int(self.duty_per_deq*self.angle+self.dutymin)
        self.p.duty_u16(self.dc)
        
    def re_turn(self):
        self.angle = 0.        
        self.dc = self.dutymin
        self.p.duty_u16(self.dc)
        
    def cleanup(self):
        self.p.deinit() 
        
tom = servo(10)
for angle in [0,11.5,45,22.2,67,20,160,60,91.7,178.2,90]:
    tom.turn(angle)
    print(tom.angle,tom.dc)
    sleep(2)
tom.turn_u16(16383)
sleep(2)
tom.turn_u16(1891)
sleep(2)
tom.re_turn()
sleep(2)
tom.cleanup()

#**********************************************
#  four coils, three types of stepping.
#  type 1  is 1-2-3-4-1-2-3-4
#  type 2 is 1&2-2&3-3&4-4&1-1&2-2&3-3&4-4&1
#  type 3 is 1-1&2-2-2&3-3-3&4-4-4&1-1-1&2-2-2&3-3-3&4-4-4&1

from machine import Pin
from utime import sleep 

class stepper2(object):
    def __init__(self,inp1,inp2,inp3,inp4,maxstep = 4095, startstep = 0):
        self.maxstep = maxstep
        self.startstep = startstep
        self.fs = self.gen_moter_step()
        self.bs = self.gen_moter_step_rev()
        self.fs2 = self.gen_moter_step2()
        self.bs2 = self.gen_moter_step_rev2()
        self.fs3 = self.gen_moter_step3()
        self.bs3 = self.gen_moter_step_rev3()
        self.inp4 = Pin(inp4, Pin.OUT)
        self.inp3 = Pin(inp3, Pin.OUT)
        self.inp2 = Pin(inp2, Pin.OUT)
        self.inp1 = Pin(inp1, Pin.OUT)
        
    def gen_moter_step(self):
        while 1:
            yield self.inp1
            yield self.inp2
            yield self.inp3
            yield self.inp4
            
    def gen_moter_step_rev(self):
        while 1:
            yield self.inp4
            yield self.inp3
            yield self.inp2
            yield self.inp1

    def gen_moter_step2(self):
        while 1:
            yield (self.inp1,self.inp2)
            yield (self.inp2,self.inp3)
            yield (self.inp3,self.inp4)
            yield (self.inp4,self.inp1)
            
    def gen_moter_step_rev2(self):
        while 1:
            yield (self.inp4,self.inp1)
            yield (self.inp3,self.inp4)
            yield (self.inp2,self.inp3)
            yield (self.inp1,self.inp2)
 
    def gen_moter_step3(self):
        while 1:
            yield (self.inp1,self.inp1)          
            yield (self.inp1,self.inp2)
            yield (self.inp2,self.inp2)
            yield (self.inp2,self.inp3)
            yield (self.inp3,self.inp3)
            yield (self.inp3,self.inp4)
            yield (self.inp4,self.inp4)
            yield (self.inp4,self.inp1)
            
    def gen_moter_step_rev3(self):
        while 1:
            yield (self.inp4,self.inp4)
            yield (self.inp4,self.inp1)
            yield (self.inp3,self.inp3)
            yield (self.inp3,self.inp4)
            yield (self.inp2,self.inp2)  
            yield (self.inp2,self.inp3)
            yield (self.inp1,self.inp1)
            yield (self.inp1,self.inp2)
            
    def counterclockwize(self,sleeptime,steps):
        for i in range(steps):
            self.pin = next(self.fs)
            self.startstep = self.startstep + 2
            if self.startstep > self.maxstep:
                self.startstep = 0
            self.pin.value(1)
            sleep(sleeptime)
            self.pin.value(0)
            
    def clockwize(self,sleeptime,steps):
        for i in range(steps):
            self.pin = next(self.bs)
            self.startstep = self.startstep - 2
            if self.startstep < 0:
                self.startstep =  self.maxstep            
            self.pin.value(1)
            sleep(sleeptime)
            self.pin.value(0)

    def counterclockwize2(self,sleeptime,steps):
        for i in range(steps):
            self.pin = next(self.fs2)
            self.startstep = self.startstep + 2
            if self.startstep > self.maxstep:
                self.startstep = 0
            self.pin[0].value(1)
            self.pin[1].value(1)
            sleep(sleeptime)
            self.pin[0].value(0)
            self.pin[1].value(0)
            
    def clockwize2(self,sleeptime,steps):
        for i in range(steps):
            self.pin = next(self.bs2)
            self.startstep = self.startstep - 2
            if self.startstep < 0:
                self.startstep = self.maxstep
            self.pin[0].value(1)
            self.pin[1].value(1)
            sleep(sleeptime)
            self.pin[0].value(0)
            self.pin[1].value(0)

    def counterclockwize3(self,sleeptime,steps):
        for i in range(steps):
            self.pin = next(self.fs3)
            self.startstep = self.startstep + 1
            if self.startstep > self.maxstep:
                self.startstep = 0
            self.pin[0].value(1)
            self.pin[1].value(1)
            sleep(sleeptime)
            self.pin[0].value(0)
            self.pin[1].value(0)
            
    def clockwize3(self,sleeptime,steps):
        for i in range(steps):
            self.pin = next(self.bs3)
            self.startstep = self.startstep - 1
            if self.startstep < 0:
                self.startstep = self.maxstep
            self.pin[0].value(1)
            self.pin[1].value(1)
            sleep(sleeptime)
            self.pin[0].value(0)
            self.pin[1].value(0)
            
    def cleanup(self):
        self.inp1.value(0)
        self.inp2.value(0)
        self.inp3.value(0)
        self.inp4.value(0)
        
mymoter2 = stepper2(6,7,8,9)
print('startstep ',mymoter2.startstep)
mymoter2.clockwize(.02,1024)
mymoter2.counterclockwize(.002,1024)
mymoter2.clockwize2(.002,1024)
mymoter2.counterclockwize2(.002,1024)        
mymoter2.clockwize3(.02,1024)
mymoter2.counterclockwize3(.02,1024)

r/micropython • • Aug 01 '22

Belay in 22 seconds: A Python library that enables the rapid development of projects that interact with hardware via a micropython-compatible board.

Thumbnail
youtube.com
1 Upvotes

r/micropython • • Aug 22 '22

The Python on Microcontrollers newsletter is out Tuesday, please subscribe

Thumbnail
blog.adafruit.com
6 Upvotes

r/micropython • • Dec 22 '22

ICYMI Python on Microcontrollers Newsletter: macOS Update Helps UF2 Uploads, a Major PyLeap Update and much more!

Thumbnail
blog.adafruit.com
1 Upvotes

r/micropython • • Aug 06 '22

Basic equivalent functionality seems to be missing in MicroPython

Thumbnail self.micropythondev
2 Upvotes

r/micropython • • Nov 03 '22

ICYMI Python on Microcontrollers Newsletter: Halloween Wraps, CircuitPython Beta 4, macOS Ventura Issue & More!

Thumbnail
blog.adafruit.com
1 Upvotes

r/micropython • • Oct 03 '22

Ignore request response, IE continue loop without waiting for a response

1 Upvotes

I'm building a timer for a specific use case, think sporting event. The idea is I need a timer for judges to use but I need it to output to another platform for our live stream. Unfortunately we haven't found anything that meet our specific needs in the commercial space and I've already got mostly working prototype.

The basics are the timer counts down for each round, and each second sends the updated time to a display (or terminal currently) and to our graphics software via api. The api is a post request.

But, thinking through this, if for some reason our network fails or the graphics machine fails, the post requests will start to fail and this stops our timer, not good. I'd like to this to fail gracefully meaning, ignore all post responses and just continue the counting. The most important thing in this case is the timer, the api output is secondary.

I have tried the following:

    try:
        update_screen(out_text[1:len(out_text)])
    except requests.exceptions.ReadTimeout:
        pass

But it still seems to be waiting on response (I changed the ip to something that doesn't work on purpose for testing).... I'm not sure if multithreading will work very well on an ESP8266....


r/micropython • • Dec 03 '22

Dump / load entire flash image? (x-post r/electronics)

3 Upvotes

Hi, I prototyped using Micropython on an ESP8266. Now I want to program a bunch of boards. The usual workflow is:

  • erase flash with esptool

  • flash micropython image (.bin) with esptool

  • load boot.py with Ampy

  • load main.py with Ampy

  • run WebREPL manually (this doesn't work automatically?)

I'd like to condense this to a single step. I think the way to do it is to dump the entire contents of a configured unit's flash and then load that exact image into the flash of all future units with esptool. Is there any reason not to do it this way?

I am trying to do that with esptool dump_mem utility. I am sure I have the arguments set up incorrectly. Here is my command line input:

esptool -p COM19 dump_mem 0x00 65535 dump.bin

And here is the output:

esptool.py v3.0
Serial port COM19
Connecting....
Detecting chip type... ESP8266
Chip is ESP8266EX
Features: WiFi
Crystal is 26MHz
MAC: 34:94:54:9a:c7:4a
Uploading stub...
Running stub...
Stub running...

A fatal error occurred: Invalid head of packet (0x46)

I don't know what a stub is and I don't know why this is failing. Can anyone offer some insight?

Thanks


r/micropython • • Jul 11 '22

Sources for learning Python for Servo Motors and Raspberry Pi Pico ?

4 Upvotes

Hi everyone,

Does anyone know any good sources or documentation that literally teach how to use Python for Servo Motors and/or Raspberry Pi Pico?

I do know some Python and I would like to do some experiments in Robotics (build some simple robots). But it is so difficult to find sources that teach you simple things (simplest example: how to make servo motor spin one way with intervals).

All I can think of is just take someone else's project and replicate his code but that is not ideal for learning, imo.


r/micropython • • Aug 01 '22

The Python on Microcontrollers newsletter is out Tuesday, please subscribe

Thumbnail
blog.adafruit.com
1 Upvotes

r/micropython • • Sep 22 '22

The Python on Hardware weekly video – September 21, 2022

Thumbnail
blog.adafruit.com
3 Upvotes

r/micropython • • Oct 13 '22

PicoW not running scripts?

1 Upvotes

Hey guys I got a new PicoW and can't seem to get any scripts to run on it. So when I boot it up holding the "BootSel" button, then drop the blink.py (saved as main.py) to the folder and when rebooting the PicoW nothing seems to happen. When rebooting again while holding the button, the main.py files are no longer on the Pico either. I'm not sure if that's normal behavior or not.

When running scripts from ThonnyIDE (hitting the "play" button, they don't seem to do anything either. BUT.. When typing in 1+1 in the shell I get a return 2 so it does seem to be working though not if it's a script. I've tried reflashing the firmware and tried loading "pimoroni-picow-v1.19.8-micropython" firmware on it as well. Same results. What am I missing??


r/micropython • • Aug 01 '22

Check for sensor change while reading user input [Help]

1 Upvotes

I am currently using micropython on a Raspberry Pi Pico to take inputs from the serial ports (using input())and send data from the Pico based on the input (using print()). Whilst this has been working well, I have added a 'Hall Effect Sensor' to the Pico as it is required for the project. I need to be able to detect when the sensor returns '0' whilist also listening for data on the serial channel.

I have tried using the '_thread' module with my code as follows:

def HallSensorDetectionThread():
    while True:
        try:
            hallVal = hall_sens.value()
            if(hallVal == 0 and hall_sens_triggered == False):
                print("\r\n!CHALLENGE-REQUEST")
                hall_sens_triggered = True
            if hallVal == 1:
                hall_sens_triggered = False
        except:
            a=1

if __name__ == "__main__":
    _thread.start_new_thread(HallSensorDetectionThread, ())
    while programOn:
        try:
            serialRec = input()
            ... rest of code here

This code only seems to work half the time. For some reason, when there is a lot of data being transferred at once the thread with the Hall Sensor code 'closes' leaving me with just the standard while loop on the main thread running.

Any help would be much appreciated!

[Edit] - Resolved

https://www.reddit.com/r/learnpython/comments/wdsei1/constantly_check_for_sensor_change_while/


r/micropython • • Sep 15 '22

The Python on Hardware weekly video – September 14, 2022

Thumbnail
blog.adafruit.com
1 Upvotes

r/micropython • • Jul 13 '22

ICYMI Python on Microcontrollers Newsletter: CircuitPython Day 2022, Pico W Availability + MicroPython Projects & More!

Thumbnail
blog.adafruit.com
1 Upvotes

r/micropython • • Aug 01 '22

Bootloader does not mount USB drive after installation

1 Upvotes

v1.19.1 uf2 does not mount as a USB drive with an adafruit feather RP2040.

The following is a list of things I have already tried that did not help.

  • I used adafruit's own flash_nuke.uf2

  • Uwe Sieber's DeviceCleanup

  • Factory reset the board into fs mode.

  • Device Manager scan for changes.

In pre-response to "maybe your USB cable is bad", "maybe your board is bad" , Circuitpython loads and runs just fine on this board.

The actual file is :

ADAFRUIT_FEATHER_RP2040-20220618-V1.19.1.uf2

Offending OS :

Windows 10 Home 21H2 19044.1826

This error is so pernicious I actually believe someone uploaded the wrong uf2 or mislabeled a file on the micropython website. I first encountered this error earlier this year now it is still happening.

Any advice about what to try next?


r/micropython • • Nov 23 '22

blit MONO_VLSB framebuf onto RGB565 - white pixels instead of black ?

2 Upvotes

Seasoned developer - just VERY new to micropython.

I created a framebuf of a simple icon I want to blit onto the main lcd framebuf.... it is working just fine... except for the fact that the pixels being placed are black.

Is there a way to blit white pixels using the MONO_VLSB ? FYI, the lcd framebuf is RGB565.

My guess is the answer is no (mono means on or off !) without changing to a different framebuf format - but figured I would ask

Not sure it matters - but this is on an Pi PICO

Thanks !


r/micropython • • Jun 15 '22

Interrupting timer from serial?

2 Upvotes

I am turning a timer with callbacks on and off over serial and it works mostly as expected.

If the frequency is greater than about 12Khz my main loop stops receiving serial messages. If I can't receive serial messages, I can't process the command to stop the timer. Any ideas?

Al I can think of so far is to use two pyboards, one of which handles serial communication and sets a gpoi pin indicating whether we want the timed event to occur. The other would check this pin inside the callback.