1. Trang chủ
  2. » Kỹ Thuật - Công Nghệ

Arduino meets linux

362 395 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 362
Dung lượng 5,08 MB

Nội dung

công nghệ ngày càng phát triển. và nhu cầu tiếp cận với các tài liệu chuẩn về kỹ thuật bằng Tiếng Anh ngày càng cao, tài liệu tiếng Anh mang lại cho bạn đọc các kiến thức cơ bản nhất, nền tảng nhất và hơn nữa là gồm cả những kiến thức chuyên sâu. mà ít sáng tiếng Việt nào đáp ứng được. và đây là cuốn sách nói về công nghệ của chíp điều khiển arduino, tài liệu 100% bằng tiếng Anh, hứa hẹn sẽ làm thỏa mãn nhu cầu khám phá của những bạn đọc có đam mê

Arduino Meets Linux: The User’s Guide to Arduino Yún Development Copyright © 2015 Bob Hammell EBooks are not transferable All rights reserved No part of this publication may be reproduced, distributed, or transmitted in any form or by any means, including photocopying, recording, or other electronic or mechanical methods, without the prior written permission of the publisher, except in the case of brief quotations embodied in critical reviews and certain other non-commercial uses permitted by copyright law Trademarked names, logos, and images may appear in this book Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image, the names, logos, and images are used only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark The information in this publication is provided by Bob Hammell on an “AS IS” basis Bob Hammell makes no warranties, express or implied, regarding use of the information alone or in combination with your products Neither the author nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made Published in the United States of America by Bob Hammell ISBN-10 (Print): 1-514-23022-4 ISBN-13 (Print): 978-1-514-23022-0 ISBN-13 (ePub): 978-1-329-19359-8 Any source code or supplementary materials referenced by the author in this text are available for readers at www.arduinomeetslinux.com Table of Contents Preface Getting Started Features and connectors of the Arduino Yún • Connecting the Arduino Yún to a network • Changing your password • Opening the advanced configuration panel • Uploading sketches to the Arduino Introducing OpenWRT and Linux Connecting to the Arduino Yún and transferring files from another computer • Using the command prompt • Editing text files with GNU nano • Writing shell scripts • Installing Linux software • Resetting the operating system • Backing up the Arduino Yún Programming in Python Running Python scripts on the Yún • Writing your own Python functions • Working with classes and objects • Using packages and modules • Reading and writing to files • Handling the errors in scripts Using the Bridge Library Storing data in the AR9331’s memory from the ATmega32u4 • Running Linux commands and scripts • Working with files in the Linux file system • Using the M ailbox and sending messages • Communicating over local networks and the Internet Hosting Websites and Services Setting up a website on the Arduino Yún • Server-side scripting with CGI and Python • Project – Building a web-based temperature monitor • M aking web services and APIs • Project – Controlling an LED matrix through a web API Project – Making an MP3 Jukebox Connecting a parallel 16x2 LCD display to the Arduino Yún • Using a USB audio interface • Playing M P3 files from Python scripts Project – Hosting a USB Game Controller How USB devices communicate • Using PyUSB to communicate with a USB device • Working with M icrosoft Xbox 360®, Sony PlayStation®, and PC game controllers Project – Making a USB Accelerometer Mouse Connecting to an accelerometer module • Using pin headers to fit a ProtoShield to an Arduino Yún • Using the M ouse class to turn the Yún into a USB mouse Project – Making a Translating Keyboard Hosting a USB keyboard • Using Temboo and M icrosoft Translator • Translating text from an Arduino sketch • Using the Keyboard class to turn the Yún into a USB keyboard • Reading the position of a rotary switch Project – Controlling your Arduino Projects with Voice Commands Recording from a microphone • Translating speech to text with the AT&T Speech API • Responding to voice commands • Translating text to speech • Playing a wav file Preface The Arduino Yún is a very powerful and very flexible development board It combines the best aspects of the Arduino platform – an easy-to-use integrated development environment (IDE), simple access to hardware pins, and a helpful community – with the power and customization options of a Linux-based computer To this, the Arduino Yún includes both an ATmega32u4 microprocessor from the Atmel Corporation (as used in other Arduinos) and a 400 M Hz, 32-bit M IPS central processing unit (CPU) from Atheros The inclusion of the M IPS chip means that the Yún can perform tasks that other Arduinos not have the speed or memory resources to And because the Yún runs the Linux operating system, you can use programming languages and software programs that you cannot run on other Arduinos The Yún gives you a choice: You can use the Linux side of the Yún to add faster processing and more-capable networking to your ATmega32u4 projects – writing the main parts of your projects in Arduino sketches; Or you can use the ATmega32u4 to add a friendly hardware interface to your Linuxbased projects For Arduino users who not have experience and knowledge of running Linux on embedded devices and programming in that environment, it can be difficult to learn how to make use of the extra power What’s in this Book? M y aim in writing Arduino M eets Linux is to show you how you can use the full power of the Arduino Yún The chapters and projects in this book guide you through: Working with the Arduino Yún; Using the Linux operating system; and Developing projects that use both the ATmega32u4 and the Atheros AR9331 to create devices that are extremely difficult (or even impossible) to build using other Arduinos To program the ATmega32u4 on the Yún, you can use the Arduino IDE This book introduces the libraries and functions that are specific to the Yún and that are built-in to the Arduino IDE Every feature of the Yún is included, with sample code to help you learn to use these features To write programs and build projects on the Linux side of the Yún, you can use a variety of techniques and programming languages Arduino M eets Linux concentrates on using the Linux command line and the Python scripting language If you don’t have any experience of using Linux operating systems or programming in Python, don’t worry You can find introductions to these subjects in the book Because the Yún is extremely capable at communicating over local networks and over the Internet, I have also included projects that demonstrate: Hosting your own web sites and web services on the Yún; Fetching information from third-party web services across the Internet; and Using Temboo to simplify how you can access many web services I hope that you find these projects interesting But remember, my hope is that you learn how to make use of the Arduino Yún and develop your own ideas The techniques and explanations in my projects are intended to help you build your own For that reason, I recommend that you read through all of the chapters in this book and build the projects You can learn far more by making and experimenting than I can put into words Who Should Read this Book? If the Yún is your first Arduino, you should take some time to study the beginners’ tutorials at http://www.arduino.cc If you ignore the Atheros AR9331, the Arduino Yún works almost identically to an Arduino Uno or Arduino Leonardo To an extent, Arduino M eets Linux assumes that the Yún is not your first Arduino Although I have taken precautions to explain concepts that may be new to you, you should have a basic grasp of the fundamentals of building projects on the Arduino platform This includes: writing sketches in Arduino C in the IDE; and safely building simple, electronic circuits If your main computer is a Windows PC or Apple M ac, and you have never used Linux before, then this book will help you Everything you need to know is included And the skills that you learn working with Linux on the Arduino Yún will help you if you ever want to use a Linux operating system on another development board or computer Arduino M eets Linux is for Arduino users who want to expand their skill set and learn to take advantage of the extra power and resources that only the Arduino Yún has Online Resources ArduinoMeetsLinux.com is the companion website for this book You can contact me there if there’s anything I can help you with, or if you want to let me know about the great things you build with the Arduino Yún I’ve also put all of the project sketches and scripts up there for you to download It’ll be worth your while to visit the site regularly – news, updates, and addendum to this book will be posted there first To the best of my ability, I have verified the accuracy of all of the information in this book And I have tried to ensure that the code samples are robust enough for you to use, but not so full of optimized programming and error-checking that it is difficult to understand the code However, things change and mistakes happen You can help me to improve future editions, for the benefit of other Arduino fans, by contacting me at ArduinoMeetsLinux.com if you find any errors, inaccuracies, or places where information is not as easy to understand as you would have liked Conventions Used in this Book The following table describes the text conventions used in this book Convention Meaning Italic Text that appears in italics refers to file names, variable and function names, or other code that exists in the project sketch, Python scripts, or Arduino libraries Within the context of giving instruction, italic text should be typed exactly as shown Bold Within the context of giving instruction, items in bold text are user interface elements, such as key strokes, menu items, or button labels In other contexts, words may be emboldened for emphasis M onospace font A monospace font is used for Arduino C, Python, and Linux command line code that you may need to type Colored text Items shown with colored text are links to other pages in this book Add the following dictionary to the yuri.py script, underneath the APP_SECRET pins = {"one" : "1", "two" : "2", "to" : "2", "too" : "2", "three" : "3", "four" : "4", "for" : "4", "five" : "5", "six" : "6", "sex" : "6", "seven" : "7", "eight" : "8", "ate" : "8", "nine" : "9", "ten" : "10", "tan" : "10", "teen" : "10", "eleven" : "11", "twelve" : "12", "thirteen" : "13"} Then define the following function: def processCommand(words): processed = False if len(words) == 3: if words[0] == "turn": if words[1] == "on": client.mailbox("n" + pins[words[2]]) processed = True elif words[1] == "off": client.mailbox("f" + pins[words[2]]) processed = True if processed == False: os.system("madplay /mnt/sda1/P7/yuri-off.mp3") To use the M ailbox from Python, you need to import the BridgeClient module into your script Underneath the line that reads import wave, add the following code: import sys sys.path.insert(0, "/usr/lib/python2.7/bridge/") from bridgeclient import BridgeClient And then add this line above audio = pyaudio.PyAudio(): client = BridgeClient() For more information about exchanging information between the Atheros AR9331 and the ATmega32u4 using the M ailbox, see Using M ailbox and Sending M essages Underneath the line that reads vData = json.loads(response.read()), add the following code: if vData["Recognition"]["Status"] == "OK": processCommand(vData["Recognition"]["NBest"][0]["Hypothesis"].split(' ')) else: os.system("madplay /mnt/sda1/P7/yuri-off.mp3") M ake sure you indent this code so that it is inside the try block Although Words is a list of the words in the response from the Speech API, it may also include punctuation marks and capital letters that you not want for this project Instead, the code splits Hypothesis into a list so that each word after a space is a new entry Save the script file To make the voice control work, your Arduino sketch needs to read the messages from the M ailbox, and then change a digital pin depending on the content of the message In the Arduino IDE, underneath the line that reads #include , add: #include And then underneath the line that reads Bridge.begin();, add: Mailbox.begin(); In your sketch’s loop() function, add the following code to the end of the loop: if (Mailbox.messageAvailable()) { String message; Mailbox.readMessage(message); if (message.length() >= 2) { int pin = atoi(&message[1]); pinMode(pin, OUTPUT); if (message[0] == 'n') { digitalWrite(pin, HIGH); } else if (message[0] == 'f') { digitalWrite(pin, LOW); } } } Tip: atoi() is a C function that converts a string to an integer The string must contain a number represented by ASCII characters For example, “123” Because the first character in message is either ‘n’ or ‘f’, you pass in the memory address of the second character in message, so that atoi() does not see the first character Upload the sketch to your Arduino and then press (and hold) the button After the sound effect, say “turn on thirteen” If the Speech API and Python script file recognize your command, the sketch turns on the Arduino Yún’s built-in LED If the Speech API and Python script not recognize your command, the script plays another sound To extend this project, you have to write code into yuri.py to understand new commands and pass these to the ATmega32u4 Then modify your sketch to respond to the new commands Translating Text to Speech Because the project only supports turning Arduino digital pins on or off, the results are easy to see For more complicated voice control, it can be useful to make the script speak back to the user The AT&T Speech API has a method for doing this However, you can also this using a Linux program that performs the translation without sending information across the Internet The program that you need to install is called “espeak” If you have not installed the GCC compiler, you need to so now At the OpenWrt-Yun command prompt, type the following command and then press Enter: opkg update Type the following command and then press Enter: opkg install binutils Type the following command and then press Enter: opkg -t /root install yun-gcc To install espeak, Type the following command and then press Enter: wget http://www.arduinomeetslinux.com/download/espeak_1.48.04_ar71xx.ipk Type the following command and then press Enter: opkg install espeak_1.48.04_ar71xx.ipk Type the following command and then press Enter: rm espeak_1.48.04_ar71xx.ipk To test espeak from the command line, Type the following command and then press Enter: espeak "Hello from Arduino Meets Linux." The espeak program accepts command-line parameters that you can use to change how the program speaks your text The following table shows a few of the most common options that you may need to use Parameter Description a Sets the volume This is a number in the range through 200 The default setting is 100 p Sets the pitch This is a number in the range through 99 The default setting is 50 s Sets the speed in words per minute The default setting is 175 There is no upper limit, but the lowest setting that you can use is 80 m Specifies that the text contains speech synthesis markup language (SSM L) You can use SSM L for more precise control of espeak’s pronunciation w Writes the speech output to a wave file v Selects a language and voice The available English languages are:2 en – standard English en-us – American English en-sc – English with a Scottish accent en-n – English with a northern accent en-rp – Received Pronunciation (“BBC English”) en-wm – English with an accent from the West M idlands For a full description of all of the available options, see http://espeak.sourceforge.net/commands.html To set an option: put a dash before the parameter name, then a space, and then type the value for the option To set more than option, separate each with a space For example: espeak -a 50 -v en -w /mnt/sda1/P7/test.wav "Hello" There are an additional seven male voice variants, and five female voice variants To use these, specify +m1, +m2, +m3, +m4, +m5, +m6, +m7, +f1, +f2, +f3, +f4, or +f5 after the language espeak -v en-n+m3 "Hello" Calling espeak directly can sometimes cause crackles and noise through the speakers To ensure reliable audio, this project tells espeak to save the speech to a wav file, and then the script plays the file through PyAudio In your Python script, above the line that declares APP_KEY, add the following Python class: class AudioPlay: chunk = 1024 def init (self, file): self.wf = wave.open(file, 'rb') self.p = pyaudio.PyAudio() self.stream = self.p.open( format = self.p.get_format_from_width(self.wf.getsampwidth()), channels = self.wf.getnchannels(), rate = self.wf.getframerate(), output = True ) def play(self): data = self.wf.readframes(self.chunk) while data != '': self.stream.write(data) data = self.wf.readframes(self.chunk) def close(self): self.stream.close() self.p.terminate() You create an AudioPlay object by passing in the file name of the wave file that you want to play The play() method plays the audio through your speakers or headphones, and the close() method closes the file and releases the audio device In your script, find the code that reads: if vData["Recognition"]["Status"] == "OK": processCommand(vData["Recognition"]["NBest"][0]["Hypothesis"].split(' ')) else: os.system("madplay /mnt/sda1/P7/yuri-off.mp3") And change it to: if vData["Recognition"]["Status"] == "OK": processCommand(vData["Recognition"]["NBest"][0]["Hypothesis"].split(' ')) else: os.system('espeak -w /mnt/sda1/P7/tmp.wav "Sorry I not understand."') spk = AudioPlay("/mnt/sda1/P7/tmp.wav") spk.play() spk.close() os.remove("/mnt/sda1/P7/tmp.wav") os.system("madplay /mnt/sda1/P7/yuri-off.mp3") Then change the end of the processCommand() function so that it reads: if processed == False: os.system('espeak -w /mnt/sda1/P7/tmp.wav "Sorry I not understand."') spk = AudioPlay("/mnt/sda1/P7/tmp.wav") spk.play() spk.close() os.remove("/mnt/sda1/P7/tmp.wav") os.system("madplay /mnt/sda1/P7/yuri-off.mp3") Save the file To run this code, press and hold the button on the circuit Then, after the tone, either: Stay silent; or Say something that the processCommand() function does not understand Reading from Sensors and Speaking the Result Using speech to tell the user the value of an input can be very useful, particularly in projects that not have a display The process for doing this is: In your Arduino sketch, read the value of a sensor or input Send this data to a Python script on the Atheros AR9331 For more information about exchanging information between the ATmega32u4 and the Atheros AR9331, see Using the Bridge Library Process the data and create a string of words Convert the string to a wav file, and then play it The following example uses the Adafruit M CP9808 temperature sensor from Project – Building a Web-Based Temperature M onitor If you have not completed that project, it is recommended that you so now In particular, make sure you install the SoftI2CMaster library in your Arduino IDE Then unplug the power from your Arduino and connect the Adafruit M CP9808 as shown in Connecting the Adafruit M CP9808 Temperature Sensor to the Arduino When you speak the command “tell me the temperature”, the example responds To modify your current Arduino sketch to support this, Add the following #include statement to the top of the sketch: #include Create an instance of the SoftI2CMaster class as a global variable: SoftI2CMaster i2c = SoftI2CMaster(A3, A2); In your sketch’s setup() function, before the call to Bridge.begin(), add the following code: pinMode(A0, OUTPUT); digitalWrite(A0, HIGH); pinMode(A1, OUTPUT); digitalWrite(A1, LOW); Copy the getTemperature() function from Source Code – Sketch, and then paste it into your current sketch In your sketch’s loop() function, add the following code to the end: Bridge.put("MCP9808_Temperature", String(getTemperature())); These changes update the variable MCP9808_Temperature in the shared-storage memory that both the ATmega32u4 and the Atheros AR9331 can use In the yuri.py script, find the processCommand() function Then add the following code after the second processed = True statement Indent this code with four spaces, so that it joins onto the first if statement in the function elif len(words) == 4: if words[0] == "tell" and words[1] == "me" and words[2] == "the": if words[3] == "temperature": temp = (float(client.get("MCP9808_Temperature")) * 1.5) + 32 speech = "The temperature is {0:.1f} degrees fahrenheit.".format(temp) os.system('espeak -w /mnt/sda1/P7/tmp.wav "' + speech + '"') spk = AudioPlay("/mnt/sda1/P7/tmp.wav") spk.play() spk.close() os.remove("/mnt/sda1/P7/tmp.wav") processed = True To extend this example so that the Python script speaks the time when you say “tell me the time”, add the following code underneath the processed = True statement in the code above Indent this code with 12 spaces, so that it joins onto the if words[3] == "temperature" statement elif words[3] == "time": speech = "The time is " + strftime("%I %M %p", gmtime()) os.system('espeak -w /mnt/sda1/P7/tmp.wav "' + speech + '"') spk = AudioPlay("/mnt/sda1/P7/tmp.wav") spk.play() spk.close() os.remove("/mnt/sda1/P7/tmp.wav") processed = True And add the following import statement to the list at the top of the script: from time import gmtime, strftime Save the file and then exit nano You have reached the end of this project This project is only an example of how you can add voice control to your Arduino projects, but the steps for building a more complicated system are the same As your code for handling the different voice commands grows larger, you may want to research how compilers and interpreters work The techniques involved in writing compilers can help you process natural language Source Code – Sketch #include #include #include #define BTN_1 Process p; SoftI2CMaster i2c = SoftI2CMaster(A3, A2); float getTemperature() { i2c.beginTransmission(0x18); i2c.send(0x05); i2c.endTransmission(); i2c.requestFrom(0x18); uint16_t v = i2c.receive(); v int(8000 / 1024 * 2): if sum([x > threshold for x in q])

Ngày đăng: 18/09/2016, 08:31

TỪ KHÓA LIÊN QUAN

w