Posts with «send» label

Send HEX values to Arduino

FIVE MINUTE TUTORIAL

Project Description: Sending Hex values to an Arduino UNO


This simple tutorial will show you how to send Hexadecimal values from a computer to an Arduino Uno. The "Processing" programming language will be used to send the HEX values from the computer when a mouse button is pressed. The Arduino will use these values to adjust the brightness of an LED.



 

Learning Objectives


  • To Send Hexadecimal (Hex) values from a computer to the Arduino
  • Trigger an action based on the press of a mouse button
  • Learn to create a simple Computer to Arduino interface
  • Use Arduino's PWM capabilities to adjust brightness of an LED
  • Learn to use Arduino's analogWrite() function
  • Create a simple LED circuit


 

Parts Required:


Fritzing Sketch


The diagram below will show you how to connect an LED to Digital Pin 10 on the Arduino.
Don't forget the 330 ohm resistor !
 


 
 

Arduino Sketch


The latest version of Arduino IDE can be downloaded here.
 
  1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/* ==================================================================================================================================================
         Project: 5 min tutorial: Send Hex from computer to Arduino
          Author: Scott C
         Created: 21th June 2015
     Arduino IDE: 1.6.4
         Website: http://arduinobasics.blogspot.com/p/arduino-basics-projects-page.html
     Description: Arduino Sketch used to adjust the brightness of an LED based on the values received
                  on the serial port. The LED needs to be connected to a PWM pin. In this sketch
                  Pin 10 is used, however you could use Pin 3, 5, 6, 9, or 11 - if you are using an Arduino Uno.
===================================================================================================================================================== */

byte byteRead; //Variable used to store the byte received on the Serial Port
int ledPin = 10; //LED is connected to Arduino Pin 10. This pin must be PWM capable.

void setup() {
 Serial.begin(9600); //Initialise Serial communication with the computer
 pinMode(ledPin, OUTPUT); //Set Pin 10 as an Output pin
 byteRead = 0;                   //Initialise the byteRead variable to zero.
}

void loop() {
  if(Serial.available()) {
    byteRead = Serial.read(); //Update the byteRead variable with the Hex value received on the Serial COM port.
  }
  
  analogWrite(ledPin, byteRead); //Use PWM to adjust the brightness of the LED. Brightness is determined by the "byteRead" variable.
}


 


 
 

Processing Sketch


The latest version of the Processing IDE can be downloaded here.
 
  1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/* ==================================================================================================================================================
         Project: 5 min tutorial: Send Hex from computer to Arduino
          Author: Scott C
         Created: 21th June 2015
  Processing IDE: 2.2.1
         Website: http://arduinobasics.blogspot.com/p/arduino-basics-projects-page.html
     Description: Processing Sketch used to send HEX values from computer to Arduino when the mouse is pressed.
                  The alternating values 0xFF and 0x00 are sent to the Arduino Uno to turn an LED on and off.
                  You can send any HEX value from 0x00 to 0xFF. This sketch also shows how to convert Hex strings
                  to Hex numbers.
===================================================================================================================================================== */

import processing.serial.*; //This import statement is required for Serial communication

Serial comPort;                       //comPort is used to write Hex values to the Arduino
boolean toggle = false; //toggle variable is used to control which hex variable to send
String zeroHex = "00"; //This "00" string will be converted to 0x00 and sent to Arduino to turn LED off.
String FFHex = "FF"; //This "FF" string will be converted to 0xFF and sent to Arduino to turn LED on.

void setup(){
    comPort = new Serial(this, Serial.list()[0], 9600); //initialise the COM port for serial communication at a baud rate of 9600.
    delay(2000);                      //this delay allows the com port to initialise properly before initiating any communication.
    background(0); //Start with a black background.
    
}


void draw(){ //the draw() function is necessary for the sketch to compile
    //do nothing here //even though it does nothing.
}


void mousePressed(){ //This function is called when the mouse is pressed within the Processing window.
  toggle = ! toggle;                   //The toggle variable will change back and forth between "true" and "false"
  if(toggle){ //If the toggle variable is TRUE, then send 0xFF to the Arduino
     comPort.write(unhex(FFHex)); //The unhex() function converts the "FF" string to 0xFF
     background(0,0,255); //Change the background colour to blue as a visual indication of a button press.
  } else {
    comPort.write(unhex(zeroHex)); //If the toggle variable is FALSE, then send 0x00 to the Arduino
    background(0); //Change the background colour to black as a visual indication of a button press.
  }
}


 

The Video


 

