目前分類:Raspberry (9)

瀏覽方式: 標題列表 簡短摘要


 

虛擬環境的好處

為什麼需要虛擬環境?這就像是為了這次的學習建立一個遊樂場,在這個場子裡,可以翻滾、可以東敲西打,不用擔心把場地搞亂了無法收拾,只要離開虛擬環境,再造下一個就好了。在實務上,有時會碰到不同專案會使用不同的套件,甚至使用相同套件但是使用不同版本的情況。那麼在管理上就會是一個問題了。如果你只需要使用特定的套件,或是想要嘗試各種不同的環境應用,但又不想彼此的開發環境受到影響,那miniconda的套件管理系統conda將會是一個很好的作法。

conda命令是管理在安裝不同package時的主要介面,使用conda時,你可以進行建立(create)輸出(export)列表(list)移除(remove)更新(update)環境於不同Python版本及Packages,同時也可以分享你的虛擬環境

(1)在pi 上建立及更新miniconda

可以輸入下列命令來檢查目前版本。

conda –V

想要進行更新,可以輸入下列命令

conda update conda

(2)建立虛擬環境

輸入下面命令看目前系統已經安裝幾個虛擬環境。

conda env list

假設我們要建立一個叫做myenv的虛擬環境,並且是安裝python 3.5的版本,那我們可以鍵入下面的命令。

sudo -i
cd /home/pi/miniconda3/bin
conda create --name myenv

or

sudo -i

conda create --name test --clone base

conda create -n mytest --clone myenv

(3)啟動虛擬環境

啟動一個新的虛擬環境可以利用下面命令。

activate myenv

如果你是LINUX或macOS,那你所需輸入啟動的方式將會是

source activate myenv

啟動後指令列會有 myenv 在最前頭,可在這時輸入 which python 詢問 Python 版本

(4)安裝專案所需要的package

利用下面命令來查看,目前此虛擬環境中已經先安裝了那些東西。

conda list

python --version

---------------------------------------------------

安裝python 3.6

conda config --add channels rpi

conda install python=3.6

如果要在此虛擬環境下安裝所需套件,例如numpy那只需要輸入下令命令即可。

conda install numpy

(5):離開虛擬環境

若要關閉虛擬環境,在windows中可使用下列命令

deactivate

而在macOS或LINUX則可以使用

source deactivate

(6):刪除虛擬環境或package

若要刪除虛擬環境中某個package(例如在剛剛建立的虛擬環境myenv中的numpy),那可以輸入下面命令

conda remove --name myenv numpy

如果是要刪除整個虛擬環境,則可輸入下面命令即可完成刪除

conda env remove --name myenv

結語

為每一個不同需求的專案建立一個獨立適合的虛擬環境是一個很好的習慣,因為它並不會去影響其他的系統配置而產生不預期問題。

若在配置上產生了問題只要輕易的移除某個package或是虛擬環境再重新建構它即可

 

 

stanley 發表在 痞客邦 留言(0) 人氣()

https://medium.com/@lin7lic/%E5%9C%A8raspberry-pi-3-%E5%AE%89%E8%A3%9Dpython-3-opencv-34c9740d78e4

 

Pi3b 安裝 OpenCV3
										
### 強烈建議安裝Miniconda
---------------------------------------------------------------------------------									
Install Miniconda3
-------------------------------------------------------------------------------
wget http://repo.continuum.io/miniconda/Miniconda3-latest-Linux-armv7l.sh
sudo md5sum Miniconda3-latest-Linux-armv7l.sh # (optional) check md5
sudo /bin/bash Miniconda3-latest-Linux-armv7l.sh # -> change default directory to /home/pi/miniconda3
sudo nano /home/pi/.bashrc # -> add: export PATH="/home/pi/miniconda3/bin:$PATH"
sudo reboot -h now

update miss permission of the directory:
----------------------------------------------
sudo chown -R pi miniconda3

---------------------------------------------------
Test測試你的環境
conda
python --version

---------------------------------------------------
安裝python 3.6 
conda config --add channels rpi
conda install python=3.6
---------------------------------------------------
安裝opencv3
conda install -y -c conda-forge opencv
---------------------------------------------------

