Saturday, 3 June 2023

Motor direction 2

from machine import Pin import utime in1=Pin(15,Pin.OUT)#purple in2=Pin(14,Pin.OUT)#blue in3=Pin(17,Pin.OUT)#white in4=Pin(16,Pin.OUT)#green while True: print('Not turning') in1.value(0) in2.value(0) in3.value(0) in4.value(0) utime.sleep(5) #wheel spin towards motor controller L298N print('forward direction') in1.value(0) in2.value(1) in3.value(0) in4.value(1) utime.sleep(5) print('Not turning') in1.value(1) in2.value(1) in3.value(1) in4.value(1) utime.sleep(5) #wheel spin away from motor controller L298N print('backward direction') in1.value(1) in2.value(0) in3.value(1) in4.value(0) utime.sleep(5) #https://www.youtube.com/watch?v=dRXJAFPhKTY&list=PLgFwxqENEmX_8kdXEFYdETEqB4PPkMyc0&index=11

Motor direction 1

from machine import Pin import utime in1=Pin(14,Pin.OUT)#blue in2=Pin(15,Pin.OUT)#purple in3=Pin(16,Pin.OUT)#green in4=Pin(17,Pin.OUT)#white while True: print('Not turning') in1.value(0) in2.value(0) in3.value(0) in4.value(0) utime.sleep(5) #wheel spin away from motor controller L298N print('backward direction') in1.value(0) in2.value(1) in3.value(0) in4.value(1) utime.sleep(5) print('Not turning') in1.value(1) in2.value(1) in3.value(1) in4.value(1) utime.sleep(5) #wheel spin towards motor controller L298N print('forward direction') in1.value(1) in2.value(0) in3.value(1) in4.value(0) utime.sleep(5) #https://www.youtube.com/watch?v=dRXJAFPhKTY&list=PLgFwxqENEmX_8kdXEFYdETEqB4PPkMyc0&index=11

Wednesday, 26 April 2023

CoreElectronics 2: Create a Simple HTTP Server

Part 1 # Hardware Test # Blink and LED (GP15) slowly/quickly while a button (GP16) is not-pressed/pressed from machine import Pin from time import sleep_ms led = Pin(15, Pin.OUT) button = Pin(16, Pin.IN, Pin.PULL_UP) while True: if button.value() == 0: # button pressed delay = 100 # short delay else: delay = 1000 # long delay led.toggle() sleep_ms(delay) #https://core-electronics.com.au/guides/raspberry-pi-pico-w-create-a-simple-http-server/ #https://www.youtube.com/watch?v=AK8UYh7pMGM&t=515s Part 2 # Simple HTTP Server Example # Control an LED and read a Button using a web browser import time import network import socket from machine import Pin led = Pin(15, Pin.OUT) ledState = 'LED State Unknown' button = Pin(16, Pin.IN, Pin.PULL_UP) ssid = 'xxxxx' password = 'xxxxx' wlan = network.WLAN(network.STA_IF) wlan.active(True) wlan.connect(ssid, password) html = """ Pico W

Pico W HTTP Server

Hello, World!

%s

""" # Wait for connect or fail max_wait = 10 while max_wait > 0: if wlan.status() < 0 or wlan.status() >= 3: break max_wait -= 1 print('waiting for connection...') time.sleep(1) # Handle connection error if wlan.status() != 3: raise RuntimeError('network connection failed') else: print('Connected') status = wlan.ifconfig() print( 'ip = ' + status[0] ) # Open socket addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1] s = socket.socket() s.bind(addr) s.listen(1) print('listening on', addr) # Listen for connections, serve client while True: try: cl, addr = s.accept() print('client connected from', addr) request = cl.recv(1024) print("request:") print(request) request = str(request) led_on = request.find('led=on') led_off = request.find('led=off') print( 'led on = ' + str(led_on)) print( 'led off = ' + str(led_off)) if led_on == 8: print("led on") led.value(1) if led_off == 8: print("led off") led.value(0) ledState = "LED is OFF" if led.value() == 0 else "LED is ON" # a compact if-else statement if button.value() == 1: # button not pressed print("button NOT pressed") buttonState = "Button is NOT pressed" else: print("button pressed") buttonState = "Button is pressed" # Create and send response stateis = ledState + " and " + buttonState response = html % stateis cl.send('HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n') cl.send(response) cl.close() except OSError as e: cl.close() print('connection closed') #https://core-electronics.com.au/guides/raspberry-pi-pico-w-create-a-simple-http-server/ #https://www.youtube.com/watch?v=AK8UYh7pMGM&t=515s Part 3 # Good graphical interface on HTTP surver # Control an LED and read a Button using a web browser import time import network import socket from machine import Pin led = Pin(15, Pin.OUT) ledState = 'LED State Unknown' button = Pin(16, Pin.IN, Pin.PULL_UP) ssid = 'xxxxx' password = 'xxxxx' wlan = network.WLAN(network.STA_IF) wlan.active(True) wlan.connect(ssid, password) # replace the "html" variable with the following to create a more user-friendly control panel html = """

Control Panel









%s

