qtsharp 发表于 2012-10-25 21:08:27

【软硬结合】树莓派+python做的智能远程控制原型

使用的工具:
树莓派+python+django+pyserial+STC89C52单片机。


树莓派通过usb转串口与单片机,linux上自带usb转串口芯片的驱动,真爽!

网页与后台使用django,通过django调用pyserial库向单片机发送命令。

基于这种原型,可以很方便的利用手机浏览器控制家里的电器,好好利用django的账户安全功能,又可以做到远程控制需要的安全保密性!

树莓派+python+django+pyserial这个方案,是我认为在学习成本、搭建速度、开发速度、安全性、易用度、客户端无关性方面比较完美的集合。


http://player.youku.com/player.php/sid/XNDY2Nzg2NjI0/v.swf

视频里使用的手机QQ浏览器,由于手机网络不给力,并且又通过qq服务器压缩转发,所以能看出延迟,如果用电脑操作效果更好。

1、这个方案其实完全可以拿掉单片机,直接将python+django+rpi.gpio结合可以做同样的事,一个树莓派结合继电器就可以做远程网页控制了。2、但是直接通过单片机利用蓝牙芯片进行串口连接,可以降低无线控制系统的成本。
3、由于网页使用python语言编写,所以可以十分方便的进行本地操作,更有超多的现成库,可实现的功能远远比网页脚本语言强大得多。
4、估计没几个能有比django的admin模块更简单的健全的账户安全系统了。
5、其实整个系统的核心就在django上,所以这个系统运行在任何一个linux终端上上均可以,不单单是树莓派。
6、但是树莓派最大的优势就是低功耗,高度优化的系统和rpi.gpio,作为一个日常低负载的服务器没有人会不喜欢——如果CPU能再给力点的话。
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1、django教程:http://djangobook.py3k.cn/2.0/ 如果碰到无法理解的问题,别急,去https://docs.djangoproject.com/en/1.4/找找答案。
2、51单片机的串口例程:http://www.elecfans.com/emb/danpianji/20110509197678.html
3、PySerial方面完全可以用6楼提供的代码:http://www.shumeipai.net/read.php?tid=1118&ds=1#11689

4、下面贴一下django里的部分app代码:
control.py:


#!/usr/bin/env python
import serial

class Control():
    def __init__(self,device='/dev/ttyUSB0',BAUD=4800):
      self.client = serial.Serial(device,BAUD,timeout=1)
    def command(self,CMD):
      try:
            self.client.write(CMD)
            self.client.close()
      except:
            pass


views.py:


from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponse,HttpResponseRedirect, Http404
from control import Control

def control(request):
    DEMO=None
    if request.method == 'POST':
      if 'CMD' in request.POST:
            CON = Control()
            CMD = request.POST['CMD']
            CON.command(CMD)
      if 'demo' in request.POST:
            DEMO=request.POST['demo']
      if 'not_demo' in request.POST:
            DEMO=None
    return render_to_response('controller.html',{'demo':DEMO},context_instance=RequestContext(request))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
再贴上有点偏离主题的视频里示范网页的html模板代码:


{% extends "basepage.html" %}

{% block title %}远程控制{% endblock %}
{% block content %}
{% if not demo %}
<form action="" method="post">{% csrf_token %}
<p><input type="submit" name='demo' title='视频演示' accesskey="y" value="视频演示"></button></p>
</form>
<form action="" method="post">{% csrf_token %}
<p><input type="submit" name='CMD' title='开' accesskey="k" value="01">开</button></p>
<p><input type="submit" name='CMD' title='关' accesskey="g" value="00">关</button></p>
<p><input type="submit" name='CMD' title='闪' accesskey="s" value="88">闪</button></p>
</form>
{% endif %}
{% if demo %}
<form action="" method="post">{% csrf_token %}
<p><input type="submit" name='not_demo' title='返回控制' accesskey="f" value="返回控制"></button></p>
</form>
<br>
<embed src="http://player.youku.com/player.php/sid/XNDY2Nzg2NjI0/v.swf" allowFullScreen="true" quality="high" width="480" height="400" align="middle" allowScriptAccess="always" type="application/x-shockwave-flash"></embed>
{% endif %}
{% endblock%}