到此完成




以下選用
#######################################################################
安裝Spyder
pip3 install spyder

---------------------------------------------------
CONDA環境下安裝
安裝anaconda client

pip3 install opencv-python
conda install -y -c conda-forge opencv
---------------------------------------------------


update 更新套件
---------------------------------------------------
conda update conda
conda update --all

pip install --upgrade pip

---------------------------------------------------
安裝anaconda client
conda install anaconda-client
---------------------------------------------------

stanley 發表在 痞客邦 留言(0) 人氣()

Quick Reference NEMA size 17 1.8° 2-phase stepper motor(參考手冊)

https://reprap.org/wiki/NEMA_17_Stepper_motor (簡單規格)
Step Motor 42BYGH47-401A (規格),

1.8° It has 200 steps per revolution, and can operate at at 60 RPM,

Step Angle: 1.8°
Voltage: 24
Phase Current: 1.5A/Phase
Phase Resistance: 1.6ohm/Phase 
Phase inductance: 2.8mH/Phase
Holding Torque: 5500g.cm
Lead Wire: 4
中文規格說明

https://tutorials-raspberrypi.com/how-to-control-a-stepper-motor-with-raspberry-pi-and-l293d-uln2003a/ (程式)

https://www.electronicshub.org/raspberry-pi-stepper-motor-control/ (接線)

https://www.raspberrypi.org/forums/viewtopic.php?t=55580 (接線)

undefined

import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
control_pins = [7,11,13,15]
for pin in control_pins:
  GPIO.setup(pin, GPIO.OUT)
  GPIO.output(pin, 0)
halfstep_seq = [
  [1,0,0,0],
  [1,1,0,0],
  [0,1,0,0],
  [0,1,1,0],
  [0,0,1,0],
  [0,0,1,1],
  [0,0,0,1],
  [1,0,0,1]
]
for i in range(512):
  for halfstep in range(8):
    for pin in range(4):
      GPIO.output(control_pins[pin], halfstep_seq[halfstep][pin])
    time.sleep(0.001)
GPIO.cleanup()

 

stanley 發表在 痞客邦 留言(0) 人氣()

https://towardsdatascience.com/how-tracking-apps-analyse-your-gps-data-a-hands-on-tutorial-in-python-756d4db6715d

stanley 發表在 痞客邦 留言(0) 人氣()

資料參考:https://alysivji.github.io/reactive-dashboards-with-dash.html (frameware,good)
Big Data Analytics with Pandas and SQLite in Python
https://datacarpentry.org/python-ecology-lesson/09-working-with-sql/index.html

https://sqlitebrowser.org/
https://medium.com/a-r-g-o/using-plotlys-dash-to-deliver-public-sector-decision-support-dashboards-ac863fa829fb (another porject)

 

Dash Application Design: MVC Pattern

Every Dash application could be divided into the following components:
(1)Data Manipulation - Perform operations to read / transform data for display
(2)Dashboard Layout - Visually render data into output representation
(3)Interaction Between Components - Convert user input to commands for data manipulation + render
When designing a Dash application, we should stucture our code into three sections:

1. Data Manipulation (Model)
2. Dashboard Layout (View)
3. Interaction Between Components (Controller)


We created the following template to help us get started:
 

Historical Match-up Dashboard

In this section, we will create a full-featured Dash application that can be used to view historical soccer data.

We will use the following process to create / modify Dash applications:

  1. Create/Update Layout - Figure out where components will be placed
  2. Map Interactions with Other Components - Specify interaction in callback decorators
  3. Wire in Data Model - Data manipulation to link interaction and render

Data is stored in an SQLite database:

Download the Dash application template file from above:

$ export DB_URI=sqlite:///soccer-stats.db
$ python app.py
* Running on http://0.0.0.0:8050/ (Press CTRL+C to quit)
* Restarting with stat

 


 

 

 

stanley 發表在 痞客邦 留言(0) 人氣()

