NodeMCU Projects: Difference between revisions

Content added Content deleted
Line 2: Line 2:
__TOC__
__TOC__
<br/>
<br/>


= Small Projects =

== Playing with GPIO ==

<syntaxhighlight lang="python">
import machine
import time
import urandom

pin = machine.Pin(2, machine.Pin.OUT)

def toggle(p):
p.value(not p.value())

while True:
time.sleep_ms(urandom.getrandbits(8))
toggle(pin)
</syntaxhighlight>


== Fading an LED ==
<syntaxhighlight lang="python">
import time, math
import machine

led = machine.PWM(machine.Pin(2), freq=1000)

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

while True:
pulse(led, 20)
</syntaxhighlight>


== Control a hobby servo ==
#Hobby servo motors can be controlled using PWM.
#They require a frequency of 50Hz and a duty between about 40 and 115, with 77 being the center value.

*Manual Movements
<syntaxhighlight lang="python">
servo = machine.PWM(machine.Pin(12), freq=50)
servo.duty(40)
servo.duty(115)
servo.duty(77)
</syntaxhighlight>

*Random movements:
<syntaxhighlight lang="python">
servo = machine.PWM(machine.Pin(12), freq=50)
while True:
servo.duty(urandom.getrandbits(8))
time.sleep(1)
</syntaxhighlight>

== One Wire DS18B20 Temp Sensor ==
<syntaxhighlight lang="python">
import time
import machine
import onewire, ds18x20

# the device is on GPIO12
dat = machine.Pin(12)

# create the onewire object
ds = ds18x20.DS18X20(onewire.OneWire(dat))

# scan for devices on the bus
roms = ds.scan()
print('found devices:', roms)

# loop 10 times and print all temperatures
for i in range(10):
print('temperatures:', end=' ')
ds.convert_temp()
time.sleep_ms(750)
for rom in roms:
print(ds.read_temp(rom), end=' ')
print()
</syntaxhighlight>