qtsharp 发表于 2012-10-25 21:25:03

沙发自己占

会跑的蜗牛 发表于 2012-10-25 23:14:00

能不能留一下联系方式,交流一下如何实现的?

qtsharp 发表于 2012-10-25 23:40:42

回 会跑的蜗牛 的帖子

会跑的蜗牛:能不能留一下联系方式,交流一下如何实现的? (2012-10-25 23:14) images/back.gif

你想问什么,我可以直接在帖子里给你回复,这样大家都能看到。

glutamine 发表于 2012-10-25 23:42:23

大概能猜出来怎么做的。话说u版写过一个树莓派实现远程监控的帖子来着。

qtsharp 发表于 2012-10-26 00:02:39

1、这个方案其实完全可以拿掉单片机,直接将python+django+rpi.gpio结合可以做同样的事,一个树莓派结合继电器就可以做远程网页控制了。
2、但是直接通过单片机利用蓝牙芯片进行串口连接,可以降低无线控制系统的成本。
3、由于网页使用python语言编写,所以可以十分方便的进行本地操作,更有超多的现成库,可实现的功能远远比网页脚本语言强大得多。
4、估计没几个能有比django的admin模块更简单的健全的账户安全系统了。
5、其实整个系统的核心就在django上,所以这个系统运行在任何一个linux终端上上均可以,不单单是树莓派。
6、但是树莓派最大的优势就是低功耗,高度优化的系统和rpi.gpio,作为一个日常低负载的服务器没有人会不喜欢——如果CPU能再给力点的话。

james11 发表于 2012-10-26 08:15:10

借花献佛---转贴一篇Raspberry Pi and Arduino()
就不翻译了,很简单的英文



TheRaspberry Pi is creatingquite a storm of interest. I have just got mine and one of the firstthings that I wanted to try was to get it talking to an Arduino over USBusing Python.




.. and you know what? It proved to be a lot easier than I expected. Thisis mainly because, after all, despite its diminutive price tag, the Piis just a Linux box. I got communication working both ways, with theArduino sending 'Hello Pi' to the Pi and at the same time, testing for adigit coming in. When it receives a digit, it flashes the number oftimes indicated by the digit.

Arduino

Let's start with the Arduino end. I used an Arduino Uno and Arduinosoftware version 1.0. I haven't tried an older board, but I suspect theFTDI generation Arduinos before the Uno may have trouble with USB.

Here is the sketch - paste it into a new Arduino IDE window and load it up onto your Arduino using your regular computer.


const int ledPin = 13;


void setup()
{
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}


void loop()
{
Serial.println("Hello Pi");
if (Serial.available())
{
   flash(Serial.read() - '0');
}
delay(1000);
}


void flash(int n)
{
for (int i = 0; i < n; i++)
{
    digitalWrite(ledPin, HIGH);
    delay(100);
    digitalWrite(ledPin, LOW);
    delay(100);
}
}



Raspberry Pi

