NodeMCU Projects: Difference between revisions
Content added Content deleted
Line 75: | Line 75: | ||
== Projects == |
== Projects == |
||
===Playing with GPIO=== |
|||
<syntaxhighlight lang="python"> |
<syntaxhighlight lang="python"> |
||
Line 93: | Line 93: | ||
===Fading an LED=== |
|||
<syntaxhighlight lang="python"> |
<syntaxhighlight lang="python"> |
||
import time, math |
import time, math |
||
Line 110: | Line 110: | ||
=== Control a hobby servo === |
|||
Hobby servo motors can be controlled using PWM. |
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. |
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"> |
<syntaxhighlight lang="python"> |
||
servo = machine.PWM(machine.Pin(12), freq=50) |
servo = machine.PWM(machine.Pin(12), freq=50) |
||
Line 122: | Line 123: | ||
</syntaxhighlight> |
</syntaxhighlight> |
||
*Random movements: |
|||
<syntaxhighlight lang="python"> |
<syntaxhighlight lang="python"> |
||
servo = machine.PWM(machine.Pin(12), freq=50) |
servo = machine.PWM(machine.Pin(12), freq=50) |
||
Line 127: | Line 129: | ||
servo.duty(urandom.getrandbits(8)) |
servo.duty(urandom.getrandbits(8)) |
||
time.sleep(1) |
time.sleep(1) |
||
</syntaxhighlight> |
|||
* Analog Temperature Meter: |
|||
Requirements: |
|||
DS18B20 Temperature sensor |
|||
Servo Motor |
|||
Micropython based NodeMCU |
|||
Wiring details: |
|||
Servo motor = D4 => GPIO 2 |
|||
DS18B20 = D7 => GPIO 13 |
|||
<syntaxhighlight lang="python"> |
|||
import time |
|||
import machine |
|||
import onewire, ds18x20 |
|||
# the device is on GPIO13 |
|||
dat = machine.Pin(13) |
|||
# create the onewire object |
|||
ds = ds18x20.DS18X20(onewire.OneWire(dat)) |
|||
# scan for devices on the bus |
|||
roms = ds.scan() |
|||
print('found devices:', roms) |
|||
# servo is connected to GPIO2 |
|||
servo = machine.PWM(machine.Pin(2), freq=50) |
|||
# Function for mapping range |
|||
def translate(value, leftMin, leftMax, rightMin, rightMax): |
|||
# Figure out how 'wide' each range is |
|||
leftSpan = leftMax - leftMin |
|||
rightSpan = rightMax - rightMin |
|||
# Convert the left range into a 0-1 range (float) |
|||
valueScaled = float(value - leftMin) / float(leftSpan) |
|||
# Convert the 0-1 range into a value in the right range. |
|||
return rightMin + (valueScaled * rightSpan) |
|||
# print all temperatures |
|||
while True: |
|||
ds.convert_temp() |
|||
time.sleep_ms(1000) |
|||
for rom in roms: |
|||
print(ds.read_temp(rom)) |
|||
temp = ds.read_temp(rom) |
|||
srv = translate(temp, 20, 35, 40, 115) |
|||
print(int(srv)) |
|||
if (temp>=20) & (temp<=35): |
|||
servo.duty(int(srv)) |
|||
else: |
|||
print("Out of Range") |
|||
</syntaxhighlight> |
</syntaxhighlight> |
||