Ejemplo n.º 1
0
lamp_blue = 0
lamp_white = 0
lamp_random = 0
lamp_speed = 0

lamp_saturation_white = 0
lamp_saturation_color = 0

# init pwm pins
pin_green = machine.Pin(GREEN)
pin_red = machine.Pin(RED)
pin_blue = machine.Pin(BLUE)
pin_white = machine.Pin(WHITE)
pin_switch = machine.Pin(SWITCH, machine.Pin.OUT)

pwm_green = machine.PWM(pin_green)
pwm_red = machine.PWM(pin_red)
pwm_blue = machine.PWM(pin_blue)
pwm_white = machine.PWM(pin_white)
# max duty is 1024
pwm_green.freq(500)
pwm_green.duty(0)
pwm_red.freq(500)
pwm_red.duty(0)
pwm_blue.freq(500)
pwm_blue.duty(0)
pwm_white.freq(500)
pwm_white.duty(1024)


def rgbw_calc_color(color):
blueLed=machine.Pin(27,machine.Pin.OUT)
greenLed=machine.Pin(33,machine.Pin.OUT)
button1=machine.Pin(36,machine.Pin.IN)
button2=machine.Pin(39,machine.Pin.IN)
file=open('datafile.txt','w')

#Turn on only blue LED
redLed.value(1)
greenLed.value(1)
blueLed.value(0)

data=machine.ADC(machine.Pin(32))
data.atten(ADC.ATTN_11DB)
#data.width(ADC.WIDTH_11BIT)

mainLed=machine.PWM(machine.Pin(13))
mainLed.freq(78000)
mainLed.duty(600)
k=0
r=0



while True:
    if button1.value()!=0:
        blueLed.value(1)
        redLed.value(0)

        while k<100:
            r+=data.read()
            k+=1
Ejemplo n.º 3
0
import machine as m
import time as t

#---WEMOS D1 PIN <- ESP8266 PIN---#
D0 = m.Pin(16,m.Pin.OUT)
D5 = m.Pin(14,m.Pin.OUT)
D2 = m.Pin(4,m.Pin.IN)
D1 = m.Pin(5,m.Pin.OUT)
led = m.Pin(2, m.Pin.OUT)
periodo = 0.9

adc = m.ADC(0)

pwmD1 = m.PWM(D1) 
pwmD5 = m.PWM(D5)

pwmD1.freq(60)
pwmD1.duty(1024) 
pwmD5.freq(60)
pwmD5.duty(1024) 

pwmVel_d1 = 128
pwmVel_d5 = 128


velocidade = 5
liga = 1


while True:
# Assignment 2.4: Maker Driver for Pi Pico
# Docu: https://th.cytron.io/p-maker-drive-simplifying-h-bridge-motor-driver-for-beginner

import machine, utime

M1A = machine.PWM(machine.Pin(0))
M1B = machine.PWM(machine.Pin(1))

M1A.freq(50)  # 50Hz is the default frequency for most servos
M1B.freq(50)

while True:
    for i in range(0, 65535):  # Servo has 65536 resolution level
        M1A.duty_u16(i)
    for i in range(0, 65535):
        M1B.duty_u16(i)
Ejemplo n.º 5
0
<input type="text" name="headx" id="headx" value="" placeholder="0.00">
<input type="submit" value="head x">
</form>
</body>
<!--http://192.168.101.102/?headx=0.37-->
</html>

"""

#Setup drives
# LE0 = machine.Pin(0, machine.Pin.OUT)
# LED2 = machine.Pin(2, machine.Pin.OUT)
# motor_a_p = machine.PWM(machine.Pin(5), freq=50)
# motor_a_m = machine.PWM(machine.Pin(0), freq=50)
# serv = machine.PWM(machine.Pin(12), freq=50)
sevr_head_x = machine.PWM(machine.Pin(14), freq=50)

#Setup Socket WebServer
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 80))
s.listen(5)
print('DBG: opened connection to port 80')
while True:
    conn, addr = s.accept()
    print("Got a connection from %s" % str(addr))
    request = conn.recv(1024)
    # print("Content = %s" % str(request))  # print full request
    request = str(request)
    # # LEDON0 = request.find('/?LED=ON0')
    # # LEDOFF0 = request.find('/?LED=OFF0')
    # # LEDON2 = request.find('/?LED=ON2')
Ejemplo n.º 6
0
""" + robot_ip + """
<br>
</body>
</html>

"""

