[PYTHON] Make a Nyan button

Purpose

I want to tweet when I want to

Nyan Button No. 1

Made with IFTTT. スケッチ.png

Tweet with the current time when the button is pressed. Very convenient to use on smartphones and Apple Watch Screenshot_20170818-121248.png IMG_-96qcj7.jpg

problem

The posted text becomes something like Nyan August 24, 2017 at 03:45 AM, and if it is within 1 minute, you cannot post due to duplicate posts. Sometimes you want to continuously throw Nyan.

Nyan Button No. 2

I have a Raspberry Pi at home so I want him to work As an exercise, try Webhooking with IFTTT I made an applet to skip webhooks and an applet to receive with IFTTT.

maker.ifttt.com-use-dFATP1QGninuFBL9kK7NLv(Laptop with HiDPI screen).png When I open the Webhook Setting with IFTTT, a URL that says POST should be displayed like this, so I should have used it as it is. Webhook is very convenient An example of curl input is also displayed

Webhook skipper

ifttt.com-applets-59725732d--edit(Laptop with HiDPI screen).png

The one who receives the webhook

ifttt.com-applets-59725732d--edit(Laptop with HiDPI screen) (1).png Specify the event name decided by the person to skip.

No. 2 also works nicely. All you have to do is ask Raspberry Pi to fly it.

Nyan Button No. 3

Speaking of Raspberry Pi, it seems to be Python, so I decided to use Python

import wiringpi as pi ,time,requests,datetime
SW_PIN = 15 #Pin number to which the switch is connected
url='https://maker.ifttt.com/trigger/python1/with/key/******'
swi=0
pi.wiringPiSetupGpio()
pi.pinMode(SW_PIN,pi.INPUT)
pi.pullUpDnControl(SW_PIN,pi.PUD_DOWN)

while True:
    if(pi.digitalRead(SW_PIN)==pi.HIGH):
        if(swi==0):
            print("Switch ON")
            str = datetime.datetime.now().strftime('%H:%M:%S')
            payload = {'value1':str}
            requests.post(url,data=payload)
            swi=1
    else:
       print("Switch OFF")
       swi=0
    time.sleep(0.01)

Holds the switch on and off in swi, fetches the time when it changes from 0 to 1, and skips it to the webhook destination.

payload = {'value1':str}
requests.post(url,data=payload)

You can skip the time data by doing. IMG_-x10jmo.jpg Post by pressing a button

problem

It takes a long time to send POST, and even if I hit it repeatedly during sending, it doesn't work. I want to hit more

Nyan Button No. 4

I want to thread only the transmitter and make it asynchronous. When I looked it up, Python had a function to create subthreads, but I'm not sure, so I decided to move only the transmitter in the background and it was solved.

The problem was solved by dividing the transmitter into nyaan.py and rewriting it as ʻos.system ('sudo python3 nyaan.py &')`. With this, even if you hit the Nyan button repeatedly, you can Nyan at the shortest interval of 1 second. Ideal.

problem

It's a bit disappointing because you'll be running sudo python3 nyaan.py & every time. I want to compile it, but I'm sleepy so I'll do it again.

Nyan Button No. 5

Since the momentum of repeated hits has increased, it corresponds to the millisecond display. In the specifications so far, one tweet per second was the limit (duplicate tweets)

now = datetime.datetime.now()
str = now.strftime('%H:%M:%S.') + "%03d" % (now.microsecond // 1000)

Difficult Progura Mingu I don't really understand http://shohu.hatenablog.com/entry/20081117/1226936130 I just moved here.

result

Theoretically, you can tweet 1000 times a second without any problem.

Nyan Button No. 6

Since then, there have been various things, and it has become multi-threaded and sound comes out from the speakers.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import threading,tweepy,datetime,kjfsm4,wiringpi as pi,time

import pygame.mixer

SW_PIN = 14
swi=0
pi.wiringPiSetupGpio()
pi.pinMode(SW_PIN,pi.INPUT)
pi.pullUpDnControl(SW_PIN,pi.PUD_DOWN)

auth = tweepy.OAuthHandler(kjfsm4.consumer_key,kjfsm4.consumer_secret)
auth.set_access_token(kjfsm4.access_token,kjfsm4.access_secret)
api = tweepy.API(auth)

pygame.mixer.init()
pygame.mixer.music.load('nyan.mp3')

def tweet():
    pygame.mixer.music.play(1)
    print("tweet")
    now = datetime.datetime.now()
    str = now.strftime('%H:%M:%S.') + "%03d" % (now.microsecond // 1000)
    print (str)
    str = 'Nyan'+str
    api.update_status(str)

while True:
    if(pi.digitalRead(SW_PIN)==pi.HIGH):
        if(swi==0):
            th_me = threading.Thread(target=tweet,name="th_me")
            th_me.start()
            swi=1
    else:
       swi=0
    time.sleep(0.01)

Recommended Posts

Make a Nyan button
Make a squash game
Make a function decorator
I'll make a password!
Make a Tetris-style game!
Make a Base64 decoder
Make a simple Slackbot with interactive button in python
Let's make a Discord Bot.
Make a Blueqat backend ~ Part 1
[Django] Make a pull-down menu
Make a LINE BOT (chat)
Make a bookmarklet in Python
Make Responder a daemon (service)
Make a fire with kdeplot
Make a math drill print
Let's make a remote rumba [Hardware]
How to make a Japanese-English translation
Make a Santa classifier from a Santa image
Let's make a remote rumba [Software]
Make a Tweet box for Pepper
Make a sound with Jupyter notebook
Make a face recognizer using TensorFlow
How to make a slack bot
Let's make a breakout with wxPython
Let's make a spot sale service 1
How to make a crawler --Advanced
How to make a recursive function
Make C compilation a little easier
python / Make a dict from a list.
[Python] Make the function a lambda function
Make a recommender system with python
How to make a deadman's switch
[Blender] How to make a Blender plugin
Make Flask a Cloud Native application
Make a filter with a django template
Let's make a graph with python! !!
Let's make a supercomputer with xCAT
How to make a crawler --Basic
Make a model iterator with PySide
Make a nice graph with plotly
Make a curtain generator in Blender
Let's make a spot sale service 3
Let's make a shiritori game with Python
Make a video player with PySimpleGUI + OpenCV
Try to make a kernel of Jupyter
Make Jupyter Notebook a service on CentOS
Make a Notebook Pipeline with Kedro + Papermill
Make a partially zoomed figure with matplotlib
Make a drawing quiz with kivy + PyTorch
Let's make a voice slowly with Python
Make a cascade classifier with google colaboratory
Let's make a simple language with PLY 1
Make Qt for Python app a desktop app
Do you make something like a rocket?
Make a logic circuit with a perceptron (multilayer perceptron)
Make a Yes No Popup with Kivy
Make a wash-drying timer with a Raspberry Pi
ROS course 107 Make a client for rosblidge
Make a GIF animation with folder monitoring
I tried to make a Web API
To make a dict type property read-only