LoginSignup
4
5

More than 1 year has passed since last update.

Raspberry PiとArduinoと光センサで部屋の照度をツイートしてみた

Last updated at Posted at 2017-07-07

部屋の明るさををArduinoと光センサを用いて取得し,Raspberry Piから取得した情報をツイートするシステムの作成方法を説明します.

コードはGitHubに掲載しました.
https://github.com/Choke222/Arduino_RaspberrPi

必要なもの

  • Raspberry Pi
  • Arduino
  • CdS素子
  • 抵抗(10kΩ)
  • Twitterアカウント

準備

  • Twitterアプリケーションの作成

Rasberry PiとTwitterを連携するためには,Twitterアプリケーションを作成する必要があります.
具体的には以下の4つの情報を取得します.

  1. Consumer key
  2. Consumer secret
  3. Access token
  4. Access token secret

参考サイト:Twitterアプリケーションの作成(Consumer key、Consumer secret、Access token、Access token secretの確認方法)

  • Raspberry Piのpythonにパッケージをインストール
sudo apt-get update
sudo apt-get install python-setuptools
sudo easy_install pip #pipコマンドのインストール
sudo pip install twython #twythonをpipコマンドでインストール
  • 回路作成

CdS素子と10kΩ抵抗を用いて作成します.
参考サイト:照度センサー回路

Arduino側

  • CdS素子により取得した照度をシリアルモニタに出力します.
arudino_cds.ino
int pin = 0; //センサーのピン番号
int get_a0 = 0; //センサーデータ取得
int flag = 0;
int s=0;
void setup(){
  Serial.begin(9600);

}

void loop()
{

  get_a0 = analogRead(pin); // 照度センサーからデータを取得
  s = 0;
  Serial.println(s); // シリアルモニタに出力
  if ( get_a0 <= 200 ) {
    if(flag == 0){
      s = 1000;//OFF!
      Serial.println(s); // シリアルモニタに出力
    }
    flag=1;
  } else if ( get_a0 > 200 ) {
    if(flag == 1){
      s = 2000;//ON
      Serial.println(s); // シリアルモニタに出力
    }
    flag=0;
  }
  delay(200);
}

Raspberry Pi側

  • 各種インポート
tweet_cds.py
import serial
import time
import os
from twython import Twython
  • Twitter APIの設定
tweet_cds.py
#print('twitterの認証情報を入力')
CONSUMER_KEY = 'xxxxxxxxxxxxxxxx'
CONSUMER_SECRET = 'xxxxxxxxxxxxxxxx'
ACCESS_KEY = 'xxxxxxxxxxxxxxxx'
ACCESS_SECRET = 'xxxxxxxxxxxxxxxx'
api = Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_KEY,ACCESS_SECRET)
  • Arduinoとシリアル通信する際の設定
tweet_cds.py
#print('シリアル通信開始')
ser = serial.Serial('/dev/ttyACM0', 9600)
  • Arduinoから照度データを取得しツイート
tweet_cds.py
while 1:
	data = ser.readline()#Arduinoからデータの読み込み

	data2 = int(data)#int型に変換
	print('部屋の照明監視中' + time.ctime() + ',' + '照明状況' + ',' + str(data))
	#取得した照度情報をツイート
	if data2 == 2000:
		print('電気がついたよ!')
		api.update_status(status= time.ctime()+'おはよう!')
		time.sleep(1)
	elif data2 == 1000:
		print('電気が消えたよ!')
		api.update_status(status= time.ctime()+'おやすみなさい')
		time.sleep(1)

参考まで

4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5