""" # Wait for connect or fail max_wait = 10 while max_wait > 0: if wlan.status() < 0 or wlan.status() >= 3: break max_wait -= 1 print('waiting for connection...') time.sleep(1) # Handle connection error if wlan.status() != 3: raise RuntimeError('network connection failed') else: print('Connected') status = wlan.ifconfig() print( 'ip = ' + status[0] ) # Open socket addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1] s = socket.socket() s.bind(addr) s.listen(1) print('listening on', addr) # Listen for connections, serve client while True: try: cl, addr = s.accept() print('client connected from', addr) request = cl.recv(1024) print("request:") print(request) request = str(request) led_on = request.find('led=on') led_off = request.find('led=off') print( 'led on = ' + str(led_on)) print( 'led off = ' + str(led_off)) if led_on == 8: print("led on") led.value(1) if led_off == 8: print("led off") led.value(0) ledState = "LED is OFF" if led.value() == 0 else "LED is ON" # a compact if-else statement if button.value() == 1: # button not pressed print("button NOT pressed") buttonState = "Button is NOT pressed" else: print("button pressed") buttonState = "Button is pressed" # Create and send response stateis = ledState + " and " + buttonState response = html % stateis cl.send('HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n') cl.send(response) cl.close() except OSError as e: cl.close() print('connection closed') #https://core-electronics.com.au/guides/raspberry-pi-pico-w-create-a-simple-http-server/ #https://www.youtube.com/watch?v=AK8UYh7pMGM&t=515s

CoreElectronics 1: Connecting to the Internet

# A simple example that: # - Connects to a WiFi Network defined by "ssid" and "password" # - Performs a GET request (loads a webpage) # - Queries the current time from a server import network # handles connecting to WiFi import urequests # handles making and servicing network requests import utime # Connect to network wlan = network.WLAN(network.STA_IF) wlan.active(True) # Fill in your network name (ssid) and password here: ssid = 'xxxxx' password = 'xxxxx' wlan.connect(ssid, password) # Example 1. Make a GET request for google.com and print HTML # Print the html content from google.com print("1. Querying google.com:") r = urequests.get("http://www.google.com") print(r.content) r.close() # Example 2. urequests can also handle basic json support! Let's get the current time from a server print("\n\n2. Querying the current GMT+0 time:") r = urequests.get("http://date.jsontest.com") # Server that returns the current GMT+0 time. #print the tuple print(r.json()) # Get the 'date and time' value from the JSON response date_str = r.json()['date'] time_str = r.json()['time'][:-3] # Remove the last 3 characters (' PM' or ' AM') # Print only the time part print("Today's date GMT+0 is ", date_str.split(' ')) print("Current time GMT+0 is ",time_str.split(' ')) #Adding [0] will remove the [AM/PM] string #https://core-electronics.com.au/guides/raspberry-pi-pico-w-connect-to-the-internet/ #https://www.youtube.com/watch?v=GiT3MzRzG48&t=306s

Wednesday, 19 April 2023

TTB07: Pico W LESSON 7: Controlling 3 LED with a Potentiometer in Micropython

from machine import Pin, ADC from time import sleep potPin = 28 greenLED = 3 yellowLED = 9 redLED = 15 myPot = ADC(potPin) myGreen = Pin(greenLED,Pin.OUT) myYellow = Pin(yellowLED,Pin.OUT) myRed = Pin(redLED,Pin.OUT) while True: potVal = myPot.read_u16() myVal=(100/65103)*potVal-(100*432/65103) print(myVal) sleep(.1) if myVal<80: myGreen.value(1) myYellow.value(0) myRed.value(0) if myVal>=80: myGreen.value(0) myYellow.value(1) myRed.value(0) if myVal>=95: myGreen.value(0) myYellow.value(0) myRed.value(1) Modification using compound conditional statement: if myVal>=80 and myVal<95: myGreen.value(0) myYellow.value(1) myRed.value(0)

Friday, 10 March 2023

TTB06: Using 'IF' statement (NO potentiometer)

from machine import Pin import time led=Pin(15,Pin.OUT) while True: CMD=input('What is your Command? (ON/OFF/TOGGLE) ') if CMD=='ON': led.value(1) if CMD=='OFF': led.value(0) if CMD=='TOGGLE' : led.toggle()

TTB06a: Using 'IF' statements with a Potentiometer in RPi Pico

from machine import Pin from time import sleep potPin = 28 myPot = machine.ADC(potPin) ledR = Pin(2,Pin.OUT) ledY = Pin(4,Pin.OUT) ledG = Pin(15,Pin.OUT) try: while True: potVal = myPot.read_u16() percentage = (-100/65262)*potVal-(-100/65262*272)+100 if percentage<80: ledG.value(1) ledY.value(0) ledR.value(0) if percentage>=80 and percentage <95: ledG.value(0) ledY.value(1) ledR.value(0) if percentage>=95: ledG.value(0) ledY.value(0) ledR.value(1) print(int(percentage)) sleep(0.5) except KeyboardInterrupt: ledR.value(0) ledY.value(0) ledG.value(0) print('LEDs are off, Goodbye')

Saturday, 4 March 2023

Loads of leds (random display)

from picozero import LED from time import sleep as zzz from random import randint #max of 16 LEDs if using picozero, due to PWM conflicts. #Using 0 to 15 to make setup easier num_leds = 8 overflow_num=2**num_leds leds=[] for i in range(0,num_leds): leds.append(LED(i)) #shuffle LEDs for j in range(num_leds): i=randint(1,num_leds-1) leds[j],leds[i]=leds[i],leds[j] #reverse the order of i and j try: while True: i=randint(0,overflow_num) for j, led in enumerate(leds): led.brightness=int(bin(i+overflow_num)[j+3]) zzz(3) except KeyboardInterrupt: for led in leds: led.off() print('Turn off LEDs and quit') #https://www.youtube.com/watch?v=9MZGQmkeLAA

TTB05: Reading Analog Voltages Using a Potentiometer

import machine from time import sleep potPin = 28 myPot = machine.ADC(potPin) while True: potVal=myPot.read_u16() #print('PotVal =',potVal) #max=65535, min=1024, middle=65535-1024=64511 voltage = (3.3/64511)*potVal - (1024*3.3/64511) #print('Voltage =',voltage) percentage = (100/64511)*potVal-(1024*100/64511) #print('Percentage = ',int(percentage)) print('PotVal =',potVal, 'Voltage =',voltage, 'Percentage = ',int(percentage)) sleep(1) #https://www.youtube.com/watch?v=ODWwErH_iGA&list=PLGs0VKk2DiYz8js1SJog21cDhkBqyAhC5&index=5

TTB04a: Creating a Knight Rider LED display using a Pi Pico W

from machine import Pin from time import sleep for i in range (8,14): Pin((i), Pin.OUT) delay = 0.2 kr=[8,0,8,9,0,9,10,0,10,11,0,11,12,0,12,13,0,13] def KITT(): for j in range(len(kr)): if kr[j] == 0: sleep(delay) else: Pin(kr[j]).toggle() try: while True: KITT() except KeyboardInterrupt: for k in range(8,14): Pin(k).value(0) print('Keboard Interrupted, LEDs off') #https://www.youtube.com/watch?v=cGgDzVtppaQ

TTB04: Create a Binary Counter Using the Pico W

from machine import Pin from time import sleep led1 = Pin(15, Pin.OUT) led2 = Pin(14, Pin.OUT) led3 = Pin(13, Pin.OUT) led4 = Pin(12, Pin.OUT) while True: led1.value(0) led2.value(0) led3.value(0) led4.value(0) sleep(.5) led1.value(0) led2.value(0) led3.value(0) led4.value(1) sleep(.5) led1.value(0) led2.value(0) led3.value(1) led4.value(0) sleep(.5) led1.value(0) led2.value(0) led3.value(1) led4.value(1) sleep(.5) led1.value(0) led2.value(1) led3.value(0) led4.value(0) sleep(.5) led1.value(0) led2.value(1) led3.value(0) led4.value(1) sleep(.5) led1.value(0) led2.value(1) led3.value(1) led4.value(0) sleep(.5) led1.value(0) led2.value(1) led3.value(1) led4.value(1) sleep(.5) led1.value(1) led2.value(0) led3.value(0) led4.value(0) sleep(.5) led1.value(1) led2.value(0) led3.value(0) led4.value(1) sleep(.5) led1.value(1) led2.value(0) led3.value(1) led4.value(0) sleep(.5) led1.value(1) led2.value(0) led3.value(1) led4.value(1) sleep(.5) led1.value(1) led2.value(1) led3.value(0) led4.value(0) sleep(.5) led1.value(1) led2.value(1) led3.value(0) led4.value(1) sleep(.5) led1.value(1) led2.value(1) led3.value(1) led4.value(0) sleep(.5) led1.value(1) led2.value(1) led3.value(1) led4.value(1) sleep(.5) https://www.youtube.com/watch?v=P1dzHNgAtvg&list=PLGs0VKk2DiYz8js1SJog21cDhkBqyAhC5&index=4

Saturday, 25 February 2023

1 more Easy raspberrypi Pico Projects (Morse Code)

from machine import Pin, PWM from time import sleep # Create a dictionary of Morse Code. s is for Short (or dots), l is for Long (or dashes) MorseCodes = { ' ': '', 'a': 'sl', 'b': 'lsss', 'c': 'lsls', 'd': 'lss', 'e': 's', 'f': 'ssls', 'g': 'lls', 'h': 'ssss', 'i': 'ss', 'j': 'slll', 'k': 'lsl', 'l': 'slss', 'm': 'll', 'n': 'ls', 'o': 'lll', 'p': 'slls', 'q': 'llsl', 'r': 'sls', 's': 'sss', 't': 'l', 'u': 'ssl', 'v': 'sssl', 'w': 'sll', 'x': 'lssl', 'y': 'lsll', 'z': 'llss', '1': 'sllll', '2': 'sslll', '3': 'sssll', '4': 'ssssl', '5': 'sssss', '6': 'lssss', '7': 'llsss', '8': 'lllss', '9': 'lllls', '0': 'lllll'} button = Pin(10, Pin.IN, Pin.PULL_UP) shortled = Pin(11, Pin.OUT) longled = Pin(12, Pin.OUT) speaker = PWM(Pin(13)) fast = 0.1 slow = 0.2 sound = True light = True pitch = 600 volume = 1500 speaker.freq(600) #pitch of sound. Higher number is higher pitch shortled.low() longled.low() def letterlookup(stringvalue): for k in MorseCodes: if MorseCodes[k] == stringvalue: return k return " " def blinkletter(letter): if letter != "": currentletter = MorseCodes[letter] if letter == " ": sleep(0.6) return print(letter + " : " + currentletter) for c in currentletter: if (c == 'l'): blinkspeed = slow if (c =='s'): blinkspeed = fast if light : shortled.high() if sound : speaker.freq(pitch) speaker.duty_u16(volume) sleep(blinkspeed) if light : shortled.low() if sound : speaker.duty_u16(0) sleep(blinkspeed) sleep(0.6) def playmessage(message): for c in message: blinkletter(str.lower(c)) def recordmessage(): print("start typing your Morse Code message! Wait 5 seconds to exit") TimeCount = 0 DelayCount = 0 CurrentLetter = "" CurrentWord = "" PreviousStatus = 1 while True: if button.value() == 0: #Button being pressed DelayCount = 0 TimeCount += 1 if TimeCount <= 15: #Its a short press! shortled.high() longled.low() elif TimeCount > 15: #Its a Long Press! shortled.low() longled.high() if PreviousStatus != button.value(): speaker.duty_u16(1500) elif button.value() == 1: #Button not being pressed speaker.duty_u16(0) shortled.low() longled.low() if TimeCount > 0: if TimeCount <= 15: CurrentLetter = CurrentLetter + "s" elif TimeCount > 15: CurrentLetter = CurrentLetter + "l" TimeCount = 0 DelayCount = DelayCount + 1 if DelayCount > 60: if CurrentLetter != "": CurrentWord = CurrentWord + letterlookup(CurrentLetter) CurrentLetter = "" print(CurrentWord) if DelayCount == 300: #Add a space CurrentWord = CurrentWord + " " if DelayCount == 500: print("You recorded " + CurrentWord) print("Exiting recording mode") return sleep(0.01) #After execute the program, on the shell, type {playmessage('SOS')} #https://www.youtube.com/watch?v=k2thJQxO17w #https://github.com/printnplay/Pico-MicroPython/blob/main/MorseCodeCreator.py

2 Easy raspberrypi Pico Projects (temperature and music)

from machine import ADC from time import sleep tempsensor = ADC(4) conversion_factor = 3.3 / (65535) # Conversion from Pin read to proper voltage while True: currentvoltage = tempsensor.read_u16() * conversion_factor temp = 27 - ((currentvoltage - 0.706)/0.001721) print(str(currentvoltage) + " : " + str(temp)) sleep(2) #https://www.youtube.com/watch?v=k2thJQxO17w #https://github.com/printnplay/Pico-MicroPython/blob/main/ReadTemp.py ======================================================================== from machine import PWM, Pin from time import sleep MusicNotes = {"B0": 31, "C1": 33,"CS1": 35,"D1": 37,"DS1": 39,"E1": 41,"F1": 44,"FS1": 46,"G1": 49,"GS1": 52,"A1": 55,"AS1": 58,"B1": 62, "C2": 65,"CS2": 69,"D2": 73,"DS2": 78,"E2": 82,"F2": 87,"FS2": 93,"G2": 98,"GS2": 104,"A2": 110,"AS2": 117,"B2": 123,"C3": 131,"CS3": 139, "D3": 147,"DS3": 156,"E3": 165,"F3": 175,"FS3": 185,"G3": 196,"GS3": 208,"A3": 220,"AS3": 233,"B3": 247,"C4": 262,"CS4": 277,"D4": 294, "DS4": 311,"E4": 330,"F4": 349,"FS4": 370,"G4": 392,"GS4": 415,"A4": 440,"AS4": 466,"B4": 494,"C5": 523,"CS5": 554,"D5": 587,"DS5": 622, "E5": 659,"F5": 698,"FS5": 740,"G5": 784,"GS5": 831,"A5": 880,"AS5": 932,"B5": 988,"C6": 1047,"CS6": 1109,"D6": 1175,"DS6": 1245,"E6": 1324, "F6": 1397,"FS6": 1480,"G6": 1568,"GS6": 1661,"A6": 1760,"AS6": 1865,"B6": 1976,"C7": 2093,"CS7": 2217,"D7": 2349,"DS7": 2489,"E7": 2637, "F7": 2794,"FS7": 2960,"G7": 3136,"GS7": 3322,"A7": 3520,"AS7": 3729,"B7": 3951,"C8": 4186,"CS8": 4435,"D8": 4699,"DS8": 4978} mario = ["E7", "E7", "0", "E7", "0", "C7", "E7", "0", "G7", "0", "0", "0", "G6", "0", "0", "0", "C7", "0", "0", "G6", "0", "0", "E6", "0", "0", "A6", "0", "B6", "0", "AS6", "A6", "0", "G6", "E7", "0", "G7", "A7", "0", "F7", "G7", "0", "E7", "0","C7", "D7", "B6", "0", "0", "C7", "0", "0", "G6", "0", "0", "E6", "0", "0", "A6", "0", "B6", "0", "AS6", "A6", "0", "G6", "E7", "0", "G7", "A7", "0", "F7", "G7", "0", "E7", "0","C7", "D7", "B6", "0", "0"] hotcrossedbuns = ["E3", "0", "D3", "0", "C3", "0", "S", "E3", "0", "D3", "0", "C3", "0", "S", "C3", "C3", "C3", "C3", "D3", "D3", "D3", "D3", "S", "E3", "0", "D3", "0", "C3", "0"] speaker = PWM(Pin(13)) blueled = Pin(12, Pin.OUT) redled = Pin(11, Pin.OUT) def playnote(Note, Duration): if Note == "0": sleep(Duration) if Note == "S": speaker.duty_u16(0) sleep(Duration) elif Note != "0": speaker.duty_u16(0) sleep(0.05) blueled.toggle() redled.toggle() speaker.duty_u16(1500) speaker.freq(MusicNotes[Note]) sleep(Duration) blueled.high() redled.low() for c in hotcrossedbuns: playnote(c, 0.2) sleep(1) for c in mario: playnote(c, 0.4) speaker.duty_u16(0) #https://www.youtube.com/watch?v=k2thJQxO17w #https://github.com/printnplay/Pico-MicroPython/blob/main/MusicTest.py

Wednesday, 22 February 2023

Exercise 1 using TM1637

#Library import utime import tm1637 from machine import Pin #setup tm = tm1637.TM1637(clk=machine.Pin(4), dio=machine.Pin(5)) #to clear the display tm.show(' ') utime.sleep(2) #to present data on the display #here are the examples tm.number(1) utime.sleep(2) tm.number(12) utime.sleep(2) tm.number(123) utime.sleep(2) tm.number(1234) utime.sleep(2) #notice that the display starts from right to left tm.show("AbCd") utime.sleep(2) #Show scrolling text #delay controls the speed of the scrolling text. #The default delay is set as 250ms tm.scroll("8888 8888 8888", delay=300) utime.sleep(2) #to display time with the colon seperating hour and minutes tm.numbers(12,30) utime.sleep(2) #Temperature #Display with the degree Celsius sign #it accepts 2 digit +ve no. or a single digit with -ve no. tm.temperature(37) utime.sleep(2) #digital clock while True: time=utime.localtime() print(time) #(2023, 2, 6, 20, 14, 57, 0, 37) # 0 1 2 3 4 5 6 7 hr=time[3] mn=time[4] tm.numbers(hr,mn) utime.sleep(15) tm.show(' ') #if you open up tm1637.py you can see the functions number() and numbers() #in this library #From SSGoh on Github #Also From: https://microcontrollerslab.com/7-segment-display-raspberry-pi-pico/

Tuesday, 21 February 2023

Stop watch using TM1637

from machine import Pin import time import tm1637 tm = tm1637.TM1637(clk=Pin(4), dio=Pin(5)) Button = Pin(2, Pin.IN) a = 0 b = 0 tm.show(' ') tm.numbers(a,b) while True: if Button.value() == 1: while True: tm.numbers(a,b) b = b+1 time.sleep(1) if b > 59: b = 0 a = a+1 time.sleep(1) #Stop watch using Raspberry Pi Pico #https://electricdiylab.com/stopwatch-using-raspberry-pi-pico/#Schematic_Diagram

Thursday, 9 February 2023

Morse Code - SOS

from machine import Pin from time import sleep # the message to send in morse-code messages = ["sos sos sos sos sos sos"] #timing for encoding beatLen = 0.15 #length of dits and dahs ditLen = beatLen * 1 dahLen = beatLen * 3 #assign the signal lamp pin and amke sure its off signalLamp = Pin(15, Pin.OUT) signalLamp.off() #according to stories I've heard... hellNotFrozen = True #table to transform readable letters into morse code code = {'A':'.-', 'B':'-...', 'C':'-.-.', 'D':'-..', 'E':'.', 'F':'..-.', 'G':'--.', 'H':'....', 'I':'..', 'J':'.---', 'K':'-.-', 'L':'.-..', 'M':'--', 'N':'-.', 'O':'---', 'P':'.--.', 'Q':'--.-', 'R':'.-.', 'S':'...', 'T':'-', 'U':'..-', 'V':'...-', 'W':'.--', 'X':'-..-', 'Y':'-.--', 'Z':'--..', '1':'.----', '2':'..---', '3':'...--', '4':'....-', '5':'.....', '6':'-....', '7':'--...', '8':'---..', '9':'----.', '0':'-----', ', ':'--..--', '.':'.-.-.-', '?':'..--..', '/':'-..-.', '-':'-....-', '(':'-.--.', ')':'-.--.-'} while hellNotFrozen: #loop through the list of messages for message in messages: # more code only has uppercase message = message.upper().strip() #loop through each character in the message for xmitChr in message: print(xmitChr, end = '') # show off the character on if xmitChr == ' ': # space means end of word # end of word - wait 4 more beats (7 total) sleep(beatLen * 4) else:# encode a character #loop through the ditdah code for this character for ditDah in code[xmitChr]: #turn the signal lamp on and count beats signalLamp.on() if ditDah == ".": sleep(ditLen) else: sleep(dahLen) # turn off signal lamp and 1 beat pause between signalLamp.off() sleep(beatLen) # end of character - wait for 2 more beats (3 in total) sleep(beatLen * 2) #end of message - wait 4 more beats (7 in total) sleep(beatLen * 4) print() #https://www.youtube.com/watch?v=cCSYFUeO-CU Observe the video for 'short short short', 'long long long', 'short short short'

Wednesday, 8 February 2023

Control an LED through Wi-Fi with a Raspberry Pi PICO W

import network import socket import time import secret1 from machine import Pin led = Pin(15, Pin.OUT) ssid = secret1.SSID password = secret1.PASSWORD wlan = network.WLAN(network.STA_IF) wlan.active(True) wlan.connect(ssid, password) html = """ Raspberry Pi Pico

