Sunday, April 1, 2018

Raspberry Pi, NOOBS, LAMP and ALEXA

How to setup a $35 computer using a Raspberry Pi, NOOBS, a LAMP webserver and ALEXA:
by J.B. Wylzan




First, you need the following items:
  • MicroSD card with preloaded NOOBS (or load it yourself here)
  • HDMI monitor
  • HDMI cable
  • USB keyboard and mouse
  • 2.5A microUSB power supply
  • Ethernet cable (for internet connection)
To set up your Raspberry Pi as a computer and configure it to work as a web server using LAMP, which stands for Linux, Apache, MySQL, PHP, follow the quick start guidelines below:

A) Install GUI Linux:

1. Insert all of the items above to the raspberry pi board.
2. Insert the microSD card (this is your hard drive)
3. Power it up by connecting the 2.5A power adapter
4. Once the NOOBS is running, select the "Raspbian" as your operating system
5. When done, shut it down properly using the terminal editor
    -type:  sudo shutdown -h now

To Setup as a Webserver:

B) Install Apache:
 
Apache is a popular web server application you can install on the Raspberry Pi to allow it to serve web pages.

On its own, Apache can serve HTML files over HTTP, and with additional modules can serve dynamic web pages using scripting languages such as PHP.

Install the apache2 package by typing the following command into the terminal:

sudo apt-get install apache2 -y

Test the web server

By default, Apache puts a test HTML file in the web folder. This default web page is served when you browse to http://localhost/ on the Pi itself, or http://192.168.1.10 (whatever the Pi's IP address is) from another computer on the network.

To find out the Pi's IP address, type hostname -I at the command line.

Browse to the default web page, either on the Pi or from another computer on the network, and you should see the following:

Changing the default web page

This default web page is just a HTML file on the filesystem. It is located at /var/www/html/index.html.

Note: The directory was /var/www/html in Raspbian Jessie

Navigate to this directory in the Terminal and have a look at what's inside:

cd /var/www/html
ls -al

As you can see, by default the html directory and index.html file are both owned by the root user, so you'll need to use sudo to edit them.

Try editing this file and refreshing the browser to see the web page change.

Press Ctrl + X and hit Enter to save and exit.

C) Install PHP:
 
PHP is a preprocessor; it's code that runs when the server receives a request for a web page. It runs, works out what needs to be shown on the page, then sends that page to the browser. Unlike static HTML, PHP can show different content under different circumstances. Other languages are capable of this, but since WordPress is written in PHP, that's what we need to use this time.

Install the PHP and Apache packages with the following command:

sudo apt-get install php5 libapache2-mod-php5 -y

Test PHP

Create the file index.php:
sudo nano index.php

Put some PHP content in it:
<?php echo "hello world"; ?>

Now save the file. Next delete index.html because it takes precendence over index.php:
sudo rm index.html

Refresh your browser. You should see "hello world". This is not dynamic but it is still served by PHP. If you see the raw PHP above instead of "hello world", reload and restart Apache like so:
sudo service apache2 restart

Otherwise try something dynamic, for example:
<?php echo date('Y-m-d H:i:s'); ?>
 
Or show your PHP info:
<?php phpinfo(); ?>
 
D) Install MySQL:
 
MySQL (pronounced My Sequel or My S-Q-L) is a popular database engine.

Like PHP, its overwhelming presence on web servers enhanced its popularity. This is why projects like WordPress use it, and why those projects are so popular.

Install the MySQL Server and PHP-MySQL packages by entering the following command into the terminal:
sudo apt-get install mysql-server php5-mysql -y

When installing MySQL you will be asked for a root password. You'll need to remember this to allow your website to access the database.

Now restart Apache:
sudo service apache2 restart 




E) Install Alexa:

Step 1: Setting up your Pi
Step 2: Register for an Amazon developer account
Step 3: Create a device and security profile
  • Allowed Origins: https://localhost:3000
  • Allowed Return URLs: https://localhost:3000/authresponse
Step 4: Clone the sample app
  • cd Desktop
  • git clone https://github.com/alexa/alexa-avs-sample-app.git