資料來源: Control of your Appliances and IoT Devices at your Fingertips with Flask
Connecting to your database
https://dzone.com/articles/restful-web-services-with-python-flask

 

E:xample : Browser Graphical User Interface (GUI) for Sprinkler System

undefined

 

undefined

TEST & Control the relay(s) for the Sprinkler system:
This python routine starts the vales connected to the Raspberry Pi pins with the numbers listed
​​​​​​​in the array “zone” (8, 7, 14, 15, 18, 23, 24, 25), 

# import the necessary packages
import RPi.GPIO as GPIO
import time

# set the GPIO mode
GPIO.setmode(GPIO.BCM)

zone = [8, 7, 10, 9, 14, 15, 18, 23, 24, 25]
#################################################
# List of zones with the times for each zone ####
#################################################
#8  = House front left, Large tree, at walk way
s8  = [zone[0], 200]
#7  = House front left, Large tree, at garage wall
s7  = [zone[1], 200]
#10 = right corner of backyard behind shed
s10 = [zone[2], 200]
#9  = Backyard cherry trees
s9  = [zone[3], 200]

#14 = Orange Trees, Plum trees, Apple tree..
s14 = [zone[4], 200]
#15 = Front right stripe
s15 = [zone[5], 200]
#18 = Cypresses left
s18 = [zone[6], 200]
#23 = planting boxes
s23 = [zone[7], 200]
#24 = Roses house wall
s24 = [zone[8], 150]
#25 = House wall at AC
s25 = [zone[9], 150]

def openCloseValves(valve, zeit):
        print("Opening Valve",valve," for ",zeit," seconds")
        time.sleep(5.0)
        GPIO.setup(valve, GPIO.OUT)
        GPIO.output(valve, GPIO.LOW)    # Open valve
        time.sleep(zeit)
        GPIO.output(valve, GPIO.HIGH)   # Close valve
        time.sleep(5.0)
        print("done...")

def run():
        openCloseValves(s8[0],s8[1])
        openCloseValves(s7[0],s7[1])
        openCloseValves(s10[0],s10[1])
        openCloseValves(s9[0],s9[1])

        openCloseValves(s14[0],s14[1])
        openCloseValves(s15[0],s15[1])
        openCloseValves(s18[0],s18[1])
        openCloseValves(s23[0],s23[1])
        openCloseValves(s24[0],s24[1])
        openCloseValves(s25[0],s25[1])

        # perform a bit of cleanup
        GPIO.cleanup()
        
if __name__=='__main__':
        try:
                run()
        except:
                # Shut all valves...
                for num in zone:
                        GPIO.setup(num, GPIO.OUT)
                        GPIO.output(num, GPIO.HIGH)
                GPIO.cleanup()
                print("An Error occured OR user stopped routine...!!!")
                raise

The file webForm contains following python code

1
sudo chmod ug+x webForm.py
$> ./webForm

settings.json 

{
    "0": [
        "25",
        "200"
    ],
    "1": [
        "27",
        "200"
    ],
    "2": [
        "21",
        "200"
    ],
    "3": [
        "23",
        "200"
    ]
}

 

sprinklerMain.py

import RPi.GPIO as GPIO
import time
import json
import os
from collections import OrderedDict 
 
def openCloseValves(valve, zeit):
    print("Opening Valve " + str(valve) + " for " + str(zeit) + " seconds..."),
    GPIO.setwarnings(False)
    GPIO.setmode(GPIO.BCM)
    time.sleep(5.0)
    GPIO.setup(valve, GPIO.OUT)
    GPIO.output(valve, GPIO.LOW)    # Open valve
    time.sleep(zeit)
    GPIO.output(valve, GPIO.HIGH)    # Close valve
    time.sleep(5.0)
    print("Done")
    
def openValve(valve):
    print("Opening Valve " + str(valve) + " ..."),
    #GPIO.setwarnings(False)
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(valve, GPIO.OUT)
    GPIO.output(valve, GPIO.LOW)    # Open valve
    print("Done")
    return()
    
def closeValve(valve):
    print("Closing Valve " + str(valve) + " ..."),
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(valve, GPIO.OUT)
    GPIO.output(valve, GPIO.HIGH)    # Close valve
    print("Done")
    return()
    