html_ok = """<html><body>OK</body>
</html>

"""

# Setup drives
# LE0 = machine.Pin(0, machine.Pin.OUT)
# LED2 = machine.Pin(2, machine.Pin.OUT)
motor_a_p = machine.PWM(machine.Pin(5), freq=50)
motor_a_m = machine.PWM(machine.Pin(0), freq=50)
servo_direction = machine.PWM(machine.Pin(12), freq=50)
servo_head_x = machine.PWM(machine.Pin(14), freq=50)
servo_hand_y = machine.PWM(machine.Pin(13), freq=50)
servo_catch = machine.PWM(machine.Pin(15), freq=50)

networkpin = machine.Pin(2, machine.Pin.OUT)
# networkpin.on()


def blink_report(n_blinks):
    networkpin.off()
    time.sleep(SHORT_SLEEP * 2)
    for blinks in range(n_blinks):
        networkpin.on()
Ejemplo n.º 7
0
import machine, time
Pin = machine.Pin

servo = machine.PWM(Pin(13), freq=50)


def rotate(deg):
    maxDutyCoef = 135
    minDutyCoef = 20
    maxDeg = 180

    if deg == 0:
        dutyCoef = minDutyCoef
    elif deg >= 180:
        dutyCoef = maxDutyCoef
    else:
        coef = maxDeg / deg
        dutyCoef = (maxDutyCoef / coef) + minDutyCoef

    servo.duty(round(dutyCoef))


while True:
    rotate(0)
    time.sleep(0.3)
    rotate(90)
    time.sleep(0.3)
    rotate(180)
    time.sleep(0.3)
Ejemplo n.º 8
0
 def attach(self, pin):
     self.pin = machine.Pin(pin)
     self.pwm = machine.PWM(self.pin, freq=self.freq, duty=0)
     self._attached = True
Ejemplo n.º 9
0
 def __init__(self, pin_number: int):
     pin = machine.Pin(pin_number, machine.Pin.OUT)
     self._pwm = machine.PWM(pin)
# EECSE4764 Lab3 Check4
# Group 6: NetSpeed Fast
# Group members: Ruochen You (ry2349), Penghe Zhang (pz2244), Linnan Li(ll3235)
# Date: 10/2/2018

import time, machine, ssd1306
from machine import Pin

rtc = machine.RTC()
rtc.datetime((2018, 1, 1, 0, 0, 0, 0, 0))
alarm_time = [0, 0, 0]

i2c = machine.I2C(-1, Pin(5), Pin(4))
pwm = machine.PWM(machine.Pin(14))
adc = machine.ADC(0)
oled = ssd1306.SSD1306_I2C(128, 32, i2c)
cur = 0
mode = 0
pos = [6, 5, 4, 2, 1, 0]
pos_name = ["second", "minute", "hour", "day", "month", "year"]


# display time on the oled
def display_time():
    oled.fill(0)
    cur_date = "date: " + str(rtc.datetime()[0]) + '/' + str(
        rtc.datetime()[1]) + '/' + str(rtc.datetime()[2])
    cur_time = "time: " + str(rtc.datetime()[4]) + ':' + str(
        rtc.datetime()[5]) + ':' + str(rtc.datetime()[6])
    alarm = "alarm: " + str(alarm_time[2]) + ':' + str(
        alarm_time[1]) + ':' + str(alarm_time[0])