Step 5: Update the install script with your credentials
  • cd ~/Desktop/alexa-avs-sample-app
  • nano automated_install.sh
Step 6: Run the install script
  • cd ~/Desktop/alexa-avs-sample-app
  • . automated_install.sh
Step 7: Run your web service, sample app and wake word engine
Terminal 1
  • cd ~/Desktop/alexa-avs-sample-app/samples
  • cd companionService && npm start
Terminal 2
  • cd ~/Desktop/alexa-avs-sample-app/samples
  • cd javaclient && mvn exec:exec
Terminal 3
  • cd ~/Desktop/alexa-avs-sample-app/samples
  • cd wakeWordAgent/src && ./wakeWordAgent -e kitt_ai
Step 8: Talk to Alexa
Step 9: How to Log Out of the Sample App
To log out of the AVS java sample app you must clear your sessionId in /samples/javaclient/config.json, and delete your refresh_tokens file in the /samples/companionService folder. Otherwise, the sample app will authenticate on each reboot.
Solution:
Follow these instructions to log out of the AVS java sample app:
Quit the AVS java sample app (CTRL + C).
Open /samples/javaclient/config.json and clear your sessionId. It should look like this:

"sessionId": ""

Delete the refresh_tokens file in samples/companionService.

The next time you log in you will be prompted to authenticate.

Reference:  github.com/alexa/alexa-avs-sample-app/wiki/Raspberry-Pi


NOTICE: Articles on this site are composed on random thoughts. The transcript may not be in its final form. It maybe updated or even revised in the future.



"Everything is a switch, each one can be turned ON and OFF." ~ Joey Lawsin



Disclaimer:  We shall not be liable for any loss or damage of whatever nature - direct, indirect, consequential, or otherwise - which may arise as a result of your use of any information on this website. However, if you are interested in using any of the projects for personal or educational purposes, please inform the author by email. 

PPublic Domain Notice: Copyright (c) 2000. All rights reserved. This article is part of a book entitled iHackRobot. Copies are welcome to be shared or distributed publicly as long proper citations are observed. Please cite as follows: Biotronics: The Silver Species, Joey Lawsin, 1988, USA.

================================================================== 
The Homotronics® and Homodruinos® logos are registered trademarks.
Copyright Biotronics© Inc. iHackRobot®. All Rights Reserved.
Patent Pending. 2000 © ®

L.A.W.S.I.N. Educational Production
 ================================================================== 








Saturday, December 9, 2017

PIR Motion Detection with Email Notification

How to build a Robot on an Arduino that can be activated by a PIR Motion Sensor:
by J.B. Wylzan
Project 36:  PIR Motion Sensor

This project shows how to use a PIR motion detector 
that sends an email whenever motion is detected.

Infrared Sensor




Hardware:
1 PIR Motion Sensor
1 Led (optional)
1 servo(optional)
1 speaker (optional)
connecting wires
breadboard
Ethernet Shield
Arduino R3 UNO board


Block Diagram:
Note: Although the sensor above is not a PIR but a Humidity and Temperature sensor
the schematic is still the same. (1=gnd, + = 5v,  S = ~)


Arduino Sketch:

/*
  iHacklab Motion Detection via Email
  This sketch was automatically generated by Temboo software. 
  A step by step tutorial is available on their site.
  The sketch varies defending on your arduino and ethernet shields.
 */
#include <SPI.h>
#include <Dhcp.h>
#include <Dns.h>
#include <Ethernet.h>
#include <EthernetClient.h>
#include <Temboo.h>
#include "TembooAccount.h"

byte ethernetMACAddress[] = ETHERNET_SHIELD_MAC;
EthernetClient client;

int numRuns = 1;   // Execution count, so this doesn't run forever
int maxRuns = 10;   // Maximum number of times the Choreo should be executed

void setup() {
  Serial.begin(9600);  
  delay(4000);
  while(!Serial);

  Serial.print("DHCP:");
  if (Ethernet.begin(ethernetMACAddress) == 0) {
    Serial.println("FAIL");
    while(true);
  }
  Serial.println("OK");
  delay(5000);

  Serial.println("Setup complete.\n");
}