def run():
    value =[]
    with open('/home/pi/flaskSprinkler/settings.json') as data_file:
        sprinkler = json.load(data_file)
        for i in range(0,len(sprinkler)):
            value = sprinkler[str(i)]
            valve = int(value[0])
            zeit = int(value[1])
            print("sprinkler new " + str(valve) + " value : " + str(zeit))
            openCloseValves(valve, zeit)
    # Perform a bit of cleanup...
    GPIO.cleanup()
    
def closeAllValves():
    GPIO.setmode(GPIO.BCM)
    for value in range(2,28):
        try:
            GPIO.setup(int(value), GPIO.OUT)
            GPIO.output(int(value), GPIO.HIGH)
        except:
            continue    # continue with the next GPIO pin...
    GPIO.cleanup()
 
        # Kill routine sprinkler script in case that is running...
        try:
                os.system("sudo pkill -9 sprinklerMain.py")
                time.sleep(1)
        except:
                pass
 
  
    
if __name__=="__main__":
    try:
        run()
    except:
        closeAllValves()
        print("An Error occured OR user stopped routine...!!!")
        raise

 

 

 guiPage.html. This file needs to be in the folder templates/.

<div class="container">
<h2>Sprinkler Setting Web Form</h2>
&nbsp;
 
<form action="" method="post">
<div class="form-group">
<table class="responsable">
<tbody>
<tr>
<td><label for="Z0">Zone 0 : Front left, at walk way</label></td>
<td><input id="Z0" class="form-control" name="Z0" type="text" placeholder="Front left, at walk way..." /></td>
<td><button style="width: 100px; font-size: 18pt; padding: 2px; border: 3px solid green;" name="submit" type="submit" value="start0">Start0</button></td>
<td><button style="width: 100px; font-size: 18pt; padding: 2px; border: 3px solid red;" name="submit" type="submit" value="stop0">Stop0</button></td>
</tr>
<tr>
<td><label for="Z1">Zone 1 : Front left, at garage wall</label></td>
<td><input id="Z1" class="form-control" name="Z1" type="text" placeholder="Front left, at garage wall..." /></td>
<td><button style="width: 100px; font-size: 18pt; padding: 2px; border: 3px solid green;" name="submit" type="submit" value="start1">Start1</button></td>
<td><button style="width: 100px; font-size: 18pt; padding: 2px; border: 3px solid red;" name="submit" type="submit" value="stop1">Stop1</button></td>
</tr>
<tr>
<td><label for="Z2">Zone 2 : Right backyard, behind shed</label></td>
<td><input id="Z2" class="form-control" name="Z2" type="text" placeholder="Right backyard, behind shed..." /></td>
<td><button style="width: 100px; font-size: 18pt; padding: 2px; border: 3px solid green;" name="submit" type="submit" value="start2">Start2</button></td>
<td><button style="width: 100px; font-size: 18pt; padding: 2px; border: 3px solid red;" name="submit" type="submit" value="stop2">Stop2</button></td>
</tr>
<tr>
<td><label for="Z3">Zone 3 : Backyard cherry trees.</label></td>
<td><input id="Z3" class="form-control" name="Z3" type="text" placeholder="Backyard cherry trees..." /></td>
<td><button style="width: 100px; font-size: 18pt; padding: 2px; border: 3px solid green;" name="submit" type="submit" value="start3">Start3</button></td>
<td><button style="width: 100px; font-size: 18pt; padding: 2px; border: 3px solid red;" name="submit" type="submit" value="stop3">Stop3</button></td>
</tr>
</tbody>
</table>
&nbsp;
 
</div>
<button class="btn btn-success" style="width: 650px; font-size: 18pt; padding: 2px; border: 6px solid black;" name="submit" type="submit" value="submitAll">Write times specified (let-out fileds not changed)</button> <button class="btn btn-success" style="width: 650px; font-size: 18pt; padding: 2px; border: 6px solid green;" name="submit" type="submit" value="startAll">Start all zones</button> <button class="btn btn-success" style="width: 650px; font-size: 18pt; padding: 2px; border: 6px solid red;" name="submit" type="submit" value="stopAll">Stop all zones</button>
<h3>Values Set:</h3>
</form></div>
&nbsp;

 

undefined

Keeping it Running

 

@reboot /home/pi/flaskSprinkler/shutSprinkler.py

15 22 * * * nohup /home/pi/flaskSprinkler/sprinklerMain.py &
*/5 * * * * nohup /home/pi/flaskSprinkler/isFlaskRunning.sh &

#----------------------

shutSprinkler.py

# import the necessary packages
import RPi.GPIO as GPIO
import time
#import cv2

# load the input image and display it to our screen
#print("click on the image and press any key to continue...")
#image = cv2.imread("hoover_dam.jpg")
#cv2.imshow("Image", image)
#cv2.waitKey(0)
#print("moving on...")

# set the GPIO mode
GPIO.setmode(GPIO.BCM)

# loop over the LEDs on the TrafficHat and light each one
# individually
for i in (14,15,18,23,24,25,8,7,2,3,4,17,27,22,10,9):
        GPIO.setup(i, GPIO.OUT)
        time.sleep(0.1)
        GPIO.output(i, GPIO.HIGH)

# perform a bit of cleanup
GPIO.cleanup()

isFlaskRunning.sh

laskRunning.sh
 
 
 
 
 
Default
1
2
3
4
5
6
7
#!/bin/bash
#!/bin/bash
 
service="webForm"
 
if ! ps -e | grep "$service" ; then
/home/pi/flaskSprinkler/webForm
fi
文章標籤

stanley 發表在 痞客邦 留言(0) 人氣()

參考資料:http://dreamingecho.es/blog/internet-of-things-with-python-and-flask
Tutorials For IoT-Makers

 

(1) USING TEMPLATES AND STYLING THINGS

We store all the HTML templates in a special directory called templates, and
all our public content (like stylesheets, javascripts, images...) in a special directory called static

To do some quick styling, I'm going to use Bootstrap with the Jumbotron Narrow example HTML,
so we only have to 
download the files and put it into our static folder.

Once we got all the Bootstrap files on the static folder, we're going to integrate it with the application.
Firstly, let's open the 
main.py file and change our index method with this lines:

@app.route("/")
def index():
    return render_template('index.html')

we have replaced the return "Hello World!" thing for return render_template('index.html' )
 

index.html file
 

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="description" content="">
  <meta name="author" content="">
  <link rel="icon" href="{{ url_for('static', filename='images/favicon.ico') }}">

  <title>Flask Internet of Things App</title>

  <link href="{{ url_for('static', filename='css/bootstrap.min.css') }}" rel="stylesheet">

  <link href="{{ url_for('static', filename='css/jumbotron-narrow.css') }}" rel="stylesheet">

  <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
  <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
</head>

<body>

  <div class="container">

    <!-- A bunch of magic HTML code :) -->

  </div>
  <!-- /container -->
</body>

</html>

we're going to create a very simple class in the root of our application called raspi.py. With the help of the RPi.GPIO library, we're going to code some very simple methods to be able to read the sensor value and modify the state of the LED. The content of the class will looks like this:

import RPi.GPIO as GPIO

SENSOR_PIN  = 22
LED_PIN     = 23

class Raspi(object):

    def __init__(self):
      GPIO.setmode(GPIO.BCM)
      GPIO.setup(SENSOR_PIN, GPIO.IN)
      GPIO.setup(LED_PIN, GPIO.OUT)

    def read_sensor(self):
      return GPIO.input(SENSOR_PIN)

    def change_led(self, value):
      GPIO.output(LED_PIN, value)

Ok, with this done, let's modify our main.py file to use this new class and be able to interact with the GPIOvia web. At the end we'll have something like this:

import raspi
from flask import *

app = Flask(__name__)
raspi = raspi.Raspi()

# Index route
@app.route("/")
def index():
  # Read the value of the sensor
  value = raspi.read_sensor()
  # Render the index.html template passing the value of the sensor
  return render_template('index.html', sensor_value=value)

# About route
@app.route("/about")
def about():
  # Render the about.html template
  return render_template('about.html')

# Change LED value POST request.
@app.route("/change_led_status/<int:status>", methods=['POST'])
def change_led_status(status):
  # Check the value of the parameter
  if status == 0:
    raspi.change_led(False)
  elif status == 1:
    raspi.change_led(True)
  else:
    return ('Error', 500)
  return ('', 200)

# Starts the app listening to port 5000 with debug mode
if __name__ == "__main__":
  app.run(host="0.0.0.0", debug=True)

To send the value of this parameter we're gonna use some jQuery to do some POST requests to the route depending of the button we click. Something like this:

$(document).ready(function() {
  $('#set_on').click(function() {
    $.post('/change_led_status/1');
  });
  $('#set_off').click(function() {
    $.post('/change_led_status/0');
  });
});

stanley 發表在 痞客邦 留言(0) 人氣()

Raspberry 常用指令

(1) How to set up WiFi on your Raspberry Pi without a keyboard or monitor (or ethernet)
    (1.1) Put the Raspbian SD card into your computer
             (1.2) cd /Volumes/boot
             (1.3) Add your wpa_supplicant.conf file
                    Create a file in this directory called wpa_supplicant.conf. The file should contain the following details:
                    network={ ssid="YOUR_NETWORK_NAME" psk="YOUR_PASSWORD" key_mgmt=WPA-PSK }
              With this file in place, Raspbian will move it in /etc/wpa_supplicant/ when the system is booted.
            (1.4) Put your SD card in the Raspberry Pi, boot, and connect
(2) Raspberry Pi 3 B and B+ - How to Configure Wi-Fi and Bluetooth
     Now you need to add your Wi-Fi settings to the wpa-supplicant configuration file. Type the following in the command line to the configuration file: sudo nano /etc/wpa_supplicant/wpa_supplicant.conf.
    Go to the bottom of the file and add the following Wi-Fi setting, adding your setting in the quotation marks.
    network={
       ssid="The_ESSID_from_earlier"
       psk="Your_wifi_password"
    }

(3) RASPBERRY GPIO SETUP.
pi@raspberrypi:~ $ apt-get update
pip install RPi.GPIO
 

(3) install FTP

http://yhhuang1966.blogspot.com/2017/02/ftp.html
sudo raspi-config

stanley 發表在 痞客邦 留言(0) 人氣()

參考資料:
(1) https://www.instructables.com/id/Python-WebServer-With-Flask-and-Raspberry-Pi/
(2) https://medium.com/@rovai/python-webserver-with-flask-and-raspberry-pi-398423cc6f5d

(1) Installing FLASK and Setting Your RPi WebServer

sudo apt-get update
sudo pip install Flask

(2) Create folder  
(2.0) cd Documents
(2.1)  mkdir rpiWebServer
(2.2)  cd rpiWebServer
(2.3)  mkdir static
(2.4) mkdir templates

(3)  Create helloWorld.py     

from flask import Flask
app = Flask(__name__) 
@app.route("/")
def hello():
    return "Hello World!" 
if __name__ == '__main__':
    app.run(debug=True, port=80, host='0.0.0.0')

 

The final folder “tree”, will look like:

undefined

(4) Execute Hello World program

 pi@scpi:~/Documents/rpiWebServer $ sudo python helloWorld.py
 * Serving Flask app "helloWorld" (lazy loading)
 * Environment: production
   WARNING: Do not use the development server in a production environment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Running on http://0.0.0.0:80/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 159-728-082

(5) in WebBrower keyin
   http://192.168.0.110/

 


     

  

文章標籤

stanley 發表在 痞客邦 留言(0) 人氣()

Close

您尚未登入,將以訪客身份留言。亦可以上方服務帳號登入留言

請輸入暱稱 ( 最多顯示 6 個中文字元 )

請輸入標題 ( 最多顯示 9 個中文字元 )

請輸入內容 ( 最多 140 個中文字元 )

reload

請輸入左方認證碼:

看不懂,換張圖

請輸入驗證碼