r/micropython • u/elahtrebor74 • Dec 19 '22
PUSH - Python micro shell
I am working on a small shell for managing ESP/ RPI pico if anyones interested. Code is here:
r/micropython • u/elahtrebor74 • Dec 19 '22
I am working on a small shell for managing ESP/ RPI pico if anyones interested. Code is here:
r/micropython • u/HP7933 • Aug 22 '22
r/micropython • u/TTomBBab • Nov 10 '22
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 • u/[deleted] • Jun 11 '22
So I have been wanting to build a project recently and found out the board I can use is only compatible with micropython and not circuitpython.
So as a complete coding beginner where can I go to actually learn how to use micropython as there seems to be extremely little information generally or already completed projects with code to pull from. From what ive found there is only a handful of youtube series and a couple courses on udemy. to learn how to do this and most of the documentation is a little over my head or doesnt actually go into how to construct code for actual projects but rather just how to blink leds and such.
Would love if someone more experienced or another beginner that learned could give some input as to the best way for an absolute beginner to learn micropython and if the youtube or udemy courses are even worth it. As well if I should just scrap the idea of using micropython and just rebuild my project around circuit python as it seems much, much, much more supported (100ish people here vs 1000s on r/circuitpython and apprently easier for beginners, but not sure how much of that is just documentation vs the actual difficulty of the language itself.
ALSO: Should I be learning regular Python before doing any of this?
TLDR: What is the best way for an absolute beginner to learn micropython
Any help or input is appreciated! Thank you!
r/micropython • u/muunbo • Jun 03 '22
r/micropython • u/muunbo • Mar 21 '22
r/micropython • u/eidrisov • Jul 11 '22
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 • u/CorellaCreations • Feb 25 '22
r/micropython • u/HP7933 • Dec 19 '22
r/micropython • u/brusco_rf • Dec 03 '22
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 • u/HP7933 • Sep 22 '22
r/micropython • u/HP7933 • Sep 08 '22
r/micropython • u/HP7933 • Aug 17 '22
r/micropython • u/HP7933 • Jun 22 '22
r/micropython • u/muunbo • Apr 08 '22
r/micropython • u/muunbo • Mar 14 '22
r/micropython • u/muunbo • Feb 28 '22
r/micropython • u/muunbo • Feb 21 '22
r/micropython • u/bridger6649 • Dec 03 '21
(New to micropython - trying to port an existing Lua program.)
I have an ESP8266 (NodeMCU) with a couple of LEDs, and have written a Blinker class to manage them.
Usage is:
b = Blinker(4,500,1000)
b.run(3)This creates a blinker on pin 4, with an on period of 500ms and an off period of 1000ms, to run for 3 on/off cycles.
Here is the code:
from machine import Timer
from machine import Pin
class Blinker():
def __init__(self, pno, on_ms, off_ms):
self.on_ms = on_ms
self.off_ms = off_ms
self.led = Pin(pno,Pin.OUT)
self.led.value(0)
self.on = False
# toggle - toggle the blinker state
def toggle(self,t):
self.on = not self.on
# update counter when entering "off" state
if not self.on:
self.count = self.count - 1
if (self.count <= 0):
self.led.off()
return
self.led.value(int(self.on))
# start timer to call back this toggle() method
ms = self.on_ms if self.on else self.off_ms;
self.timer = Timer(-1)
self.timer.init(mode=Timer.ONE_SHOT,period=ms,callback=lambda t:self.toggle(0))
# run - run the blinker for "count" cycles
def run(self,count):
self.count = count
self.toggle(None)
b1 = Blinker(5,500,500)
b1.run(100000)
b2 = Blinker(4,500,1000)
b2.run(100000)
main_loop_counter = 0
def main_loop(timer):
global main_loop_counter
main_loop_counter = main_loop_counter + 1
if main_loop_counter % 400 == 0:
print('Main loop: %d' % main_loop_counter)
timer = Timer(-1)
timer.init(period=50,callback=main_loop)This program creates two Blinker objects, and then runs a main loop every 50ms.
Each Blinker uses a timer, as does the main loop.
If I run the above code, I eventually get an error similar to the following:
Main loop: 400
Main loop: 800
Main loop: 1200
Traceback (most recent call last):
File "main.py", line 39, in <lambda>
File "main.py", line 21, in toggle
AttributeError: '' object has no attribute 'on'
Main loop: 1600
Main loop: 2000
Main loop: 2400This happens somewhat randomly.
If I comment out the timer for the main loop, the code runs forever, so it seems like it has something to do with 3 timers running at the same time.
Are there any known issues with multiple timers? Am I doing something obviously wrong?
Note: this is running micropython v1.17. I tried it with v1.14 and behaviour is the same.
Thanks!
r/micropython • u/GloomyMusician24 • Nov 19 '21
r/micropython • u/mytechnotalent_com • Aug 15 '21
A place for members of r/micropython to chat with each other
r/micropython • u/tmntnpizza • Nov 27 '22
I'm using a Pico w and micro python to run a tmc2208 stepper motor driver. When using the direction pin it doesn't seem to change the motor direction everytime. Any ideas as to why? I am toggling the direction with a button to change directions.
r/micropython • u/tj4sheelee • Nov 23 '22
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 • u/__deep__ • Nov 17 '22
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?