Ejemplo n.º 11
0
def serve_web_client(cl, addr, CONFIG, analog_value, name2value):
    print('Accepted connection:', cl, addr)
    cl.settimeout(1)  # larger timeout than accept() timeout
    cl_file = cl.makefile('rwb', 0)
    try:
        request_line = ""
        while True:
            line = cl_file.readline()
            #print('Request line: {}'.format(line))
            if not line or line == b'\r\n':
                break
            # hack: check for matching URL strings anywhere in what looks like the HTTP request line TODO: properly parse
            # also, allowing any of these verbs for convenience, though technically should PUT only change state? TODO restfulness
            if line.startswith('GET ') or line.startswith(
                    'POST ') or line.startswith('PUT '):
                request_line = line

        for info in CONFIG['output_gpio']:
            new_value = None
            if info['on_path'] in request_line:
                new_value = True
            if info['off_path'] in request_line:
                new_value = False

            if new_value is not None:
                print(
                    'Request via {} to change value of GPIO output: {} ({}) -> {}'
                    .format(line, info['name'], info['pin'], new_value))
                if info.get('pwm'):
                    # pulse-width modulation
                    if 'object' not in info:
                        obj = machine.PWM(machine.Pin(info['pin']))
                        info[
                            'object'] = obj  # cached to avoid recreating objects
                    obj = info['object']
                    if new_value is False:
                        obj.duty(0)
                        # TODO: could deinit(), but this works alright
                    else:
                        # on, but at what frequency / duty cycle?
                        match = re.search(r'freq=(\d+)&duty=(\d+)',
                                          request_line)
                        if match:
                            freq = int(match.group(1))
                            duty = int(match.group(2))
                        else:
                            freq = 10
                            duty = 512

                        # TODO: why doesn't this regex-free code load on boot?
                        #sline = str(request_line)
                        #at = sline.find('freq=')
                        #freq = None
                        #duty = None
                        #if at != -1:
                        #    s = sline[at + 5:]
                        #    freq = int(s[:s.rfind('&')])
                        #at = sline.find('duty=')
                        #if at != -1:
                        #    s = sline[at + 5:]
                        #    duty = int(s[:s.rfind(' ')])

                        if freq is None: freq = 10
                        if duty is None: duty = 512
                        obj.freq(freq)
                        obj.duty(duty)

                else:
                    # regular GPIO on/off
                    if 'object' not in info:
                        obj = machine.Pin(info['pin'], machine.Pin.OUT)
                        info[
                            'object'] = obj  # cached to avoid recreating objects
                    obj = info['object']
                    obj.value(new_value)

                # TODO: redirect back to homepage

    except Exception as e:
        print('Exception from client:', e)
        pass

    title = CONFIG['client_id'].decode('ascii')
    html = """<html>
<head>
<title>{}</title>
</head>
<body>
<h1>{}</h1>
<table>
 <tr>
  <td>Analog Sensor</td>
  <td>{}</td>
 </tr>
""".format(title, title, analog_value)

    for name in sorted(name2value.keys()):
        value = name2value[name]
        html += """
 <tr>
  <td>{}</td>
  <td>{}</td>
 </tr>""".format(name, value)

    for info in CONFIG['output_gpio']:
        html += """
 <tr>
  <td>{}</td>
  <td><a href="{}">On</a> | <a href="{}">Off</a></td>
 </tr>
""".format(info['name'], info['on_path'], info['off_path'])

    html += """
</table>
</body>
</html>"""

    response = """HTTP/1.1 200 OK\r
Content-Type: text/html\r
Content-Length: {}\r
\r
{}
""".format(len(html), html)

    cl.send(response)
    cl.close()
Ejemplo n.º 12
0
# Materiel :
#            Testé sur ESP32 WROOM et Heltec Wifi Kit 32
#            Bras impression 3D (https://www.thingiverse.com/thing:34829)
#            5 servos SG90
#            MicroPython version 1.10
#
# Programme qui permet de piloter le bras articule via un navigateur
# internet en WiFi et de jouer un scenario sauvegarde
#
# Auteur : iTechnoFrance
#

import machine, time, network, socket, _thread

# declaration des servos avec une frequence de 50 Hertz
servo_pivot = machine.PWM(machine.Pin(12), freq=50)
servo_bras_1 = machine.PWM(machine.Pin(13), freq=50)
servo_bras_2 = machine.PWM(machine.Pin(14), freq=50)
servo_bras_3 = machine.PWM(machine.Pin(26), freq=50)
servo_pince = machine.PWM(machine.Pin(27), freq=50)

# parametres des servos
position_pivot = 0
position_bras_1 = 0
position_bras_2 = 0
position_bras_3 = 0
position_pince = 0

# permet de sauvegarder les mouvements pour les rejouer
mouvements_pivot = []
mouvements_bras_1 = []
Ejemplo n.º 13
0
import time
import machine
pwm = machine.PWM(machine.Pin(15))
pwm.freq(60)
pwm.duty(1023)
pwm.duty(512)
pwm.duty(0)
Ejemplo n.º 14
0
import machine
import time