void loop() {
  if (numRuns <= maxRuns) {
    Serial.println("Running SendEmail - Run #" + String(numRuns++));

    TembooChoreo SendEmailChoreo(client);

    // Invoke the Temboo client
    SendEmailChoreo.begin();

    // Set Temboo account credentials
    SendEmailChoreo.setAccountName(TEMBOO_ACCOUNT);
    SendEmailChoreo.setAppKeyName(TEMBOO_APP_KEY_NAME);
    SendEmailChoreo.setAppKey(TEMBOO_APP_KEY);

    // Set profile to use for execution
    SendEmailChoreo.setProfile("ver");

    // Identify the Choreo to run
    SendEmailChoreo.setChoreo("/Library/Google/Gmail/SendEmail");

    // Run the Choreo; when results are available,print them to serial
    SendEmailChoreo.run();

    while(SendEmailChoreo.available()) {
      char c = SendEmailChoreo.read();
      Serial.print(c);
    }
    SendEmailChoreo.close();
  }

  Serial.println("\nWaiting...\n");
  delay(30000); // wait 30 seconds between SendEmail

calls
}



/*
HEADER FILE:

IMPORTANT NOTE about TembooAccount.h

TembooAccount.h contains your Temboo account information and must be included
alongside your sketch. To do so, make a new tab in Arduino, call it TembooAccount.h,
and copy this content into it.
*/

#define TEMBOO_ACCOUNT "..."  // Your Temboo account name
#define TEMBOO_APP_KEY_NAME "..."  // Your Temboo app key name
#define TEMBOO_APP_KEY"..."  // Your Temboo app key

#define ETHERNET_SHIELD_MAC {0x0D, 0xE0, 0xAD, 0x0B, 0xE0, 0xEF}

/*
Keeping your account information in a separate file means you can share the
main .ino file without worrying that you forgot to delete your credentials.
*/


Challenges:

1. Add a blinking Led to indicate motion is detected.
2. Play a warning tone when motion is detected.
3. Use other types of sensors
4. Send yourself an hourly temperature/humidity reports via email.

Python Code:

/* You need to install Python on your PC.
 The example code is public domain */

import time
import serial
import smtplib

TO = 'putyour@email.here'
GMAIL_USER = 'putyour@email.here'
GMAIL_PASS = 'putyourpasswordhere'

SUBJECT = 'Intrusion!!'
TEXT = 'Your PIR sensor detected movement'

ser = serial.Serial('COM4', 9600)

def send_email():
    print("Sending Email")
    smtpserver = smtplib.SMTP("smtp.gmail.com",587)
    smtpserver.ehlo()
    smtpserver.starttls()
    smtpserver.ehlo
    smtpserver.login(GMAIL_USER, GMAIL_PASS)
    header = 'To:' + TO + '\n' + 'From: ' + GMAIL_USER
    header = header + '\n' + 'Subject:' + SUBJECT + '\n'
    print header
    msg = header + '\n' + TEXT + ' \n\n'
    smtpserver.sendmail(GMAIL_USER, TO, msg)
    smtpserver.close()
 
while True:
    message = ser.readline()
    print(message)
    if message[0] == 'M' :
        send_email()
    time.sleep(0.5)




Disclaimer:  We shall not be liable for any loss or damage of whatever nature - direct, indirect, consequential, or otherwise - which may arise as a result of your use of any information on this website. However, if you are interested in using any of the projects for personal or educational purposes, please inform the author by email. 

Public Domain Notice: Copyright (c) 2000. All rights reserved. This article is part of a book entitled iHackRobot. Copies are welcome to be shared or distributed publicly as long proper citations are observed. Please cite as follows: Biotronics: The Silver Species, Joey Lawsin, 1988, USA.

================================================================== 
The Homotronics® and Homodruinos® logos are registered trademarks.
Copyright Biotronics© Inc. iHackRobot®. All Rights Reserved.
Patent Pending. 2000 © ®

L.A.W.S.I.N. Educational Production
 ================================================================== 







Sunday, October 29, 2017

FREE Arduino Android Apps



This android app is yours for FREE. It turns On/Off a light bulb. It speaks when you press a button. It gets grumpy when shaken. It controls any device wirelessly via Bluetooth. These four features, a four dollars value, are all yours for free. You just need to request the APK code by sending me an email at JBWylzan at gmail dot com. 

However, if you want to personalize the app with pictures, with voice messages different from the original, and upload it in your android tablet or phone as if you developed or created the app, I can provide such a request for a FEE with a minimum contribution of 1 dollar payable through Paypal. Just click the DONATE button below and send your contribution via Paypal.

SHOW YOUR APPRECIATION:

To RECEIVE ***Your First Android App for $1:00 only,
please click the DONATE button below.



HELP FUTURE PROJECTS BY SHARING A SMALL DONATION

SUPPORTERS / DONORS:
  • Marie C.      $20
  • Abby M.     $1
  • Michael L.    $1 
  • Emmy T.      $5
  • Josie A.       $10
  • Tony R.       $1
  • Ariel C.       $10

THANK YOU FOR SUPPORTING THIS WEBSITE ;)


 
FREE Arduino Android Apps from iHackRobot on Vimeo
 
 

This app is almost identical to the free app.
However, there are some additional features (see below)
To receive this BT Led Controller App for $1:00, 
please click the DONATE button below.



Arduino BT Led Controller App Features:
1. The  same screenshot as in the video.
2. The green button speaks "Device is ON.
3. The red button speaks "Device is OFF".
4. or, Turns off the led by shaking.
5. The connect button list a selection of bluetooth available in your area.
6. No ads eg developers name and website.
7. The app is provided "As Is" ***.


An app that controls six of your home appliances:

A more sophisticated iHackRobot Arduino Android App. The application is a wireless controller that can turn ON and OFF six appliances in your home and even your car ignition by simply swiping the color-coded sliders on either end. The app can also control LEDs, servos, toy cars, and even your robots. The great fun about this app is you can turn OFF all six appliances by simply shaking your smartphone.


Arduino Robot controlled by Android Smartphone
from iHackRobot on Vimeo.



WARRANTY:
ALL Android Apps on this site is provided "As Is" ***.
*** AS-IS means YOU EXPRESSLY UNDERSTAND AND AGREE THAT YOUR USE OF THE APPLICATION(APP) IS AT YOUR SOLE RISK AND IS PROVIDED "AS IS" AND "AS AVAILABLE" WITHOUT WARRANTY OR GUARANTY OF ANY KIND. YOUR USE OF THE APP AND ANY MATERIAL DOWNLOADED OR OTHERWISE OBTAINED THROUGH THE SITE IS AT YOUR OWN DISCRETION AND RISK AND YOU ARE SOLELY RESPONSIBLE FOR ANY DAMAGE TO YOUR COMPUTER SYSTEM OR OTHER DEVICE OR LOSS OF DATA THAT RESULTS FROM SUCH USE. THE APP WAS ONLY TESTED ON SAMSUNG GALAXY S5 SM-G900A AND ANDROID SOPHIX TABLET MODEL NO: TAB 730G AS EMULATOR. THE APP MIGHT NOT WORK WITH ALL OTHER SMARTPHONES AND TABLETS.
 
Disclaimer:  We shall not be liable for any loss or damage of whatever nature - direct, indirect, consequential, or otherwise - which may arise as a result of your use of any information on this website. However, if you are interested in using any of the projects for personal or educational purposes, please inform the author by email. 

Public Domain Notice: Copyright (c) 2000. All rights reserved. This article is part of a book entitled iHackRobot. Copies are welcome to be shared or distributed publicly as long proper citations are observed. Please cite as follows: Biotronics: The Silver Species, Joey Lawsin, 1988, USA.

================================================================== 
The Homotronics® and Homodruinos® logos are registered trademarks.
Copyright Biotronics®  Inc. iHackRobot®. All Rights Reserved.
 Patent Pending. 2000 © ®

L.A.W.S.I.N. Educational Production© 
 ================================================================== 


iHackRobot Apps

How to make an apps that can control any Arduino Robots via Android phones:
by J.B. Wylzan

 
APPS Features
Android Arduino Controller App
  1. Green to turn Device ON
  2. Red to turn Device OFF
  3. Bluetooth Selection button
  4. Developer's name
  5. Developer's Website
Bluetooth Scanner App
  1. Bluetooth scan
  2. Select HC05
  3. Device pin 12345
  4. Activate HC-05
Scribble & Swipe Ball  App

  1. Draws RGY lines
  2. Draws small dots
  3. Draw big dots
  4. Ball swipe
  5. Dog speaks
  6. Shake to erase scribbles
Smash the Bugs Game

  1. Smash the bug
  2. Hit = 1 point
  3. Score counter
  4. Reset button
  5. Add more bugs
LED Bluetooth Controller

  1. Green speaks Device ON
  2. Red speaks Device OFF
  3. Bluetooth Selection button
  4. Accelerometer shake
  5. VoiceTranslator
Home Appliances Control Station

  1. Connect to Bluetooth
  2. Turns On/Off device  1
  3. Turns On/Off device  2
  4. Turns On/Off device  3
  5. Turns On/Off device  4
  6. Turns On/Off device  5
  7. Turns On/Off device  6
  8. Shake to turn ALL off
Talking Zero

  1. Zero meows when tap
  2. Button gives instruction
  3. Bug tilts as iphone tilts
  4. Voice alert when shaken
  5. Tells time and date

  1. Connects to Bluetooth
  2. Activates device 1
  3. Activates device 2
  4. Activates device 3
  5. Activates device 4
  6. Activates device 5
  7. Swipe to deactivate

Generic Robotics Control Pad
  1. Activates Bluetooth
  2. Robot moves Forward
  3. Robot moves Backward
  4. Robot moves Left
  5. Robot moves Right
  6. Robot plays dead
  7. Robot speaks 
  8. Robot sleeps
  9. Shake phone to deactivate
T.U.R.N. = The Ultimate Robotics Navigator

  1. Activates Bluetooth
  2. Robot walks
  3. Robot drives
  4. Robot flies
  5. Robot propels in water
  6. Robot plays dead
  7. Robot speaks 
  8. Robot sleeps
  9. Robot detects motion
  10. Robot sounds an alarm 
  11. Robot flashes warning light
  12. Shake phone to deactivate
Speech Recognition Home Automation

  1. Activates Bluetooth
  2. Tap microphone
  3. Say "ON"
  4. Say "Blue"
  5. Say "Blink"
  6. Say "Off"
  7. Lights follow voice commands
More Apps to Come



WARRANTY:
*** AS IS means YOU EXPRESSLY UNDERSTAND AND AGREE THAT YOUR USE OF THE APPLICATION(APP) IS AT YOUR SOLE RISK AND IS PROVIDED "AS IS" AND "AS AVAILABLE" WITHOUT WARRANTY OF ANY KIND. YOUR USE OF THE APP AND ANY MATERIAL DOWNLOADED OR OTHERWISE OBTAINED THROUGH THE SITE IS AT YOUR OWN DISCRETION AND RISK AND YOU ARE SOLELY RESPONSIBLE FOR ANY DAMAGE TO YOUR COMPUTER SYSTEM OR OTHER DEVICE OR LOSS OF DATA THAT RESULTS FROM SUCH USE. THE APP WAS ONLY TESTED ON SAMSUNG GALAXY S5 SM-G900A AND ANDROID SOPHIX TABLET MODEL NO: TAB 730G AS EMULATOR. THE APP MIGHT NOT WORK WITH ALL OTHER SMARTPHONES AND TABLETS.


Disclaimer:  We shall not be liable for any loss or damage of whatever nature - direct, indirect, consequential, or otherwise - which may arise as a result of your use of any information on this website. However, if you are interested in using any of the projects for personal or educational purposes, please inform the author by email. 

Public Domain Notice: Copyright (c) 2000. All rights reserved. This article is part of a book entitled iHackRobot. Copies are welcome to be shared or distributed publicly as long proper citations are observed. Please cite as follows: Biotronics: The Silver Species, Joey Lawsin, 1988, USA.

================================================================== 
The Homotronics® and Homodruinos® logos are registered trademarks.
Copyright Biotronics© Inc. iHackRobot®. All Rights Reserved.
Patent Pending. 2000 © ®

L.A.W.S.I.N. Educational Production
 ================================================================== 





.

Friday, October 21, 2016

Android Bluetooth Arduino

How to build a Robot on an Arduino that can be controlled by an Android apps:
by J.B. Wylzan


Project 34:  Arduino Controlled by Android

This project shows how to control an andruino Led 
using Bluetooth and Android smartphone.


Android Bluetooth Arduino from JB Wylzan on Vimeo.




HC-05 Circuit Wiring:  
   HC05 Gnd      - Arduino pin Gnd
   HC05 3.3        - Arduino pin 3.3v
   HC05 Tx         - Arduino pin 3 (Tx)
   HC05 Rx         - Arduino pin 2 (Rx)
  
Block Diagram:

Note: use pin 2 and pin 3 for Rx and Tx
Hardware:
HC05 bluetooth 

Arduino phone (samsung galaxy) 
9v battery 
1 LEDconnecting wires
breadboard
Arduino R3 UNO board


Code 34:
/* ===============================================================
      Project # 34: Android Smartphone with Bluetooth
      Author: J. B. Wylzan 
      Website: http://www.ihackrobot.blogspot.com
      Abstract: How to control an led using smartphone
================================================================== */

#include <SoftwareSerial.h>
SoftwareSerial BTserial(2, 3); // RX | TX

 int ledPin = 12;
char data = 0;  

void setup()
{
     pinMode(ledPin, OUTPUT);
     BTserial.begin(9600);
     // Serial.begin(9600);
     // serial.println("Hello World");
}

void loop()
{
    if (BTserial.available())
    {
    data = BTserial.read();              //Read incoming value and store it into data
    if(data == '1')                            //when data is equal to 1
      digitalWrite(ledPin, HIGH);     // then LED is ON
    else if(data == '0')                     //when data is equal to 0
      digitalWrite(ledPin, LOW);     // then LED is OFF
       }
}

Layout:




Challenges:
1. Try to control 2 leds using the smartphone, 
2. Try to control 3 servos.
3. Create an apps
4. Use smartphone terminal and serial monitor as a chatroom/text messaging
5. Control a robot using an android smartphone bluetooth terminal
6. Control a robot using the some of the iHackRobot apps just like as shown below



Arduino Robot controlled by an Android Smartphone:


Arduino Robot controlled by Android Smartphone
from iHackRobot on Vimeo.

A more sophisticated arduino android app. The app is an arduino controller that can turn ON and OFF six appliances in your home and even you car ignition by simply swiping the sliders on either ends. You can also use this app to control leds, servos, toy cars and even your robots. The great fun about this app is you can turn OFF all appliances by simply shaking the phone.

Home Appliances Control Tablet

Home Appliances Control  Phone

WARRANTY:
ALL Android Apps on this site are provided "As Is" ***.
*** AS IS means YOU EXPRESSLY UNDERSTAND AND AGREE THAT YOUR USE OF THE APPLICATION(APP) IS AT YOUR SOLE RISK AND IS PROVIDED "AS IS" AND "AS AVAILABLE" WITHOUT WARRANTY OR GUARANTY OF ANY KIND. YOUR USE OF THE APP AND ANY MATERIAL DOWNLOADED OR OTHERWISE OBTAINED THROUGH THE SITE IS AT YOUR OWN DISCRETION AND RISK AND YOU ARE SOLELY RESPONSIBLE FOR ANY DAMAGE TO YOUR COMPUTER SYSTEM OR OTHER DEVICE OR LOSS OF DATA THAT RESULTS FROM SUCH USE. THE APP WAS ONLY TESTED ON SAMSUNG GALAXY S5 SM-G900A AND ANDROID SOPHIX TABLET MODEL NO: TAB 730G AS EMULATOR. THE APP MIGHT NOT WORK WITH ALL OTHER SMARTPHONES AND TABLETS.

Disclaimer:  We shall not be liable for any loss or damage of whatever nature - direct, indirect, consequential, or otherwise - which may arise as a result of your use of any information on this website. However, if you are interested in using any of the projects for personal or educational purposes, please inform the author by email. 

Public Domain Notice: Copyright (c) 2000. All rights reserved. This article is part of a book entitled iHackRobot. Copies are welcome to be shared or distributed publicly as long proper citations are observed. Please cite as follows: Biotronics: The Silver Species, Joey Lawsin, 1988, USA.
================================================================== 
The Homotronics® and Homodruinos® logos are registered trademarks.
Copyright Biotronics© Inc. iHackRobot®. All Rights Reserved.
Patent Pending. 2000 © ®

L.A.W.S.I.N. Educational Production
 ================================================================== 





Sunday, October 2, 2016

Three Axis Accelerometer ADXL345

How to build a Robot on an Arduino that can be controlled by ADXL345 accelerometer:
by J.B. Wylzan


Project 27:  Accelerometer ADXL345

This project shows how to test a 3-axis accelerometer
through the Serial Monitor and control a video camera.






Hardware:
1 accelerometer; ADXL345
1 prototype shield
3 servos (optional)
connecting wires scl5 sda4 cs2
Arduino R3 UNO board

Block Diagram:





Serial Monitor Test:
/* ===============================================================
      Project # 27: Accelerometer ADXL345 Testing
      Author: J. B. Wylzan with the Arduino Community
      Website: http://www.ihackrobot.blogspot.com
      Abstract: How to test a 3-axis accelerometer
================================================================== */

#include <Wire.h>

#define ADXL345_ADDRESS (0xA6 >> 1)
#define ADXL345_REGISTER_XLSB (0x32)
int accelerometer_data[3];
                                 
void i2c_write(int address, byte reg, byte data) {                                                                    
Wire.beginTransmission(address);      
Wire.write(reg);                              
Wire.write(data);                              
Wire.endTransmission();
}
                                             
void i2c_read(int address, byte reg, int count, byte* data) {
int i = 0;                                                
Wire.beginTransmission(address);        
Wire.write(reg);                                  
Wire.endTransmission();
Wire.beginTransmission(address);
Wire.requestFrom(address, count);
while(Wire.available())                  
{
char c = Wire.read();                    
data[i] = c;
i++;
}
Wire.endTransmission();
}

void init_adxl345() {
byte data = 0;
i2c_write(ADXL345_ADDRESS, 0x31, 0x0B);             // 13-bit mode +_ 16g
i2c_write(ADXL345_ADDRESS, 0x2D, 0x08);             // Power register
i2c_write(ADXL345_ADDRESS, 0x1E, 0x00);             // X
i2c_write(ADXL345_ADDRESS, 0x1F, 0x00);             // Y
i2c_write(ADXL345_ADDRESS, 0x20, 0x05);              // Z

// View values on the serial monitor!
i2c_read(ADXL345_ADDRESS, 0X00, 1, &data);
if(data==0xE5)
Serial.println("Success");
else
Serial.println("Failure");
}

void read_adxl345() {
byte bytes[6];
memset(bytes,0,6);
i2c_read(ADXL345_ADDRESS, ADXL345_REGISTER_XLSB, 6, bytes);
for (int i=0;i<3;++i) {
accelerometer_data[i] = (int)bytes[2*i] + (((int)bytes[2*i + 1]) << 8);
}
}

void setup() {
Wire.begin();
Serial.begin(9600);
for(int i=0; i<3; ++i) {
accelerometer_data[i] = 0;
}
init_adxl345();
}

void loop() {
read_adxl345();
Serial.print("x-y-z: ");
Serial.print(float(accelerometer_data[0])*3.9/1000);    
Serial.print("\t");
Serial.print(float(accelerometer_data[1])*3.9/1000);
Serial.print("\t");
Serial.print(float(accelerometer_data[2])*3.9/1000);
Serial.print("\n");
delay(100);
}




Code # 27:
/* scl = a5   sda = a4  */

#include <Wire.h>
#include <Servo.h>
Servo servox;
#define device (0xA6 >> 1)   //(0x53)    
int ledpin = 11;
byte mem[6] ;
int i;
int x;