The tutorial above is a quick demonstration of how to convert Hex strings on your computer and send them to an Arduino. The Arduino can use the values to change the brightness of an LED as shown in this tutorial, however you could use it to modify the speed of a motor, or to pass on commands to another module. Hopefully this short tutorial will help you with your project. Please let me know how it helped you in the comments below.

 
 



If you like this page, please do me a favour and show your appreciation :

 
Visit my ArduinoBasics Google + page.
Follow me on Twitter by looking for ScottC @ArduinoBasics.
I can also be found on Pinterest and Instagram.
Have a look at my videos on my YouTube channel.


 
 
             


 
 



However, if you do not have a google profile...
Feel free to share this page with your friends in any way you see fit.

Send HEX values to Arduino

FIVE MINUTE TUTORIAL

Project Description: Sending Hex values to an Arduino UNO


This simple tutorial will show you how to send Hexadecimal values from a computer to an Arduino Uno. The "Processing" programming language will be used to send the HEX values from the computer when a mouse button is pressed. The Arduino will use these values to adjust the brightness of an LED.



 

Learning Objectives


  • To Send Hexadecimal (Hex) values from a computer to the Arduino
  • Trigger an action based on the press of a mouse button
  • Learn to create a simple Computer to Arduino interface
  • Use Arduino's PWM capabilities to adjust brightness of an LED
  • Learn to use Arduino's analogWrite() function
  • Create a simple LED circuit


 

Parts Required:


Fritzing Sketch


The diagram below will show you how to connect an LED to Digital Pin 10 on the Arduino.
Don't forget the 330 ohm resistor !
 


 
 

Arduino Sketch


The latest version of Arduino IDE can be downloaded here.
 
  1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/* ==================================================================================================================================================
         Project: 5 min tutorial: Send Hex from computer to Arduino
          Author: Scott C
         Created: 21th June 2015
     Arduino IDE: 1.6.4
         Website: http://arduinobasics.blogspot.com/p/arduino-basics-projects-page.html
     Description: Arduino Sketch used to adjust the brightness of an LED based on the values received
                  on the serial port. The LED needs to be connected to a PWM pin. In this sketch
                  Pin 10 is used, however you could use Pin 3, 5, 6, 9, or 11 - if you are using an Arduino Uno.
===================================================================================================================================================== */

byte byteRead; //Variable used to store the byte received on the Serial Port
int ledPin = 10; //LED is connected to Arduino Pin 10. This pin must be PWM capable.

void setup() {
 Serial.begin(9600); //Initialise Serial communication with the computer
 pinMode(ledPin, OUTPUT); //Set Pin 10 as an Output pin
 byteRead = 0;                   //Initialise the byteRead variable to zero.
}

void loop() {
  if(Serial.available()) {
    byteRead = Serial.read(); //Update the byteRead variable with the Hex value received on the Serial COM port.
  }
  
  analogWrite(ledPin, byteRead); //Use PWM to adjust the brightness of the LED. Brightness is determined by the "byteRead" variable.
}


 


 
 

Processing Sketch


The latest version of the Processing IDE can be downloaded here.
 
  1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/* ==================================================================================================================================================
         Project: 5 min tutorial: Send Hex from computer to Arduino
          Author: Scott C
         Created: 21th June 2015
  Processing IDE: 2.2.1
         Website: http://arduinobasics.blogspot.com/p/arduino-basics-projects-page.html
     Description: Processing Sketch used to send HEX values from computer to Arduino when the mouse is pressed.
                  The alternating values 0xFF and 0x00 are sent to the Arduino Uno to turn an LED on and off.
                  You can send any HEX value from 0x00 to 0xFF. This sketch also shows how to convert Hex strings
                  to Hex numbers.
===================================================================================================================================================== */

import processing.serial.*; //This import statement is required for Serial communication

Serial comPort;                       //comPort is used to write Hex values to the Arduino
boolean toggle = false; //toggle variable is used to control which hex variable to send
String zeroHex = "00"; //This "00" string will be converted to 0x00 and sent to Arduino to turn LED off.
String FFHex = "FF"; //This "FF" string will be converted to 0xFF and sent to Arduino to turn LED on.

void setup(){
    comPort = new Serial(this, Serial.list()[0], 9600); //initialise the COM port for serial communication at a baud rate of 9600.
    delay(2000);                      //this delay allows the com port to initialise properly before initiating any communication.
    background(0); //Start with a black background.
    
}


void draw(){ //the draw() function is necessary for the sketch to compile
    //do nothing here //even though it does nothing.
}