LED Status Indicator

%s

""" # Wait for connect or fail max_wait = 10 while max_wait > 0: if wlan.status() < 0 or wlan.status() >= 3: break max_wait -= 1 print('waiting for connection...') time.sleep(1) # Handle connection error if wlan.status() != 3: raise RuntimeError('network connection failed') else: print('connected') status = wlan.ifconfig() print( 'ip = ' + status[0] ) # Open socket addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1] s = socket.socket() s.bind(addr) s.listen(1) print('listening on', addr) # Listen for connections while True: try: cl, addr = s.accept() print('client connected from', addr) request = cl.recv(1024) print(request) request = str(request) led_on = request.find('/light/on') led_off = request.find('/light/off') print( 'led on = ' + str(led_on)) print( 'led off = ' + str(led_off)) if led_on == 6: print("led on") led.value(1) stateis = "LED is ON" if led_off == 6: print("led off") led.value(0) stateis = "LED is OFF" response = html % stateis cl.send('HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n') cl.send(response) cl.close() except OSError as e: cl.close() print('connection closed') #https://www.youtube.com/watch?v=51m7umIEjd4

Monday, 6 February 2023

Traffic Light Controller with Raspberry Pi Pico & MicroPython

from machine import Pin from time import sleep import tm1637 tm = tm1637.TM1637(clk=Pin(4), dio=Pin(5)) Led_R = Pin(0, Pin.OUT) Led_Y = Pin(1, Pin.OUT) Led_G = Pin(2, Pin.OUT) while True: num = 30 Led_R.value(1) for i in range(30): num=num-1 tm.number(num) sleep(1) Led_R.value(0) for i in range(5): Led_Y.value(1) sleep(0.3) Led_Y.value(0) sleep(0.3) Led_G.value(1) sleep(10) Led_G.value(0) #https://how2electronics.com/traffic-light-controller-with-raspberry-pi-p

Feb05 Display time and date using f-string

#Libraries from machine import Pin, I2C #,RTC , WDT from ssd1306 import SSD1306_I2C import utime #set up WIDTH =128 HEIGHT= 64 i2c=I2C(0,scl=Pin(17),sda=Pin(16),freq=200000) oled = SSD1306_I2C(WIDTH,HEIGHT,i2c) week=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"] while True: #time.sleep(1) date_time_now = utime.time() date_time_now=utime.localtime(date_time_now) print(date_time_now) #date_time_now is in this tuple format #(2022, 12, 15, 14, 54, 27, 3, 349) # 0 1 2 3 4 5 6 7 #local_date_time=str(date_time_now[3]) + ':' + str(date_time_now[4]) + ':' + str(date_time_now[5]) local_year_day=f"{date_time_now[0]}/{date_time_now[1]:02}/{date_time_now[2]:02}" print(local_year_day) local_date_time=f"{date_time_now[3]:02}:{date_time_now[4]:02}:{date_time_now[5]:02}" print(local_date_time) local_wk_day=f"{week[date_time_now[6]]}" print(local_wk_day) #display in ssd1306 oled.fill(0) #clear display oled.text("Today's date is ",0,0) oled.text(local_year_day, 0, 14) oled.text(local_wk_day,0,28) oled.text("Current time is ", 0,42) oled.text(local_date_time, 0, 56) oled.show() utime.sleep(5)

Friday, 3 February 2023

TRL - Exercise2c

#Using def function #Library from gpiozero import LED from time import sleep #Setup Components / Variables tf_red_led = LED(13) tf_amber_led = LED(19) tf_green_led = LED(26) #Alorgithm #Initialize the LEDs tf_red_led.off() tf_amber_led.off() tf_green_led.off() def trafficLight(): tf_green_led.on() sleep(10) tf_green_led.off() tf_amber_led.on() sleep(5) tf_amber_led.off() tf_red_led.on() sleep(10) tf_red_led.off() while True: trafficLight()

Thursday, 2 February 2023

SF2.2 Display the Level

import machine import utime pin = [6,7,8,9,10,11,12,13] led= [] for i in range(8): led.append(None) led[i] = machine.Pin(pin[i], machine.Pin.OUT) while True: for i in range(8): led[i].toggle() utime.sleep(0.5) #SunFounder Kepler kit 2.2 Display the Level

Wednesday, 1 February 2023

TTB02A Make an LED send SOS

from machine import Pin from time import sleep blueLed=Pin(15,Pin.OUT) dot=.3 dash=2*dot while True: for i in range(1,4): blueLed.value(0) sleep(dot) blueLed.value(1) sleep(dot) for i in range(1,4): blueLed.value(0) sleep(dash) blueLed.value(1) sleep(dash) for i in range(1,4): blueLed.value(0) sleep(dot) blueLed.value(1) sleep(dot) for i in range(1,4): blueLed.value(0) sleep(1) #S.O.S represented in Morse code is #▄ ▄ ▄ ▄▄▄ ▄▄▄ ▄▄▄ ▄ ▄ ▄ #https://www.youtube.com/watch?v=pWzyb8VvxTY

TTB02 Understanding and Using Breadboards

from machine import Pin from time import sleep blueLED = Pin(15, Pin.OUT) while True: blueLED.value(0) sleep(1) blueLED.value(1) sleep(1) #https://www.youtube.com/watch?v=eGdrtikKc5U

TTB01A How Fast Can You Blink the LED and Still See It?

# This program loops through a list of sleep times to see how # fast I can blink the internal LED on a Pico W and still see # it blink # In this version, I moved the print outside of the blink loops # to avoid any delay due to running too many prints inside the blink loop # January 2023 # Lori Pfahler # import needed modules/functions import machine # utime and time are the same - the time library just points to utime library from utime import sleep # setup internal LED as an output # regular pico use GP25; on Pico W use 'LED' # for regular pico use: internalLED = machine.Pin(25, machine.Pin.OUT internalLED = machine.Pin('LED', machine.Pin.OUT) # create a list of sleep durations to test my eyes myList = [1.0, 0.90, 0.80, 0.70, 0.60, 0.50, 0.40, 0.30,0.20, 0.10, 0.05, 0.04, 0.03, 0.02, 0.019, 0.018, 0.017, 0.016, 0.015, 0.014, 0.013, 0.012, 0.011, 0.010] while True: for num in myList: # loop over numbers on myList if num >= 0.5: # blink 5 times for longer sleep times print('Can you see this speed? ', num, 'seconds') for nBlinks in range(0, 10): internalLED.toggle() sleep(num) elif num >= 0.1 and num < 0.5: # blink 10 times for medium sleep times print('Can you see this speed? ', num, 'seconds') for nBlinks in range(0, 20): internalLED.toggle() sleep(num) else: # blink 50 times for short sleep times print('Can you see this speed? ', num, 'seconds') for nBlinks in range(0, 100): internalLED.toggle() sleep(num) #https://www.youtube.com/watch?v=Bur4Ch7wvo8

TTB01 Flashing LED

from machine import Pin from time import sleep myLED=Pin('LED', Pin.OUT) myLED.off() print('LED now flashes with toggle') for x in range(1, 30, 1): myLED.toggle() sleep(1) print('LED now flashes asymmetrically') while True: myLED.value(1) sleep(1) myLED.value(0) sleep(.1) #https://www.youtube.com/watch?v=SL4_oU9t8Ss&t=0s

Sunday, 29 January 2023

4Buttons to control RGB led using Raspberry Pi Pico

from picozero import Button, RGBLED from time import sleep rgb = RGBLED(red = 1, green = 2, blue = 3) button = Button(18) option = 0 # store the current option def choice(): # call the next function and update the option global option if option == 0: rgb.color = (255, 0, 0) elif option == 1: rgb.color = (0, 255, 0) elif option == 2: rgb.color = (0, 0, 255) elif option == 3: rgb.off() # move to the next option if option == 3: option = 0 else: option = option + 1 button.when_pressed = choice # Call the choice function when the button is pressed #https://projects.raspberrypi.org/en/projects/

3Playing music with Raspberry Pi Pico

from picozero import Speaker from time import sleep #from random import randint speaker = Speaker(5) print("Play the frequency 523, middle C.") sound = [ [523, 1], [None, 0.1], [523, 4] ] speaker.play(sound) speaker.play(sound, wait=False) # don't delay the main code sleep(0.5) print("Gradually increases in frequency to create a positive sound") for i in range(2000, 5000, 100): speaker.play(i, 0.05) # short duration sleep(0.5) print("Decreases the pitch to create a bird chirping sound.") for i in range(5000, 2000, -100): speaker.play(i, 0.05) # very short duration sleep(0.5) print("Create a list of notes and durations to make a tune. You can then play the tune.") BEAT = 0.6 # The length of a note in a single beat liten_mus = [ ['d5', BEAT / 2], ['d#5', BEAT / 2], ['f5', BEAT], ['d6', BEAT], ['a#5', BEAT], ['d5', BEAT], ['f5', BEAT], ['d#5', BEAT], ['d#5', BEAT], ['c5', BEAT / 2],['d5', BEAT / 2], ['d#5', BEAT], ['c6', BEAT], ['a5', BEAT], ['d5', BEAT], ['g5', BEAT], ['f5', BEAT], ['f5', BEAT], ['d5', BEAT / 2], ['d#5', BEAT / 2], ['f5', BEAT], ['g5', BEAT], ['a5', BEAT], ['a#5', BEAT], ['a5', BEAT], ['g5', BEAT], ['g5', BEAT], ['', BEAT / 2], ['a#5', BEAT / 2], ['c6', BEAT / 2], ['d6', BEAT / 2], ['c6', BEAT / 2], ['a#5', BEAT / 2], ['a5', BEAT / 2], ['g5', BEAT / 2], ['a5', BEAT / 2], ['a#5', BEAT / 2], ['c6', BEAT], ['f5', BEAT], ['f5', BEAT], ['f5', BEAT / 2], ['d#5', BEAT / 2], ['d5', BEAT], ['f5', BEAT], ['d6', BEAT], ['d6', BEAT / 2], ['c6', BEAT / 2], ['b5', BEAT], ['g5', BEAT], ['g5', BEAT], ['c6', BEAT / 2], ['a#5', BEAT / 2], ['a5', BEAT], ['f5', BEAT], ['d6', BEAT], ['a5', BEAT], ['a#5', BEAT * 1.5] ] speaker.play(liten_mus) sleep(0.5) print("Also can use a loop to play the tune, one note at a time.") for note in liten_mus: speaker.play(note) #https://projects.raspberrypi.org/en/projects/i

Friday, 27 January 2023

TRL-Exercise3m

#Library from gpiozero import LED, Buzzer, Button from time import sleep from signal import pause import tm1637 #Component setup green_led = LED(18) red_led = LED(14) anti_spam_led = LED(7) buzz = Buzzer(25) button = Button(24) display=tm1637.TM1637(20,16) #Function def activate(): if anti_spam_led.value == 1: pass else: anti_spam_led.on() greenman() def greenman(): print('Button was pressed') sleep(10) red_led.off() green_led.on() sleep(10) for counter in range(5,-1,-1): green_led.blink(on_time=0.5, off_time=0.5, n=1) buzz.blink(on_time=0.5, off_time=0.5, n=1) display.set_values([' ',' ',' ',counter]) sleep(1) green_led.off() red_led.on() anti_spam_led.off() display.clear() print('Waiting for Next Button Press') #Algorithm red_led.on() anti_spam_led.off() display.clear() print('Program Started') print('Waiting for button to be pressed') button.when_pressed = activate pause()

TRL-Exercise3g

#Library from gpiozero import LED from time import sleep #Component setup green_led = LED(18) red_led = LED(14) #Algorith red_led.on() sleep(10) red_led.off() green_led.on() sleep(10) green_led.blink(on_time=0.5, off_time=0.5, n=5) sleep(5) green_led.off() red_led.on()

2RGB led running on Raspberry Pi Pico

from picozero import RGBLED from time import sleep rgb = RGBLED(red = 1, green = 2, blue = 3) rgb.blink() # red for 1 second, green for 1 second, blue for 1 second print("Blinking with all colors") # Runs immediately sleep(3) rgb.off() # blink purple 2 seconds, off 0.5 seconds rgb.blink(on_times=(2, 0.5), colors=((255, 0, 255), (0, 0, 0)), wait=True, n=3) print("Finished blinking purple") # Runs after 3 repeats sleep(3) rgb.off() # blink red 1 second, green 0.5 seconds, blue 0.25 seconds rgb.blink((1, 0.5, 0.25), colors=((255, 0, 0), (0, 255, 0), (0, 0, 255)), wait=True, n=2) print("Finished blinking different color different duration") # Runs after 2 blink repeats sleep(3) rgb.off() for x in range(1, 4, 1): rgb.color = (255, 0, 0) sleep(0.5) rgb.color = (0, 255, 0) sleep(0.5) rgb.color = (0, 0, 255) sleep(0.5) print("ON and OFF the 3 colors") rgb.off() rgb.pulse() # pulse red for 1 second, green for 1 second, blue for 1 second print("Pulsing") # Runs immediately sleep(3) rgb.off() # 2 second to fade from purple to off, 0.5 seconds to change from off to purple rgb.pulse(fade_times=(2, 0.5), colors=((255, 0, 255), (0, 0, 0)), wait=True, n=3) print("Finished pulsing") # Runs after 3 pulses sleep(3) rgb.off() rgb.cycle() # Gradually colour cycle through colours between red and green, green and blue then blue and red print("Cycle") # Runs immediately sleep(3) rgb.off() # Colour cycle slower in the opposite direction rgb.cycle(fade_times=3, colors=((0, 0, 255), (0, 255, 0), (255, 0, 0)), wait=True, n=2) print("Cycle slowly 2 times") sleep(3) rgb.off() #https://projects.raspberrypi.org/en/projects/introduction-to-the-pico/8

1LED project on Raspberry Pi Pico

from picozero import LED from time import sleep yellow = LED(13) yellow.on() sleep(2) yellow.off() print("led ON") #yellow.blink() # on for 1 second then off for one second sleep(1) yellow.blink(on_time=1, off_time=0.5, n=3, wait=True) yellow.off() print("Finished blinking") # Runs after 3 on/off blinks sleep(1) yellow.pulse() # take 1 second to brighten and 1 second to dim sleep(3) yellow.off() print("Pulsing") # Runs immediately sleep(1) yellow.pulse(fade_in_time=3, fade_out_time=3, n=4, wait=True) # take 2 seconds to brighten and 1 second to dim sleep(3) yellow.off() print("Finished pulsing") # Runs after 4 pulses sleep(1) yellow.blink(on_time=1, off_time=1, fade_in_time=3, fade_out_time=3) # On for 1 second, off for 1 second, fade between sleep(3) yellow.off() print("Fancy") # Runs immediately #https://projects.raspberrypi.org/en/projects/introduction-to-the-pico/7