Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon

How-To Tutorials - Home Automation

8 Articles
article-image-apple-joins-the-thread-group-signaling-its-smart-home-ambitions-with-homekit-siri-and-other-iot-products
Bhagyashree R
09 Aug 2018
3 min read
Save for later

Apple joins the Thread Group, signaling its Smart Home ambitions with HomeKit, Siri and other IoT products

Bhagyashree R
09 Aug 2018
3 min read
Apple is now a part of the Thread Group’s list of members, alongside its top rivals - Nest (a subsidiary of Google) and Amazon. This indicates some advancements in their HomeKit software framework and inter-device communication between iOS devices. Who is the Thread Group? The Thread Group is a non-profit company who have developed the network protocol Thread, with the aim of being the best way to connect and control IoT products. These are the features that enable them to do so: Mesh networking: It uses mesh network design, connecting hundreds of products securely and reliably, which also means no single point of failure. Secure: It provides security at network and application layers. To ensure only authorized devices join the network, it uses product install codes. They use AES encryption to close security holes that exist in other wireless protocols and smartphone-era authentication scheme. Battery friendly: Based on the power efficient IEEE 802.15.4 MAC/PHY, it ensures extremely low power consumption. Short messaging, streamlined routing protocol, use of low power wireless system-on-chips also makes it battery friendly. Based on IPv6: It is interoperable by design using proven, open standards and IPv6 technology with 6LoWPAN (short for, IPv6 over Low-Power Wireless Personal Area Networks) as the foundation. 6LoWPAN is an IPv6 based low-power wireless personal area network which is comprises of devices that conform to the IEEE 802.15.4-2003 standard Scalable: It can scale upto 250+ devices into a single network supporting multiple hops. What this membership brings to Apple? The company has not revealed their plans yet, but nothing is stopping us from imagining what they possibly could do with Thread. According to a redditor, the following are some potential use of Thread by Apple HomeKit by Apple uses WiFi and Bluetooth as its wireless protocols. WiFi is very power hungry and Bluetooth is short-ranged. With Thread’s mesh network and power-efficient design this problem could be solved. Apple only allows certain products to operate on battery, requiring others to be plugged into power constantly, HomeKit cameras, for instance. Critical to both Apple and extended-use home devices, Thread promises “extremely low power consumption.” Apple could have plans to provide support for the number of IoT smart home devices the HomePod is capable of connecting to with Thread. With the support of Thread, iOS devices could guarantee better inter-device Siri communications, more reliable continuity features, and secure geo-fencing. Apple joining the group could mean that it may become open to more hardware when it comes to its HomeKit and also become reasonable from a cost perspective in the smart home area. Apple releases iOS 12 beta 2 with screen time and battery usage updates among others macOS Mojave: Apple updates the Mac experience for 2018 Apple stocks soar just shy of $1 Trillion market cap as revenue hits $53.3 Billion in Q3 earnings 2018
Read more
  • 0
  • 0
  • 3874

article-image-aquarium-monitor
Packt
27 Jan 2016
16 min read
Save for later

Aquarium Monitor