void mousePressed(){ //This function is called when the mouse is pressed within the Processing window.
  toggle = ! toggle;                   //The toggle variable will change back and forth between "true" and "false"
  if(toggle){ //If the toggle variable is TRUE, then send 0xFF to the Arduino
     comPort.write(unhex(FFHex)); //The unhex() function converts the "FF" string to 0xFF
     background(0,0,255); //Change the background colour to blue as a visual indication of a button press.
  } else {
    comPort.write(unhex(zeroHex)); //If the toggle variable is FALSE, then send 0x00 to the Arduino
    background(0); //Change the background colour to black as a visual indication of a button press.
  }
}


 

The Video


 

The tutorial above is a quick demonstration of how to convert Hex strings on your computer and send them to an Arduino. The Arduino can use the values to change the brightness of an LED as shown in this tutorial, however you could use it to modify the speed of a motor, or to pass on commands to another module. Hopefully this short tutorial will help you with your project. Please let me know how it helped you in the comments below.

 
 



If you like this page, please do me a favour and show your appreciation :

 
Visit my ArduinoBasics Google + page.
Follow me on Twitter by looking for ScottC @ArduinoBasics.
I can also be found on Pinterest and Instagram.
Have a look at my videos on my YouTube channel.


 
 
             


 
 



However, if you do not have a google profile...
Feel free to share this page with your friends in any way you see fit.

Arduino Tutorials – Chapter 30 – twitter

Learn how to tweet from your Arduino.

This is chapter thirty of our huge Arduino tutorial seriesUpdated 16/06/2014

In this article you will learn how to send messages from an Ethernet-enabled Arduino to twitter. For the uninitiated who may be thinking “what is all this twitter nonsense about?”, twitter is a form of microblogging. 

You can create a message with a maximum length of 140 characters, and broadcast this on the twitter service. For people to receive your messages (or tweets) they also need to be a member of twitter and choose to subscribe to your tweets.

Generally people will use the twitter service using one of two methods: either using a web browser, or using the twitter application on a smartphone or tablet computer. For example, here is a typical web browser view:

… and here is an example of a twitter application running on an Android OS smartphone:

The neat thing about twitter on a mobile device is that if your username is mentioned in a tweet, you will be notified pretty well immediately as long as you have mobile data access. More on that later. In some areas, you can set twitter to send tweets from a certain user to your mobile phone via SMS – however if doing so be careful to confirm possible charges to your mobile phone account.

Finally, if you are worried about privacy with regards to your tweets, you can set your account to private and only allow certain people to follow your tweets.

So let’s get started.

First of all – you will need a twitter account. If you do not have one, you can sign up for one here. If you already have a twitter account, you can always open more for other uses – such as an Arduino.

For example, my twitter account is @tronixstuff, but my demonstration machine twitter account is @tronixstuff2. Then I have set my primary account to follow my machine’s twitter account.

Now log into twitter with using the account you will have for your Arduino and visit this page and get yourself a token by following the Step One link. The process will take you through authorising the “tweet library” page to login to your twitter account – this is ok. It will then present you with a long text called a “token”, for example:

Save your token somewhere safe, as you will need to insert it into your Arduino sketch. Finally, don’t give it to others as then they will be able to post onto twitter using your account. Next, follow step two from the same page – which involves download and installation of the required Arduino library.

Now for the hardware.

You will need an Arduino Uno or compatible board with an Ethernet shield that uses the W5100 Ethernet controller IC (pretty much all of them) – or consider using a Freetronics EtherTen – as it has everything all on the one board, plus some extras:

Furthermore you will need to power the board via the external DC socket – the W5100 IC uses more current than the USB power can supply. A 9V 1A plug pack/wall wart will suffice. Finally it does get hot – so be careful not to touch the W5100 after extended use. In case you’re not sure – this is the W5100 IC:

If you’re looking for an Arduino-twitter solution with WiFi, check out the Arduino Yún tutorials.

From this point it would be a good idea to check your hardware is working. To do so, please run the webserver example sketch as explained in chapter sixteen (Ethernet). While you do that, we’ll have a break…

Sending your first tweet

If you want your Arduino to send a simple tweet consider the following sketch. We have a simple function tweet() which simply sends a line of text (which has a maximum length of 140 characters). Don’t forget to update your IP address, MAC address and token:

// Simple twitter interface

#include <SPI.h>
#include <Ethernet.h>
#include <Twitter.h>