pin17 = machine.Pin(17)
speaker = machine.PWM(pin17)
speaker.duty(0)

t0 = machine.TouchPad(machine.Pin(4))
t1 = machine.TouchPad(machine.Pin(12))
t2 = machine.TouchPad(machine.Pin(14))
t3 = machine.TouchPad(machine.Pin(15))

current = 0
thresh = 350


def keys():
    global thresh
    while True:
        if t0.read() < thresh:
            time.sleep(0.02)
            if t0.read() < thresh:
                setTone(1)
        elif t1.read() < thresh:
            time.sleep(0.02)
            if t1.read() < thresh:
                setTone(2)
        elif t2.read() < thresh:
            time.sleep(0.02)
            if t2.read() < thresh:
                setTone(3)
Ejemplo n.º 15
0
    time_on_screen = time_hour + ":" + time_min + ":" + time_sec
    return date_on_screen, time_on_screen


###########################callback test##################################

# i2c & OLED
i2c = machine.I2C(-1, machine.Pin(5), machine.Pin(4))
oled = ssd1306.SSD1306_I2C(128, 32, i2c)
# RTC
rtc = machine.RTC()
rtc.datetime((2014, 5, 1, 4, 13, 9, 40, 0))
# ADC
adc = machine.ADC(0)
# PWM/BLINK
pwm15 = machine.PWM(machine.Pin(15), freq=1)
pwm15.duty(512)  # create and configure in one go
# Button
Button_A = machine.Pin(0, machine.Pin.IN, machine.Pin.PULL_UP)
Button_B = machine.Pin(16, machine.Pin.IN,
                       machine.Pin.PULL_UP)  # Button B has a 100K pullup
Button_C = machine.Pin(2, machine.Pin.IN, machine.Pin.PULL_UP)
# # # # # # # # # # # # # # # # # # # # # #
#button_b press down is 0 and bounce up is 1
##########test case initital state#############
oled.fill(0)
oled.pixel(12, 2, 1)
oled.show()
time.sleep(1)

oled.fill(1)
Ejemplo n.º 16
0
    while True:
      if wifi.ifconfig()[0] != '0.0.0.0':
        print("Connected, IP: {}".format(wifi.ifconfig()[0]))
        break
      if time.ticks_ms() - now > timeout:
        break
  return wifi

wifi = init_wifi("signalhuset", "signal+huset2017")
# wifi = init_wifi("HomeBox-10E0_5G", "a6cfdf567")
# wifi = init_wifi("AndroidAPAD82", "odon3187")

status, header, data = curl.get('api.openweathermap.org/data/2.5/onecall?lat=55.6761&lon=12.5683&exclude=minutely,hourly,current&&units=metric&appid=4641ad3e90202b3e5b93bb82490ca04f')
weather = Forecast(json.loads(data)['daily'])

servo = machine.PWM(machine.Pin(17), freq=50)
pin_r = machine.PWM(machine.Pin(27))
pin_g = machine.PWM(machine.Pin(26))
pin_b = machine.PWM(machine.Pin(25))

def on_data(temp):
    print(temp[2])
    today = json.loads(data)['daily'][0]['weather'][0]
    print(today['main'])
    if today['main'] == 'Clear':
        servo.duty(7)
    elif today['main'] == 'Clouds':
        servo.duty(11)
    elif today['main'] == 'Rain':
        print("Rain")
        servo.duty(3)
Ejemplo n.º 17
0
#####################################################################
						Shreejicharan Electronics
#####################################################################

import machine,time, math                    #import machine, time & math module from firmware
led = machine.PWM(machine.Pin(2), freq=1000) #creat pwm object for pin 2 with frequency of 1000 hz

#define function as pulse
def pulse(l, t):
    for i in range(20):         
        l.duty(int(math.sin(i / 10 * math.pi) * 500 + 500)) #set the duty cycle
        #l.duty(i)
        time.sleep_ms(t)

#do infinitely
while True:
    pulse(led, 50)       #
Ejemplo n.º 18
0
import time
#import network
#import socket
#od lava: 