Packt
27 Jan 2016
16 min read
In this article by Rodolfo Giometti, author of the book BeagleBone Home Automation Blueprints, we'll see how to realize an aquarium monitor where we'll be able to record all the environment data and then control the life of our loved fishes from a web panel. (For more resources related to this topic, see here.) By using specific sensors, you'll learn how to monitor your aquarium with the possibility to set alarms, log the aquarium data (water temperature), and to do some actions like cooling the water and feeding the fishes. Simply speaking, we're going to implement a simple aquarium web monitor with a real-time live video, some alarms in case of malfunctioning, and a simple temperature data logging that allows us to monitor the system from a standard PC as well as from a smartphone or tablet, without using any specifying mobile app, but just using the on-board standard browser only. The basic of functioning This aquarium monitor is a good (even if very simple) example about how a web monitoring system should be implemented, giving to the reader some basic ideas about how a mid-complex system works and how we can interact with it in order to modify some system settings, displaying some alarms in case of malfunctioning and plotting a data logging on a PC, smartphone, or tablet. We have a periodic task that collects the data and then decides what to do. However, this time, we have a user interface (the web panel) to manage, and a video streaming to be redirected into a web page. Note also that in this project, we need an additional power supply in order to power and manage 12V devices (like a water pump, a lamp, and a cooler) with the BeagleBone Black, which is powered at 5V instead. Note that I'm not going to test this prototype on a real aquarium (since I don't have one), but by using a normal tea cup filled with water! So you should consider this project for educational purpose only, even if, with some enhancements, it could be used on a real aquarium too! Setting up the hardware About the hardware, there are at least two major issues to be pointed out: first of all, the power supply. We have two different voltages to use due to the fact the water pump, the lamp, and the cooler are 12V powered, while the other devices are 5V/3.3V powered. So, we have to use a dual output power source (or two different power sources) to power up our prototype. The second issue is about using a proper interface circuitry between the 12V world and the 5V one in such a way as to not damage the BeagleBone Black or other devices. Let me remark that a single GPIO of the BeagleBone Black can manage a voltage of 3.3V, so we need a proper circuitry to manage a 12V device. Setting up the 12V devices As just stated, these devices need special attention and a dedicated 12V power line which, of course, cannot be the one we wish to use to supply the BeagleBone Black. On my prototype, I used a 12V power supplier that can supply a current till 1A. These characteristics should be enough to manage a single water pump, a lamp, and a cooler. After you get a proper power supplier, we can pass to show the circuitry to use to manage the 12V devices. Since all of them are simple on/off devices, we can use a relay to control them. I used the device shown in the following image where we have 8 relays: The devices can be purchased at the following link (or by surfing the Internet): http://www.cosino.io/product/5v-relays-array Then, the schematic to connect a single 12V device is shown in the following diagram: Simply speaking, for each device, we can turn on and off the power supply simply by moving a specific GPIO of our BeagleBone Black. Note that each relays of the array board can be managed in direct or inverse logic by simply choosing the right connections accordingly as reported on the board itself, that is, we can decide that, by putting the GPIO into a logic 0 state, we can activate the relay, and then, turning on the attached device, while putting the GPIO into a logic 1 state, we can deactivate the relay, and then turn off the attached device. By using the following logic, when the LED of a relay is turned on, the corresponding device is powered on. The BeagleBone Black's GPIOs and the pins of the relays array I used with 12V devices are reported in the following table: Pin Relays Array pin 12V Device P8.10 - GPIO66 3 Lamp P8.9 - GPIO69 2 Cooler P8.12 - GPIO68 1 Pump P9.1 - GND GND   P9.5 - 5V Vcc   To test the functionality of each GPIO line, we can use the following command to set up the GPIO as an output line at high state: root@arm:~# ./bin/gpio_set.sh 68 out 1 Note that the off state of the relay is 1, while the on state is 0. Then, we can turn the relay on and off by just writing 0 and 1 into /sys/class/gpio/gpio68/value file, as follows: root@arm:~# echo 0 > /sys/class/gpio/gpio68/value root@arm:~# echo 1 > /sys/class/gpio/gpio68/value Setting up the webcam The webcam I'm using in my prototype is a normal UVC-based webcam, but you can safely use another one which is supported by the mjpg-streamer tool. See the mjpg-streamer project's home site for further information at http://sourceforge.net/projects/mjpg-streamer/. Once connected to the BeagleBone Black USB host port, I get the following kernel activities: usb 1-1: New USB device found, idVendor=045e, idProduct=0766 usb 1-1: New USB device strings: Mfr=1, Product=2, SerialNumber=0 usb 1-1: Product: Microsoft LifeCam VX-800 usb 1-1: Manufacturer: Microsoft ... uvcvideo 1-1:1.0: usb_probe_interface uvcvideo 1-1:1.0: usb_probe_interface - got id uvcvideo: Found UVC 1.00 device Microsoft LifeCam VX-800 (045e:0766) Now, a new driver called uvcvideo is loaded into the kernel: root@beaglebone:~# lsmod Module Size Used by snd_usb_audio 95766 0 snd_hwdep 4818 1 snd_usb_audio snd_usbmidi_lib 14457 1 snd_usb_audio uvcvideo 53354 0 videobuf2_vmalloc 2418 1 uvcvideo ... Ok, now, to have a streaming server, we need to download the mjpg-streamer source code and compile it. We can do everything within the BeagleBone Black itself with the following command: root@beaglebone:~# svn checkout svn://svn.code.sf.net/p/mjpg-streamer/code/ mjpg-streamer-code The svn command is part of the subversion package and can be installed by using the following command: root@beaglebone:~# aptitude install subversion After the download is finished, we can compile and install the code by using the following command line: root@beaglebone:~# cd mjpg-streamer-code/mjpg-streamer/ && make && make install If no errors are reported, you should now be able to execute the new command as follows, where we ask for the help message: root@beaglebone:~# mjpg_streamer --help ----------------------------------------------------------------------- Usage: mjpg_streamer -i | --input "<input-plugin.so> [parameters]" -o | --output "<output-plugin.so> [parameters]" [-h | --help ]........: display this help [-v | --version ].....: display version information [-b | --background]...: fork to the background, daemon mode ... If you get an error like the following: make[1]: Entering directory `/root/mjpg-streamer-code/mjpg-streamer/plugins/input_testpicture' convert pictures/960x720_1.jpg -resize 640x480! pictures/640x480_1.jpg /bin/sh: 1: convert: not found make[1]: *** [pictures/640x480_1.jpg] Error 127 ...it means that your system misses the convert tool. You can install it by using the usual aptitude command: root@beaglebone:~# aptitude install imagemagick OK, now we are ready to test the webcam. Just run the following command line and then point a web browser to the address http://192.168.32.46:8080/?action=stream (where you should replace my IP address 192.168.32.46 with your BeagleBone Black's one) in order to get the live video from your webcam: root@beaglebone:~# LD_LIBRARY_PATH=/usr/local/lib/ mjpg_streamer -i "input_uvc.so -y -f 10 -r QVGA" -o "output_http.so -w /var/www/" Note that you can use the USB ethernet address 192.168.7.2 too if you're not using the BeagleBone Black's Ethernet port. If everything works well, you should get something as shown in the following screenshot: If you get an error as follows: bind: Address already in use ...it means that some other process is holding the 8080 port, and most probably, it's occupied by the Bone101 service. To disable it, you can use the following commands: root@BeagleBone:~# systemctl stop bonescript.socket root@BeagleBone:~# systemctl disable bonescript.socket rm '/etc/systemd/system/sockets.target.wants/bonescript.socket' Or, you can simply use another port, maybe port 8090, with the following command line: root@beaglebone:~# LD_LIBRARY_PATH=/usr/local/lib/ mjpg_streamer -i "input_uvc.so -y -f 10 -r QVGA" -o "output_http.so -p 8090 -w /var/www/" Connecting the temperature sensor The temperature sensor used in my prototype is the one shown in the following screenshot: The devices can be purchased at the following link (or by surfing the Internet): http://www.cosino.io/product/waterproof-temperature-sensor. The datasheet of this device is available at http://datasheets.maximintegrated.com/en/ds/DS18B20.pdf. As you can see, it's a waterproof device so we can safely put it into the water to get its temperature. This device is a 1-wire device and we can get access to it by using the w1-gpio driver, which emulates a 1-wire controller by using a standard BeagleBone Black GPIO pin. The electrical connection must be done according to the following table, keeping in mind that the sensor has three colored connection cables: Pin Cable color P9.4 - Vcc Red P8.11 - GPIO1_13 White P9.2 - GND Black Interested readers can follow this URL for more information about how 1-Wire works: http://en.wikipedia.org/wiki/1-Wire Keep in mind that, since our 1-wire controller is implemented in software, we have to add a pull-up resistor of 4.7KΩ between the red and white cable in order to make it work! Once all connections are in place, we can enable the 1-wire controller on the P8.11 pin of the BeagleBone Black's expansion connector. The following snippet shows the relevant code where we enable the w1-gpio driver and assign to it the proper GPIO: fragment@1 { target = <&ocp>; __overlay__ { #address-cells = <1>; #size-cell = <0>; status = "okay"; /* Setup the pins */ pinctrl-names = "default"; pinctrl-0 = <&bb_w1_pins>; /* Define the new one-wire master as based on w1-gpio * and using GPIO1_13 */ onewire@0 { compatible = "w1-gpio"; gpios = <&gpio2 13 0>; }; }; }; To enable it, we must use the dtc program to compile it as follows: root@beaglebone:~# dtc -O dtb -o /lib/firmware/BB-W1-GPIO-00A0.dtbo -b 0 -@ BB-W1-GPIO-00A0.dts Then, we have to load it into the kernel with the following command: root@beaglebone:~# echo BB-W1-GPIO > /sys/devices/bone_capemgr.9/slots If everything works well, we should see a new 1-wire device under the /sys/bus/w1/devices/ directory, as follows: root@beaglebone:~# ls /sys/bus/w1/devices/ 28-000004b541e9 w1_bus_master1 The new temperature sensor is represented by the directory named 28-000004b541e9. To read the current temperature, we can use the cat command on the w1_slave file as follows: root@beaglebone:~# cat /sys/bus/w1/devices/28-000004b541e9/w1_slave d8 01 00 04 1f ff 08 10 1c : crc=1c YES d8 01 00 04 1f ff 08 10 1c t=29500 Note that your sensors have a different ID, so in your system you'll get a different path name in the /sys/bus/w1/devices/28-NNNNNNNNNNNN/w1_slave form. In the preceding example, the current temperature is t=29500, which is expressed in millicelsius degree (m°C), so it's equivalent to 29.5° C. The reader can take a look at the book BeagleBone Essentials, edited by Packt Publishing and written by the author of this book, in order to have more information regarding the management of the 1-wire devices on the BeagleBone Black. Connecting the feeder The fish feeder is a device that can release some feed by moving a motor. Its functioning is represented in the following diagram: In the closed position, the motor is at horizontal position, so the feed cannot fall down, while in the open position, the motor is at vertical position, so that the feed can fall down. I have no real fish feeder, but looking at the above functioning we can simulate it by using the servo motor shown in the following screenshot: The device can be purchased at the following link (or by surfing the Internet): http://www.cosino.io/product/nano-servo-motor. The datasheet of this device is available at http://hitecrcd.com/files/Servomanual.pdf. This device can be controlled in position, and it can rotate by 90 degrees with a proper PWM signal in input. In fact, reading into the datasheet, we discover that the servo can be managed by using a periodic square waveform with a period (T) of 20 ms and with an high state time (thigh) between 0.9 ms and 2.1 ms with 1.5 ms as (more or less) center. So, we can consider the motor in the open position when thigh =1 ms and in the close position when thigh=2 ms (of course, these values should be carefully calibrated once the feeder is really built up!) Let's connect the servo as described by the following table: Pin Cable color P9.3 - Vcc Red P9.22 - PWM Yellow P9.1 - GND Black Interested readers can find more details about the PWM at https://en.wikipedia.org/wiki/Pulse-width_modulation. To test the connections, we have to enable one PWM generator of the BeagleBone Black. So, to respect the preceding connections, we need the one which has its output line on pin P9.22 of the expansion connectors. To do it, we can use the following commands: root@beaglebone:~# echo am33xx_pwm > /sys/devices/bone_capemgr.9/slots root@beaglebone:~# echo bone_pwm_P9_22 > /sys/devices/bone_capemgr.9/slots Then, in the /sys/devices/ocp.3 directory, we should find a new entry related to the new enabled PWM device, as follows: root@beaglebone:~# ls -d /sys/devices/ocp.3/pwm_* /sys/devices/ocp.3/pwm_test_P9_22.12 Looking at the /sys/devices/ocp.3/pwm_test_P9_22.12 directory, we see the files we can use to manage our new PWM device: root@beaglebone:~# ls /sys/devices/ocp.3/pwm_test_P9_22.12/ driver duty modalias period polarity power run subsystem uevent As we can deduce from the preceding file names, we have to properly set up the values into the files named as polarity, period and duty. So, for instance, the center position of the servo can be achieved by using the following commands: root@beaglebone:~# echo 0 > /sys/devices/ocp.3/pwm_test_P9_22.12/polarity root@beaglebone:~# echo 20000000 > /sys/devices/ocp.3/pwm_test_P9_22.12/period root@beaglebone:~# echo 1500000 > /sys/devices/ocp.3/pwm_test_P9_22.12/duty The polarity is set to 0 to invert it, while the values written in the other files are time values expressed in nanoseconds, set at a period of 20 ms and a duty cycle of 1.5 ms, as requested by the datasheet (time values are all in nanoseconds.) Now, to move the gear totally clockwise, we can use the following command: root@beaglebone:~# echo 2100000 > /sys/devices/ocp.3/pwm_test_P9_22.12/duty On the other hand, the following command is to move it totally anticlockwise: root@beaglebone:~# echo 900000 > /sys/devices/ocp.3/pwm_test_P9_22.12/duty So, by using the following command sequence, we can open and then close (with a delay of 1 second) the gate of the feeder: echo 1000000 > /sys/devices/ocp.3/pwm_test_P9_22.12/duty sleep 1 echo 2000000 > /sys/devices/ocp.3/pwm_test_P9_22.12/duty Note that by simply modifying the delay, we can control how much feed should fall down when the feeder is activated. The water sensor The water sensor I used is shown in the following screenshot: The device can be purchased at the following link (or by surfing the Internet): http://www.cosino.io/product/water_sensor. This is a really simple device that implements what is shown in the following screenshot, where the resistor (R) has been added to limit the current when the water closes the circuit: When a single drop of water touches two or more teeth of the comb in the schematic, the circuit is closed and the output voltage (Vout) drops from Vcc to 0V. So, if we wish to check the water level in our aquarium, that is, if we wish to check for a water leakage, we can manage to put the aquarium into a sort of saucer, and then this device into it, so, if a water leakage occurs, the water is collected by the saucer, and the output voltage from the sensor should move from Vcc to GND. The GPIO used for this device are shown in the following table: Pin Cable color P9.3 - 3.3V Red P8.16 - GPIO67 Yellow P9.1 - GND Black To test the connections, we have to define GPIO67 as an input line with the following command: root@beaglebone:~# ../bin/gpio_set.sh 67 in Then, we can try to read the GPIO status while the sensor is into the water and when it is not, by using the following two commands: root@beaglebone:~# cat /sys/class/gpio/gpio67/value 0 root@beaglebone:~# cat /sys/class/gpio/gpio67/value 1 The final picture The following screenshot shows the prototype I realized to implement this project and to test the software. As you can see, the aquarium has been replaced by a cup of water! Note that we have two external power suppliers: the usual one at 5V for the BeagleBone Black, and the other one with an output voltage of 12V for the other devices (you can see its connector in the upper right corner on the right of the webcam.) Summary In this article we've discovered how to interface our BeagleBone Black to several devices with a different power supply voltage and how to manage a 1-wire device and PWM one. Resources for Article: Further resources on this subject: Building robots that can walk [article] Getting Your Own Video and Feeds [article] Home Security by BeagleBone [article]
Read more
  • 0
  • 0
  • 2397

article-image-getting-started-intel-galileo
Packt
30 Mar 2015
12 min read
Save for later

Getting Started with Intel Galileo

