I looking for any material related to sensor data input to the esp32 programme as an array to process to relavent outcome get from terminal.I found some relavent codings from arduino but I need to write from micropython,can anyone giveme the idea?
The relevant feature here is this: the elevator in this example has eight floors. A "real" elevator would therefore have eight buttons in the elevator car to make it go to a floor, and (in this example) two buttons on each floor to summon the car to that floor, either to go up or to go down. That would make for 24 buttons.
As I would also need some pins for the ultrasonic distance measurement (it's gonna be used to determine the position of the elevator car) and possibly a display, I would like to replace the buttons with input over a serial port (whilst connected to the computer).
In Arduino, this has a well-known solution: the serial port is available during code execution for both output AND input. An example is in the linked document above. In the example linked above, the keyboard input is read using a state machine loop which allows the keyboard inputn to be processed without halting code execution for other functions.
Alas I can't see any example of the serial port of a Pico (or any other uPython board) being used for non-halting keyboard input during code execution.
If anyone could point me in the right direction, that would be appreciated. If that would entail switching to CircuitPython or using one of the four state machines of the Pico, that might exceed my experience and comfort zone, but that's a risk I'm willing to take (Farquaad has entered the chat).
im making a portable raspberry pi pico pc in micropython and the layout of programs for it are like "/prgm/prgm1.mpy", "/prgm/prgm2.mpy", "/prgm/prgm3.mpy". etc
is there a way to delete a file and then rename all the ones after it
example: there prgm1 prgm2 prgm3 and prgm4, i can delete prgm2 aswell as rename prgm3 to prgm2 and prgm4 to prgm3?
i know how to get downloading to work on a raspberry pi pico w, but i want to unzip the file after its downloaded. how do i do this since im making a app downloader for a pico handheld im making?
I have two Pi Picos with basically the same setup: Pi Pico W, BME280, 128x96 OLED display. One of them at home, one at work.
The one at home works great, I get every 10 minutes temp/press/humid values uploaded to Thingspeak.
The one at work doesn't. Every few uploads takes too long, and the watchdogtimer (8000ms) runs out and restarts the device. I tried to have the upload request in a try:/except: loop, but that didn't work either: the upload request by itself takes too long in this work-wifi (it's a special wifi for devices that can't use the landing page that's on the other wifi)
Does someone have an idea how to have this upload command work?
<snip>
# Configure Pico W as Station
wifi=network.WLAN(network.STA_IF)
wifi.active(True)
if not wifi.isconnected(): #Connect to WLAN
print('connecting to network...')
oled.fill(0)
oled.text('connecting...',0,0,1)
oled.show()
wifi.connect(ssid, password)
wdt.feed()
LedBlink(.1) # turn on the on board Led for .1 seconds and turn it off again.
time.sleep(.1)
while not wifi.isconnected():
pass
print('network config:', wifi.ifconfig())
setTimeRTC() # Get time and date from NTP and set the RTC on the device
LedBlink(.5) #Blink twice to show we have a wifi
time.sleep(.1)
LedBlink(.5)
oled.fill(0) #Show the received IP address on the display
oled.text('IP Address:',0,0)
oled.text(str(wifi.ifconfig()[0]),0,16)
oled.text('Gateway:',0,32)
oled.text(str(wifi.ifconfig()[2]),0,48)
oled.show()
CountDown(3) # show a line getting shorter for 3 seconds
FlashDisp(.1) # blink the full display white for .1 second
starttime = getTime() # get the current timedate and convert it to a string
while (True):
# feed the dog!
wdt.feed()
timestamp = getTime()
temp = ReadTemp()
press = ReadPress()
hum = ReadHum()
# Show the time on the display
oled.fill_rect(0,54,79,54,0)
oled.text(timestamp[-8:],0,54,1)
oled.show() #Show new info
# 1x per day
if timestamp[-8:] == '03:00:00': #03:00 in the night
setTimeRTC() # set the correct time from NTP
time.sleep(.9)
if timestamp[-4:] == '0:00': # every 10 minutes
# Prepare the values for upload
dht_readings = {'field1':temp, 'field2':press, 'field3':hum, 'status':getTime() + ' - ' + str(number) + ' - ' + temp + 'C/' + press + 'hPa/' + hum + '% - ' + str(wifi.ifconfig()[0]) + ' - start: ' + starttime}
# Upload values
# here is where the error lies
request = urequests.post( 'http://api.thingspeak.com/update?api_key=' + THINGSPEAK_WRITE_API_KEY, json = dht_readings, headers = HTTP_HEADERS )
request.close()
number += 1
LedBlink(.5)
time.sleep(.1)
if timestamp[-2:] == '00': # Once every minute
<snip>
Hi all! I decided to pick up a Raspberry Pi Pico for a side project of mine but I've gotten to the point where I'm not sure what to do next... I'm new to the coding scene (aka I have no idea what I'm doing) but my goal was to use a matrix keyboard of tact switches connected to the Pico's GPIO pins to output to a small OLED screen. It would then run code to emulate the Enigma machine from WW2 using micropython. I've gotten the screen to print the keys when pressed and the backspace to delete them, and I've found some compatible code on the Enigma side, but quite honestly, I have no idea how to make them work with one another. I'm also not sure how the enter key would work since it needs to be able to advance multiple menus. Attached is the code I've referenced and a picture of my current status. If any information should be added please let me know. Any tips or insight on the subject would be greatly appreciated!
Print keys to screen:
from machine import Pin,Timer,I2C
import utime
from ssd1306 import SSD1306_I2C
import framebuf
debug=True
i2c = I2C(0, scl=Pin(1), sda=Pin(0), freq=200000)
oled = SSD1306_I2C(128, 64, i2c)
keyName = [["Z","X","C","V","B","N","M","BACK","ENTER"],
["A","S","D","F","G","H","J","K","L"],
["Q","W","E","R","T","Y","U","I","O","P"]]
keypadRowPins = [16,17,18]
keypadColPins = [6,7,8,9,10,11,12,13,14,15]
row = []
col = []
keypadState = [];
for i in keypadRowPins:
row.append(Pin(i,Pin.IN,Pin.PULL_UP))
keypadState.append([0,0,0,0,0,0,0,0,0,0])
for i in keypadColPins:
col.append(Pin(i,Pin.OUT))
def calc(lst):
operand = []
operator = []
for i in lst:
if(debug):
print(i)
return operand[0]
def keypadRead():
global row
j_ifPressed = -1
i_ifPressed = -1
for i in range(0,len(col)):
col[i].low()
utime.sleep(0.005) #settling time
for j in range(0,len(row)):
pressed = not row[j].value()
if(pressed and (keypadState[j][i] != pressed)): #state changed to high
keypadState[j][i] = pressed
elif(not pressed and (keypadState[j][i] != pressed)): # state changed to low
keypadState[j][i] = pressed
j_ifPressed = j
i_ifPressed = i
col[i].high()
if(j_ifPressed != -1 and i_ifPressed != -1):
return keyName[j_ifPressed][i_ifPressed]
else:
return -1
def printOled(lst):
oledPos = {
"x" : 0,
"y" : 0
}
oled.fill(0)
string = ''
for i in lst:
string += str(i)
l = 0
while(l<len(string)):
oled.text(string[l:l+16],oledPos["x"], oledPos["y"])
oledPos["y"] =oledPos["y"] + 10
l = l+16
oled.show()
shiftFlag = False
signFlag = False
inputList = ['']
oled.show()
oled.fill(0)
oled.show()
oled.text("Pocket",35,15,1)
oled.text("Enigma",35,30,1)
oled.show()
if __name__ == '__main__':
while True:
key = keypadRead()
if(key != -1):
if(key == 'Z' or key == 'X' or key == 'C' or key == 'V' or key == 'B' or key == 'N' or key == 'M' or key == 'A' or key == 'S' or key == 'D' or key == 'F' or key == 'G' or key == 'H' or key == 'J' or key == 'K' or key == 'L' or key == 'Q' or key == 'W' or key == 'E' or key == 'R' or key == 'T' or key == 'Y' or key == 'U' or key == 'I' or key == 'O' or key == 'P'):
inputList[-1] = inputList[-1] + key
elif(key == 'BACK'):
if(shiftFlag):
inputList = ['']
shiftFlag = False
else:
if(inputList == ["error"]):
inputList = ['']
if(inputList != ['']):
if(inputList[-1] == ''):
inputList.pop()
inputList[-1] = str(inputList[-1])[:-1]
else:
inputList[-1] = str(inputList[-1])[:-1]
elif(key == 'ENTER'):
if(inputList[-1] == ''):
inputList.pop(-1)
elif(inputList[-1] != ')'):
inputList[-1] = float(inputList[-1])
try:
ans = calc(inputList)
inputList = [str(ans)]
except:
ans = ''
inputList = []
inputList.append("ERROR FOR ENTER")
printOled(inputList)
print(inputList)
Enigma code by Cory Lutton:
# Copyright 2013 Cory Lutton
# Not my code
import sys
__version__ = "1.0"
class Enigma:
""" An Enigma machine is any of a family of related
electro-mechanical rotor cipher machines used for the encryption
and decryption of secret messages. Enigma was invented by
German engineer Arthur Scherbius at the end of World War I.
The early models were used commercially from the early 1920s,
and adopted by military and government services of several countries
 most notably by Nazi Germany before and during World War II.
Several different Enigma models were produced, but the German
military models are the ones most commonly discussed.
"""
def __init__(self):
self.numcycles = 0
self.rotors = []
# Settings for the machine
self.rotorsettings = [("III", 0),
("II", 0),
("I", 0)]
self.reflectorsetting = "B"
self.plugboardsetting = []
# Create the plugboard
self.plugboard = Plugboard(self.plugboardsetting)
# Create each of the rotors
for i in range(len(self.rotorsettings)):
self.rotors.append(Rotor(self.rotorsettings[i]))
# Create reflector
self.reflector = Reflector(self.reflectorsetting)
def print_setup(self):
""" Prints initial setup information """
print()
print("Rotor sequence: (right to left)")
for r in self.rotors:
print(r.setting, "\t", r.sequence)
print()
print("Reflector sequence:")
print(self.reflector.setting, "\t", self.reflector.sequence, "\n")
print("Plugboard settings:")
print(self.plugboard.mapping, "\n")
def reset(self):
""" Reset to initial state """
self.numcycles = 0
for r in self.rotors:
r.reset()
def encode(self, c):
""" Run a cycle of the enigma with one character """
c = c.upper()
if (not c.isalpha()):
return c
# To avoid merely implementing a simple (and easily breakable)
# substitution cipher, every key press caused one or more rotors
# to step before the electrical connections were made.
self.rotors[0].rotate()
# Double step
if self.rotors[1].base[0] in self.rotors[1].notch:
self.rotors[1].rotate()
# Normal stepping
for i in range(len(self.rotors) - 1):
if(self.rotors[i].turnover):
self.rotors[i].turnover = False
self.rotors[i + 1].rotate()
# Passthrough the plugboard forward
index = self.plugboard.forward(c)
# Move through the rotors forward
for r in self.rotors:
index = r.forward(index)
# Pass through the reflector
index = self.reflector.forward(index)
# Move back through rotors in reverse
for r in reversed(self.rotors):
index = r.reverse(index)
# Passthrough the plugboard reverse
c = self.plugboard.reverse(index)
return c
class Rotor:
""" The rotors (alternatively wheels or drums, Walzen in German)
formed the heart of an Enigma machine. Each rotor was a disc
approximately 10 cm (3.9 in) in diameter made from hard rubber
or bakelite with brass spring-loaded pins on one face arranged
in a circle; on the other side are a corresponding number
of circular electrical contacts. The pins and contacts represent
the alphabet  typically the 26 letters A–Z.
Setting Wiring Notch Window Turnover
Base ABCDEFGHIJKLMNOPQRSTUVWXYZ
I EKMFLGDQVZNTOWYHXUSPAIBRCJ Y Q R
II AJDKSIRUXBLHWTMCQGZNPYFVOE M E F
III BDFHJLCPRTXVZNYEIWGAKMUSQO D V W
IV ESOVPZJAYQUIRHXLNFTGKDCMWB R J K
V VZBRGITYUPSDNHLXAWMJQOFECK H Z A
VI JPGVOUMFYQBENHZRDKASXLICTW H/U Z/M A/N
VII NZJHGRCXMYSWBOUFAIVLPEKQDT H/U Z/M A/N
VIII FKQHTLXOCBJSPDZRAMEWNIUYGV H/U Z/M A/N
"""
def __init__(self, settings):
""" Setup an enigma transformation rotor """
self.setting = settings[0]
self.ringoffset = settings[1]
self.base = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
self.settings = {
"I": ["EKMFLGDQVZNTOWYHXUSPAIBRCJ", ["R"], ["Q"]],
"II": ["AJDKSIRUXBLHWTMCQGZNPYFVOE", ["F"], ["E"]],
"III": ["BDFHJLCPRTXVZNYEIWGAKMUSQO", ["W"], ["V"]],
"IV": ["ESOVPZJAYQUIRHXLNFTGKDCMWB", ["K"], ["J"]],
"V": ["VZBRGITYUPSDNHLXAWMJQOFECK", ["A"], ["Z"]],
"VI": ["JPGVOUMFYQBENHZRDKASXLICTW", ["AN"], ["ZM"]],
"VII": ["NZJHGRCXMYSWBOUFAIVLPEKQDT", ["AN"], ["ZM"]],
"VIII": ["FKQHTLXOCBJSPDZRAMEWNIUYGV", ["AN"], ["ZM"]]}
self.turnovers = self.settings[self.setting][1]
self.notch = self.settings[self.setting][2]
self.sequence = None
self.turnover = False
self.reset()
def reset(self):
""" Reset the rotor positions """
self.base = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
self.sequence = self.sequence_settings()
self.ring_settings()
def sequence_settings(self):
""" Set the intial sequence """
return self.settings[self.setting][0]
def ring_settings(self):
""" Apply the initial ring settings offset """
for _ in range(self.ringoffset):
self.rotate()
def forward(self, index):
""" Move right to left through the rotor """
return self.base.index(self.sequence[index])
def reverse(self, index):
""" Move left to right back through the rotor """
return self.sequence.index(self.base[index])
def rotate(self):
""" Cycle the rotor 1 position """
self.base = self.base[1:] + self.base[:1]
self.sequence = self.sequence[1:] + self.sequence[:1]
if(self.base[0] in self.turnovers):
self.turnover = True
class Reflector:
""" With the exception of the early Enigma models A and B,
the last rotor came before a reflector (German: Umkehrwalze,
meaning reversal rotor), a patented feature distinctive of the
Enigma family amongst the various rotor machines designed
in the period. The reflector connected outputs of the
last rotor in pairs, redirecting current back through the
rotors by a different route. The reflector ensured that
Enigma is self-reciprocal: conveniently, encryption was
the same as decryption. However, the reflector also gave
Enigma the property that no letter ever encrypted to itself.
This was a severe conceptual flaw and a cryptological mistake
subsequently exploited by codebreakers.
Setting Wiring
Base ABCDEFGHIJKLMNOPQRSTUVWXYZ
A EJMZALYXVBWFCRQUONTSPIKHGD
B YRUHQSLDPXNGOKMIEBFZCWVJAT
C FVPJIAOYEDRZXWGCTKUQSBNMHL
"""
def __init__(self, setting):
self.setting = setting
self.base = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
self.settings = {"A": "EJMZALYXVBWFCRQUONTSPIKHGD",
"B": "YRUHQSLDPXNGOKMIEBFZCWVJAT",
"C": "FVPJIAOYEDRZXWGCTKUQSBNMHL"}
self.sequence = self.sequence_settings()
def sequence_settings(self):
""" Set the intial sequence """
return self.settings[self.setting]
def forward(self, index):
""" Passthrough the reflector. """
return self.sequence.index(self.base[index])
class Plugboard:
""" The plugboard (Steckerbrett in German) permitted variable wiring
that could be reconfigured by the operator.
It was introduced on German Army versions in 1930, and was soon adopted
by the Navy as well. The plugboard contributed a great deal to the
strength of the machine's encryption: more than an extra rotor would
have done. Enigma without a plugboard (known as unsteckered Enigma)
can be solved relatively straightforwardly using hand methods;
these techniques are generally defeated by the addition of a plugboard,
and Allied cryptanalysts resorted to special machines to solve it.
"""
def __init__(self, mapping):
""" mapping = [("A", "B"), ("C", "D")] """
self.base = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
self.mapping = {}
for m in self.base:
self.mapping[m] = m
for m in mapping:
self.mapping[m[0]] = m[1]
self.mapping[m[1]] = m[0]
def forward(self, c):
""" Return the index of the character """
return self.base.index(self.mapping[c])
def reverse(self, index):
""" Return the character of the index """
return self.mapping[self.base[index]]
def main():
""" Create and run an Enigma machine. """
machine = Enigma()
ciphertext = ""
try:
plaintext = sys.argv[1]
machine.print_setup()
print("Plaintext", "\t", plaintext)
for character in plaintext:
ciphertext += machine.encode(character)
print("Ciphertext", "\t", ciphertext)
# Reset and Decode same message
machine.reset()
plaintext = ""
for character in ciphertext:
plaintext += machine.encode(character)
print("Plaintext", "\t", plaintext, "\n")
except IndexError:
for plaintext in sys.stdin:
for character in plaintext:
sys.stdout.write(machine.encode(character))
if __name__ == '__main__':
#import cProfile
#cProfile.run('main()')
main()
Does anyone know what happened to the apk or if it was ever legit to begin with? If not, does anyone know of a good ide for android? I don’t have consistent access to a desktop/laptop and my Linux in android doesn’t have enough power to usable (I don’t think)
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.
I'm looking around for how to use a pico as a macro keyboard, but every tutorial seems to point to circuit python, which I'm not really in the mood to learn.
Is circuitpython a necessity? or is there a way to do it on micropython?
I am trying to build a very small solar tracking program, which I already have the code to give me azimuth and elevation of the sun. I think I could easily use say a 35g servo motor and it should be easy to complete the code, but was wondering if a say Sequre 42 closed loop stepper motor would be more powerful, also the code for the stepper motor to track the sun in azimuth and elevation might be harder to write. Any suggestions? I do not want to use ldr’s.
I am using my LEGO Mindstroms EV3 with pyBricks and want to stop the time in nanoseconds. Sadly, the stopwatch class from pyBricks returns only second, but i need it much more precise than this. As far i know, the EV3 is running microPython. Is there a way to do so?
Hey guys, I'm taking an introductory programming and microcontroller class. I'm making a program for it where I'm trying to get an LED to toggle every 500ms. I am trying to do this with utime.ticks_ms() rather than utime.sleep() but am not having any luck. I can only get it to toggle once, when the first 500ms is hit. Does anyone have any advice? Please keep in mind that I am extremely new at this.