pins = [16,5,4,0,2,14,12]
Pin1 = machine.Pin(16,machine.Pin.IN)
Pin2 = machine.Pin(5,machine.Pin.IN)
Pin3 = machine.Pin(4,machine.Pin.IN)
Pin4 = machine.Pin(0,machine.Pin.IN)
Pin5 = machine.Pin(2,machine.Pin.IN)
Pin6 = machine.Pin(14,machine.Pin.IN)
Pin7 = machine.Pin(12,machine.Pin.IN)
for i in range(len(pins)):
    pins[i] = machine.Pin(pins[i], machine.Pin.IN)
pwmPin = machine.PWM(machine.Pin(13), freq = 50)
#coefficient ktorym musime vynasobit servo aby sa premenilo na PWM hdonotu

coefficient = 0.457
print(coefficient)


sensorPins = [Pin1,Pin2,Pin3,Pin4,Pin5,Pin6,Pin7]
sensorHodnoty = [0,0,0,0,0,0,0,0]
#funkcia ktora dava umiesnenie lopty od 0 do 180
def getFirePos():
    #premene ktore nam pomouzu vypocitat poziciu 
    sucet = 0
    sensorPocet = 0
    #cyklus ktory iteruje cez hodnoty senzorov a snima ci vidia plamen
    for i in range(len(sensorHodnoty)):
Ejemplo n.º 19
0
import machine

servo = machine.PWM(machine.Pin(12), freq=50)
servo.duty(40)
Ejemplo n.º 20
0
import time, math
import machine
from board import A20, A21
pwm = machine.PWM(machine.Pin(A20), freq=5000, duty=20)
pwm1 = machine.PWM(machine.Pin(A21), freq=8000, duty=60)
Ejemplo n.º 21
0
import machine
import utime

buzzer = machine.PWM(machine.Pin(15))

def tone(pin,frequency,duration):
    pin.freq(frequency)
    pin.duty_u16(30000)
    utime.sleep_ms(duration)
    pin.duty_u16(0)

tone(buzzer,440,250)
utime.sleep_ms(500)
tone(buzzer,494,250)
utime.sleep_ms(500)
tone(buzzer,523,250)
Ejemplo n.º 22
0
 def __init__(self, pin_num):
     self.pin = machine.Pin(pin_num, machine.Pin.OUT)
     self.pwm = machine.PWM(self.pin)
     self.pwm.freq(50)
     self.pwm.duty(0)
Ejemplo n.º 23
0
    ## setup i2c
    i2c = i2c_init()
    i2c_scan(i2c)
    i2c = I2C(scl=Pin(22), sda=Pin(21), freq=100000)
    devices = i2c.scan()
    b = BME280.BME280(i2c=i2c, fmt=False)

    #evnts = EVENTS("Sensors","fd9a:6f5b:21d1::ee1")
    evnts = EVENTS("Sensors1", "192.168.1.118", id)
    evnts.logit(ts, 0, 0, 0, device=500)

    #Due to limitations of the ESP8266 chip the internal real-time clock (RTC) will overflow every 7:45h.
    #If a long-term working RTC time is required then time() or localtime() must be called at least once within 7 hours.
    #MicroPython will then handle the overflow.
    led2 = machine.PWM(machine.Pin(2), freq=1000)
    print("PWM.duty=", led2.duty())
    print("Byte Order=", sys.byteorder)
    print("Implementation: ", sys.implementation.name,
          sys.implementation.version)
    print("Sensor Starting:", rtc.datetime())

    #  set alert off to save amps
    if initalert == "001":
        time.sleep(.1)
        led2.duty(0)
        time.sleep(.2)
        led2.duty(200)
        time.sleep(.2)
        led2.duty(512)
        time.sleep(.2)
Ejemplo n.º 24
0
response_template = """HTTP/1.0 200 OK

%s
"""

import machine
import ntptime, utime
from machine import RTC
from time import sleep

pin = machine.Pin(16, machine.Pin.OUT)
sw_pin = machine.Pin(10, machine.Pin.IN)
adc = machine.ADC(0)
pwm = machine.Pin(5, machine.Pin.OUT)
pwm = machine.PWM(pwm)

rtc = RTC()
try:
    seconds = ntptime.time()