Packt
30 Mar 2015
12 min read
In this article by Onur Dundar, author of the book Home Automation with Intel Galileo, we will see how to develop home automation examples using the Intel Galileo development board along with the existing home automation sensors and devices. In the book, a good review of Intel Galileo will be provided, which will teach you to develop native C/C++ applications for Intel Galileo. (For more resources related to this topic, see here.) After a good introduction to Intel Galileo, we will review home automation's history, concepts, technology, and current trends. When we have an understanding of home automation and the supporting technologies, we will develop some examples on two main concepts of home automation: energy management and security. We will build some examples under energy management using electrical switches, light bulbs and switches, as well as temperature sensors. For security, we will use motion, water leak sensors, and a camera to create some examples. For all the examples, we will develop simple applications with C and C++. Finally, when we are done building good and working examples, we will work on supporting software and technologies to create more user friendly home automation software. In this article, we will take a look at the Intel Galileo development board, which will be the device that we will use to build all our applications; also, we will configure our host PC environment for software development. The following are the prerequisites for this article: A Linux PC for development purposes. All our work has been done on an Ubuntu 12.04 host computer, for this article and others as well. (If you use newer versions of Ubuntu, you might encounter problems with some things in this article.) An Intel Galileo (Gen 2) development board with its power adapter. A USB-to-TTL serial UART converter cable; the suggested cable is TTL-232R-3V3 to connect to the Intel Galileo Gen 2 board and your host system. You can see an example of a USB-to-TTL serial UART cable at http://www.amazon.com/GearMo%C2%AE-3-3v-Header-like-TTL-232R-3V3/dp/B004LBXO2A. If you are going to use Intel Galileo Gen 1, you will need a 3.5 mm jack-to-UART cable. You can see the mentioned cable at http://www.amazon.com/Intel-Galileo-Gen-Serial-cable/dp/B00O170JKY/. An Ethernet cable connected to your modem or switch in order to connect Intel Galileo to the local network of your workplace. A microSD card. Intel Galileo supports microSD cards up to 32 GB storage. Introducing Intel Galileo The Intel Galileo board is the first in a line of Arduino-certified development boards based on Intel x86 architecture. It is designed to be hardware and software pin-compatible with Arduino shields designed for the UNOR3. Arduino is an open source physical computing platform based on a simple microcontroller board, and it is a development environment for writing software for the board. Arduino can be used to develop interactive objects, by taking inputs from a variety of switches or sensors and controlling a variety of lights, motors, and other physical outputs. The Intel Galileo board is based on the Intel Quark X1000 SoC, a 32-bit Intel Pentium processor-class system on a chip (SoC). In addition to Arduino compatible I/O pins, Intel Galileo inherited mini PCI Express slots, a 10/100 Mbps Ethernet RJ45 port, USB 2.0 host, and client I/O ports from the PC world. The Intel Galileo Gen 1 USB host is a micro USB slot. In order to use a generation 1 USB host with USB 2.0 cables, you will need an OTG (On-the-go) cable. You can see an example cable at http://www.amazon.com/Cable-Matters-2-Pack-Micro-USB-Adapter/dp/B00GM0OZ4O. Another good feature of the Intel Galileo board is that it has open source hardware designed together with its software. Hardware design schematics and the bill of materials (BOM) are distributed on the Intel website. Intel Galileo runs on a custom embedded Linux operating system, and its firmware, bootloader, as well as kernel source code can be downloaded from https://downloadcenter.intel.com/Detail_Desc.aspx?DwnldID=23171. Another helpful URL to identify, locate, and ask questions about the latest changes in the software and hardware is the open source community at https://communities.intel.com/community/makers. Intel delivered two versions of the Intel Galileo development board called Gen 1 and Gen 2. At the moment, only Gen 2 versions are available. There are some hardware changes in Gen 2, as compared to Gen 1. You can see both versions in the following image: The first board (on the left-hand side) is the Intel Galileo Gen 1 version and the second one (on the right-hand side) is Intel Galileo Gen 2. Using Intel Galileo for home automation As mentioned in the previous section, Intel Galileo supports various sets of I/O peripherals. Arduino sensor shields and USB and mini PCI-E devices can be used to develop and create applications. Intel Galileo can be expanded with the help of I/O peripherals, so we can manage the sensors needed to automate our home. When we take a look at the existing home automation modules in the market, we can see that preconfigured hubs or gateways manage these modules to automate homes. A hub or a gateway is programmed to send and receive data to/from home automation devices. Similarly, with the help of a Linux operating system running on Intel Galileo and the support of multiple I/O ports on the board, we will be able to manage home automation devices. We will implement new applications or will port existing Linux applications to connect home automation devices. Connecting to the devices will enable us to collect data as well as receive and send commands to these devices. Being able to send and receive commands to and from these devices will make Intel Galileo a gateway or a hub for home automation. It is also possible to develop simple home automation devices with the help of the existing sensors. Pinout helps us to connect sensors on the board and read/write data to sensors and come up with a device. Finally, the power of open source and Linux on Intel Galileo will enable you to reuse the developed libraries for your projects. It can also be used to run existing open source projects on technologies such as Node.js and Python on the board together with our C application. This will help you to add more features and extend the board's capability, for example, serving a web user interface easily from Intel Galileo with Node.js. Intel Galileo – hardware specifications The Intel Galileo board is an open source hardware design. The schematics, Cadence Allegro board files, and BOM can be downloaded from the Intel Galileo web page. In this section, we will just take a look at some key hardware features for feature references to understand the hardware capability of Intel Galileo in order to make better decisions on software design. Intel Galileo is an embedded system with the required RAM and flash storages included on the board to boot it and run without any additional hardware. The following table shows the features of Intel Galileo: Processor features 1 Core 32-bit Intel Pentium processor-compatible ISA Intel Quark SoC X1000 400 MHz 16 KB L1 Cache 512 KB SRAM Integrated real-time clock (RTC) Storage 8 MB NOR Flash for firmware and bootloader 256 MB DDR3; 800 MT/s SD card, up to 32 GB 8 KB EEPROM Power 7 V to 15 V Power over Ethernet (PoE) requires you to install the PoE module Ports and connectors USB 2.0 host (standard type A), client (micro USB type B) RJ45 Ethernet 10-pin JTAG for debugging 6-pin UART 6-pin ICSP 1 mini-PCI Express slot 1 SDIO Arduino compatible headers 20 digital I/O pins 6 analog inputs 6 PWMs with 12-bit resolution 1 SPI master 2 UARTs (one shared with the console UART) 1 I2C master Intel Galileo – software specifications Intel delivers prebuilt images and binaries along with its board support package (BSP) to download the source code and build all related software with your development system. The running operating system on Intel Galileo is Linux; sometimes, it is called Yocto Linux because of the Linux filesystem, cross-compiled toolchain, and kernel images created by the Yocto Project's build mechanism. The Yocto Project is an open source collaboration project that provides templates, tools, and methods to help you create custom Linux-based systems for embedded products, regardless of the hardware architecture. The following diagram shows the layers of the Intel Galileo development board: Intel Galileo is an embedded Linux product; this means you need to compile your software on your development machine with the help of a cross-compiled toolchain or software development kit (SDK). A cross-compiled toolchain/SDK can be created using the Yocto project; we will go over the instructions in the following sections. The toolchain includes the necessary compiler and linker for Intel Galileo to compile and build C/C++ applications for the Intel Galileo board. The binary created on your host with the Intel Galileo SDK will not work on the host machine since it is created for a different architecture. With the help of the C/C++ APIs and libraries provided with the Intel Galileo SDK, you can build any C/C++ native application for Intel Galileo as well as port any existing native application (without a graphical user interface) to run on Intel Galileo. Intel Galileo doesn't have a graphical processor unit. You can still use OpenCV-like libraries, but the performance of matrix operations is so poor on CPU compared to systems with GPU that it is not wise to perform complex image processing on Intel Galileo. Connecting and booting Intel Galileo We can now proceed to power up Intel Galileo and connect it to its terminal. Before going forward with the board connection, you need to install a modem control program to your host system in order to connect Intel Galileo from its UART interface with minicom. Minicom is a text-based modem control and terminal emulation program for Unix-like operating systems. If you are not comfortable with text-based applications, you can use graphical serial terminals such as CuteCom or GtkTerm. To start with Intel Galileo, perform the following steps: Install minicom: $ sudo apt-get install minicom Attach the USB of your 6-pin TTL cable and start minicom for the first time with the –s option: $ sudo minicom –s Before going into the setup details, check the device is connected to your host. In our case, the serial device is /dev/ttyUSB0 on our host system. You can check it from your host's device messages (dmesg) to see the connected USB. When you start minicom with the –s option, it will prompt you. From minicom's Configuration menu, select Serial port setup to set the values, as follows: After setting up the serial device, select Exit to go to the terminal. This will prompt you with the booting sequence and launch the Linux console when the Intel Galileo serial device is connected and powered up. Next, complete connections on Intel Galileo. Connect the TTL-232R cable to your Intel Galileo board's UART pins. UART pins are just next to the Ethernet port. Make sure that you have connected the cables correctly. The black-colored cable on TTL is the ground connection. It is written on TTL pins which one is ground on Intel Galileo. We are ready to power up Intel Galileo. After you plug the power cable into the board, you will see the Intel Galileo board's boot sequence on the terminal. When the booting process is completed, it will prompt you to log in; log in with the root user, where no password is needed. The final prompt will be as follows; we are in the Intel Galileo Linux console, where you can just use basic Linux commands that already exist on the board to discover the Intel Galileo filesystem: Poky 9.0.2 (Yocto Project 1.4 Reference Distro) 1.4.2   clanton clanton login: root root@clanton:~# Your board will now look like the following image: Connecting to Intel Galileo via Telnet If you have connected Intel Galileo to a local network with an Ethernet cable, you can use Telnet to connect it without using a serial connection, after performing some simple steps: Run the following commands on the Intel Galileo terminal: root@clanton:~# ifup eth0 root@clanton:~# ifconfig root@clanton:~# telnetd The ifup command brings the Ethernet interface up, and the second command starts the Telnet daemon. You can check the assigned IP address with the ifconfig command. From your host system, run the following command with your Intel Galileo board's IP address to start a Telnet session with Intel Galileo: $ telnet 192.168.2.168 Summary In this article, we learned how to use the Intel Galileo development board, its software, and system development environment. It takes some time to get used to all the tools if you are not used to them. A little practice with Eclipse is very helpful to build applications and make remote connections or to write simple applications on the host console with a terminal and build them. Let's go through all the points we have covered in this article. First, we read some general information about Intel Galileo and why we chose Intel Galileo, with some good reasons being Linux and the existing I/O ports on the board. Then, we saw some more details about Intel Galileo's hardware and software specifications and understood how to work with them. I believe understanding the internal working of Intel Galileo in building a Linux image and a kernel is a good practice, leading us to customize and run more tools on Intel Galileo. Finally, we learned how to develop applications for Intel Galileo. First, we built an SDK and set up the development environment. There were more instructions about how to deploy the applications on Intel Galileo over a local network as well. Then, we finished up by configuring the Eclipse IDE to quicken the development process for future development. In the next article, we will learn about home automation concepts and technologies. Resources for Article: Further resources on this subject: Hardware configuration [article] Our First Project – A Basic Thermometer [article] Pulse width modulator [article]
Read more
  • 0
  • 0
  • 4254

article-image-central-air-and-heating-thermostat
Packt
03 Mar 2015
15 min read
Save for later

Central Air and Heating Thermostat

Packt
03 Mar 2015
15 min read
In this article by Andrew K. Dennis, author of the book Raspberry Pi Home Automation with Arduino Second Edition, you will learn how to build a thermostat device using an Arduino. You will also learn how to use the temperature data to switch relays on and off. Relays are the main components that you can use for interaction between your Arduino and high-voltage electronic devices. The thermostat will also provide a web interface so that you can connect to it and check out the temperature. (For more resources related to this topic, see here.) Introducing the thermostat A thermostat is a control device that is used to manipulate other devices based on a temperature setting. This temperature setting is known as the setpoint. When the temperature changes in relation to the setpoint, a device can be switched on or off. For example, let's imagine a system where a simple thermostat is set to switch an electric heater on when the temperature drops below 25 degrees Celsius. Within our thermostat, we have a temperature-sensing device such as a thermistor that returns a temperature reading every few seconds. When the thermistor reads a temperature below the setpoint (25 degrees Celsius), the thermostat will switch a relay on, completing the circuit between the wall plug and our electric heater and providing it with power. Thus, we can see that a simple electronic thermostat can be used to switch on a variety of devices. Warren S. Johnson, a college professor in Wisconsin, is credited with inventing the electric room thermostat in the 1880s. Johnson was known throughout his lifetime as a prolific inventor who worked in a variety of fields, including electricity. These electric room thermostats became a common feature in homes across the course of the twentieth century as larger parts of the world were hooked up the electricity grid. Now, with open hardware electronic tools such as the Arduino available, we can build custom thermostats for a variety of home projects. They can be used to control baseboard heaters, heat lamps, and air conditioner units. They can also be used for the following: Fish tank heaters Indoor gardens Electric heaters Fans Now that we have explored the uses of thermostats, let's take a look at our project. Setting up our hardware In the following examples, we will list the pins to which you need to connect your hardware. However, we recommend that when you purchase any device such as the Ethernet shield, you check whether certain pins are available or not. Due to the sheer range of hardware available, it is not possible to list every potential hardware combination. Therefore, if the pin in the example is not free, you can update the circuit and source code to use a different pin. When building the example, we also recommend using a breadboard. This will allow you to experiment with building your circuit without having to solder any components. Our first task will be to set up our thermostat device so that it has Ethernet access. Adding the Ethernet shield The Arduino Uno does not contain an Ethernet port. Therefore, you will need a way for your thermostat to be accessible on your home network. One simple solution is to purchase an Ethernet shield and connect it to your microcontroller. There are several shields in the market, including the Arduino Ethernet shield (http://arduino.cc/en/Main/ArduinoEthernetShield) and Seeed Ethernet shield (http://www.seeedstudio.com/wiki/Ethernet_Shield_V1.0). These shields are plugged into the GPIO pins on the Arduino. If you purchase one of these shields, then we would also recommend buying some extra GPIO headers. These are plugged into the existing headers attached to the Ethernet shield. Their purpose is to provide some extra clearance above the Ethernet port on the board so that you can connect other shields in future if you decide to purchase them. Take a board of your choice and attach it to the Arduino Uno. When you plug the USB cable into your microcontroller and into your computer, the lights on both the Uno and Ethernet shield should light up. Now our device has a medium to send and receive data over a LAN. Let's take a look at setting up our thermostat relays. Relays A relay is a type of switch controlled by an electromagnet. It allows us to use a small amount of power to control a much larger amount, for example, using a 9V power supply to switch 220V wall power. Relays are rated to work with different voltages and currents. A relay has three contact points: Normally Open, Common Connection, and Normally Closed. Two of these points will be wired up to our fan. In the context of an Arduino project, the relay will also have a pin for ground, 5V power and a data pin that is used to switch the relay on and off. A popular choice for a relay is the Pololu Basic SPDT Relay Carrier. This can be purchased from http://www.pololu.com/category/135/relay-modules. This relay has featured in some other Packt Publishing books on the Arduino, so it is a good investment. Once you have the relay, you need to wire it up to the microcontroller. Connect a wire from the relay to digital pin 5 on the Arduino, another wire to the GRD pin, and the final wire to the 5V pin. This completes the relay setup. In order to control relays though, we need some data to trigger switching them between on and off. Our thermistor device handles the task of collecting this data. Connecting the thermistor A thermistor is an electronic component that, when included in a circuit, can be used to measure temperature. The device is a type of resistor that has the property whereby its resistance varies as the temperature changes. It can be found in a variety of devices, including thermostats and electronic thermometers. There are two categories of thermistors available: Negative Thermistor Coefficient (NTC) and Positive Thermistor Coefficient (PTC). The difference between them is that as the temperature increases, the resistance decreases in the case of an NTC, and on the other hand, it increases in the case of a PTC. We are going to use a prebuilt digital device with the model number AM2303. This can be purchased at https://www.adafruit.com/products/393. This device reads both temperature and humidity. It also comes with a software library that you can use in your Arduino sketches. One of the benefits of this library is that many functions that precompute values, such as temperature in Celsius, are available and thus don't require you to write a lot of code. Take your AM203 and connect it to the GRD pin, 5V pin and digital pin 4. The following diagram shows how it should be set up: You are now ready to move on to creating the software to test for temperature readings. Setting up our software We now need to write an application in the Arduino IDE to control our new thermostat device. Our software will contain the following: The code responsible for collecting the temperature data Methods to switch relays on and off based on this data Code to handle accepting incoming HTTP requests so that we can view our thermostat's current temperature reading and change the setpoint A method to send our temperature readings to the Raspberry Pi The next step is to hook up our Arduino thermostat with the USB port of the device we installed the IDE on. You may need to temporarily disconnect your relay from the Arduino. This will prevent your thermostat device from drawing too much power from your computer's USB port, which may result in the port being disabled. We now need to download the DHT library that interacts with our AM2303. This can be found on GitHub, at https://github.com/adafruit/DHT-sensor-library. Click on the Download ZIP link and unzip the file to a location on your hard drive. Next, we need to install the library to make it accessible from our sketch: Open the Arduino IDE. Navigate to Sketch | Import Library. Next, click on Add library. Choose the folder on your hard drive. You can now use the library. With the library installed, we can include it in our sketch and access a number of useful functions. Let's now start creating our software. Thermostat software We can start adding some code to the Arduino to control our thermostat. Open a new sketch in the Arduino IDE and perform the following steps: Inside the sketch, we are going to start by adding the code to include the libraries we need to use. At the top of the sketch, add the following code: #include "DHT.h" // Include this if using the AM2302 #include <SPI.h> #include <Ethernet.h> Next, we will declare some variables to be used by our application. These will be responsible for defining:     The pin the AM2303 thermistor is located on     The relay pin     The IP address we want our Arduino to use, which should be unique     The Mac address of the Arduino, which should also be unique     The name of the room the thermostat is located in     The variables responsible for Ethernet communication The IP address will depend on your own home network. Check out your wireless router to see what range of IP addresses is available. Select an address that isn't in use and update the IPAddress variable as follows: #define DHTPIN 4 // The digital pin to read from #define DHTTYPE DHT22 // DHT 22 (AM2302)   unsigned char relay = 5; //The relay pins String room = "library"; byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; IPAddress ip(192,168,3,5); DHT dht(DHTPIN, DHTTYPE); EthernetServer server(80); EthernetClient client; We can now include the setup() function. This is responsible for initializing some variables with their default values, and setting the pin to which our relay is connected to output mode: void setup() {   Serial.begin(9600);   Ethernet.begin(mac, ip);   server.begin();   dht.begin();   pinMode(relay, OUTPUT); } The next block of code we will add is the loop() function. This contains the main body of our program to be executed. Here, we will assign a value to the setpoint and grab our temperature readings: void loop() {   int setpoint = 25;   float h = dht.readHumidity();   float t = dht.readTemperature(); Following this, we check whether the temperature is above or below the setpoint and switch the relay on or off as needed. Paste this code below the variables you just added: if(t <setpoint) {   digitalWrite(relay,HIGH); } else {   digitalWrite(relay,LOW); } Next, we need to handle the HTTP requests to the thermostat. We start by collecting all of the incoming data. The following code also goes inside the loop() function: client = server.available(); if (client) {   // an http request ends with a blank line   booleancurrentLineIsBlank = true;   String result;   while (client.connected()) {     if (client.available()) {       char c = client.read();       result= result + c;     } With the incoming request stored in the result variable, we can examine the HTTP header to know whether we are requesting an HTML page or a JSON object. You'll learn more about JavaScript Object Notation (JSON) shortly. If we request an HTML page, this is displayed in the browser. Next, add the following code to your sketch: if(result.indexOf("text/html") > -1) {   client.println("HTTP/1.1 200 OK");   client.println("Content-Type: text/html");   client.println();   if (isnan(h) || isnan(t)) {     client.println("Failed to read from DHT sensor!");     return;   }   client.print("<b>Thermostat</b> set to: ");   client.print(setpoint);    client.print("degrees C <br />Humidity: ");   client.print(h);   client.print(" %t");   client.print("<br />Temperature: ");   client.print(t);   client.println(" degrees C ");   break; } The following code handles a request for the data to be returned in JSON format. Our Raspberry Pi will make HTTP requests to the Arduino, and then process the data returned to it. At the bottom of this last block of code is a statement adding a short delay to allow the Arduino to process the request and close the client connection. Paste this final section of code in your sketch: if( result.indexOf("application/json") > -1 ) { client.println("HTTP/1.1 200 OK"); client.println("Content-Type: application/json;charset=utf-8"); client.println("Server: Arduino"); client.println("Connnection: close"); client.println(); client.print("{"thermostat":[{"location":""); client.print(room); client.print(""},"); client.print("{"temperature":""); client.print(t); client.print(""},"); client.print("{"humidity":""); client.print(h); client.print(""},"); client.print("{"setpoint":""); client.print(setpoint); client.print(""}"); client.print("]}"); client.println(); break;           }     } delay(1); client.stop();   }  } This completes our program. We can now save it and run the Verify process. Click on the small check mark in a circle located in the top-left corner of the sketch. If you have added all of the code correctly, you should see Binary sketch size: 16,962 bytes (of a 32,256 byte maximum). Now that our code is verified and saved, we can look at uploading it to the Arduino, attaching the fan, and testing our thermostat. Testing our thermostat and fan We have our hardware set up and the code ready. Now we can test the thermostat and see it in action with a device connected to the mains electricity. We will first attach a fan and then run the sketch to switch it on and off. Attaching the fan Ensure that your Arduino is powered down and that the fan is not plugged into the wall. Using a wire stripper and cutters, cut one side of the cable that connects the plug to the fan body. Take the end of the cable attached to the plug, and attach it to the NO point on the relay. Use a screwdriver to ensure that it is fastened correctly. Now, take the other portion of the cut cable that is attached to the fan body, and attach this to the COM point. Once again, use a screwdriver to ensure that it is fastened securely to the relay. Your connection should look as follows: You can now reattach your Arduino to the computer via its USB cable. However, do not plug the fan into the wall yet. Starting your thermostat application With the fan connected to our relay, we can upload our sketch and test it: From the Arudino IDE, select the upload icon. Once the code has been uploaded, disconnect your Arduino board. Next, connect an Ethernet cable to your Arduino. Following this, plug the Arduino into the wall to get mains power. Finally, connect the fan to the wall outlet. You should hear the clicking sound of the relay as it switches on or off depending on the room temperature. When the relay switch is on (or off), the fan will follow suit. Using a separate laptop if you have it, or from your Raspberry Pi, access the IP address you specified in the application via a web browser, for example, http://192.168.3.5/. You should see something similar to this: Thermostat set to: 25degrees C  Humidity: 35.70 % Temperature: 14.90 degrees C You can now stimulate the thermistor using an ice cube and hair dryer, to switch the relay on and off, and the fan will follow suit. If you refresh your connection to the IP address, you should see the change in the temperature output on the screen. You can use the F5 key to do this. Let's now test the JSON response. Testing the JSON response A format useful in transferring data between applications is JavaScript Object Notation (JSON). You can read more about this on the official JSON website, at http://www.json.org/. The purpose of us generating data in JSON format is to allow the Raspberry Pi control device we are building to query the thermostat periodically and collect the data being generated. We can verify that we are getting JSON data back from the sketch by making an HTTP request using the application/json header. Load a web browser such as Google Chrome or FireFox. We are going to make an XML HTTP request directly from the browser to our thermostat. This type of request is commonly known as an Asynchronous JavaScript and XML (AJAX) request. It can be used to refresh data on a page without having to actually reload it. In your web browser, locate and open the developer tools. The following link lists the location and shortcut keys in major browsers: http://webmasters.stackexchange.com/questions/8525/how-to-open-the-javascript-console-in-different-browsers In the JavaScript console portion of the developer tools, type the following JavaScript code: var xmlhttp; xmlhttp=new XMLHttpRequest(); xmlhttp.open("POST","192.168.3.5",true); xmlhttp.setRequestHeader("Content-type","application/json"); xmlhttp.onreadystatechange = function() {//Call a function when the state changes.    if(xmlhttp.readyState == 4 &&xmlhttp.status == 200) {          console.log(xmlhttp);    } }; xmlhttp.send() Press the return key or run option to execute the code. This will fire an HTTP request, and you should see a JSON object return: "{"thermostat":     [      {"location":"library"},      {"temperature":"14.90"},      {"humidity":"29.90"},      {"setpoint":"25"}   ] }" This confirms that our application can return data to the Raspberry Pi. We have tested our software and hardware and seen that they are working. Summary In this article, we built a thermostat device. We looked at thermistors, and we learned how to set up an Ethernet connection. To control our thermostat, we wrote an Arduino sketch, uploaded it to the microcontroller, and then tested it with a fan plugged into the mains electricity. Resources for Article: Further resources on this subject: The Raspberry Pi and Raspbian? [article] Clusters Parallel Computing and Raspberry Pi Brief Background [article] The Arduino Mobile Robot [article]
Read more
  • 0
  • 0
  • 2864

article-image-hardware-configuration
Packt
21 Jul 2014
2 min read
Save for later

Hardware configuration

Packt
21 Jul 2014
2 min read
The hardware configuration of this project is not really complex. For each motion sensor module you want to build, you'll need to do the following steps. The first one is to plug an XBee module on the XBee shield. Then, you need to plug the shield into your Arduino board, as shown in the following image: Now, you can connect the motion sensor. It has three pins: VCC (for the positive power supply), GND (which corresponds to the reference voltage level), and SIG (which will turn to a digital HIGH state in case any motion is detected). Connect VCC to the Arduino 5V pin, GND to Arduino GND, and SIG to Arduino pin number 8 (the example code uses pin 8, but you could also use any digital pin). You should end up with something similar to this image: You will also need to set a jumper correctly on the board so we can upload a sketch. On the XBee shield, you have a little switch close to the XBee module to choose between the XBee module being connected directly to the Arduino board serial interface (which means you can't upload any sketches anymore) or leaving it disconnected. As we need to upload the Arduino sketch first, you need to put this switch to DLINE, as shown in this image: You will also need to connect the XBee explorer board to your computer at this point. Simply insert one XBee module to the board as shown in the following image: Now that this is done, you can power up everything by connecting the Arduino board and explorer module to your computer via USB cables. If you want to use several XBee motion sensors, you will need to repeat the beginning of the procedure for each of them: assemble one Arduino board with an XBee shield, one XBee module, and one motion sensor. However, you only need one USB XBee module connected to your computer if you have many sensors. Summary In this article, we learned about the hardware configuration required to build wireless XBee motion detectors. We looked at Arduino R3 board, XBee module, and XBee shield and the other important hardware configuration. Resources for Article: Further resources on this subject: Playing with Max 6 Framework [Article] Our First Project – A Basic Thermometer [Article] Sending Data to Google Docs [Article]
Read more
  • 0
  • 0
  • 1939

article-image-pulse-width-modulator
Packt
19 Dec 2013
4 min read
Save for later

Pulse width modulator

Packt
19 Dec 2013
4 min read
(For more resources related to this topic, see here.) PWM allows us to drive a certain pin to on and off at desired frequency and duty cycle. This way we can pulse our LEDs much faster than our eyes can react, and while we only see a dimmer or a brighter LED, if one would look at it with a high speed camera, one would see that the LED still only turns on or off. Our eyes just perceive this differently. There are three basic terms you need to understand about PWM: Frequency: This defines how many full on/off "cycles" are generated in a second Period: This defines how long one complete pulse cycle takes Duty cycle: This specifies the time the signal is high during one full period Think about the following figure: In the preceding figure, we have PWM generating first a 50 percent duty cycle and then dropping to 25 percent. The effective time the LED spends as on and off can be controlled with very high precision, and this way we can achieve smooth brightness fluctuations. Let's try doing just that. First, we will design a schematic with two LEDs that are connected to two different PWMs. Nothing fancy here either really, we have a current limiting resistor after the LEDs and that's it. This time we will be using input from both headers, as PWM1 and PWM2 are located on P9 and P8, respectively. Our third and last program in this article will be called racing_PWMs.py. As usual, we need to include the Adafruit library here as well, this time the PWM part of it: import Adafruit_BBIO.PWM as PWM When you initialize a PWM, you can initialize it with two to four parameters listed as follows: Channel (header pin) Duty (as in percent, 0-100) Frequency (periods in a second, default is 2000) And polarity (0 or 1. With this you can invert the duty cycle, default is 0) So, we will initialize both our channels: PWM.start("P9_14", 50, 100) #50% duty and 100hz cycle PWM.start("P8_13", 50, 100) At this point, the LEDs will light up, and now we can start changing our duty cycle in a loop to adjust the average voltage. Full listing of racing_PWMs.py is as follows: #!/usr/bin/python import time import Adafruit_BBIO.PWM as PWM sleep_time=0.005 #The lower the value the faster the activity PWM.start("P9_14", 50, 100) #50% duty and 100hz cycle PWM.start("P8_13", 50, 100) while True: for i in range(100,1, -1): PWM.set_duty_cycle("P9_14", i) # Dimming PWM.set_duty_cycle("P8_13", abs(i-100)+1) # Getting brighter time.sleep(sleep_time) for i in range(1, 100): PWM.set_duty_cycle("P9_14", i) PWM.set_duty_cycle("P8_13", abs(i-100)+1 ) time.sleep(sleep_time) When you run the program, you should see both LEDs racing (blinking) in opposite phases. As you see, the Adafruit BBIO library is extremely useful and easy to use. And so far we have only used two functionalities it provides. Actually, the library also supports easy access to SPI and I2C communication and Analog to Digital Converter(ADC) as well. Summary In this article we went through foundations of input and output on a very basic level. We talked about the general purpose I/O pins, and how they can be used to control external components, such as LEDs or buttons. As you must have gathered already, with proper application of voltage and care, we can operate many of the basic electronic components. You should now feel comfortable with the basic building blocks that can help you build some external inputs and outputs to your Beagle programs. Resources for Article: Further resources on this subject: Home Security by BeagleBone [Article] Introducing BeagleBoard [Article] Viewing on Mobile Devices [Article]
Read more
  • 0
  • 0
  • 2244
Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at $19.99/month. Cancel anytime
article-image-get-connected-bluetooth-basics
Packt
11 Sep 2013
15 min read
Save for later

Get Connected – Bluetooth Basics

Packt
11 Sep 2013
15 min read
(For more resources related to this topic, see here.) Why Bluetooth? There are other forms of wireless communication that we could use, like infrared and Wi-Fi, but Bluetooth is perfect for many household projects. It is cheap, very easy to set up, will typically use less power than Wi-Fi because of the shorter range, and it's very responsive. It's important to keep in mind that there isn't a single "best" form of communication. Each type will suit each project (or perhaps budget) in different ways. In terms of performance, I have found that a short message will be transmitted in under 20 milliseconds from one device to another, and the signal will work for just less than 10 meters (30 feet). These numbers, however, will vary based on your environment. Things you need The things required for this project are as follows: Netduino Breadboard Bluetooth module Windows Phone 8 Lots of different Bluetooth modules exist, but I have found that the JY-MCU is very cheap (around $10) and reliable. Any Windows Phone 8 device can be used, as they all have Bluetooth. The project setup The setup for this project is extremely basic because we are just connecting the Bluetooth module and nothing else. Once our phone is connected we will use it to control the onboard LED, however, you can expand this to control anything else too. The Bluetooth module you buy may look slightly different to the diagram, but not to worry, just make sure you match up the labels on the Bluetooth module (GND, 3-3V or VCC, TX, and RX) to the diagram. If you encounter a situation where everything is hooked up right but no data is flowing, examine the minimum baud rate in your Bluetooth module's manual or specifications sheet. It has been reported that some Bluetooth modules do not work well communicating at 9600 baud. This can be easily remedied by setting the baud rate in your SerialPort's constructor to 115200. For example, SerialPort(new SerialPort(SerialPorts.COM1, 115200, Parity.None, 8, StopBits.One). Once it is wired up, we can get onto the coding. First we will do the Netduino part. The Netduino will listen for messages over Bluetooth, and will set the brightness of the onboard LED based on the percentage it receives. The Netduino will also listen for "ping", and if it receives this then it will send the same text back to the other device. We do this as an initial message to make sure that it gets from the phone to the Netduino, and then back to the phone successfully. After that we will code the phone application. The phone will connect, send a "ping", and then wait until it receives the "ping" back. When the phone receives the "ping" back then it can start sending messages. In this article only Windows Phone 8 will be covered, however, the same concepts apply, and it won't be too hard to code the equivalent app for another platform. The Netduino code will remain the same no matter what device you connect to. Coding Because we will be using a phone to connect to the Netduino, there are two distinct parts which need to be coded. The Netduino code Open up Visual Studio and create a new Netduino Plus 2 Application. Add a reference to SecretLabs.NETMF.Hardware.PWM. Open Program.cs from the Solution Explorer. You need to add the following using statements at the top: using System.IO.Ports;using System.Text;using NPWM = SecretLabs.NETMF.Hardware.PWM; You need to get the phone paired with the Bluetooth module on the Netduino. So in Program.cs, replace the Main method with this: private static SerialPort _bt;public static void Main(){_bt = new SerialPort(SerialPorts.COM1, 9600,Parity.None, 8, StopBits.One);_bt.Open();while (true){Thread.Sleep(Timeout.Infinite);}} This code creates a new instance of a SerialPort (the Bluetooth module), then opens it, and finally has a loop (which will just pause forever). Plug in your Netduino and run the code. Give it a few seconds until the blue light goes off—at this point the Bluetooth module should have a flashing red LED. On your Windows Phone, go to Settings | Bluetooth and make sure that it is turned on. In the list of devices there should be one which is the Bluetooth module (mine is called "linvor") so tap it to connect. If it asks for a pin try the default of "1234", or check the data sheet. As it connects, the red LED on the Bluetooth module will go solid, meaning that it is connected. It will automatically disconnect in 10 seconds; that's fine. Now that you've checked that it connects correctly, start adding in the real code: private static SerialPort _bt;private static NPWM _led;private static string _buffer;public static void Main(){_led = new NPWM(Pins.ONBOARD_LED);_bt = new SerialPort(SerialPorts.COM1, 9600,Parity.None, 8, StopBits.One);_bt.DataReceived += new SerialDataReceivedEventHandler(rec_DataReceived);_bt.Open();while (true){Thread.Sleep(Timeout.Infinite);}} This is close to the code you replaced but also creates an instance of the onboard LED, and declares a string to use as a buffer for the received data. Next you need to create the event handler that will be fired when data is received. Something that can easily trip you up is thinking that each message will come through as a whole. That's incorrect. So if you send a "ping" from your phone, it will usually come through in two separate messages of "p" and "ing". The simplest way to work around that is to just have a delimiter that marks the end of a message (in the same way as military personnel end radio communications by saying "10-4"). So send the message as "ping|" with a pipe at the end. This code for the DataReceived event handler builds up a buffer until it finds a pipe (|), then processes the message, then resets the buffer (or sets it to whatever is after the pipe, which will be the first part of the next message): private static void rec_DataReceived(object sender,SerialDataReceivedEventArgs e){byte[] bytes = new byte[_bt.BytesToRead];_bt.Read(bytes, 0, bytes.Length);char[] converted = new char[bytes.Length];for (int b = 0; b < bytes.Length; b++){converted[b] = (char)bytes[b];}string str = new String(converted);if (str != null && str.Length > 0){if (str.IndexOf("|") > -1){_buffer += str.Substring(0, str.IndexOf("|"));ProcessReceivedString(_buffer);_buffer = str.Substring(str.LastIndexOf("|") +1);}else{_buffer += str;}}} At the start of the event handler, you create a byte array to hold the received data, then loop through that array and convert each byte to a char and put those chars into a char array. Once you have a char array, create a new string using the char array as a parameter, which will give the string representation of the array. After checking that it is not null or empty you check whether it has a pipe (meaning it contains the end of a message). If so, add all the characters up to the pipe onto the buffer and then process the buffer. If there is no pipe then just add to the buffer. The only thing that remains is the method to process the received string (the buffer) and a method to send messages back to the phone. So put these methods below the event handler that you just added: private static void ProcessReceivedString(string _buffer){if (_buffer == "ping"){Write(_buffer);}else{uint val = UInt32.Parse(_buffer);_led.SetDutyCycle(val);}}private static void Write(string message){byte[] bytes = Encoding.UTF8.GetBytes(message + "|");_bt.Write(bytes, 0, bytes.Length);} As mentioned before, if you receive a "ping" then just send it back, or alternatively convert the string into an unsigned integer and set the brightness of the onboard LED. The last method simply adds a pipe to the end of the string, converts it to a byte array, then writes it to the Bluetooth SerialPort to send to the phone. At this point, you should run the code on the Netduino, but keep in mind that the same thing as before will happen because we are not sending it any data yet. So next up, we need to make the phone application that helps us send messages to the Netduino. The phone code As mentioned, we will be using a Windows Phone 8 device to connect to the Netduino. The same principles demonstrated in this section will apply to any platform, and it all revolves around just knowing how to read and write the Bluetooth data. You may notice that much of the phone code resembles the Netduino code—this is because both are merely sending and receiving messages. Before moving on, you will need the Windows Phone 8 SDK installed. Download and install it from here: http://developer.windowsphone.com You may need to close any copies of Visual Studio that are open. Once it is installed you can go ahead and open the Netduino project (from the previous section) again, then follow these steps: We could create the phone project in the same solution as the Netduino project, but in terms of debugging, it's easier to have them in separate instances of Visual Studio. So open up another copy of Visual Studio and click on File | New | Project. Find the Windows Phone App template by navigating to Installed | Templates | Visual C# | Windows Phone. Name the project and then click on OK to create it. A dialog may appear asking you to choose which version of the OS you would like to target. Make sure that Windows Phone OS 8.0 is selected (Windows Phone 7.1 does not have the required APIs for third party developers). When creating a new Windows Phone application, MainPage.xaml will automatically be displayed. This is the first page of the app that the user will see when they run your app. XAML is the layout language used on Windows Phone, and if you've ever used HTML then you will be quite at home. In the XAML window, scroll down until you find the grid named ContentPanel. Replace it with: <Grid x_Name="ContentPanel" Grid.Row="1"Margin="12,0,12,0"><Slider IsEnabled="False" Minimum="0" Maximum="100"x:Name="slider" ValueChanged="slider_ValueChanged"/></Grid> This will add a Slider control to the page with the value at the far left being 0 and the far right being 100—essentially a percent. Whenever the user drags the slider, it will fire the ValueChanged event handler, which you will add soon. That is the only UI change you need to make. So in the Solution Explorer, right-click on MainPage.xaml | View Code. Add these Using statements to the top: using Windows.Storage.Streams;using System.Text;using Windows.Networking.Sockets;using Windows.Networking.Proximity;using System.Runtime.InteropServices.WindowsRuntime; We need to declare some variables, so replace the MainPage constructor with this: StreamSocket _socket;string _receivedBuffer = "";bool _isConnected = false;public MainPage(){InitializeComponent();TryConnect();}private void slider_ValueChanged(object sender,RoutedPropertyChangedEventArgs<double> e){if (_isConnected){Write(((int)slider.Value).ToString());}}async private void Write(string str){var dataBuffer = GetBufferFromByteArray(Encoding.UTF8.GetBytes(str + "|"));await _socket.OutputStream.WriteAsync(dataBuffer);}private IBuffer GetBufferFromByteArray(byte[] package){using (DataWriter dw = new DataWriter()){dw.WriteBytes(package);return dw.DetachBuffer();}} The StreamSocket is essentially a way to interact with the phone's Bluetooth chip, which will be used in multiple methods in the app. When the slider's value changes, we check that the phone is connected to the Netduino, and then use the Write method to send the value. The Write method is similar to the one we made on the Netduino, except it requires a few lines extra to convert the byte array into an IBuffer. In the previous step, you might have noticed that we ran a method called TryConnect in the MainPage constructor. As you may have guessed, in this method we will try to connect to the Netduino. Add this method below the ones you added previously: private async void TryConnect(){PeerFinder.AlternateIdentities["Bluetooth:Paired"] ="";var pairedDevices = await PeerFinder.FindAllPeersAsync();if (pairedDevices.Count == 0){MessageBox.Show("Make sure you pair the devicefirst.");}else{SystemTray.SetProgressIndicator(this,new ProgressIndicator { IsIndeterminate = true,Text = "Connecting", IsVisible = true });PeerInformation selectedDevice = pairedDevices[0];_socket = new StreamSocket();await _socket.ConnectAsync(selectedDevice.HostName, "1");WaitForData(_socket);Write("ping");}} We first get a list of all devices that have been paired with the phone (even if they are not currently connected), and display an error message if there are no devices. If it does find one or more devices, then we display a progress bar at the top of the screen (in the SystemTray) and proceed to connect to the first Bluetooth device in the list. It is important to note that in the example code we are connecting to the first device in the list—in a real-world app, you would display the list to the user and let them decide which is the right device. After connecting, we call a method to wait for data to be received (this will happen in the background and will not block the rest of the code), and then write the initial ping message. Don't worry, we are almost there! The second last method you need to add is the one that will wait for the data to be received. It is an asynchronous method, which means that it can have a line within it that blocks execution (for instance, in the following code the line that waits for data will block the thread), but the rest of the app will carry on fine. Add in this method: async private void WaitForData(StreamSocket socket){try{byte[] bytes = new byte[5];await socket.InputStream.ReadAsync(bytes.AsBuffer(), 5, InputStreamOptions.Partial);bytes = bytes.TakeWhile((v, index) =>bytes.Skip(index).Any(w => w != 0x00)).ToArray();string str = Encoding.UTF8.GetString(bytes, 0,bytes.Length);if (str.Contains("|")){_receivedBuffer += str.Substring(0,str.IndexOf("|"));DoSomethingWithReceivedString(_receivedBuffer);_receivedBuffer = str.Substring(str.LastIndexOf("|") + 1);}else{_receivedBuffer += str;}}catch{MessageBox.Show("There was a problem");}finally{WaitForData(socket);}} Yes, this code looks complicated, but it is simple enough to understand. First we create a new byte array (the size of the array isn't too important, and you can change it to suit your application), then wait for data to come from the Netduino. Once it does, we copy all non-null bytes to our array, then convert the array to a string. From here, it is exactly like the Netduino code. The final code left to write is the part that handles the received messages. In this simple app, we don't need to check for anything except the return of the "ping". Once we receive that ping, we know it has connected successfully and we enable the slider control to let the user start using it: private void DoSomethingWithReceivedString(string buffer){if (buffer == "ping"){_isConnected = true;slider.IsEnabled = true;SystemTray.SetProgressIndicator(this, null);}} We also set the progress bar to null to hide it. Windows Phone (and other platforms) needs to explicitly define what capabilities they require for security reasons. Using Bluetooth is one such capability, so to define that we are using it, in the Solution Explorer find the Properties item below the project name. Left-click on the little arrow on the left of it to expand its children. Now double-click on WMAppManifest.xml to open it up then click the Capabilities tab near the top. The list on the left defines each specific capability. Ensure that both ID_CAP_PROXIMITY and ID_CAP_NETWORKING are checked. And that's it! Make sure your Netduino is plugged in (and running the program you made in this article), then plug your Windows Phone 8 in, and run the code. The run button may say Emulator X, you will need to change it to Device by clicking on the little down arrow on the right of the button. Once the two devices are connected, slide the slider on the phone forwards and backwards to see the onboard LED on the Netduino go brighter and dimmer. Not working? If the phone does not connect after a few seconds then something has probably gone wrong. After double-checking your wiring, the best thing to try is to unplug both the Netduino and phone, then plug them back in. If you are using a different Bluetooth board, you may have to pair it again to the phone. Repeat step 5 of the The Netduino Code section of this article. With both plugged back in, run the Netduino code (and give it a few seconds to boot up), then run the phone code. If that still doesn't work, unplug both again, and only plug back in the Netduino. When it is powered up, it will run the last application deployed to it. Then with your phone unplugged, go to the app list and find the phone app you made, and tap on it to run it. Summary You've managed to control your Netduino from afar! This article had a lot more code than most of the rest will because of needing to code both the Netduino and phone. However, the knowledge you've gained here will help you in many other projects, and we will be using this article as a base for some of the others. Resources for Article: Further resources on this subject: Automating the Audio Parameters – How it Works [Article] Ease the Chaos with Automated Patching [Article] Skype automation [Article]
Read more
  • 0
  • 0
  • 1589

article-image-our-first-project-basic-thermometer
Packt
26 Feb 2013
24 min read
Save for later

Our First Project – A Basic Thermometer

Packt
26 Feb 2013
24 min read
(For more resources related to this topic, see here.) Building a thermometer A thermometer is a device used for recording temperatures and changes in temperatures. The origins of the thermometer go back several centuries, and the device has evolved over the years. Traditional thermometers are usually glass devices that measure these changes via a substance such as mercury, which rises in the glass tube and indicates a number in Fahrenheit or Celsius. The introduction of microelectronics has allowed us to build our own digital thermometers. This can be useful for checking the temperature in parts of your house such as the garage or monitoring the temperature in rooms where it can affect the contents, for example, a wine cellar. Our thermometer will return its readings to the Raspberry Pi and display them in the terminal window. Lets start by setting up the hardware for our thermometer. Setting up our hardware There are several components that you will need to use in this article. You can solder the items to your shield if you wish or use the breadboard if you plan to use the same components for the projects in the articles that follow. Alternatively, you may have decided to purchase an all-in-one unit that combines some of the following components into a single electronic unit. We will make the assumption that you have purchased separate electronic components and will discuss the process of setting these up. We recommend that you switch Raspberry Pi off while connecting the components, especially if you plan on soldering any of the items. If your device is switched on and you accidently spill hot solder onto an unintended area of the circuit board, this can short your device, damaging it. Soldering while switched off allows you to clean up any mistakes using the de-soldering tool. An introduction to resistors Let's quickly take a look at resistors and what exactly these are. A resistor is an electronic component with two connection points (known as terminals) that can be used to reduce the amount of electrical energy passing through a point in a circuit. This reduction in energy is known as resistance. Resistance is measured in Ohms (O). You can read more about how this is calculated at the Wikipedia link http://en.wikipedia.org/wiki/Ohm's_law. You will find resistors are usually classified into two groups, fixed resistors and variable resistors. The typical types of fixed resistor you will encounter are made of carbon film with the resistance property marked in colored bands, giving you the value in Ohms. Components falling into the variable resistance group are those with resistance properties that change when some other ambient property in their environment changes. Let's now examine the two types of resistors we will be using in our circuit — a thermistor and a 10K Ohm resistor. Thermistor A thermistor is an electronic component which, when included in a circuit, can be used to measure temperature. The device is a type of resistor that has the property whereby its resistance varies as the temperature changes. It can be found in a variety of devices, including thermostats and electronic thermometers. There are two categories of thermistors available, these being Negative Thermistor Coefficient(NTC)and Positive Thermistor Coefficient(PTC). The difference between them is that as the temperature increases the resistance decreases in the case of a NTC, or increases in the case of a PTC. There are two numerical properties that we are interested in with regards to using this device in our project. These are the resistance of the thermistor at room temperature (25 degrees Celsius) and the beta coefficient of the thermistor. The coefficient can be thought of as the amount the resistance changes by as the ambient temperature around the thermistor changes. When you purchase a thermistor, you should have been provided with a datasheet that lists these two values. If you are unsure of the resistance of your thermistor, you can always check it by hooking it up to a voltage detector and taking a reading at room temperature. For example, if you bought a 10K thermistor, you should expect a reading of around 10K Ohms. For this project, we recommend purchasing a 10K thermistor. 10K Ohm resistor A 10K Ohm resistor, unlike a thermistor, is designed to have a constant resistance regardless of temperature change. This type of device falls into the fixed resistor category. You can tell the value of a resistor by the colored bands located on its body. When you purchase resistors, you may find they come with a color-coding guide, otherwise you can check the chart on Wikipedia (http://en.wikipedia.org/wiki/Electronic_color_code#Resistor_color_coding) in order to ascertain what the value is. As part of the circuit we are building, you will need the 10K resistor in order to convert the changing resistance into a voltage that the analog pin on your Raspberry Pi to Arduino can understand. Wires For this project, you will require three wires. One will attach to the 5V pin on your shield, one to the ground, and finally, one to the analog 0 pin. In the wiring guide, we will be using red, black, and yellow wires. The red will connect to 5V pin, the black to ground, and the yellow to the analog 0 pin. Breadboard Finally, in order to connect our component, we will use the breadboard as we did when connecting up the LED. Connecting our components Setting up our components for the thermometer is a fairly easy task. Once again, at this point, there is no need to attempt any soldering if you plan on re-using the components. Follow these steps in order to connect up everything in the correct layout. Take the red wire and connect it from the 5V pin on the shield to the connect point on the bus strip corresponding to the supply voltage. There are often two bus strips on a breadboard. These can be found on either of the long sides of the board and often have a blue or red strip indicating supply voltage and ground. Next take the black wire and connect it from the ground pin to the ground on the breadboard. We are now going to hook up the resistor. Connect one pin of your 10K resistor to the supply voltage strip that your red wire is connected to and take the other end and connect it to a terminal strip. Terminal strips are the name given to the area located in the middle of the breadboard where you connect your electronic components. Now that the resistor is in place, our next task will be to connect the thermistor. Insert one leg/wire of the thermistor into the ground on the bus strip, and place the second leg into the same row as you placed the resistor. The thermistor and resistor are daisy-chained together with the supply voltage. This leaves us now with the final task, which is connecting up the analog pin to our daisy chain. Finally connect one end of your yellow wire from the analog 0 (A0) on your shield to the terminal strip you selected for the preceding components. Sanity check The setup of your circuit is now complete. However, before switching on your Raspberry Pi check that you have connected up everything correctly. You can compare your setup to the following diagram: Our thermometer circuit is now complete, and you can now boot up your Raspberry Pi. Of course, without any software to return readings to the screen, the circuit is little more than a combination of electronic components! So let's get started on the software portion of our project. Software for our thermometer Now that we have the hardware for our thermometer, we will need to write some code that is capable of converting the values returned from the thermistor into a readable temperature in Celsius and Fahrenheit. First up, we are going to look at a new code editing application. This IDE allows you to develop code in the Raspberry Pi X Window System environment and compile the code via a Makefile. We will start by looking at the Geany IDE. Geany IDE Geany is a lightweight Linux integrated development environment. It can be installed onto Raspbian and then used for writing code in the Arduino/C++ programming language. An added benefit of using this IDE is that we can set up a custom Makefile with the commands we have been using to compile arduPi-based projects. By combining the Makefile and Geany, we have an IDE that mimics the functionality we would use in the Arduino IDE, but with the added benefit we can save files without renaming them and compile our applications with one click. Installing the IDE We are going to use the apt-get tool to install Geany on to your Raspberry Pi. Start off with loading up your Terminal window. From the prompt, run the following command: sudo apt-get install geany You'll get the prompt alerting you to the fact that Geany will take up a certain amount of disk space. You can accept the prompt by selecting Y. Once complete, you will now see Geany located under the Programming menu option. Select the Geany icon from the previous menu to load the application. Once loaded, you will be presented with a code-editing interface. Along the top of the screen, you can find a standard toolbar. This includes the File menu where you can open and save files you are working on, and menus for Edit, Search, View, Document, Project, Build, Tools, and Help. The left-hand side of the screen contains a window that has a number of features including allowing you to jump to a function when you are editing your code. The bottom panel on the screen contains information about your application when you compile it. This is useful when debugging your code, as error messages will be displayed here. Geany has an extensive number of features. You can find a comprehensive guide to the IDE at the Geany website http://www.geany.org/. For our application development at this stage, we are only interested in creating a new file, opening a file, saving a file, and compiling a file. The options we need are located under the File menu item and the Build menu item. Feel free though to explore the IDE and get comfortable with it. In order to use the make option for compiling our application under the Build menu, we need to create a Makefile — we will now take a look at how to achieve this. An introduction to Makefiles The next tool we are going to use is the Makefile. A Makefile is executed by the Linux command make. Make is a command-line utility that allows you to compile executable files by storing the parameters into a Makefile and then calling it as needed. This method allows us to store common compilation directives and re-use them without having to type out the command each time. As you are familiar with, we have used the following command in order to compile our LED example: g++ -lrt -lpthread blink_test.cpp arduPi.o -o blink_test Using a Makefile, we could store this and then execute it when located in the same directory as the files using a simpler command. make We can try out creating a Makefile using the code. Load up Geany from the programming menu if you don't currently have it open. If you don't have a new document open, create a new one from the File menu. Now add the following lines to Blink_test/Makefile, making sure to tab the second line once: Blink: arduPi.o g++ -lrt -lpthread blink_test.cpp arduPi.o -o blink_test If you don't tab the second line containing the compilation instructions, then the Makefile won't run. Now that you have created the Makefile, we can save and run it with the following steps: From the File menu, select Save. From the Save dialog, navigate to the directory where you saved your blink_test.cpp and save the file with the title Makefile. Now open the blink_test.cpp file from the directory where you saved your Makefile. We can test our Makefile by selecting the Build option from the menu and selecting Make. In the panel at the bottom of the IDE, you will see a message indicating that the Makefile was executed successfully. Now from the Terminal window, navigate to the directory containing your blink_test project. Located in this directory, you will find your freshly compiled blink_test file. If you still have your LED example at hand, hook it up to the shield and from the command line, you can run the application by typing the following command: ./blink_test The LED should start blinking. Hopefully, you can see from this example that integrating the Makefile into the IDE allows us to write code and compile it as we go in order to debug it. This will be very useful when you start to work on projects with greater complexity. Once we have written the code to record our temperature readings, we will re-visit the Makefile and create a custom one to build our thermometer application via Geany. Now that you have set up Geany and briefly looked at Makefiles, lets get started with writing our application. Thermometer code We will be using the arduPi library for writing our code as we did for the LED test. As well as using standard Arduino and C++ syntax, we are going to explore some calculations that are used to return the results we need. In order to convert the values we are collecting from our circuit and convert them into a readable temperature, we are going to need to use an equation that converts resistance into temperature. This equation is known as the Steinhart-Hart equation. The Steinhart-Hart equation models the resistance of our thermistor at different temperatures and can be coded into an application in order to display the temperature in Kelvin, Fahrenheit, and Celsius. We will use a simpler version of this in our program (called the B parameter equation) and can use the values from the datasheet provided with our thermistor in order to populate the constants that are needed to perform the calculations. For a simpler version of the equation, we only need to know the following values: The room temperature in Kelvin The co-efficient of our thermistor (should be on the data sheet) The thermistor resistance at room temperature We will use Geany to write our application, so if you don't have it open, start it up. Writing our application From the File menu in Geany, create a new blank file; this is where we are going to add our Arduino code. If you save the file now, then Geany's syntax highlighting will be triggered making the code easier to read. Open the File menu in Geany and select Save. In the Save dialog box, navigate to the arduPi directory and save your file with the name thermometer.cpp. We will use the arduPi_template.cpp as the base for our project and add our code into it. To start, we will add in the include statements for the libraries and headers we need, as well as define some constants that will be used in our application for storing key values. Add the following block of code to your empty file, thermometer.cpp, in Geany: //Include ArduPi library #include "arduPi.h" //Include the Math library #include <math.h> //Needed for Serial communication SerialPi Serial; //Needed for accessing GPIO (pinMode, digitalWrite, digitalRead, //I2C functions) WirePi Wire; //Needed for SPI SPIPi SPI; // Values need for Steinhart-Hart equation // and calculating resistance. #define TENKRESISTOR 10000 //our 10K resistor #define BETA 4000 // This is the Beta Coefficient of your thermistor #define THERMISTOR 10000 // The resistance of your thermistor at room //temperature #define ROOMTEMPK 298.15 //standard room temperature in Kelvin //(25 Celsius). // Number of readings to take // these will be averaged out to // get a more accurate reading // You can increase/decrease this as needed #define READINGS 7 You will recognize some of the preceding code from the arduPi template, as well as some custom code we have added. This custom code includes a reference to the Math library. The Math library in C++ contains a number of reusable complex mathematical functions that can be called and which would help us avoid writing these from scratch. As you will see later in the program, we have used the logarithm function log() when calculating the temperature in Kelvin. Following are a number of constants; we use the #define statement here to initialize them: TENKRESISTOR: This is the 10K Ohm resistor you added to the circuit board. As you can see, we have assigned the value of 10,000 to it. BETA: This is the beta-coefficient of your thermistor. THERMISTOR: The resistance of your thermometer at room temperature. ROOMTEMPK: The room temperature in Kelvin, this translates to 25 degrees Celsius. READINGS: We will take seven readings from the analog pin and average these out to try and get a more accurate reading. The values we have used previously are for a 10K thermistor with a co-efficient of 4000. These should be updated as necessary to reflect the thermistor you are using in your project. Now that we have defined our constants and included some libraries, we need to add the body of the program. From the arduPi_template.cpp file, we now include the main function that kicks our application off. /********************************************************* * IF YOUR ARDUINO CODE HAS OTHER FUNCTIONS APART FROM * * setup() AND loop() YOU MUST DECLARE THEM HERE * * *******************************************************/ /************************** * YOUR ARDUINO CODE HERE * * ************************/ int main (){ setup(); while(1){ loop(); } return (0); } Remember that you can use both // and /* */ for commenting your code. We have our reference to the setup() function and to the loop() function, so we can now declare these and include the necessary code. Below the main() function, add the following: void setup(void) { printf("Starting up thermometer \n"); Wire.begin(); } The setup() function prints out a message to the screen indicating that the program is starting and then calls Wire.begin(). This will allow us to interact with the analog pins. Next we are going to declare the loop function and define some variables that will be used within it. void loop(void) { float avResistance; float resistance; int combinedReadings[READINGS]; byte val0; byte val1; // Our temperature variables float kelvin; float fahrenheit; float celsius; int channelReading; float analogReadingArduino; As you can see in the preceding code snippet, we have declared a number of variables. These can be broken down into: Resistance readings: These are float avResistance, float resistance, and byte val0 and byte val1. The variables avResistance and resistance will be used during the program's execution for recording resistance calculations. The other two variables val0 and val1 are used to store the readings from analog 0 on the shield. Temperature calculations: The variables float kelvin, float fahrenheit, and float celsius as their names suggest are used for recording temperature in three common formats. After declaring these variables, we need to access our analog pin and start to read data from it. Copy the following code into your loop function: /******************* ADC mappings Pin Address 0 0xDC 1 0x9C 2 0xCC 3 0x8C 4 0xAC 5 0xEC 6 0xBC 7 0xFC *******************/ // 0xDC is our analog 0 pin Wire.beginTransmission(8); Wire.write(byte(0xDC)); Wire.endTransmission(); Here we have code that initializes the analog pin 0. The code comment contains the mappings between the pins and addresses so if you wish, you can run the thermistor off a different analog pin. We are using pin 0, so we can now start to take readings from it. To get the correct data, we need to take two readings of a byte each from the pin. We will do this using a for loop. The Raspberry Pi to Arduino shield does not support the analogRead() and analogWrite() functions from the Arduino programming language. Instead we need to use the Wire commands and addresses from the table provided in the comments for this code. Add the following for loop below your previous block of code: /* Grab the two bytes returned from the analog 0 pin, combine them and write the value to the combinedReadings array */ for(int r=0; r<READINGS; r++){ Wire.requestFrom(8,2); val0 = Wire.read(); val1 = Wire.read(); channelReading = int(val0)*16 + int(val1>>4); analogReadingArduino = channelReading * 1023 /4095; combinedReadings[r] = analogReadingArduino; delay(100); } Here we have a loop that grabs the data from the analog pin so we can process it. In the requestFrom() function, we pass in the declaration for the number of bytes we wish to have returned from the pin. Here we can see we have two — this is the second value in the function call. We will combine these values and then write them to an array; in total, we will do this seven times and then average out the value. You will notice we are applying a calculation on the two combined bytes. This calculation converts the values into a 10-bit Arduino resolution. The value you will see returned after this equation is the same as you would expect to get from the analogRead() function on an Arduino Uno if you had hooked up your circuit to it. After we have done this calculation, we assign the value to our array that stores each of the seven readings. Now that we have this value, we can calculate the average resistance. For this, we will use another for loop that iterates through our array of readings, combines them, and then divides them by the value we set in our READINGS constant. Here is the next for loop you will need to accomplish this: // Grab the average of our 7 readings // in order to get a more accurate value avResistance = 0; for (int r=0; r<READINGS; r++) { avResistance += combinedReadings[r]; } avResistance /= READINGS; So far, we have grabbed our readings and can now use a calculation to work out the resistance. For this, we will need our avResistance reading, the resistance value of our 10K resistor, and our thermistor's resistance at room temperature. Add the following code that performs this calculation: /* We can now calculate the resistance of the readings that have come back from analog 0 */ avResistance = (1023 / avResistance) - 1; avResistance = TENKRESISTOR / avResistance; resistance = avResistance / THERMISTOR; The next part of the program uses the resistance to calculate the temperature. This is the portion of code utilizing the simpler version of the Steinhart-hart equation. The result of this equation will be the ambient temperature in degrees Kelvin. Next add the following block of code: // Calculate the temperature in Kelvin kelvin = log(resistance); kelvin /= BETA; kelvin += 1.0 / ROOMTEMPK; kelvin = 1.0 / kelvin; printf("Temperature in K "); printf("%f \n",kelvin); So we have our temperature in degrees K and also have a printf statement that outputs this value to the screen. It would be nice to also have the temperature in two more common temperature formats, those being Celsius and Fahrenheit. These are simple calculations to perform. Let's start by adding the Celsius code. // Convert from Kelvin to Celsius celsius = kelvin -= 273.15; printf("Temperature in C "); printf("%f \n",celsius); Now that we have the temperature in degrees Celsius, we can print this to the screen. Using this value we can convert Celsius into Fahrenheit. // Convert from Celsius to Fahrenheit fahrenheit = (celsius * 1.8) + 32; printf("Temperature in F "); printf("%f \n",fahrenheit); Great! So now we have the temperature being returned in three formats. Let's finish up the application by adding a delay of 3 seconds before the application takes another temperature reading and close off our loop() function. // Three second delay before taking our next // reading delay(3000); } So there we have it. This small application will use our circuit and return the temperature. We now need to compile the code so we can give it a test. Remember to save your code now so that the changes you have added are included in the thermometer.cpp file. Our next step is to create a Makefile for our thermometer application. If you saved the blink_test Makefile into the arduPi directory, you can re-use this or you can create a new file using the previous steps. Place the following code into your Makefile: Thermo: arduPi.o g++ -lrt -lpthread thermometer.cpp arduPi.o -o thermometer Save the file with the name Makefile. We can now compile and test our application. Compiling and testing When discussing Geany earlier, we demonstrated how to run the make command from inside the IDE. Now that we have our Makefile in place, we can test this out. From the Build menu, select Make. You should see the compilation pane at the bottom of the screen spring to life and providing there are no typos or errors in your code, a file called thermometer will be successful output. The thermometer file is our executable that we will run to view the temperature. From the terminal window, navigate to the arduPi directory and locate your thermometer file. This can be launched using the following command: sudo ./thermometer The application will now be executed and text similar to the following in the screenshot should be visible: Try changing the temperature by blowing on the thermometer, placing it in some cold water if safe to do so, or applying a hair dryer to it. You should see the temperature on the screen change. If you have a thermostat or similar in the room that logs the temperature, try comparing its value to that of your thermometer to see how accurate it is. You can run an application in the background by adding an & after the command, for example, sudo ./thermometer &. In the case of our application, it outputs to the screen, so if you attempt to use the same terminal window your typing will be interrupted! To kill an application running in the background, you can type fg to bring it to the foreground and then press Ctrl + C to cancel it. What if it doesn't work Providing you had no errors when compiling your code, then the chances are that one of your components is not connected properly, is connected to the wrong pin, or may be defective. Try double-checking your circuit to make sure everything is attached and hasn't become accidently dislodged. Also ensure that the components are wired up as suggested at the beginning of this article. If everything seems to be correct, you may have a faulty component. Try substituting each item one at a time in the circuit to see if it is a bad wire or faulty resistor. Up and running If you see your temperature being output successfully, then you are up and running! Congratulations, you now have a basic thermometer. This will form the basis for our next project, which is a thermostat. As you can see, this application is useful. However, returning the output to the screen isn't the best method, it would be better for example, if we could see the results via our web browser or an LCD screen. Now that we have a circuit and an application recording temperature, this opens up a wide variety of things we can do with the data, including logging it or using it to change the heat settings in our homes. This article should have whetted your appetite for bigger projects. Summary In this article, we learned how to wire up two new components — a thermistor and resistor. Our application taught us how to use these components to log a temperature reading, and we also became familiar with Makefiles and the Geany IDE. Resources for Article : Further resources on this subject: Folding @ Home on Ubuntu: Cancer Research Made Easy [Article] Using PVR with Raspbmc [Article] Using ChronoForms to add More Features to your Joomla! Form [Article]
Read more
  • 0
  • 0
  • 2190