void setup(){
 pinMode(ledpin,OUTPUT);
 digitalWrite(ledpin,HIGH);
 Wire.begin();
 servox.attach(9);
 servox.write(90);
 delay(25);
writeTo(device, 0x2D, 8);
}

void loop(){
 int regAddress = 0x32;
 digitalWrite(ledpin,LOW);
 delay(10);
 digitalWrite(ledpin,HIGH);
 readFrom(device, regAddress, 6, mem);

 x=0;
 for(i=1;i<=5;i++){
 x += (((int)mem[1]) << 8) | mem[0];
 delay(10);
 }

 x/=5;
 if(x<-255)x= -255; else if (x>255)x=255;
 x=map(x, -255, 255, 0, 180);
 servox.write(x);
 delay(200);
}

void writeTo(int DEVICE, byte address, byte val) {
 Wire.beginTransmission(DEVICE);
 Wire.write(address);
 Wire.write(val);
 Wire.endTransmission();
}

void readFrom(int DEVICE, byte address, int num, byte mem[]) {
 Wire.beginTransmission(DEVICE);
 Wire.write(address);
 Wire.endTransmission();
 Wire.beginTransmission(DEVICE);
 Wire.requestFrom(DEVICE, num);

 int i = 0;
 while(Wire.available())  {
 mem[i]= Wire.read();
 i++;
 }
 Wire.endTransmission();
}


Challenge:
1. Try to control 2 servos, 
2. Try to control 3 servos.
3. Add a Laser beam or a turret
4. Try the Alert Detection below 


/*
Example      Sabotage Detection
Author        Stefan Hermann
Date         5.12.2011
*/

int myState=0;
int greenLedPin=11;
int redLedPin=7;
int blueLedPin=3;
int buttonPin=2;
int potPin=3;
int accZPin=0;
int accYPin=1;
int accXPin=2;

int startAccZ;
int startAccY;
int startAccX;

void setup(){
  pinMode(greenLedPin,OUTPUT);
  pinMode(redLedPin,OUTPUT);
  pinMode(blueLedPin,OUTPUT);
  pinMode(buttonPin,INPUT);
  startAccZ=analogRead(accZPin);
  startAccY=analogRead(accYPin);
  startAccX=analogRead(accXPin);
}

void alertBlinking(){
  digitalWrite(redLedPin,HIGH);
  delay(50);
  digitalWrite(redLedPin,LOW);
  delay(100);
  digitalWrite(blueLedPin,HIGH);
  delay(50);
  digitalWrite(blueLedPin,LOW); 
  delay(100);  
}

boolean senseAcceleration(int myPotVal){
  boolean myReturn=false;
  myPotVal=map(myPotVal,0,1023,0,10);
  if (analogRead(accXPin)>startAccX+myPotVal) myReturn=true;
  if (analogRead(accYPin)>startAccY+myPotVal) myReturn=true;
  if (analogRead(accZPin)>startAccZ+myPotVal) myReturn=true;
  return myReturn;
}

void loop(){
  //alertBlinking();
  switch (myState){
  case 0: //idle
    if (senseAcceleration(analogRead(potPin))==true) {
      digitalWrite(greenLedPin,LOW);
      myState=1;
    } else {
      digitalWrite(greenLedPin,HIGH);    
    };
    break;
  case 1: // alert
    alertBlinking();
    if (digitalRead(buttonPin)==HIGH){
      myState=0;
    }
    break;
  }
  delay(10);
}



Disclaimer:  We shall not be liable for any loss or damage of whatever nature - direct, indirect, consequential, or otherwise - which may arise as a result of your use of any information on this website. However, if you are interested in using any of the projects for personal or educational purposes, please inform the author by email. 

Public Domain Notice: Copyright (c) 2000. All rights reserved. This article is part of a book entitled iHackRobot. Copies are welcome to be shared or distributed publicly as long proper citations are observed. Please cite as follows: Biotronics: The Silver Species, Joey Lawsin, 1988, USA.

================================================================== 
The Homotronics® and Homodruinos® logos are registered trademarks.
Copyright Biotronics© Inc. iHackRobot®. All Rights Reserved.
Patent Pending. 2000 © ®

L.A.W.S.I.N. Educational Production
 ==================================================================