except:
    seconds = 0
rtc.datetime(utime.localtime(seconds))


def time():
    body = """<html>
<body>
<h1>Time</h1>
<p>%s</p>
</body>
Ejemplo n.º 25
0
 def wakeup(self):
     self.pin = machine.Pin(self.settings["pin"])
     self.pwm = machine.PWM(self.pin, freq=self.settings["frequency"])
Ejemplo n.º 26
0
 def __init__(self, r_pin, g_pin, b_pin):
     self.red = machine.PWM(machine.Pin(r_pin), freq=5000)
     self.green = machine.PWM(machine.Pin(g_pin), freq=5000)
     self.blue = machine.PWM(machine.Pin(b_pin), freq=5000)
BUTTON_Y = const(3)
DPAD_UP = const(4)
DPAD_DOWN = const(5)
DPAD_LEFT = const(6)
DPAD_RIGHT = const(7)

BUTTON_PINS = (PICOSYSTEM_A, PICOSYSTEM_B, PICOSYSTEM_X, PICOSYSTEM_Y,
               PICOSYSTEM_UP, PICOSYSTEM_DOWN, PICOSYSTEM_LEFT,
               PICOSYSTEM_RIGHT)
buttons = [
    machine.Pin(p, machine.Pin.IN, machine.Pin.PULL_UP) for p in BUTTON_PINS
]

# PicoSystem Audio
audio_pin = machine.Pin(PICOSYSTEM_AUDIO)
buzzer = machine.PWM(audio_pin)
buzzer.duty_u16(0)


def buzz(freq, duty=0.5):
    if freq < 50.0:  # uh... https://github.com/micropython/micropython/blob/af64c2ddbd758ab6bac0fcca94c66d89046663be/ports/rp2/machine_pwm.c#L105-L119
        buzzer.duty_u16(0)
    else:
        buzzer.freq(freq)
        buzzer.duty_u16(int(65535 * duty))


# PicoSystem Status
battery_sense = pimoroni.Analog(PICOSYSTEM_BAT_SENSE,
                                amplifier_gain=(1.0 / 3.0))
charge_status = machine.Pin(PICOSYSTEM_CHARGE_STATUS, machine.Pin.IN)
Ejemplo n.º 28
0
# Setup code goes below, this is called once at the start of the program: #
###########################################################################
import machine
import time, math

print('Pulse LED...')

_LEDPIN = 13 #13=TTGO ESP32, 5=WeMOS_Lolin32 2=Lolin_OLED, 2=WeMOS_D1R2

def pulse(l, t):
    for i in range(20):
        l.duty(int(math.sin(i / 10 * math.pi) * 500 + 500))
        time.sleep_ms(t)

def cleanup():
    global led
    led.duty(1023) #WeMOS_D1/R2: off due pullUp
    time.sleep(0.1) #waiT
    led.deinit() #deinit
    del led #remove

led = machine.PWM(machine.Pin(_LEDPIN), freq=10000)

###################################################################
# Loop code goes inside the loop here, this is called repeatedly: #
###################################################################
#for i in range(20):
while True:
    pulse(led, 20)
cleanup()
Ejemplo n.º 29
0
import machine, time
from machine import Pin, PWM

servo = machine.PWM(Pin(5), freq=200, duty=550)
time.sleep(5)

servo.deinit()


Ejemplo n.º 30
0
red=machine.Pin(14,machine.Pin.OUT)

#assign variable to receive data (blue line)
data=machine.ADC(machine.Pin(33))
#data.read()
#this will give a high value (maximum value of 4095)

#set attenuation(scaling voltage) and width
#At this stage we don't know what gives the best data, or the least noise, so change accordingly
data.atten(ADC.ATTN_11DB)
#or adc.atten(ADC.ATTN_6DB)
#now read!
data.read()

#To change setting of LED: digital to analog
led=machine.PWM(machine.Pin(12))
#set intensity 1000
led.duty(100)
#set frequency upper bound 78000
led.freq(70000)

#define a function to receive data continuously and break when button is pressed
#variable "value" is used as an indicator
end=0
value=0
def getData(data):
    while True:
        print(data.read())
        time.sleep(0.5)
        end=machine.Pin(36,machine.Pin.IN)
        if end==1: