I really enjoyed this project. It had me scratching my head for a while when I found out that the twitter API has changed from version 1 to 1.1. This means that you can no longer tweet using a simple username and password. You now need to use secure authentication called OAuth.
Firstly, you need a twitter account. Next go to dev.twitter.com and sign in. Create a new app
Place holder
Wednesday, 24 July 2013
Arduino Twitter motion temp project
This was not as difficult as I thought because I found a really easy to follow guide called arduino-tweet.
Firstly, you need a twitter account... funny enough and make your that your signed in before you do step 1, getting the OAuth token.
Download the Arduino Tweet Library here. Put the Twitter folder the Arduino Libraries folder.
The sketch below sends a tweet along with the temperature and the seconds number when motion is detected. I added 35 secs delay so as to not accidentally over do the tweets. Again as with most of my Arduino sketches I built up the string as best as I could, I'm sure it looks horrible to some programming gurus but it works and that when I stopped working with it :)
I will post up some pictures and a wiring diagram later
Firstly, you need a twitter account... funny enough and make your that your signed in before you do step 1, getting the OAuth token.
Download the Arduino Tweet Library here. Put the Twitter folder the Arduino Libraries folder.
The sketch below sends a tweet along with the temperature and the seconds number when motion is detected. I added 35 secs delay so as to not accidentally over do the tweets. Again as with most of my Arduino sketches I built up the string as best as I could, I'm sure it looks horrible to some programming gurus but it works and that when I stopped working with it :)
Anyways heres the Sketch.
#include "SPI.h"
#include "Ethernet.h"
#include <Twitter.h>
void getTemp();
void getMotionTemp();
//Data
float temperature = 0.00;
int temperaturePin = 0;
int secs = 0;
int calibrationTime = 30;
//the time when the sensor outputs a low impulse
long unsigned int lowIn;
//the amount of milliseconds the sensor has to be low
//before we assume all motion has stopped
long unsigned int pause = 5000;
boolean lockLow = true;
boolean takeLowTime;
int pirPin = 7; //the digital pin connected to the PIR sensor's output
int ledPin = 8;
// Enter a MAC address for your controller below
byte mac[] = { 0xXX, 0xXX, 0xXX, 0xXX, 0xXX, 0xXX };
//Server to connect to
Twitter twitter(" ADD YOUR TOKEN HERE");
void setup()
{
delay(1000);
Ethernet.begin(mac);
Serial.begin(9600);
pinMode(pirPin, INPUT);
pinMode(ledPin, OUTPUT);
digitalWrite(pirPin, LOW);
//give the sensor some time to calibrate
Serial.print("calibrating sensor ");
for(int i = 0; i < calibrationTime; i++){
Serial.print(".");
delay(1000);
}
Serial.println(" done");
Serial.println("SENSOR ACTIVE");
delay(50);
}
void loop()
{
delay(5000);
getTemp();
getMotionTemp();
//delay(300000);
delay(30000);
}
void getMotionTemp(){
//String data = String("Motion has been detected and the temperature in my room is "+ String(temperature,2));
//String msg = String(String(temperature,2) + "C");
char msg[140] = "Motion has been detected and the temperature in my room is ";
dtostrf(temperature,1,2, &msg[59]);
char* msg_ending = " C at ";
strcat(msg,msg_ending);
if(digitalRead(pirPin) == HIGH){
digitalWrite(ledPin, HIGH); //the led visualizes the sensors output pin state
if(lockLow){
//makes sure we wait for a transition to LOW before any further output is made:
lockLow = false;
Serial.println("---");
Serial.print("motion detected at ");
secs = millis()/1000;
Serial.print(secs);
Serial.println(" sec");
dtostrf(secs,1,0, &msg[70]);
char* msg_ending_to = " secs";
strcat(msg,msg_ending_to);
Serial.println(msg);
if (twitter.post(msg)) {
int status = twitter.wait();
if (status == 200) {
Serial.println("OK.");
} else {
Serial.print("failed : code ");
Serial.println(status);
}
} else {
Serial.println("connection failed.");
}
delay(50);
}
takeLowTime = true;
}
if(digitalRead(pirPin) == LOW){
digitalWrite(ledPin, LOW); //the led visualizes the sensors output pin state
if(takeLowTime){
lowIn = millis(); //save the time of the transition from high to LOW
takeLowTime = false; //make sure this is only done at the start of a LOW phase
}
//if the sensor is low for more than the given pause,
//we assume that no more motion is going to happen
if(!lockLow && millis() - lowIn > pause){
//makes sure this block of code is only executed again after
//a new motion sequence has been detected
lockLow = true;
Serial.print("motion ended at "); //output
Serial.print((millis() - pause)/1000);
Serial.println(" sec");
delay(50);
}
}
}
float getVoltage(int pin){
return (analogRead(pin) * .004882814);
}
void getTemp()
{
//temperature = (((temperature - 0.5) * 100)*1.8) + 32;
temperature = (getVoltage(temperaturePin) - .5) * 100;
}
Monday, 17 June 2013
Babylon 5 unfairly treated?
Right, I am a huge Sci-fi fan, in fact it's probably my most favorite genre when it comes to television series. And so of course I have watched all the Star Treks - the bread and butter of sci-fi, Stargate, Battle Star Galactica, Sliders, Farscape (another series that warrants the same question) but Babylon 5 completely fell through the gap for me. In fact, I don't think I really even was aware of the series 10 years after the show had ended and while I find this quite sad it was awesome to watch them all consecutively.
Here are a list of reasons why I think Babylon 5 has become probably my most favorite sci-fi series of all time:
I really love the way the series is based around the 4 questions (taken straight from wikipedia):
So those are just a few short reasons of why I really like Babylon 5, like I said I may expand on a few of those points but I'm not sure I need to. Wikipedia is your friend. I have also look on amazon to see if there were any Babylon 5 books written in the expanded universe and luckily there are some and so I have ordered The Technomage Trilogy. I have heard good reviews about it. I'll update this post about what I thought of it later.
Please post your thought on why you like or dislike (boo) this franchise.
Here are a list of reasons why I think Babylon 5 has become probably my most favorite sci-fi series of all time:
- The story arcs are epic. Great stories that focus on major sci-fi themes such Order verses Chaos and Freewill verses Authoritarianism. The Order/Authoritarianism verses Chaos/Freewill theme manifests itself round 2 powerful ancient races, the Vorlons (Order) and the Shadows (Chaos), each with they're own ideologies. This is different from Good verses Evil and although, initially anyway the Vorlons could be reprieved as good and the shadows evil this is really not the case. The other major story line is Babylon 5 breaking away from Earth and creating it own government.
- The dialog, I thought was brilliant. I really liked Bruce Boxleitner as John Sheridan, I thought he had some really powerful lines. I love when a series has a huge cast of secondary major characters who aren't in every episode but maybe every other episode. This gives a really good feeling of a station port were people come and go. G'Kar and Londo Mollari are two such characters who were utilized really well and they're character development was outstanding. G'Kar portrayed by Andreas Katsulas is a fantastic actor and had lots of great scenes.
- The race diversity is great.
- I like the telepath story arc
- The films are great, some better than others, but that's always the case
- The spin off Crusade was really good, I'm disappointed it only lasted 1 series, it would have been great. I liked the development of the techomages and thought Peter Woodward as Galen was an excellent character.
I really love the way the series is based around the 4 questions (taken straight from wikipedia):
- Who are you? (The Vorlon Question)
- What do you want? (The Shadow Question)
- Why are you here? (Emperor Turhan's Question)
- Where are you going? (Techno Mage's Question)
So those are just a few short reasons of why I really like Babylon 5, like I said I may expand on a few of those points but I'm not sure I need to. Wikipedia is your friend. I have also look on amazon to see if there were any Babylon 5 books written in the expanded universe and luckily there are some and so I have ordered The Technomage Trilogy. I have heard good reviews about it. I'll update this post about what I thought of it later.
Please post your thought on why you like or dislike (boo) this franchise.
Guild Wars 2 overview
After playing World of Warcraft for many many years I eventually froze my account and I'm not too sure if I'll go back. Don't get me wrong, it's still a great game, I just think it's time to stop investing time in it.
This was difficult, however, because I really love the Warcraft Universe and have read many novels, I replay Warcraft 3 all the time (with cheats - for story), and I love the races and classes. So I may have approached Guild wars 2 with a slight hostility and skepticism (it'll never be as good as WoW); the races are different; the classes; I don't know any back story or history in this universe... It's a blank slate. I think this turned out to be a really good thing though. If your anything like me, one of the best things about MMO's is the creation of your avatars and testing them out.
I was a bit slow to fully take to it and in fact it was almost out a year before I started playing somewhat properly largely because I'm a Mac user and the Mac client didn't come out a while later ( playing on Bootcamp was just a pain) but also because it felt like I was turning my back on WoW, a fairly big chunk of my gaming life -- I was still only ever a casual player.
Right, enough reminiscing about what was and lets take a look at what is - now; Guild Wars 2.
I really think this game is superb. Below is a pro/con list:
Ok, I don't have a lot of cons I can think of at the moment, I'm sure that there is a few more. however I do have a few nuances:
So these are just some of the things I wanted to mention about the game. I wanted it to be brief and simple initial experiences of what I thought of the game. I also deliberately made quite a few Wow comparisons because that is the game I moved from, essentially replacing. There are loads of websites and forums that go really in-depth, like all MMO's, so if you want more info just ask Google. The Guild Wars 2 wiki is really good.
I really think this is a great game and would recommend it to anyone who likes the genre.
This was difficult, however, because I really love the Warcraft Universe and have read many novels, I replay Warcraft 3 all the time (with cheats - for story), and I love the races and classes. So I may have approached Guild wars 2 with a slight hostility and skepticism (it'll never be as good as WoW); the races are different; the classes; I don't know any back story or history in this universe... It's a blank slate. I think this turned out to be a really good thing though. If your anything like me, one of the best things about MMO's is the creation of your avatars and testing them out.
I was a bit slow to fully take to it and in fact it was almost out a year before I started playing somewhat properly largely because I'm a Mac user and the Mac client didn't come out a while later ( playing on Bootcamp was just a pain) but also because it felt like I was turning my back on WoW, a fairly big chunk of my gaming life -- I was still only ever a casual player.
Right, enough reminiscing about what was and lets take a look at what is - now; Guild Wars 2.
I really think this game is superb. Below is a pro/con list:
Pros
- No subscription fee. Even if your only mildly interested in the game, why wouldn't you pick it up?
- The graphics are really nice; of course I can't really get the most out of it as the computer I'm playing on, the iMac, does not meet the minimum requirements although it still plays and looks fine. I love the look of the UI and the map and the cut scenes - that sort of sketchy arty look, I'm sure you know what I mean if you play.
- Character races/professions are new, different and exciting
- The game play style is really different. I wasn't sure about it at first but now I do really like it. I like the small pool of moves that don't clutter, I love the fact that moves are linked to weapons, which means that in the first couple of hours your after access to tons of different playing styles.
- I love the open group quests where you only have to be in the area of others doing the quest to get experience from it and you can join any fight/quest without having to join a group (of course this is not always the case, but sometimes you just want to cruise about on your own) if you don't want to And you don't have to accept quests or hand them in. I really really like this.
- New class types, I guess I should really call it professions, I'll talk a bit more about them down below
- Instant Auction House - called Trading Post.
Cons
- You only have 5 character slots. You can get more but I think it costs some money.
Ok, I don't have a lot of cons I can think of at the moment, I'm sure that there is a few more. however I do have a few nuances:
Nuances
- I'm not familiar with the story and so am not too sure what's going on at the moment
- This goes for the map also, knowing where to go and where things are
- Crafts - I know it's like WoW professions but it took me a while to get a handle on it
- Different weapons can drastically change game play and so finding the right combination/fit for you will take quite some time -- but that's a major part of the fun, also there are tons of forums and youtube videos
Races
- Charr - They are like cat based werewolfs -- werecats? They look pretty cool and run on all fours, they just weren't for me.
- Sylvari - I sort of considered them elf like however they are plant based lifeforms with leaves for hair. These weren't really for me either
- Norn - These are like really huge humans - think 7ft wrestlers and vikings. I quite liked these but none of the professions I wanted to play seemed like a good fit for the Norn back story (really only warrior and ranger?)
- Human - These are my favorite class. I think they look good and suit all professions. 4 of 5 of my characters are human. This may be silly because I'm playing the same starting locations 4 times but I don't care.
- Asura - These guys are a cross between Wow gnomes and Stitch from Lilo and Stitch films. I originally didn't like them much but they have grown on me and I now have one in my character slot.
Professions
- Guardian - These are sort of like WoW palidans. Excel in support and survivability. I like this profession and it is one that I use. - First alt.
- Warrior - Standard warrior type, similar to WoW warrior, a great profession for easy play and attack/defense but is not one that I use.
- Thief - Again similar to WoW rogue, utilizes stealth. I never really played rogue in WoW and this class interested me and is one that I use. Last alt.
- Ranger - Similar to Wow Hunter, utilizes pet and bow. Not really for me.
- Elementalist - Similar to Wow mage but I think more versatile as you have access to all four elements. Actually it may also have some Shaman qualities, a mage/shaman hybrid. I am interested in this class by don't have the slots.
- Engineer - A really unique profession, may have been inspired by Team Fortress. I really like this profession, it's really quite different, uses guns, turrents and belts and kits which do a ton of stuff such as medic, grenader, bomber, flamethrower, elixers that have many boons (buffs). This is one that I use, however having such a vast amount of different skills it may be difficult to juggle them. - Second alt.
- Mesmer - Another really unique profession. Can cast illusions (clones and phantasms) to confuse and manipulate foes. This could be my main profession at the moment, it really interesting but could be quiet difficult to use. - Main
- Necromancer - Maybe a sort of WoW warlock but just in name classification, and perhaps it's use of minions and it does have a demon mode of sorts. I was too sure about this class but after seeing a couple of youtube video, I changed my mind and could be a contender for my main, not sure yet.
So these are just some of the things I wanted to mention about the game. I wanted it to be brief and simple initial experiences of what I thought of the game. I also deliberately made quite a few Wow comparisons because that is the game I moved from, essentially replacing. There are loads of websites and forums that go really in-depth, like all MMO's, so if you want more info just ask Google. The Guild Wars 2 wiki is really good.
I really think this is a great game and would recommend it to anyone who likes the genre.
Saturday, 15 June 2013
Useful Oracle Commands
These are some of the oracle commands I use frequently. You should be logged on as SYS.
This SQL statement shows the users/systems that are connected to the database:
select * from v$session;
The SQL statement shows the SQL statements that are being run and also historical statements:
select * from v$sql;
It can be useful to check what sql a session is executing by using the sql_id key.
Will show you all the queries that took a long time to run:
select * from v$_longops;
It can be annoying when looking dates in the database that the dates do not show the time. The following command is a quick
way to display the time:
alter session set nls_date_format=‘yyyy-mm-dd hh24:mi:ss’;way to display the time:
To create a tablespace:
create tablespace [tablespace_name] datafile ‘[tablespace_name].dbf’ size [database_size] reuse autoextend on next 10M maxsize unlimited extent management local uniform size 1M;
The tablespace_name is the name you want to give the tablesapce
The database_size is the size you want to designate e.g. 2G
The database_size is the size you want to designate e.g. 2G
You will also need to create a user for the tablespace:
create user [user] identified by “[password]” default tablespace [tablespace_name] temporary tablespace TEMPprofile DEFAULT;
The user will also need permissions:
grant dba to [user]; grant connect, resource to [user]; grant unlimited tablespace to [user];
Note you would not want to grant dba to the user. You will need to make your own permissions.
Import/Export
The standard import functions are run from the command line and are as follows:
The standard export functions are run from the command line and are as follows:
exp [user]/[password]@[tns_name] file=file_name.dmp owner=[user] log=file_name.log statistics=none compress=yDatapump
Create a database directory by logging in as sys[dba] and runCREATE DIRECTORY [directory_name] AS ‘[directory_path]’;
GRANT read, write ON DIRECTORY [directory_name] TO [user];
To drop the directory
DROP DIRECTORY [directory_name];
To export
expdp [user]/[password]@[tns_name] directory=[directory_name] dumpfile=[dumpfile_name].dmp schemas=[owner] logfile=[logfile_name].log
To import
impdp [user]/[password]@[tns_name] directory=[directory_name] dumpfile=[dumpfile_name].dmp logfile=[logfile_name].log
other parameters
tables= comma separated list of table names
table_exists_action=truncate
Useful MySQL Commands
To create a database, log in as root:
mysql -uroot -p
create database [database_name]; create user ‘[user]’@’%’ identified by ‘[password]’; (% is a wildcard for any host) grant all privileges on [database_name].* to ‘[user]’@’%’ with grant option;
To look at the schema rows in the database:
select table_name,table_rows from information_schema.Tables where table_schema=‘[database_name]’;
select table_name,table_rows from information_schema.Tables where table_schema=‘[database_name]’;
To look at all the database variables:
show variables;
show variables;
Some useful variables are:
set global slow_query_log=‘ON’ set global slow_query_log=‘OFF’ (remember to turn it off) set long_query_time = 0.1 (time in seconds)
Importing and Exporting in MySQL is really easy:
Import
mysql -u[user] -p[password] -h[host] [database_name] < [file_name].dump
Export
mysqldump -u[user] -p[password] -h[host] [database_name] > [file_name].dump
Note: There is no space between the dash parameter names and the parameters. Also note the change of direction of the < > symbols.
If you work with MySQL alot, you may find that at some point you need to import or export a signal table. As far as I know there isn’t a nice and handy mysql command to do this but it is still easy to do it using SED, a language native to linux systems:
1. Export full database.
mysqldump -u[user] -p[password] -h[host] [database_name] > [file_name].dump
2. Use SED command, replacing table_name with the table you want
sed -n -e ‘/DROP TABLE IF EXISTS `[table_name]`/,/UNLOCK TABLES/p’ database_export.dump > table_name.dump
3. Import table the same way that you would import a database
mysql -u[user] -p[password] -h[host] [database_name] < [table_name].dump
How I created my first game
I have always been interested in gaming and have been mildly curious about how a game fits together, that is from intro screen to credits. I’m not too sure if i’ll follow this project through to the with this but i’ll attempt to anyway but I'll document my experiences anyway and it might help someone else to get started. This tutorial does not include the actual coding of my game; there are many examples on the web and to be honest if you are planning in creating a first game your first game will be a copy/paste from one of those found on the web. You can then add or remove parts to see how it works. I think more importantly is getting your computer game making ready.
Step 1 - Choosing software
After a bit of investigation I thought that the easiest game to start building would be a Flash game however I only want to use open-source/free software. I found that Haxe would suit my needs because can be compiled to all popular programming platforms such as JavaScript, Flash, NekoVM, PHP, C++, C# which means that I can try and make my game work on mobile devices, such as Android and iOS.
Firstly, I’m a Mac user and it was a bit difficult to find the right fit of applications. Mac spec used is iMac 10.6.8 snow leopard.
My first idea was inspired by Canabalt. pixelprospector was a very useful site and found that Canabalt was built using Flixel. Okay, Flixel got it, this is what I will try and use .... now what.. Well Flixel - correct me if I’m wrong is just a library and so you can use it with your favourite text editor, I use Sublime Text 2.
Step 2 - Installing
So, I saw that Adobe has a Flex sdk and I read at flixel.org/download.html that this is pretty much required if you are using a unix operating system such as Mac or linux. It is under the header ‘Flixel Development Environments’ -> The MXMLC commandline tools. Follow the link and there is either a nice big download button or else it will just automatically download. The direct link is here.
I also saw flixel source code at github http:/www.github.com/AdamAtomic/flixel/. I’m not sure if the Adobe Flex sdk covers these but I’m going to download it anyway for good measure, so if I need to import the files well I can. That bring me to my next download - FYI I’m starting from a clean install and so have nothing installed - download git if you want - git-scm.com/download/mac.
OK, so after a bit of trial and error (trying to find the right software package for me ) I found HaxeNME and this works really well with the haxe plugin for sublime text. Here is a good tutorial on how to set it up on YouTube.
First download haxeNME here.
At the command line
nme -- to check that it has installed
haxe -- to check that it has installed
haxelib install flixel - to install flixel libraries
Next install the sublime package manager if you don't already have it.
Essentially in sublime text 2 press cmd+` for the console and copy the following:
import urllib2,os; pf='Package Control.sublime-package'; ipp=sublime.installed_packages_path(); os.makedirs(ipp) if not os.path.exists(ipp) else None; urllib2.install_opener(urllib2.build_opener(urllib2.ProxyHandler())); open(os.path.join(ipp,pf),'wb').write(urllib2.urlopen('http://sublime.wbond.net/'+pf.replace(' ','%20')).read()); print('Please restart Sublime Text to finish installation')
Then restart the editor.
press cmd+shift p and start typing 'Pack'... a list should appear. Click ‘Package Control: Install Package’
Search for haxe and install.
Step 3 - Hello
This got me for a while. It turns out that if you have never used flash player to open a .swf file Mac won’t know what to open it with. As an aside, I started this project from a clean os install.
What I did was download the non browser version of flash player for mac. Open it -> File -> open -> and select the hello_world.swf file and it should work. From then on swf files will be associated with flash player.
Yes, I reran 'nme test flash' and my first ‘hello world’ app works great.
Android
So once you build an app using haxe you can compile it using:
- nme test android -- instead of nme test flash
Now it will complain that it does not have the necessary things so here’s what I did:
- nme setup android
I think you also need to install apache-ant, the easiet way to do this was through mac ports.
mac-ports requires xcode - if your on snow leopard you will need xcode 3.2.6 and iOS SDK 4.3 for Snow Leopard at developer.apple.com/downloads/index.action. Install this before you download mac-ports.
Then run the command -> sudo port install apache-ant.
Next instead of using an android emulator I just used my old HTC smart phone. To be able to use the phone for testing, on the phone go to settings -> applications -> development and tick USB debugging and Allow mock locations.
Then when you run -> nme test android in the app folder it will run the app on the phone.
Conclusion
This tutorial was just to explain some of the issues I had trying to get started so I don't think that it's really that relevent to post my code. I ended up not doing the aurorun game and instead made a small platformer which was based on an excellent tutorial by Codey Wodey.
It’s really simple:
- I created a number map
- I added some collectibles
- The collectibles count down from zero.
- The time is displayed when the count reaches zero.
- I used the graphics from the tutorial.
To further my learning of game making I would like to be able to do the following.
- Click the app and be presented with a title screen with a button to click ‘play’.
- On play click launch the game.
- How do I get a continuously visible timer.
- When count is zero execute ‘level completed’ screen.
- When ‘level completed’ screen is touched execute ‘game finished’ screen. on touch execute ‘title screen’.
I have a few things I need to understand though:
- I want to make my own textures and sprites, and I see png files with multiple images in it. Is there a special way to make them and how to I access the different images in a single file.
- I want to be able to run it on on a mobile device, say android, how do I use/make touch inputs.
- how do I make an intro screen that you can press ‘play’.
- how do you make a finished level screen.
- how do you make a finished game screen i.e. credits.
Friday, 14 June 2013
Arduino temperature logger to MySQL
As a first time blogger I decided to create a tutorial which is essentially my experiences of creating an Arduino sketch. The project is to log temperature recordings from the Arduino Ethernet directly to a local mysql database.
Components
- Arduino Ethernet
- Thermometer (TMP36)
- FTDI cable (or chip with usb cable)
- 5 wires
Step 1
Download the arduino software from here.
Step 2
Download FTDI driver from here. Choose the valid driver for your computer under the sub-heading 'Currently Supported VCP Drivers'.
Step 3
Follow the steps to create the Arduino example circ-10. A couple good guide can be found on the The Arduino Experience blog and oomalout. We will be using this code to calculate the temperature. When you upload the sketch you can go to Arduino -> Tools -> Serial Monitor to view the temperature output.
Step 4
Once you get that sketch working we can start to look at mysql. A great library can be found at Chuck's Blog. It takes a bit of effort locating the files, they can be found here. You will also need the 'sha1' library. I can't remember exactly where I downloaded it from but I think this is one is the same Arduino-oath-token. Put sha1.cpp and sha1.h in a folder called sha1 in your Arduino Library folder.
Step 5 - Preparing database
I'm going to assume you already got MySQL installed and running. Here is the SQL statement to create the table. The main thing to understand here is that 'created_at' is a timestamp defaulted to current_timestamp. This adds the time automatically when a record is inserted, so you don't have to code for it.
CREATE TABLE `temperature` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`temperature` float DEFAULT NULL,
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8
Step 6
So hopefully everything is properly installed. Here is the code.
Note. I have know prior knowledge of C programming and so I found building the insert string really difficult. It is most likely horrible code, if there is a better way to do this please post.
Replace the X's in the mac address with the characters on the back of your arduino. Replace the server_addr with the ip of the computer that has your mysql database.
#include "SPI.h"
#include "Ethernet.h"
#include "sha1.h"
#include "mysql.h"
/* Setup for Ethernet Library */
byte mac_addr[] = { 0xX, 0xX, 0xX, 0xX, 0xX, 0xX };
IPAddress server_addr(192, 168, 1, 1);
/* Setup for the Connector/Arduino */
Connector my_conn; // The Connector/Arduino reference
int temperaturePin = 0;
char user[] = "arduino";
char password[] = "arduino";
void setup() {
Ethernet.begin(mac_addr);
Serial.begin(14400);
delay(1000);
Serial.println("Connecting...");
if (my_conn.mysql_connect(server_addr, 3306, user, password))
{
Serial.println("Query Success!");
}
else
Serial.println("Connection failed.");
}
void loop() {
addTempEvent();
}
//taken straight from the adruino circ-10 example
float getVoltage(int pin){
return (analogRead(pin) * .004882814);
}
void addTempEvent()
{
//taken straight from the adruino circ-10 example
float temperature = getVoltage(temperaturePin);
//temperature = (((temperature - 0.5) * 100)*1.8) + 32; //Fahrenheit
temperature = (temperature - 0.5) * 100;
//I'm sure there is a cleaner way to build this string
char insert_sql[110] = "INSERT INTO tempMonitor.temperature (id,temperature) VALUES (ID,";
dtostrf(temperature,1,2, &insert_sql[64]);
char* array3 = ")";
strcat(insert_sql,array3);
//Serial.println(insert_sql);
delay(5000);
my_conn.cmd_query(insert_sql);
delay(120000);
}
I'm not sure if the temperature was very accurate. I may buy a better one or some of the numbers may need tweaked. However I consider the project a success as it does what I set out to do.
Any questions or improvements are more than welcome.
Subscribe to:
Comments (Atom)