// Alter IP address to suit your own network!
byte mac[] = {   0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; // create MAC address for ethernet shield
byte ip[] = {   192, 168, 0, 99}; // choose your own IP for ethernet shield
Twitter twitter("aaaaaaa"); // replace aaaaaaa with your token

void setup()
{
  delay(5000);
  Ethernet.begin(mac, ip);
  Serial.begin(9600);
}

void tweet(char msg[])
{
  Serial.println("connecting ...");
  if (twitter.post(msg))
  {
    // Specify &Serial to output received response to Serial.
    // If no output is required, you can just omit the argument, e.g.
    // int status = twitter.wait();
    int status = twitter.wait(&Serial);
    if (status == 200)
    {
      Serial.println("OK.");
    } 
    else
    {
      Serial.print("failed : code ");
      Serial.println(status);
    }
  } 
  else
  {
    Serial.println("connection failed.");
  }
}

void loop()
{
  delay(1000);
  tweet("Purple monkey dishwasher");
  do{} while(1>0); // endless loop
}

You can check the status of the tweeting via the serial monitor. For example, if the tweet was successful you will see:

However if you try to send the same tweet more than once in a short period of time, or another error takes place – twitter will return an error message, for example:

And finally if it works, the tweet will appear:

Previously we mentioned that you can be alerted to a tweet by your mobile device. This can be done by putting your own twitter account name in the contents of the tweet.

For example – my normal twitter account is @tronixstuff. If I put the text “@tronixstuff” in the text tweeted by my Arduino’s twitter account – the twitter app on my smartphone will let me know I have been mentioned – as shown in the following video:

You may have noticed in the video that a text message arrived as well – that service is a function of my cellular carrier (Telstra) and may not be available to others. Nevertheless this is a neat way of getting important messages from your Arduino to a smart phone or other connected device.

Sending data in a tweet

So what if you have  a sensor or other device whose data you want to know about via twitter? You can send data generated from an Arduino sketch over twitter without too much effort.

In the following example we’ll send the value from analogue pin zero (A0) in the contents of a tweet. And by adding your twitter @username you will be notified by your other twitter-capable devices:

// Simple twitter interface

#include <SPI.h>
#include <Ethernet.h>
#include <Twitter.h>

// Alter IP address to suit your own network!
byte mac[] = {   0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; // create MAC address for ethernet shield
byte ip[] = {   192, 168, 0, 99}; // choose your own IP for ethernet shield
Twitter twitter("aaaaaaa"); // replace aaaaaaa with your token

int analogZero;
char tweetText[140];

void setup()
{
  delay(5000);
  Ethernet.begin(mac, ip);
  Serial.begin(9600);
}

void tweet(char msg[])
{
  Serial.println("connecting ...");
  if (twitter.post(msg))
  {
    // Specify &Serial to output received response to Serial.
    // If no output is required, you can just omit the argument, e.g.
    // int status = twitter.wait();
    int status = twitter.wait(&Serial);
    if (status == 200)
    {
      Serial.println("OK.");
    } 
    else
    {
      Serial.print("failed : code ");
      Serial.println(status);
    }
  } 
  else
  {
    Serial.println("connection failed.");
  }
}

void loop()
{
  // get some data from A0. 
  analogZero=analogRead(0);

  // assemble message to send. This inserts the value of "analogZero" into the variable "tweetText" at point %d
  sprintf(tweetText, "Pin analogue zero reads: %d. @username.", analogZero); // change @username to your twitter account name

  delay(1000);
  tweet(tweetText);
  do{ } 
  while(1>0); // endless loop
}

You may have noticed a sneaky sprintf function in void loop(). This is used to insert the integer analogZero into the character array tweetText that we send with the tweet() function. And the results of the example:

So you can use the previous sketch as a framework to create your own Arduino-powered data twittering machine. Send temperature alerts, tank water levels, messages from an alarm system, or just random tweets to your loved one.

Conclusion

So there you have it, another useful way to send information from your Arduino to the outside world. Stay tuned for upcoming Arduino tutorials by subscribing to the blog, RSS feed (top-right), twitter or joining our Google Group. Big thanks to @neocat for their work with the twitter  Arduino libraries.

And if you enjoyed the tutorial, or want to introduce someone else to the interesting world of Arduino – check out my book (now in a third printing!) “Arduino Workshop” from No Starch Press.

In the meanwhile have fun and keep checking into tronixstuff.com. Why not follow things on twitterGoogle+, subscribe  for email updates or RSS using the links on the right-hand column? And join our friendly Google Group – dedicated to the projects and related items on this website. Sign up – it’s free, helpful to each other –  and we can all learn something.

Tronixstuff 04 Dec 01:52

Arduino Tutorials – Chapter 30 – twitter

Learn how to tweet from your Arduino.

This is chapter thirty of our huge Arduino tutorial seriesUpdated 16/06/2014

In this article you will learn how to send messages from an Ethernet-enabled Arduino to twitter. For the uninitiated who may be thinking “what is all this twitter nonsense about?”, twitter is a form of microblogging. 

You can create a message with a maximum length of 140 characters, and broadcast this on the twitter service. For people to receive your messages (or tweets) they also need to be a member of twitter and choose to subscribe to your tweets.

Generally people will use the twitter service using one of two methods: either using a web browser, or using the twitter application on a smartphone or tablet computer. For example, here is a typical web browser view:

… and here is an example of a twitter application running on an Android OS smartphone:

The neat thing about twitter on a mobile device is that if your username is mentioned in a tweet, you will be notified pretty well immediately as long as you have mobile data access. More on that later. In some areas, you can set twitter to send tweets from a certain user to your mobile phone via SMS – however if doing so be careful to confirm possible charges to your mobile phone account.

Finally, if you are worried about privacy with regards to your tweets, you can set your account to private and only allow certain people to follow your tweets.

So let’s get started.

First of all – you will need a twitter account. If you do not have one, you can sign up for one here. If you already have a twitter account, you can always open more for other uses – such as an Arduino.

For example, my twitter account is @tronixstuff, but my demonstration machine twitter account is @tronixstuff2. Then I have set my primary account to follow my machine’s twitter account.

Now log into twitter with using the account you will have for your Arduino and visit this page and get yourself a token by following the Step One link. The process will take you through authorising the “tweet library” page to login to your twitter account – this is ok. It will then present you with a long text called a “token”, for example:

Save your token somewhere safe, as you will need to insert it into your Arduino sketch. Finally, don’t give it to others as then they will be able to post onto twitter using your account. Next, follow step two from the same page – which involves download and installation of the required Arduino library.

Now for the hardware.

You will need an Arduino Uno or compatible board with an Ethernet shield that uses the W5100 Ethernet controller IC (pretty much all of them) – or consider using a Freetronics EtherTen – as it has everything all on the one board, plus some extras:

Furthermore you will need to power the board via the external DC socket – the W5100 IC uses more current than the USB power can supply. A 9V 1A plug pack/wall wart will suffice. Finally it does get hot – so be careful not to touch the W5100 after extended use. In case you’re not sure – this is the W5100 IC:

If you’re looking for an Arduino-twitter solution with WiFi, check out the Arduino Yún tutorials.

From this point it would be a good idea to check your hardware is working. To do so, please run the webserver example sketch as explained in chapter sixteen (Ethernet). While you do that, we’ll have a break…

Sending your first tweet

If you want your Arduino to send a simple tweet consider the following sketch. We have a simple function tweet() which simply sends a line of text (which has a maximum length of 140 characters). Don’t forget to update your IP address, MAC address and token:

// Simple twitter interface

#include <SPI.h>
#include <Ethernet.h>
#include <Twitter.h>

// Alter IP address to suit your own network!
byte mac[] = {   0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; // create MAC address for ethernet shield
byte ip[] = {   192, 168, 0, 99}; // choose your own IP for ethernet shield
Twitter twitter("aaaaaaa"); // replace aaaaaaa with your token

void setup()
{
  delay(5000);
  Ethernet.begin(mac, ip);
  Serial.begin(9600);
}

void tweet(char msg[])
{
  Serial.println("connecting ...");
  if (twitter.post(msg))
  {
    // Specify &Serial to output received response to Serial.
    // If no output is required, you can just omit the argument, e.g.
    // int status = twitter.wait();
    int status = twitter.wait(&Serial);
    if (status == 200)
    {
      Serial.println("OK.");
    } 
    else
    {
      Serial.print("failed : code ");
      Serial.println(status);
    }
  } 
  else
  {
    Serial.println("connection failed.");
  }
}

void loop()
{
  delay(1000);
  tweet("Purple monkey dishwasher");
  do{} while(1>0); // endless loop
}

You can check the status of the tweeting via the serial monitor. For example, if the tweet was successful you will see:

However if you try to send the same tweet more than once in a short period of time, or another error takes place – twitter will return an error message, for example:

And finally if it works, the tweet will appear:

Previously we mentioned that you can be alerted to a tweet by your mobile device. This can be done by putting your own twitter account name in the contents of the tweet.

For example – my normal twitter account is @tronixstuff. If I put the text “@tronixstuff” in the text tweeted by my Arduino’s twitter account – the twitter app on my smartphone will let me know I have been mentioned – as shown in the following video:

You may have noticed in the video that a text message arrived as well – that service is a function of my cellular carrier (Telstra) and may not be available to others. Nevertheless this is a neat way of getting important messages from your Arduino to a smart phone or other connected device.

Sending data in a tweet

So what if you have  a sensor or other device whose data you want to know about via twitter? You can send data generated from an Arduino sketch over twitter without too much effort.

In the following example we’ll send the value from analogue pin zero (A0) in the contents of a tweet. And by adding your twitter @username you will be notified by your other twitter-capable devices:

// Simple twitter interface

#include <SPI.h>
#include <Ethernet.h>
#include <Twitter.h>

// Alter IP address to suit your own network!
byte mac[] = {   0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; // create MAC address for ethernet shield
byte ip[] = {   192, 168, 0, 99}; // choose your own IP for ethernet shield
Twitter twitter("aaaaaaa"); // replace aaaaaaa with your token

int analogZero;
char tweetText[140];

void setup()
{
  delay(5000);
  Ethernet.begin(mac, ip);
  Serial.begin(9600);
}

void tweet(char msg[])
{
  Serial.println("connecting ...");
  if (twitter.post(msg))
  {
    // Specify &Serial to output received response to Serial.
    // If no output is required, you can just omit the argument, e.g.
    // int status = twitter.wait();
    int status = twitter.wait(&Serial);
    if (status == 200)
    {
      Serial.println("OK.");
    } 
    else
    {
      Serial.print("failed : code ");
      Serial.println(status);
    }
  } 
  else
  {
    Serial.println("connection failed.");
  }
}

void loop()
{
  // get some data from A0. 
  analogZero=analogRead(0);

  // assemble message to send. This inserts the value of "analogZero" into the variable "tweetText" at point %d
  sprintf(tweetText, "Pin analogue zero reads: %d. @username.", analogZero); // change @username to your twitter account name

  delay(1000);
  tweet(tweetText);
  do{ } 
  while(1>0); // endless loop
}

You may have noticed a sneaky sprintf function in void loop(). This is used to insert the integer analogZero into the character array tweetText that we send with the tweet() function. And the results of the example:

So you can use the previous sketch as a framework to create your own Arduino-powered data twittering machine. Send temperature alerts, tank water levels, messages from an alarm system, or just random tweets to your loved one.

Conclusion

So there you have it, another useful way to send information from your Arduino to the outside world. Stay tuned for upcoming Arduino tutorials by subscribing to the blog, RSS feed (top-right), twitter or joining our Google Group. Big thanks to @neocat for their work with the twitter  Arduino libraries.

And if you enjoyed the tutorial, or want to introduce someone else to the interesting world of Arduino – check out my book (now in a third printing!) “Arduino Workshop” from No Starch Press.

In the meanwhile have fun and keep checking into tronixstuff.com. Why not follow things on twitterGoogle+, subscribe  for email updates or RSS using the links on the right-hand column? And join our friendly Google Group – dedicated to the projects and related items on this website. Sign up – it’s free, helpful to each other –  and we can all learn something.

The post Arduino Tutorials – Chapter 30 – twitter appeared first on tronixstuff.

Tronixstuff 04 Dec 01:52

Tutorial – Send email with the Arduino Yún

Introduction

This is the third in a series of tutorials examining various uses of the Arduino Yún. In this article we’ll examine how your Arduino Yún can send email from a Google email account. Doing so gives you a neat and simple method of sending data captured by the Arduino Yún or other notifications.

Getting Started

If you haven’t already done so, ensure your Arduino Yún can connect to your network via WiFi or cable – and get a Temboo account (we run through this here). And you need (at the time of writing) IDE version 1.5.4 which can be downloaded from the Arduino website.

Finally, you will need a Google account to send email from, so if you don’t have one – sign up here. You might want to give your Arduino Yún an email address of its very own.

Testing the Arduino Yún-Gmail connection

In this first example we’ll run through the sketch provided by Temboo so you can confirm everything works as it should. This will send a simple email from your Arduino Yún to another email address. First, copy the following sketch into the IDE but don’t upload it yet:

/*
  SendAnEmail

  Demonstrates sending an email via a Google Gmail account using the Temboo Arduino Yun SDK.

  This example code is in the public domain.
*/

#include <Bridge.h>
#include <Temboo.h>
#include "TembooAccount.h" // contains Temboo account information

/*** SUBSTITUTE YOUR VALUES BELOW: ***/

// Note that for additional security and reusability, you could
// use #define statements to specify these values in a .h file.

// your Gmail username, formatted as a complete email address, eg "bob.smith@gmail.com"
const String GMAIL_USER_NAME = "sender@gmail.com";

// your Gmail password
const String GMAIL_PASSWORD = "gmailpassword";

// the email address you want to send the email to, eg "jane.doe@temboo.com"
const String TO_EMAIL_ADDRESS = "recipient@email.com";

boolean success = false; // a flag to indicate whether we've sent the email yet or not

void setup() {
  Serial.begin(9600);

  // for debugging, wait until a serial console is connected
  delay(4000);
  while(!Serial);

  Bridge.begin();
}

void loop()
{
  // only try to send the email if we haven't already sent it successfully
  if (!success) {

    Serial.println("Running SendAnEmail...");

    TembooChoreo SendEmailChoreo;

    // invoke the Temboo client
    // NOTE that the client must be reinvoked, and repopulated with
    // appropriate arguments, each time its run() method is called.
    SendEmailChoreo.begin();

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

    // identify the Temboo Library choreo to run (Google > Gmail > SendEmail)
    SendEmailChoreo.setChoreo("/Library/Google/Gmail/SendEmail");

    // set the required choreo inputs
    // see https://www.temboo.com/library/Library/Google/Gmail/SendEmail/ 
    // for complete details about the inputs for this Choreo

    // the first input is your Gmail email address
    SendEmailChoreo.addInput("Username", GMAIL_USER_NAME);
    // next is your Gmail password.
    SendEmailChoreo.addInput("Password", GMAIL_PASSWORD);
    // who to send the email to
    SendEmailChoreo.addInput("ToAddress", TO_EMAIL_ADDRESS);
    // then a subject line
    SendEmailChoreo.addInput("Subject", "Email subject line here");

     // next comes the message body, the main content of the email   
    SendEmailChoreo.addInput("MessageBody", "Email content");

    // tell the Choreo to run and wait for the results. The 
    // return code (returnCode) will tell us whether the Temboo client 
    // was able to send our request to the Temboo servers
    unsigned int returnCode = SendEmailChoreo.run();

    // a return code of zero (0) means everything worked
    if (returnCode == 0) {
        Serial.println("Success! Email sent!");
        success = true;
    } else {
      // a non-zero return code means there was an error
      // read and print the error message
      while (SendEmailChoreo.available()) {
        char c = SendEmailChoreo.read();
        Serial.print(c);
      }
    } 
    SendEmailChoreo.close();

    // do nothing for the next 60 seconds
    delay(60000);
  }
}

Before uploading you need to enter five parameters – the email address to send the email with, the password for that account, the recipient’s email address, and the email’s subject line and content. These can be found in the following lines in the sketch – for example:

const String GMAIL_USER_NAME = "sender@gmail.com";
const String GMAIL_PASSWORD = "emailpassword";
const String TO_EMAIL_ADDRESS = "recipient@email.com";
SendEmailChoreo.addInput("Subject", "This is the subject line of the email");
SendEmailChoreo.addInput("MessageBody", "And this is the content of the email");

So enter the required data in the fields above. If you’re sending from a Google Apps account instead of a Gmail account – that’s ok, just enter in the sending email address as normal. Temboo and Google will take care of the rest.

Finally, create your header file by copying the the header file data from here (after logging to Temboo) into a text file and saving it with the name TembooAccount.h in the same folder as your sketch from above. You know this has been successful when opening the sketch, as you will see the header file in a second tab, for example:

Now you can upload the sketch, and after a few moments check the recipient’s email account. If all goes well you will be informed by the IDE serial monitor as well (if your Yún is connected via USB). It’s satisfying to see an email come from your Arduino Yún, for example in this short video.

If your email is not coming through, connect your Arduino Yún via USB (if not already done so) and open the serial monitor. It will let you know if there’s a problem in relatively plain English – for example:

Error
A Step Error has occurred: “An SMTP error has occurred. Make sure that your credentials are correct and that you’ve provided a fully qualified Gmail
username (e.g., john.smith@gmail.com) for the Username input. When using Google 2-Step Verification, make sure to
provide an application-specific password. If this problem persists, Google may be restricting access to your account, and you’ll need to
explicitly allow access via gmail.com.”. The error occurred in the Stop (Authentication error) step.
HTTP_CODE
500


So if this happens, check your email account details in the sketch, and try again.

Sending email with customisable subject and content data

The example sketch above is fine if you want to send a fixed message. However what if you need to send some data? That can be easily done. For our example we’ll generate some random numbers, and integrate them into the email subject line and content. This will give you the framework to add your own sensor data to emails from your Arduino Yún. Consider the following sketch:

/*
  SendAnEmail

  Demonstrates sending an email via a Google Gmail account using the Temboo Arduino Yun SDK.

  This example code is in the public domain.
*/

#include <Bridge.h>
#include <Temboo.h>
#include "TembooAccount.h" // contains Temboo account information

/*** SUBSTITUTE YOUR VALUES BELOW: ***/

// Note that for additional security and reusability, you could
// use #define statements to specify these values in a .h file.

// your Gmail username, formatted as a complete email address, eg "bob.smith@gmail.com"
const String GMAIL_USER_NAME = "sender@gmail.com";

// your Gmail password
const String GMAIL_PASSWORD = "gmailpassword";

// the email address you want to send the email to, eg "jane.doe@temboo.com"
const String TO_EMAIL_ADDRESS = "recipient@email.com";

int a,b; // used to store our random numbers
boolean success = false; // a flag to indicate whether we've sent the email yet or not

void setup() 
{
  Serial.begin(9600);
  // for debugging, wait until a serial console is connected
  delay(4000);
  while(!Serial);
  Bridge.begin();
  randomSeed(analogRead(0)); // fire up random number generation
}

void loop()
{
  // generate some random numbers to send in the email
  a = random(1000);
  b = random(1000);
  // compose email subject line into a String called "emailSubject"
  String emailSubject("The random value of a is: ");
  emailSubject += a;
  emailSubject += " and b is: ";
  emailSubject += b;  
  // compose email content into a String called "emailContent"
  String emailContent("This is an automated email from your Arduino Yun. The random value of a is: ");
  emailContent += a;
  emailContent += " and b is: ";
  emailContent += b;  
  emailContent += ". I hope that was of some use for you. Bye for now.";  

  // only try to send the email if we haven't already sent it successfully
  if (!success) {

    Serial.println("Running SendAnEmail...");

    TembooChoreo SendEmailChoreo;

    // invoke the Temboo client
    // NOTE that the client must be reinvoked, and repopulated with
    // appropriate arguments, each time its run() method is called.
    SendEmailChoreo.begin();

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

    // identify the Temboo Library choreo to run (Google > Gmail > SendEmail)
    SendEmailChoreo.setChoreo("/Library/Google/Gmail/SendEmail");

    // set the required choreo inputs
    // see https://www.temboo.com/library/Library/Google/Gmail/SendEmail/ 
    // for complete details about the inputs for this Choreo

    // the first input is your Gmail email address
    SendEmailChoreo.addInput("Username", GMAIL_USER_NAME);
    // next is your Gmail password.
    SendEmailChoreo.addInput("Password", GMAIL_PASSWORD);
    // who to send the email to
    SendEmailChoreo.addInput("ToAddress", TO_EMAIL_ADDRESS);
    // then a subject line
    SendEmailChoreo.addInput("Subject", emailSubject); // here we send the emailSubject string as the email subject

     // next comes the message body, the main content of the email   
    SendEmailChoreo.addInput("MessageBody", emailContent); // and here we send the emailContent string

    // tell the Choreo to run and wait for the results. The 
    // return code (returnCode) will tell us whether the Temboo client 
    // was able to send our request to the Temboo servers
    unsigned int returnCode = SendEmailChoreo.run();

    // a return code of zero (0) means everything worked
    if (returnCode == 0) {
        Serial.println("Success! Email sent!");
        success = true;
    } else {
      // a non-zero return code means there was an error
      // read and print the error message
      while (SendEmailChoreo.available()) {
        char c = SendEmailChoreo.read();
        Serial.print(c);
      }
    } 
    SendEmailChoreo.close();

    // do nothing for the next 60 seconds
    delay(60000);
  }
}

Review the first section at the start of void loop(). We have generated two random numbers, and then appended some text and the numbers into two Strings – emailContent and emailSubject.

These are then inserted into the SendEmailChoreo.addInput lines to be the email subject and content. With a little effort you can make a neat email notification, such as shown in this video and the following image from a mobile phone:

Conclusion

It’s no secret that the Yún isn’t the cheapest development board around, however the ease of use as demonstrated in this tutorial shows that the time saved in setup and application is more than worth the purchase price of the board and extra Temboo credits if required.

And if you’re interested in learning more about Arduino, or want to introduce someone else to the interesting world of Arduino – check out my book (now in a third printing!) “Arduino Workshop” from No Starch Press.

In the meanwhile have fun and keep checking into tronixstuff.com. Why not follow things on twitterGoogle+, subscribe  for email updates or RSS using the links on the right-hand column? And join our friendly Google Group – dedicated to the projects and related items on this website. Sign up – it’s free, helpful to each other –  and we can all learn something.

The post Tutorial – Send email with the Arduino Yún appeared first on tronixstuff.

Tronixstuff 23 Nov 01:40
arduino  email  gmail  google  iot  lesson  mail  review  send  temboo  tronixstuff  tutorial  wifi  yún