There is a Python library for serial communications called pySerial (http://pyserial.sourceforge.net/) which has history with Arduino. So, I stood on the shoulders of giants and adapted the instructions found http://arduino.cc/playground/Interfacing/Python

Step 1. If you are not reading this page on your Pi, then switch now, so you can copy and paste.

Step 2. Browse to http://sourceforge.net/projects/pyserial/files/ and download http://sourceforge.net/projects/pyserial/files/latest/download?source=filespyserial-2.5.tar.gz (106.3 kB) and save it somewhere convenient. I saved it to the 'other' folder on the Desktop.

Step 3. This is a gziped tar file. Which needs unzipping and untaring.To unzip it open a Terminal, which you will find from the 'start menu'under 'accessories'. Now paste the following commands into it.
cd /home/pi/Desktop/other
gunzip pyserial-2.5.tar.gz
tar - xvf pyserial-2.5.tar

Step 4. Install pySerial, by typing these lines in your terminal window:
cd pyserial-2.5
sudo python setup.py install


Step 5. Run Python 2. You will find this from the menu under Programming - Use Python 2 not 3.

Thats it! Now we just need to write some Python to access the Serial port. So type the commands shown in the transcript below.



You type the parts after >>>

import serial
ser = serial.Serial('/dev/ttyACM0', 9600)

Note that the second argument here (9600) is the baud rate and should match whatever you put in your Arduino sketch.


/dev/ttyACM0 is the name for the USB interface to the Uno, at least itwas for my Uno. The way to discover the port name is to run thefollowing command in the terminal without the Uno plugged in.

ls /dev/tty*


Then plug in your Arduio and run the command again. If there is a new name, then this is the name of your port.

Now lets start a loop listening for messages from the Arduino.

while 1 :
    ser.readline()

You will need two hit enter twice after you type the second line. Messages should now start to appear!

You can see in the Blue writing where the Arduino is talking to the Pi.Then some error trace as you press ctrl-C to interrupt the messagescoming from the Arduino.

When you type

ser.write('5')

you should see the LED on the Arduino flash 5 times.

There are many possibilities here, we could put a motor shield or LCD shield onto the Arduino and control it from your Pi.

Watch out for my book 'Programming the Raspberry Pi' pub. McGraw-Hill, out towards the end of 2012.

james11 发表于 2012-10-26 08:18:36

感谢qtsharp楼主,如果方便的话,能提供一段例子代码就更好了,很有价值的文章。

qtsharp 发表于 2012-10-26 11:27:33

回 james11 的帖子

james11:感谢qtsharp楼主,如果方便的话,能提供一段例子代码就更好了,很有价值的文章。  (2012-10-26 08:18) images/back.gif

1、django教程:http://djangobook.py3k.cn/2.0/ 如果碰到无法理解的问题,别急,去https://docs.djangoproject.com/en/1.4/找找答案。
2、51单片机的串口例程:http://www.elecfans.com/emb/danpianji/20110509197678.html
3、PySerial方面完全可以用6楼提供的代码:http://www.shumeipai.net/read.php?tid=1118&ds=1#11689

qtsharp 发表于 2012-10-26 11:30:22

1、django教程:http://djangobook.py3k.cn/2.0/ 如果碰到无法理解的问题,别急,去https://docs.djangoproject.com/en/1.4/找找答案。
2、51单片机的串口例程:http://www.elecfans.com/emb/danpianji/20110509197678.html
3、PySerial方面完全可以用6楼提供的代码:http://www.shumeipai.net/read.php?tid=1118&ds=1#11689

4、下面贴一下django里的部分app代码:
control.py:


#!/usr/bin/env python
import serial

class Control():
    def __init__(self,device='/dev/ttyUSB0',BAUD=4800):
      self.client = serial.Serial(device,BAUD,timeout=1)
    def command(self,CMD):
      try:
            self.client.write(CMD)
            self.client.close()
      except:
            pass


views.py:


from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponse,HttpResponseRedirect, Http404
from control import Control

def control(request):
    DEMO=None
    if request.method == 'POST':
      if 'CMD' in request.POST:
            CON = Control()
            CMD = request.POST['CMD']
            CON.command(CMD)
      if 'demo' in request.POST:
            DEMO=request.POST['demo']
      if 'not_demo' in request.POST:
            DEMO=None
    return render_to_response('controller.html',{'demo':DEMO},context_instance=RequestContext(request))
页: [1] 2
查看完整版本: 【软硬结合】树莓派+python做的智能远程控制原型