Esp8266 Team Hack Twitter

by querry43 in Circuits > Microcontrollers

203 Views, 0 Favorites, 0 Comments

Esp8266 Team Hack Twitter

logo.png

Let's expand our reach and start to effecting the world. There are several services that act as a bridge for automating the world around us. We'll play with a service called If This then That.

Credentials

If you are following our team hack, then there are some services ready to go. Load up the credentials already on your esp8266.

# load the credentials
exec(open('ifttt.py').read())

# show the webhooks
ifttt_helloworld
ifttt_too_bright

If you are not starting from one of the team hack pre-programmed esp8266s, follow this page to setup ifttt. We have setup two endpoints: `ifttt_helloworld` and `ifttt_too_bright.` These write tweets using `Value1` and `OccurredAt`.

Tweet!

Assuming that you now have a webhook url stored in `ifttt_helloworld`, go ahead and trigger the event.

# tweet_hello_world.py

import machine
import ubinascii
import urequests

exec(open('ifttt.py').read())

# get this device's unique id
id = ubinascii.hexlify(machine.unique_id()).decode()
print("my id is: %s" % id)

# trigger the ifttt event
urequests.post(
    ifttt_helloworld,
    json={"value1": id},
    headers={"content-type": "application/json"})

You should now see a tweet from your machine id. Neat!

Let's combine this with a previous example. Like with the other long function, write this as a file `tweet_when_too_bright.py` and then load and run. This may already be on your esp8266 if it was pre-programmed for the team hack.

# tweet_when_too_bright.py

# import some libraries
from machine import ADC
from utime import sleep
import machine
import urequests

exec(open('ifttt.py').read())

# define the light sensor pin
light = ADC(0)

# define a threshold
threshold = 40000

# get this device's unique id
id = ubinascii.hexlify(machine.unique_id()).decode()
print("my id is: %s" % id)

# loop forever, tweeting when it's too bright
while True:
    sleep(1)
    if light.read_u16() > threshold:
        print("it's too bright!")
        urequests.post(
            ifttt_too_bright,
            json={"value1": id},
            headers={"content-type": "application/json"})
        sleep(60) # wait at least a minute before tweeting again

Load and run the `ifttt_too_bright` webhook and the function. Adjust the
threshold for your own light level if you need. `Control-c` to exit.

import tweet_when_too_bright

Next Steps

What else can we do with this? ifttt and other similar services can connect a large number of services. You could:

  • Tweet when the delivery person breaks a light beam at your front door.
  • Have alexa or google home tell you when to open your shades to get natural light.
  • Dim your smart lights to maintain a consistent light level.