Posts with «communication» label

433 MHz RF module with Arduino Tutorial 1


There are 4 parts to this tutorial:
To get the most out of this tutorial - it is best to start at tutorial Part 1, and then progress to Part 2 then Part 3 and then do Part 4 last. Doing the RF tutorials in this order will help you to understand the process better.



If you are looking for a way to communicate between Arduinos, but don't have much cash at your disposal, then look no further. These RF modules are not only affordable, but easy to use. They are much easier to set up than an XBee, plus you can use them without the need of a special shield. Before you rush out and buy a ton of these modules, make sure that you are not breaking any radio transmission laws in your country. Do your research, and buy them only if you are allowed to use them in your area. There are a few [OPTIONAL] libraries that can be used to help you and your particular project.


I will mention at this point however, that I did NOT use any libraries in this particular tutorial. That's right. I will show how easy it is to transmit data from one arduino to another using these RF modules WITHOUT libraries.

Also if you are looking for an easy way to record the signals and play them back without a computer - then jump to this tutorial.

Video





Project 1- RF Blink


Firstly we need to test if the RF modules are working. So we will design a very simple transmit and receive sketch to test their functionality. We will use the Arduino's onboard LED to show when the transmitter is transmitting, and when the other Arduino is receiving. There will be a slight delay between the two Arduinos. You can solder an antenna onto these modules, however I did not do this, I just kept the modules close together (1-2cm apart). I also found that I was getting better accuracy when I used 3V instead of 5V to power the receiver. While using 5V for VCC on the receiver, I would get a lot of interference, however with 3V, I hardly got any noise. If you find you are getting unpredictable results, I would suggest you switch to 3V on the receiver and move the transmitter and receiver modules right next to each other. Remember this is just a check... you can experiment with an antenna or a greater distance afterwards.

Here are the parts that you will need to carry out this project:
 

Parts Required



 

The Transmitter and Receiver Fritzing Sketch






The Transmitter

The transmitter has 3 pins




 Notice the pin called "ATAD". It took me a while to figure out what ATAD stood for, when I suddenly realised that this was just a word reversed. It should be DATA (not ATAD). Nevertheless, this is the pin responsible for transmitting the signal. We will make the Arduino's onboard LED illuminate when the transmitter pin is HIGH, and go off when LOW as described in the following table.

 
 



And this is the Arduino Sketch to carry out the data transmission.




Arduino sketch - Transmitter





 

The Receiver



If all goes to plan, the onboard LED on this Arduino should light up (and go off) at the same time as the onboard LED on the transmitting Arduino. There is a chance that the receiver may pick up stray signals from other transmitting devices using that specific frequency. So you may need to play around with the threshold value to eliminate the "noise". But don't make it too big, or you will eliminate the signal in this experiment. You will also notice a small delay between the two Arduinos.


 

Arduino sketch - Receiver




When a HIGH signal is transmitted to the other Arduino. It will produce an AnalogRead = 0.
When a LOW signal is transmitted, it will produce an AnalogRead = 400.
This may vary depending on on your module, and voltage used.
The signals received can be viewed using the Serial Monitor, and can be copied into a spreadsheet to create a chart like this:




You will notice that the HIGH signal (H) is constant, whereas the LOW signal (L) is getting smaller with each cycle. I am not sure why the HIGH signal produces a Analog reading of "0". I would have thought it would have been the other way around. But you can see from the results that a HIGH signal produces a 0 result and a LOW signal produces a value of 400 (roughly).





Tutorial 2

In tutorial 2, we will receive and display a signal from a Mercator RF Remote Controller for Fan/Light.


Tutorial 3

In tutorial 3 - we use the signal acquired from tutorial 2, and transmit the signal to the fan/light to turn the light on and off.


Tutorial 4

In tutorial 4 - we use the information gathered in the first 3 tutorials and do away with the need for a computer. We will listen for a signal, store the signal, and then play it back by pressing a button. Similar to a universal remote ! No libraries, no sound cards, no computer. Just record signal and play it back. Awesome !!


 
 



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.
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.




© Copyright by ScottC

433 MHz RF module with Arduino Tutorial 1




If you are looking for a way to communicate between Arduinos, but don't have much cash at your disposal, then look no further. These RF modules are not only affordable, but easy to use. They are much easier to set up than an XBee, plus you can use them without the need of a special shield. Before you rush out and buy a ton of these modules, make sure that you are not breaking any radio transmission laws in your country. Do your research, and buy them only if you are allowed to use them in your area. There are a few [OPTIONAL] libraries that can be used to help you and your particular project.


I will mention at this point however, that I did NOT use any libraries in this particular tutorial. That's right. I will show how easy it is to transmit data from one arduino to another using these RF modules WITHOUT libraries.

Also if you are looking for an easy way to record the signals and play them back without a computer - then jump to this tutorial.

Video





Project 1- RF Blink


Firstly we need to test if the RF modules are working. So we will design a very simple transmit and receive sketch to test their functionality. We will use the Arduino's onboard LED to show when the transmitter is transmitting, and when the other Arduino is receiving. There will be a slight delay between the two Arduinos. You can solder an antenna onto these modules, however I did not do this, I just kept the modules close together (1-2cm apart). I also found that I was getting better accuracy when I used 3V instead of 5V to power the receiver. While using 5V for VCC on the receiver, I would get a lot of interference, however with 3V, I hardly got any noise. If you find you are getting unpredictable results, I would suggest you switch to 3V on the receiver and move the transmitter and receiver modules right next to each other. Remember this is just a check... you can experiment with an antenna or a greater distance afterwards.

Here are the parts that you will need to carry out this project:
 

Parts Required



 

The Transmitter and Receiver Fritzing Sketch






The Transmitter

The transmitter has 3 pins,
Notice the pin called "ATAD". It took me a while to figure out what ATAD stood for, when I suddenly realised that this was just a word reversed. It should be DATA (not ATAD). Nevertheless, this is the pin responsible for transmitting the signal. We will make the Arduino's onboard LED illuminate when the transmitter pin is HIGH, and go off when LOW as described in the following table.

 

And this is the Arduino Sketch to carry out the data transmission.

Arduino sketch - Transmitter

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
 /* 
RF Blink - Transmit sketch 
    Written by ScottC 17 Jun 2014
    Arduino IDE version 1.0.5
    Website: http://arduinobasics.blogspot.com
    Transmitter: FS1000A/XY-FST
    Description: A simple sketch used to test RF transmission.          
------------------------------------------------------------- */

#define rfTransmitPin 4  //RF Transmitter pin = digital pin 4
#define ledPin 13        //Onboard LED = digital pin 13

void setup(){
  pinMode(rfTransmitPin, OUTPUT);
  pinMode(ledPin, OUTPUT);
}

void loop(){
  for(int i=4000; i>5; i=i-(i/3)){
    digitalWrite(rfTransmitPin, HIGH); //Transmit a HIGH signal
    digitalWrite(ledPin, HIGH); //Turn the LED on
    delay(2000); //Wait for 1 second
    
    digitalWrite(rfTransmitPin,LOW); //Transmit a LOW signal
    digitalWrite(ledPin, LOW); //Turn the LED off
    delay(i); //Variable delay
  }
}




 

The Receiver



If all goes to plan, the onboard LED on this Arduino should light up (and go off) at the same time as the onboard LED on the transmitting Arduino. There is a chance that the receiver may pick up stray signals from other transmitting devices using that specific frequency. So you may need to play around with the threshold value to eliminate the "noise". But don't make it too big, or you will eliminate the signal in this experiment. You will also notice a small delay between the two Arduinos.


 

Arduino sketch - Receiver

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
 /* 
 RF Blink - Receiver sketch 
    Written by ScottC 17 Jun 2014
    Arduino IDE version 1.0.5
    Website: http://arduinobasics.blogspot.com
    Receiver: XY-MK-5V
    Description: A simple sketch used to test RF transmission/receiver.          
------------------------------------------------------------- */

#define rfReceivePin A0  //RF Receiver pin = Analog pin 0
#define ledPin 13        //Onboard LED = digital pin 13

unsigned int data = 0; // variable used to store received data
const unsigned int upperThreshold = 70; //upper threshold value
const unsigned int lowerThreshold = 50; //lower threshold value

void setup(){
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
}

void loop(){
  data=analogRead(rfReceivePin); //listen for data on Analog pin 0
  
  if(data>upperThreshold){
    digitalWrite(ledPin, LOW); //If a LOW signal is received, turn LED OFF
    Serial.println(data);
  }
  
  if(data<lowerThreshold){
    digitalWrite(ledPin, HIGH); //If a HIGH signal is received, turn LED ON
    Serial.println(data);
  }
}




When a HIGH signal is transmitted to the other Arduino. It will produce an AnalogRead = 0.
When a LOW signal is transmitted, it will produce an AnalogRead = 400.
This may vary depending on on your module, and voltage used.
The signals received can be viewed using the Serial Monitor, and can be copied into a spreadsheet to create a chart like this:




You will notice that the HIGH signal (H) is constant, whereas the LOW signal (L) is getting smaller with each cycle. I am not sure why the HIGH signal produces a Analog reading of "0". I would have thought it would have been the other way around. But you can see from the results that a HIGH signal produces a 0 result and a LOW signal produces a value of 400 (roughly).





Tutorial 2

In tutorial 2, we will receive and display a signal from a Mercator RF Remote Controller for Fan/Light.


Tutorial 3

In tutorial 3 - we use the signal acquired from tutorial 2, and transmit the signal to the fan/light to turn the light on and off.


Tutorial 4

In tutorial 4 - we use the information gathered in the first 3 tutorials and do away with the need for a computer. We will listen for a signal, store the signal, and then play it back by pressing a button. Similar to a universal remote ! No libraries, no sound cards, no computer. Just record signal and play it back. Awesome !!


 
 



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.
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.

© Copyright by ScottC

Bluetooth Tutorial 1


Introduction:
The bluetooth shield used in this project is a great way to detach the Arduino from your computer. What is even better, is that the shield allows you to control your arduino from your mobile phone or other bluetooth enabled device through simple Serial commands. In this tutorial we will connect a Grove Chainable RGB LED to the bluetooth shield directly, and send simple commands using the Bluetooth SPP app on a Samsung Galaxy S2 to change the colour of the LED (Red , Green and Blue)



Parts Required:
Freetronics Eleven or any compatible Arduino.
Bluetooth shield
Grove Chainable RGB LED
Grove Wire connectors




The Video:





The Arduino Sketch:








Arduino Code:
You can download the Arduino IDE from this site.


 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
/* This project combines the code from a few different sources.
This project was put together by ScottC on the 15/01/2013
http://arduinobasics.blogspot.com/

Bluetooth slave code by Steve Chang - downloaded from :
http://www.seeedstudio.com/wiki/index.php?title=Bluetooth_Shield

Grove Chainable RGB code can be found here :
http://www.seeedstudio.com/wiki/Grove_-_Chainable_RGB_LED#Introduction

*/

#include <SoftwareSerial.h> //Software Serial Port

#define uint8 unsigned char
#define uint16 unsigned int
#define uint32 unsigned long int

#define RxD 6 // This is the pin that the Bluetooth (BT_TX) will transmit to the Arduino (RxD)
#define TxD 7 // This is the pin that the Bluetooth (BT_RX) will receive from the Arduino (TxD)

#define DEBUG_ENABLED 1


int Clkpin = 9; //RGB LED Clock Pin (Digital 9)
int Datapin = 8; //RGB LED Data Pin (Digital 8)

SoftwareSerial blueToothSerial(RxD,TxD);

/*----------------------SETUP----------------------------*/
void setup() {
Serial.begin(9600); // Allow Serial communication via USB cable to computer (if required)
pinMode(RxD, INPUT); // Setup the Arduino to receive INPUT from the bluetooth shield on Digital Pin 6
pinMode(TxD, OUTPUT); // Setup the Arduino to send data (OUTPUT) to the bluetooth shield on Digital Pin 7
pinMode(13,OUTPUT); // Use onboard LED if required.
setupBlueToothConnection(); //Used to initialise the Bluetooth shield

pinMode(Datapin, OUTPUT); // Setup the RGB LED Data Pin
pinMode(Clkpin, OUTPUT); // Setup the RGB LED Clock pin

}

/*----------------------LOOP----------------------------*/
void loop() {
digitalWrite(13,LOW); //Turn off the onboard Arduino LED
char recvChar;
while(1){
if(blueToothSerial.available()){//check if there's any data sent from the remote bluetooth shield
recvChar = blueToothSerial.read();
Serial.print(recvChar); // Print the character received to the Serial Monitor (if required)

//If the character received = 'r' , then change the RGB led to display a RED colour
if(recvChar=='r'){
Send32Zero(); // begin
DataDealWithAndSend(255, 0, 0); // first node data
Send32Zero(); // send to update data
}

//If the character received = 'g' , then change the RGB led to display a GREEN colour
if(recvChar=='g'){
Send32Zero(); // begin
DataDealWithAndSend(0, 255, 0); // first node data
Send32Zero(); // send to update data
}

//If the character received = 'b' , then change the RGB led to display a BLUE colour
if(recvChar=='b'){
Send32Zero(); // begin
DataDealWithAndSend(0, 0, 255); // first node data
Send32Zero(); // send to update data
}
}

//You can use the following code to deal with any information coming from the Computer (serial monitor)
if(Serial.available()){
recvChar = Serial.read();

//This will send value obtained (recvChar) to the phone. The value will be displayed on the phone.
blueToothSerial.print(recvChar);
}
}
}


//The following code is necessary to setup the bluetooth shield ------copy and paste----------------
void setupBlueToothConnection()
{
blueToothSerial.begin(38400); //Set BluetoothBee BaudRate to default baud rate 38400
blueToothSerial.print("\r\n+STWMOD=0\r\n"); //set the bluetooth work in slave mode
blueToothSerial.print("\r\n+STNA=SeeedBTSlave\r\n"); //set the bluetooth name as "SeeedBTSlave"
blueToothSerial.print("\r\n+STOAUT=1\r\n"); // Permit Paired device to connect me
blueToothSerial.print("\r\n+STAUTO=0\r\n"); // Auto-connection should be forbidden here
delay(2000); // This delay is required.
blueToothSerial.print("\r\n+INQ=1\r\n"); //make the slave bluetooth inquirable
Serial.println("The slave bluetooth is inquirable!");
delay(2000); // This delay is required.
blueToothSerial.flush();
}


//The following code snippets are used update the colour of the RGB LED-----copy and paste------------
void ClkProduce(void){
digitalWrite(Clkpin, LOW);
delayMicroseconds(20);
digitalWrite(Clkpin, HIGH);
delayMicroseconds(20);
}

void Send32Zero(void){
unsigned char i;
for (i=0; i<32; i++){
digitalWrite(Datapin, LOW);
ClkProduce();
}
}

uint8 TakeAntiCode(uint8 dat){
uint8 tmp = 0;
if ((dat & 0x80) == 0){
tmp |= 0x02;
}

if ((dat & 0x40) == 0){
tmp |= 0x01;
}

return tmp;
}

// gray data
void DatSend(uint32 dx){
uint8 i;
for (i=0; i<32; i++){
if ((dx & 0x80000000) != 0){
digitalWrite(Datapin, HIGH);
} else {
digitalWrite(Datapin, LOW);
}

dx <<= 1;
ClkProduce();
}
}

// data processing
void DataDealWithAndSend(uint8 r, uint8 g, uint8 b){
uint32 dx = 0;

dx |= (uint32)0x03 << 30; // highest two bits 1,flag bits
dx |= (uint32)TakeAntiCode(b) << 28;
dx |= (uint32)TakeAntiCode(g) << 26;
dx |= (uint32)TakeAntiCode(r) << 24;

dx |= (uint32)b << 16;
dx |= (uint32)g << 8;
dx |= r;

DatSend(dx);
}

The code above was formatted using hilite.me

Notes:
You don't need to download a library to get this project running. But if you plan to use bluetooth shields to get 2 Arduinos to communicate to each other, then I would advise that you download the library files (which are just examples) from the Seeedstudio site : here.

Visit this site to setup your phone or laptop for bluetooth communication to the shield - here

The app used on my Samsung Galaxy S2 phone was "Bluetooth SPP"

You will initially need to enter a pin of '0000' to establish a connection to the Bluetooth shield - which will appear as "SeeedBTSlave" or whatever text you place on line 90 of the Arduino code above.





Warning !

Not all phones are compatible with the bluetooth shield.
If you have used this shield before - please let me know what phone you used - so that we can build a list and inform others whether their phone is likely to work with this project or not. Obviously - those phones that do not have bluetooth within - will not work :).
And I have not tried any other apps either

I got it to work very easily with my Samsung Galaxy S2 using the free Bluetooth SPP app from the google play store.

This was fun, but I want to make my own app !
Have a look at my latest 4-part tutorial which takes you step-by-step through the process of building your own app using the Processing/Android IDE.
You can build your own GUI interface on your Android Phone and get it to communicate via Bluetooth to your Arduino/Bluetooth Shield. Click on the links below for more information:




 
 



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.
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.

Talk to my computer through Serial?

Long time no see LMR!!!!

This semester was my most brutal yet, but the rewards have been priceless!

 

Anyways, back to the robots,

So my current project is to create a virtual indentity that I can have a VERY simple conversation with. His name is Sergei, cause everyone needs an awesome Russian buddy. But I find myself being a bit stuck on one thing: Serial Communications

 

What Im really trying to better understand is how to make the Arduino respond to my serial input. 

read more

Arduino UNO - XBee Setup

There are many XBee tutorials out there, but I could not find one that I could apply to my specific Arduino/Shield/Xbee configuration. While this particular configuration may not apply to you, perhaps it will send you in the right direction, so please read on.
Please note, that your XBee shield may require you to perform extra steps, so please do further reading before jumping in head first. I am not an expert, so don't blame me if you fry your board.

The following set of steps worked for me:


Step 1: Download and Install X-CTU

The easiest way to setup your XBee module is via the X-CTU software from Digi. It can be downloaded from their site here:  http://www.digi.com/support/productdetail?pid=3257

  • Select  the Diagnostics, Utilities and MIBs section


  • Download and install the XCTU 32-bit ver 5.2.7.5 installer (do a virus check after download)
  • Please note that this is for Windows platforms only

  • FYI: We will run the software later



Step 2: Upload the bare-minimum script on your Arduino controller

I perform this step to prevent any previous projects from interfering. This may not be necessary, but I tend to do this before wiring up any of my new projects. This is the script I load onto the Arduino:

Bare Minimum Arduino Sketch:
1
2
3
4
5
6
7
void setup() {

}

void loop() {

}




Step 3: Connect the Shield to Arduino, and XBee to Shield.


  • Disconnect the Arduino UNO from the computer. 

  • Insert the XBee module into the Shield.
  • This is the XBee Shield and XBee module side by side




    This is the XBee module on the XBee Shield


  • The pins from the XBee module should slot into the respective headers on the Shield.


  • Connect the XBee shield to the Arduino

  • The pins from the XBee shield should slot into the respective headers on the Arduino board.



  • Move the little white switch in the corner to USB.

    • There are 2 options - USB mode and XBee mode.
    • We want USB mode which will allow the computer to communicate with the XBee module



Step 4: Connect Arduino to computer, and run the X-CTU Software


  • With the XBee module and Shield connected to the Arduino, and the Shield's white switch in USB mode;  connect the Arduino to the computer using a USB cable.
  • This Arduino board appears as COM7 on my computer.
  • Here is what the X-CTU software looks like when it loads up




  • Press the Test / Query button to see if the computer can talk to the XBee module.
    • If successful, you should see something like this:





  • If you accidentally leave the XBee shield in XBee mode, or if your computer fails to communicate with the XBee module, you may encounter these screens.


If you get a successful Test / Query, then move onto the next step.


Step 5: Read XBee Firmware settings:

We can now try to read the XBee firmware settings by
  • Selecting the Modem Configuration Tab

  • Select the Read button to read the XBee firmware settings


Step 6: Download older version of firmware if necessary

  • If you did not have any issues with the previous step, then continue to step 7, otherwise read on.
  • In my case, the software could not find the firmware file necessary to read the firmware settings.
  • In step 4, I could see that I had the XB24 Modem type, and 10E8 firmware version,

  • I tried downloading new versions, but this did not seem to work, as the computer could not detect any newer updates available. The problem I had, was that I needed an "older version" of firmware to communicate with the XBee module in order to read/write new settings to it.
  • I could not select the firmware version from the drop down boxes, which indicated that this particular firmware version was not installed on my computer. So here is what I did.
    • I went back to the Digi site and selected the Firmware update section.
    • This provided a link to an FTP site with "previous versions" of firmware.





  • I then selected the relevant firmware version from the list, and downloaded the zip file to a logical folder on my hard-drive.  There is no need to unzip the file, because the X-CTU software will look for a zipped file.



  • In the X-CTU software, in the Modem Configurations tab, select the "Download new versions button", and select File. Navigate to the zip-file just downloaded and select it. 


  • The software should tell you that it has updated successfully or something to that effect.
  • The modem type and version should now be an available option in the drop down boxes, however, we will continue where we left off (in step 5) and try an read the firmware settings from the XBee module, by pressing the Read button in the Modem Configurations tab on the X-CTU software.
  • It should look something like this:

TO BE CONTINUED.......

MIDI with Arduino

We have already mentioned the fantastic work of Amanda Ghassei for Instructables in this post.
I would like to report two other very useful documents.

The first is What is MIDI? and explain in detail how MIDI protocol works. The second, even more important is Send and Receive MIDI with Arduino. Please note, regarding the Midi input schematic, the use of  the 6N138 opto-isolator. Some MIDI interface schematics show the 4N25 opto-isolator which is a single transistor type, but the 6N138 shown there produces a much better output signal.

Via:[Instructables]

 

Simple Arduino Serial Communication (Part 2)

In Stages 1 to 5 , we experimented with the Serial Monitor on the Arduino IDE to transmit data to the Arduino and receive data from the Arduino. We performed simple Serial communication of data in both directions.

We then moved from transmitting a String of characters to the more difficult task of transmitting a double or a float.

Finally, we used the Serial monitor to receive sensor data from our Arduino, and played with a couple of Arduino functions.

We will now look at replacing the Serial Monitor with a much more exciting program such as "Processing" which is a free Open Source program that interfaces very easily with the Arduino. It can be downloaded here.

We will use a few processing scripts to bring our Arduino Sensor projects to life !


Stage 6: A simple Processing Sketch: BLINK


Arduino IDE vs Processing IDE




While the processing IDE looks very similar to the Arduino IDE, it is important that you realise that the Processing sketch will run on your computer, and NOT on the Arduino. In fact, you do not even need an Arduino to run a Processing sketch. And that is exactly what we are going to do: Run a Processing sketch without an Arduino.

Parts Required



  • A computer
  • Processing IDE

  • Once you have downloaded and installed the Processing IDE onto your computer, open the program and copy the following sketch into it, and then press the play button. This is different from the Arduino IDE, in that we do not have to upload it to anything, as it will be running from the computer.

    Processing Sketch


    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

    /* Stage 6: Simple Processing Blink Sketch
    Created by ScottC on the 8/7/2012
    http://arduinobasics.blogspot.com/ */


    /* Setup the color variables and switching mechanism */
    color Red=color(255,0,0);
    color White=color(255,255,255);
    Boolean mySwitch=true;


    /* The setup function only runs once */

    void setup(){
    /* Set the size of the window using size(width,height) */
    size(400,400);
    }

    /* The draw function will refresh screen only after it has
    processed all functions within it. Which is why I needed
    a switch to swap between the red and the white background
    The draw() function will run in an endless loop. */

    void draw(){
    blink(mySwitch); //Call to blink function
    delay(2000); //The blinking speed (2 secs)
    }


    /* The blink function switches the background from red to white
    or from white to red. */

    void blink(Boolean swtch){
    /* If swtch is true, make the background red
    otherwise make it white */
    if(swtch){
    background(Red); // red
    }else {
    background(White); // white
    }
    /* Toggle mySwitch between true and false */
    mySwitch=!mySwitch;
    }


    Things to Try


    1. Change the White background to a black background

    2. Insert on line 9: color Black=color(0,0,0);
      Change line 38: background(Black);


    3. Increase the blink rate to 1 second

    4. Change line 25: delay(1000);
      WARNING : Do not increase the speed too much, it may cause an epileptic fit.



    Now that wasn't too hard I hope.
    And if you want a very good site to learn Processing have a look at these


  • The official Processing reference library
  • Official Processing Tutorials
  • Getting started with Processing
  • Daniel Shiffman's Processing Examples and Tutorials




  • Stage 7: Arduino and Processing Unite.


    So how do we get our Arduino to interface with our computer? Well, if the Serial Monitor on the Arduino IDE is not good enough, then you could use any program that is capable of Serial communication. Fortunately, Processing is one of those programs, but you could use C++, Java, Python, Microsoft Excel (using VBA), VB.Net, Gobetwino or some other programming language.

    Two programs will be created: One will be uploaded to the Arduino using the Arduino IDE, and the other will run on the computer. In this example we will use Processing as the program that will run on the computer.

    Enter the following sketch into the Arduino IDE and upload it to the Arduino. It serves to generate a random number between 0 and 400 every 200msec and will send it to the computer via the USB cable , using Serial communication.

    Arduino Sketch


     1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    /* Stage 7: Simple Arduino Serial Random Number Generator
    Written by ScottC on 09/07/2012
    http://arduinobasics.blogspot.com/
    */


    void setup(){
    Serial.begin(9600); //Begin Serial Communication
    }

    void loop(){
    Serial.println(random(1,1000)); //Send Random # to computer
    delay(200); //Delay 200ms between values.
    }


    Instructions

    Once the program has been uploaded to the Arduino, we will want to make sure that it is performing to expectations before moving onto the Processing script.

    Open the Arduino Serial Monitor and make sure that you see a bunch of random numbers scrolling down the page. If not, then go back over your code and try again. Once you see the random numbers, then it is safe to move on to the next step.




    Processing

    The following Processing script will display the Random numbers being sent from the Arduino in the Processing IDE debug window. This particular script is very much like a simplified Arduino Serial Monitor, and it will show you that the Processing Script is successfully communicating with the Arduino.


    Processing Sketch

     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
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    /* Some of the Serial code was adapted from Tom Igoe's example
    on this site: http://processing.org/reference/libraries/serial/Serial.html
    and http://processing.org/reference/libraries/serial/serialEvent_.html

    The rest of this Processing code was written by ScottC on 11/07/2012
    http://arduinobasics.blogspot.com/
    */



    import processing.serial.*; /* Needed for Serial Communication */

    /* Global variables */
    Serial comPort;
    String [] comPortList;
    String comPortString;

    /*--------------------------------------------------*/

    void setup(){
    size(100,100); /* Set the size of the window */
    background(0); /* Set the background to black */


    /* Get the available com ports. If there is at least one
    com port available, then start communicating on it.
    If there are more than one com ports available, we will
    only open the first one (i.e. comPortList[0])
    The bufferUntil('\n'); statement will generate a serial Event
    when it reads a carriage return */

    comPortList = Serial.list();
    if(comPortList.length>0){
    comPort = new Serial(this, comPortList[0], 9600);
    comPort.bufferUntil('\n');
    }
    }

    /*--------------------------------------------------*/

    void draw(){
    /* The serialEvent function will update the display */
    }

    /*--------------------------------------------------*/

    void serialEvent(Serial cPort){
    comPortString = cPort.readStringUntil('\n');
    if(comPortString != null) {
    comPortString=trim(comPortString);

    /* Print to the Debug screen in Processing IDE */
    println(comPortString);
    }
    }


    When you run the Processing script, a little black window will appear. This is the Processing Graphics window, which is normally where all the action takes place. However in the sketch above, this window does nothing. Instead we make use of the black Debug window which is part of the Processing IDE (below the code window). If everything went to plan, you should see random numbers scrolling down in a similar fashion to the Arduino Serial monitor. Here is an example of what it should look like.





    Things to Try


    1. If you are having problems with COM port selection. Then have a look at the COM port being used on the Arduino IDE to upload sketches to the Arduino. Processing generally uses the same COM port. So make sure to close the Arduino Serial Monitor before running the Processing Sketches.



    The image above shows that I am currently using COM PORT 6 on my computer to upload Arduino Sketches. In the Processing sketch on line 32-35, I had this code:

    32
    33
    34
    35
      if(comPortList.length>0){
    comPort = new Serial(this, comPortList[0], 9600);
    comPort.bufferUntil('\n');
    }



    We can change line 33 to get Processing to use COM port 6 exclusively. We do this by replacing comPortList[0] with "COM6", as seen below:

    32
    33
    34
    35
      if(comPortList.length>0){
    comPort = new Serial(this, "COM6", 9600);
    comPort.bufferUntil('\n');
    }







    Stage 8 : Arduino and Processing - Random Font Project


    Arduino and Processing are speaking to each other by this stage, and we will keep our original Arduino Sketch to produce random numbers for us. Sure, we don't actually need the Arduino to do this for us, because Processing is more than capable of doing this itself, but we are building up towards an interactive sketch, so lets just go through the motions.

    Just in case your mouse scroll wheel doesn't move upwards, here is the Arduino Sketch again:

    Arduino Sketch


     1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    /* Stage 8: Simple Arduino Serial Random Number Generator
    Written by ScottC on 09/07/2012
    http://arduinobasics.blogspot.com/
    */


    void setup(){
    Serial.begin(9600); //Begin Serial Communication
    }

    void loop(){
    Serial.println(random(1,1000)); //Send Random # to computer
    delay(100); //Delay 100ms between values.
    }


    Upload the Arduino sketch to the Arduino, and then put the following code into the Processing IDE:

    Processing Sketch




    The output of this sketch should look something like this:





    For stages 9 and above: Click Here


    Simple Arduino Serial Communication

    This Tutorial is progressive and will be updated from time to time. The goal is to start from a very basic form of Arduino Serial communication, and progressively add or improve components so that we can ultimately transmit data from one computer to another using an XBee.
    Please note: I am not an expert, but am happy to share what I have learned. The Arduino forums are a great place to ask questions, feel free to link to this blog (if required).

    Let us begin.


    Stage 1: ECHO ECHO                                                                                    


    Parts Required:

    • Computer
    • USB cable
    • Arduino UNO (or equivalent)
    • Arduino IDE

    The following code will make the Arduino ECHO anything you send to it. Therefore, if you type a 3, the Arduino will send back a 3. If you type a letter F, the Arduino will send back a letter F. 
    Enter the following code into your Arduino IDE and upload it to your Arduino.


    Arduino Sketch


     1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    /* Simple Serial ECHO script : Written by ScottC 03/07/2012 */

    /* Use a variable called byteRead to temporarily store
    the data coming from the computer */
    byte byteRead;

    void setup() {
    // Turn the Serial Protocol ON
    Serial.begin(9600);
    }

    void loop() {
    /* check if data has been sent from the computer: */
    if (Serial.available()) {
    /* read the most recent byte */
    byteRead = Serial.read();
    /*ECHO the value that was read, back to the serial port. */
    Serial.write(byteRead);
    }
    }
    The above code was formatted using this site


    Instructions

    1. Once the Arduino sketch has been uploaded to the Arduino. Open the Serial monitor, which looks like a magnifying glass at the top right section of the Arduino IDE. Please note, that you need to keep the USB connected to the Arduino during this process, as the USB cable is your communication link between your computer and the Arduino.



    2. Type anything into the top box of the Serial Monitor and press <Enter> on your keyboard. This will send a series of bytes to the Arduino. The Arduino will respond by sending back your typed message in the larger textbox.



    3. Please note that we are using Serial.write(byteRead); on line 18 to get the Arduino to ECHO the message back to you on your computer. 



    Things to Try 

    1. Delete lines 16 to 18, and replace them with the following line :

                   Serial.write(Serial.read());

    This essentially eliminates the byteRead variable in the sketch above. But we will be using it later on, so once you have tested it out, put the code back together as originally displayed.


    --------------------------------------------------------------------
    2. Replace line 18 with a Serial.println instead of Serial.write

                   Serial.println(byteRead);

    Once uploaded, type 1 <enter> 2 <enter> 3 <enter>  into the Serial Monitor.
    You should see:

    49
    50
    51

    Serial.print and Serial.println will send back the actual ASCII code, whereas Serial.write will send back the actual text. See ASCII codes for more information.


    --------------------------------------------------------------------
    3. Try typing in numbers like 1.5  or  2.003  or  -15.6 into the Serial Monitor using Serial.write and Serial.print or Serial.println commands as described before.

    You will notice that the decimal point transmits as a number using Serial.print  or Serial.println, and will transmit as a decimal point when using Serial.write






    STAGE 2: Delimiters                                                                                


    How do you handle 2 or more numbers when sending or receiving?
    Let us say that you have number pairs that you want the Arduino to interpret. How do you separate the numbers? The answer is Delimiters.
    You may be familiar with CSV (comma separated value) files, where each field is separated by a comma (,). The comma is a useful way of separating or grouping information.

    Lets say you have the following stream of numbers:
    12345678910

    How will your Arduino know if this is a single number, or a series of numbers?
    Eg:

    12,34,56,78,91,0
    123,456,78,910
    1,2,3,4,5,6,7,8,9,10
    12345678910

    The comma delimiters help to identify how the numbers should be interpreted.

     In the echo example in Stage 1 above, you would have noticed that when we used Serial.print(byteRead); that the values displayed one after another in a similar fashion to 12345678910.

    You would have also noticed that Serial.println(byteRead); provided a line break between each value sent. And depending on the numbers sent, it could have looked like this:
    12
    34
    56
    78
    91
    0

    The Serial.println() function essentially uses a line feed to separate the values being sent. This line break can be used as a delimiter, but we will look at that later on. For now we will concentrate on using a comma (,).

    We will now get the Arduino to "listen" for the comma to help it identify a new number.
    According to the ASCII code site, a comma is equal to byte code 44. So when the Arduino reads a byte code that is equal to 44, we will get it to print a line feed.


    Enter the following sketch into your Arduino IDE and upload it to your Arduino.

    Arduino Sketch


     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
    /* Simple Serial ECHO script : Written by ScottC 04/07/2012 */
    /* Stage 2 : Delimiters */

    /* Use a variable called byteRead to temporarily store
    the data coming from the computer */
    byte byteRead;

    void setup() {
    // Turn the Serial Protocol ON
    Serial.begin(9600);
    }

    void loop() {
    /* check if data has been sent from the computer: */
    if (Serial.available()) {
    /* read the most recent byte */
    byteRead = Serial.read();

    /*Listen for a comma which equals byte code # 44 */
    if(byteRead==44){
    Serial.println();
    }else{
    /*ECHO the value that was read, back to the serial port. */
    Serial.write(byteRead);
    }
    }
    }
    The above code was formatted using this site


    Instructions

    1. Once the code has been uploaded to the Arduino, open the Serial Monitor once again and type the following sequence of numbers:

    1 <enter>  2 <enter> 3 <enter>

    You should see the Serial monitor display the following number:    123




    --------------------------------------------------------------------
    2. While still in the serial monitor, type the following:

    , <enter> 1 <enter> , <enter> 2 <enter> , <enter> 3 <enter> ,

    Please note the commas between each numerical entry. You should now see a pattern like this:
    1
    2
    3




    --------------------------------------------------------------------
    3. While still in the serial monitor, type the following:

    12,23,34,45, <enter>

    Please note the commas between each numerical entry. You should now see a pattern like this:
    12
    23
    34
    45

    You will notice that the commas have been replaced by line feeds, and each number should display on a new line.



    --------------------------------------------------------------------
    4. While still in the serial monitor, type the following:

    1,,2,,3, <enter>

    You should see the following pattern:
    1

    2

    3


    So hopefully that explains the concept of delimiters and how they can be used to separate a stream of numbers, no matter how long it takes to get to the Arduino. We used an IF-statement to listen for the comma, but we could have used any other delimiter provided we knew the byte code.

    We did not identify how to send delimiters FROM the Arduino, but we will get to that I promise. It is not that hard, and uses a similar principle. I am sure you can work it out, if not, stay tuned.




    STAGE 3: Arduino Maths: Simple addition                                                  


    In this stage, we are going to get the Arduino to do simple maths. We will send it two integers (or whole numbers), and the Arduino will do the hard work and send us the answer in no time at all.
    This might seem like a simple task, but when you send a number like 27 to the Arduino, it does not receive the number 27. It receives 2 and then 7 in byte form. In other words, the Arduino will see the byte codes 50 and then 55 as per the ASCII table on this page.

    One way to convert this byte code back to a 2 and a 7 is to subtract 48 from each byte received, providing the byte is in the range 48 to 57 inclusive (which equates to the numbers 0-9).
    We are not done yet. We then need to join these numbers to make 27.

    Step1: Subtract 48 from the bytes received, only if the bytes are in the range 48 to 57.
                     Example:    50 - 48 = 2
                                        55- 48 = 7

    Step2: Multiply the previous number by 10, before adding the most recent byte received.
                     Example:   (2 x 10) + 7 = 27

    If we have a number like 1928, then we would create this number using the following calculation
                                       1 =                         1
                       (1 x 10) + 9 =    10 + 9   =   19
                    (19 x 10) + 2  = 190 + 2   =  192
                  (192 x 10) + 8  = 1920 + 8 = 1928

    Step3: Use a "+" sign as a delimiter so that the Arduino can move onto the Second number

    Step4:  Capture the second number as per Step2. An "=" sign will tell the Arduino that it has reached the end of the second number, and to proceed to step 5.

    Step5:  Add the 2 numbers together and send back the answer.



    The following code will carry out the 5 steps above.
    Enter the following sketch into your Arduino IDE and upload it to your Arduino.

    Arduino Sketch


     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
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    /* Simple Serial ECHO script : Written by ScottC 05/07/2012 */
    /* Stage 3: Arduino Maths: Simple Addition */

    /* Global variables needed for programming workflow
    byteRead: holds the value being read from the COM port
    num1: holds the entire first number
    num2: holds the entire second number
    answer: holds the sum of num1 and num2
    mySwitch: enables the switch between num1 and num2 */

    byte byteRead;
    long num1, num2,answer;
    boolean mySwitch=false;

    void setup() {
    /* Turn the Serial Protocol ON and
    initialise num1 and num2 variables.*/
    Serial.begin(9600);
    num1=0;
    num2=0;
    }

    void loop() {
    /* check if data has been sent from the computer: */
    while (Serial.available()) {
    /* read the most recent byte */
    byteRead = Serial.read();

    //listen for numbers between 0-9
    if(byteRead>47 && byteRead<58){
    //number found

    /* If mySwitch is true, then populate the num1 variable
    otherwise populate the num2 variable*/
    if<!mySwitch)><br /> num1=(num1*10)+(byteRead-48);<br /> }<span>else</span>{<br /> num2=(num2*10)+(byteRead-48);<br /> }<br /> }<br /> <br /> <span>/*Listen for an equal sign (byte code 61) </span><br /><span> to calculate the answer and send it back to the</span><br /><span> serial monitor screen*/</span><br /> <span>if</span>(byteRead==61){<br /> answer=num1+num2;<br /> Serial.print(num1);<br /> Serial.print(<span>"+"</span>);<br /> Serial.print(num2);<br /> Serial.print(<span>"="</span>);<br /> Serial.println(answer);<br /> <br /> <span>/* Reset the variables for the next round */</span><br /> num1=0;<br /> num2=0;<br /> mySwitch=<span>false</span>;<br /> <br /> <span>/* Listen for the addition sign (byte code 43). This is</span><br /><span> used as a delimiter to help define num1 from num2 */</span> <br /> }<span>else</span> <span>if</span> (byteRead==43){<br /> mySwitch=<span>true</span>;<br /> }<br /> }<br />}<br /></pre></td></tr></tbody></table></div><br /><span>The above code was formatted using <a href="http://hilite.me/">this site</a></span><br /><br /><br /><h3> <u>Instructions</u></h3><br /><b>1.</b> Once the code has been uploaded to the Arduino, open the Serial Monitor once again and type the following sequence:<br /><br />         <span>1+2=   <enter></span><br /><br />You should get the following message sent back to Serial Monitor<br /><br />        <span> 1+2=3</span><br /><br /><br /><br /><h3> <b><u>Things to Try</u></b></h3><b>1.</b>   Enter this sequence: <br />              <span>10   <enter></span><br /><span>               +   <enter></span><br /><span>              10  <enter></span><br /><span>               =   <enter></span><br /><br />       Result:     <span>10+10=20</span><br /><br /><span>--------------------------------------------------------------------</span><br /><b>2. </b>  Enter this sequence:<br />            <span> 10  <enter></span><br /><span>             20  <enter></span><br /><span>             +5= <enter></span><br /><br /><br />      Result:  <span> 1020+5=1025</span><br /><br /><br /><br /><br /><span>--------------------------------------------------------------------</span><br /><b>3.</b>   Enter this sequence:<br />            <span> 10+20+30=   <enter></span><br /><br /><br />      Result:    <span>10+2030=2040</span><br /><br />I have specifically written this script to add <b>two</b> whole numbers together. If you start to introduce more complicated calculations, the results become unpredictable.<br /><br /><span>--------------------------------------------------------------------</span><br /><b>4.</b>    Enter this sequence:<br />           <span>1.2+1.0=    <enter></span><br /><br />      Result: <span>12+10=22</span><br /><br />Once again, I have only designed this script to handle whole numbers. Therefore, decimal points are ignored.<br /><br /><span>--------------------------------------------------------------------</span><br /><b>5.</b>  Enter this sequence:<br />         <span> -5 + 10=     <enter></span><br /><br /><br />     Result:    <span>5+10=15</span><br /><br /><br />This script ignores the negative sign, and treats the -5 as a positive 5.<br /><br /><br /><div>I have done this on purpose. I wanted to show you how the Arduino reads numbers from the com port, and how easy it is to exclude vital functionality in your code. I have kept this script simple, however, if you wanted to, you could make the Arduino deal with each of the above situations and more.  Multiplication, division and subtraction is handled in the same way. </div><br />This is the last thing I want you to try before we go to the next stage:<br /><br />6. Enter this sequence:<br />           <span>2147483646+1=  <enter></span>           Result:  <span>2147483646+1=2147483647</span><br />          <span> 2147483647+1=  <enter></span>           Result: <span>2147483647+1=</span><span>-</span><span>2147483648</span><br /><br /><br />Note that the maximum size of a "long" number is 2147483647. If you add one to this number, the result is equal to the minimum size of a "long" which is -2147483648.<br /><br /><br /><br /><br /><h3> <b><span><span>STAGE 4:  Sending doubles to Arduino</span> : <span>The double doubler</span>             </span></b></h3><div>Now we get to some tricky business. Sending and receiving Doubles (to and from) the Arduino.<br /><br />Up until now, I have tried to keep it simple using whole numbers, but there will come a time when you will want to send a fraction of a number through the Serial line.</div><div>To test our program, we will want to send a very small number to the Arduino, multiply the number by 2, and return it back.</div><div><br /></div><div>Our final test is to try a number like :  <b>0.000001</b></div><div>             and then a number like:<b>   123.321</b></div><div><br /></div><div><br /><b><span>IMPORTANT NOTE</span></b>:   When the Arduino sends a float or a double through the COM port using Serial.print() or Serial.println(), it will automatically send the number to 2 decimal places.<br />A number like 1.2345 will appear as 1.23,   and a number like 1.9996 will appear as 2.00<br />To demonstrate this, we will get the Arduino to send these floats/doubles to the Serial Monitor.<br /><br /><br /><div>Enter the following sketch into your Arduino IDE and upload it to your Arduino.</div><div><br /></div><h3> <u>Arduino Sketch</u></h3><br /><div><table><tbody><tr><td><pre><span><span> 1<br /> 2<br /> 3<br /> 4<br /> 5<br /> 6<br /> 7<br /> 8<br /> 9<br />10<br />11<br />12<br />13<br />14<br />15<br />16<br />17<br />18<br />19<br />20<br />21<br />22<br />23<br />24<br />25<br />26<br />27<br />28</span></span></pre></td><td><pre><span>/* Stage 4: Simple Transmission of a Double</span><br /><span> Written by ScottC on 7/7/2012 */</span><br /><br /><span>/* Declare the doubles that will be sent to the Serial Monitor */</span><br /> <span>double</span> myDub1, myDub2;<br /><br /><span>/* This part of the program only runs ONCE */</span><br /><br /> <span>void</span> setup(){<br /><br /> <span>/* Turn ON Serial Communication */</span><br /> Serial.begin(9600);<br /> <br /> <span>/* Assign a value 1.2345 and 1.9996 to the Doubles being sent */</span><br /> myDub1=1.2345;<br /> myDub2=1.9996;<br /> <br /> <span>/*Send the values to the Serial Monitor */</span><br /> Serial.print(<span>"myDub1 (1.2345) : "</span>);<br /> Serial.println(myDub1);<br /> Serial.print(<span>"myDub2 (1.9996) : "</span>);<br /> Serial.println(myDub2);<br /> }<br /><br /><br /> <span>void</span> loop(){<br /> <span>//Loop does nothing</span><br /> }<br /></pre></td></tr></tbody></table></div><span>The above code was formatted using </span><a href="http://hilite.me/">this site</a><br /><br />When you open the Serial monitor (after you have uploaded the sketch above), you will notice the following output:<br /><br /><br />         <span> myDub1 (1.2345) :</span> <span>1.23</span><br />         <span> myDub2 (1.9996) :</span> <span>2.00</span><br /><div><br /></div><br /><br />The <span>blue text</span> represents the string (or array of characters) being sent using lines 19 and 21.<br />The <span>red text</span> represents the actual double being sent using lines 20 and 22.<br /><br />You will notice that myDub2 rounds to 2.00.  This may or may not be what you want.<br />If you wish to increase the number of decimal places, then you will need to change lines 20 and 22 to the following:<br /><br /><span><span>20         Serial.println(myDub1,</span><span>4</span><span>)</span>;</span><br /><span><span>22         Serial.println(myDub2,</span><span>4</span><span>);</span></span><br /><br />The number 4 highlighted in red, indicates the number of decimal places you wish to send.<br />Try it ! And try changing this number to something bigger or smaller.<br /><br />---------------------------------------------------------------------------------------------------<br />Ok - now that we understand this little Serial.print(double,decimals) trick, we will now get the Arduino to echo back a Double.<br /><br />Before we jump in, perhaps we should try and map out our strategy. For this we will choose a simple decimal to make it easier. So in this example, we will choose <b>0.1</b></div><div>Once we get this working, we can then do our final test (as mentioned above).</div><div><br /></div><div>If we send 0.1 to the Arduino, it will read the following byte code</div><div><br /></div><div>48                    0</div><div>46                    .</div><div>49                    1</div><div><br /></div><div>We can use the decimal point as a delimiter.<br />We will use the following 5 steps to echo the double back to the Serial Monitor:</div><div><br /></div><div><b><span>Step1</span>:</b> Arduino collects all numbers before the decimal point using the same technique as in Stage3.<br /><br /></div><div><b><span>Step2</span>: </b>When the Arduino receives byte code 46, it will go into decimal mode.<br /><br /></div><div><b><span>Step3</span>:</b> The Arduino will collect numbers after the decimal point using a similar technique to step1.<br /><br /></div><div><b><span>Step4</span>:</b> Use maths to create the double, and then multiply it by 2<br /><br /></div><div><b><span>Step5</span>:</b> Display the doubled Double value in the Serial monitor.</div><div><br /></div><div><br /></div><div><br /><div>Enter the following sketch into your Arduino IDE and upload it to your Arduino.</div><div><br /></div><h3> <u>Arduino Sketch</u></h3></div><div><br /></div><div><table><tbody><tr><td><pre><span><span> 1<br /> 2<br /> 3<br /> 4<br /> 5<br /> 6<br /> 7<br /> 8<br /> 9<br />10<br />11<br />12<br />13<br />14<br />15<br />16<br />17<br />18<br />19<br />20<br />21<br />22<br />23<br />24<br />25<br />26<br />27<br />28<br />29<br />30<br />31<br />32<br />33<br />34<br />35<br />36<br />37<br />38<br />39<br />40<br />41<br />42<br />43<br />44<br />45<br />46<br />47<br />48<br />49<br />50<br />51<br />52<br />53<br />54<br />55<br />56<br />57<br />58<br />59<br />60<br />61<br />62<br />63<br />64<br />65<br />66<br />67<br />68<br />69<br />70<br />71<br />72<br />73<br />74<br />75<br />76<br />77<br />78<br />79<br />80<br />81<br />82<br />83<br />84<br />85</span></span></pre></td><td><pre><span>/* Simple Serial ECHO script : Written by ScottC 06/07/2012 */</span><br /><span>/* Stage 4: Double doubler */</span><br /><br /><span>/* Global variables needed for programming workflow</span><br /><span> ------------------------------------------------------</span><br /><span> byteRead: holds the value being read from the COM port</span><br /><span> num1: holds the number before the decimal point</span><br /><span> num2: holds the number after the decimal point</span><br /><span> complNum: holds the complete number (before multiplation)</span><br /><span> answer: holds the final value after multiplication</span><br /><span> counter: is used to convert num2 to the number after the decimal</span><br /><span> numOfDec: counts the numbers after the decimal point</span><br /><span> mySwitch: enables the switch between num1 and num2 */</span><br /> <br /> byte byteRead;<br /> <span>double</span> num1, num2;<br /> <span>double</span> complNum,answer,counter;<br /> <span>int</span> numOfDec;<br /> boolean mySwitch=<span>false</span>;<br /><br /><br /> <span>void</span> setup() { <br /><span>/* Turn the Serial Protocol ON and </span><br /><span> initialise num1 and num2 variables.*/</span><br /> Serial.begin(9600);<br /> num1=0;<br /> num2=0;<br /> complNum=0;<br /> counter=1;<br /> numOfDec=0;<br /> }<br /><br /> <span>void</span> loop() {<br /><span>/* check if data has been sent from the computer: */</span><br /> <span>while</span> (Serial.available()) {<br /> <span>/* read the most recent byte */</span><br /> byteRead = Serial.read();<br /> <br /> <span>//listen for numbers between 0-9</span><br /> <span>if</span>(byteRead>47 && byteRead<58){<br /> <span>//number found</span><br /> <br /> <span>/* If mySwitch is true, then populate the num1 variable</span><br /><span> otherwise populate the num2 variable*/</span><br /> <span>if</span><!mySwitch)><br /> num1=(num1*10)+(byteRead-48);<br /> }<span>else</span>{<br /> num2=(num2*10)+(byteRead-48);<br /> <br /> <span>/* These counters are important */</span><br /> counter=counter*10;<br /> numOfDec++;<br /> }<br /> }<br /> <br /> <span>/*Listen for an equal sign (byte code 61) </span><br /><span> to calculate the answer and send it back to the</span><br /><span> serial monitor screen*/</span><br /> <span>if</span>(byteRead==61){<br /> <span>/* Create the double from num1 and num2 */</span><br /> complNum=num1+(num2/(counter));<br /> <br /> <span>/* Multiply the double by 2 */</span> <br /> answer=complNum*2;<br /> <br /> <span>/* Send the result to the Serial Monitor */</span> <br /> Serial.print(complNum,numOfDec);<br /> Serial.print(<span>" x 2 = "</span>);<br /> Serial.println(answer,numOfDec);<br /> <br /> <span>/* Reset the variables for the next round */</span><br /> num1=0;<br /> num2=0;<br /> complNum=0;<br /> counter=1;<br /> mySwitch=<span>false</span>;<br /> numOfDec=0;<br /> <br /> <span>/* Listen for the decimal point (byte code 46). This is</span><br /><span> used as a delimiter to help define num1 from num2 */</span> <br /> }<span>else</span> <span>if</span> (byteRead==46){<br /> mySwitch=<span>true</span>;<br /> }<br /> }<br /> }<br /></pre></td></tr></tbody></table></div><div><span>The above code was formatted using </span><a href="http://hilite.me/">this site</a></div><div><br /></div><div><br /></div><div><br /><h3> <b><u>Things to Try</u></b></h3><div><b><u><br /></u></b></div><div>1. Type the following into the serial monitor:</div><div><br /></div><div>       <span>1.2=  <enter></span>                             Result:   <span>1.2 x 2 = 2.4</span></div><div><br /></div><div>Make sure that you type the equal sign (=) before you press enter, otherwise the Arduino will not know that you are finished, and will not send anything back.</div><div><br /></div><div>--------------------------------------------------------------------</div><div>2. Type the following into the serial monitor:</div><div><br /></div><div>      <span>100.001=  <enter></span>                      Result:   <span>100.001 x 2 = 200.002</span></div><div><br /></div><div>You will notice that the Arduino is formatting the decimal to the SAME number of decimals as that entered.</div><div>This is controlled by the variable: <span>numOfDec</span>.</div><div>---------------------------------------------------------------------</div><div>3. Now for our final test: Type the following into the serial monitor:</div><div><br /></div><div>   <span> 0.000001= <enter></span>                       Result: <span>0.000001 x 2 = 0.000002</span></div><div><br /></div><div>First test:<span> PASSED</span></div><div><br /></div><div>----------------------------------------------------------------------</div><div>4. Type the following into the Serial monitor for our last test:</div><div><br /></div><div>     <span>123.321=  <enter></span>                      Result: <span>123.321 x 2 = 246.642</span></div><div><br /></div><div>Second test: <span>PASSED</span></div><div>-----------------------------------------------------------------------</div><div><br /></div><div><span>BEWARE</span>: While everything looks perfect, let me tell you that it isn't. But hopefully this code will help you get on the right track. If you decide to type in a number like 123123.111222, you will not get the answer you expected. </div><div>I have found that this program will work if the amount of numbers before and after the decimal point are less than about 9.  Eg. 1234.1234   will produce the right result.</div><div>However, 11111.2222 will NOT, because there are 9 numbers represented.</div><div><br /></div><div>I think this has something to do with the memory allocated to a double, but I am not sure. </div><div>I don't know if people work with these types of numbers, but I am sure there is a workaround, and I am sure someone out there can work it out. I don't personally need this kind of precision, but thought to mention it just in case you do.</div><div><br /></div><div><br />----------------------------------------------------------------------- <br />----------------------------------------------------------------------- <br /><br /><h3> <b><span><span>STAGE 5:  Sending sensor data to the Serial Monitor</span>             </span></b></h3><br /><br />We know the Arduino is very good at copy-Cat games, how about getting the Arduino to send us some data from one of our sensors. We will use the Serial Monitor to view the sensor data.<br /><br />Disconnect the USB cable, and hook up one of your favourite analog sensors to your Arduino. For simplicity, I am going to hook up a potentiometer as per the Fritzing sketch below.<br /><br /><h3> <u> Parts Required</u></h3><br /><ul><li>Arduino UNO (or equivalent)</li><li>Computer with USB cable</li><li>Breadboard</li><li>Potentiometer</li><li>3 Wires</li></ul><div><br /></div><br /><h3> <u> Arduino Fritzing Sketch</u></h3><br /></div><div><div><a href="http://1.bp.blogspot.com/-JZlWUi3MDck/T_g6ldkqSVI/AAAAAAAAAPY/_UJj4EU3YYE/s1600/Fritzing_Potentiometer_Sketch.jpg"><img src="http://1.bp.blogspot.com/-JZlWUi3MDck/T_g6ldkqSVI/AAAAAAAAAPY/_UJj4EU3YYE/s400/Fritzing_Potentiometer_Sketch.jpg" /></a></div><br /></div><div><br /></div><div>     </div><div><br /></div><div><br /></div></div><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />Once you have attached your sensor to the board, plug your USB cable into the Arduino, and upload the following sketch.<br /><br /><br /><h3> <u>Arduino Sketch</u></h3><div><u><br /></u></div><div><table><tbody><tr><td><pre><span><span> 1<br /> 2<br /> 3<br /> 4<br /> 5<br /> 6<br /> 7<br /> 8<br /> 9<br />10<br />11<br />12<br />13<br />14<br />15<br />16<br />17<br />18<br />19<br />20<br />21</span></span></pre></td><td><pre> <span>/* Stage 5: Send Sensor Value to Serial Monitor</span><br /><span> Written by ScottC on 7/7/2012 */</span><br /><br /> <span>int</span> sensorVal = 0; <br /><br /> <span>void</span> setup() {<br /> <span>// Setup Serial communication with computer</span><br /> Serial.begin(9600);<br /> }<br /><br /> <span>void</span> loop() {<br /> <span>// Read the value from the sensor:</span><br /> sensorVal = analogRead(A0);<br /> <br /> <span>// Send the value to the Serial Monitor</span><br /> Serial.print(<span>"Sensor Value="</span>);<br /> Serial.println(sensorVal);<br /><br /> <span>// Interval between readings = 1 second</span><br /> delay(1000); <br /> }<br /></pre></td></tr></tbody></table></div><div><span>The above code was formatted using </span><a href="http://hilite.me/">this site</a><br /><u><br /></u><br /><u><br /></u><br /><h3> <u>Instructions</u></h3></div></div></div><div>1. Open the Serial monitor and watch the readings change depending on the input conditions. In my case, by turning the potentiometer from left to right, I get an output similar to the picture below.</div><div><br /></div><div><a href="http://2.bp.blogspot.com/-F8H8h8YkXJo/T_g_dcPTN1I/AAAAAAAAAPk/AXQaR5x_UFk/s1600/Serial+Monitor.jpg"><img src="http://2.bp.blogspot.com/-F8H8h8YkXJo/T_g_dcPTN1I/AAAAAAAAAPk/AXQaR5x_UFk/s400/Serial+Monitor.jpg" /></a></div><div><br /></div><div><br /></div><div><br /></div><div><br /></div><div><br /></div><div><br /></div><div><br /></div><div><br /></div><div><br /></div><div><br /></div><div><br /></div><div><br /></div><div><br /></div><div><br /></div><div><br /></div><div><br /></div><div><br /></div><div><br /></div><div><br /></div><div>As per the Arduino reference site, <a href="http://arduino.cc/en/Reference/analogRead">AnalogRead</a> returns an integer between 0 and 1023. You can see this is true based on the picture above. But what if we do not want a value between 0 and 1023. Let us say we want a value between 0 and 100?</div><div><br /></div><div>You would have to use the <a href="http://arduino.cc/en/Reference/Map">map function</a>. We will do it by changing line 13 to this:</div><div><br /></div><div><pre><span><span>13</span></span><span> </span><span><span><b>sensorVal = map(analogRead(A0),0,1023,0,100);</b></span></span></pre></div><div><br /></div><div>The map function is quite a cool function, and good fun to play around with. So here are some things to try.</div><div><h3> <b><u>Things to Try</u></b></h3></div><div>1. Change line 13 to the following, upload to the Arduino </div><div>    and then open the Serial Monitor to see the effect.</div><div><br /></div><div><b><span>Trial 1</span></b>:</div><div><pre><span><span>13</span></span><span> </span><span><span><b>sensorVal = map(analogRead(A0),0,1023,100,0);</b></span></span></pre></div><div><br /></div><div><div><b><span>Trial 2</span></b>:</div><div><pre><span><span>13</span></span><span> </span><span><span><b>sensorVal = map(analogRead(A0),0,1023,0,1000);</b></span></span></pre></div></div><div><br /></div><div><div><span><b>Trial 3</b></span>:</div><div><pre><span><span>13</span></span><span> </span><span><span><b>sensorVal = map(analogRead(A0),200,800,0,100);</b></span></span></pre></div></div><div><br /></div><div><br /></div><div>In <b><span>Trial 1</span></b>: We see that the values have been inverted. Instead of ranging from 0 up to100, they now go from 100 down to 0.</div><div><br /></div><div>In <b><span>Trial 2</span></b>: The analog readings are now mapped to a range of 0 up to 1000. </div><div><br /></div><div>In <b><span>Trial 3</span></b>: The analog readings that range from 200 to 800 are mapped to a range of 0 to 100. Therefore if the analog readings drop below 200, we will end up with a negative value for sensorVal. </div><div>If the analog readings go above 800, we will end up with a value greater than 100.  For this particular example, my readings actually range from  -33 to 137.</div><div><br /></div><div>Therefore an Analog reading of 0 = -33</div><div>                 Analog reading of 200 = 0</div><div>                 Analog reading of 800 = 100</div><div>               Analog reading of 1023 = 137</div><div><br /></div><div><br /></div><div>----------------------------------------------------------------------------------</div><div>What if we don't want the output to go beyond our intended limits of 0 to 100?</div><div>Then you would have to use the <a href="http://arduino.cc/en/Reference/Constrain">constrain function</a>. This essentially trims the reading range of the sensor, and sets a minimum and maximum value.</div><div><br /></div><div>Replace line 13 with the following code:</div><div><br /></div><div><pre><span><span>13</span></span><span> </span><span><span><b>sensorVal = constrain(map(analogRead(A0),200,800,0,100),0,100);</b></span></span></pre></div><div><br /></div><div><div>Therefore an Analog reading of 0 = 0</div><div>                 Analog reading of 100 = 0</div><div>                 Analog reading of 200 = 0</div><div>                 Analog reading of 800 = 100</div><div>                  Analog reading of 955 = 100</div><div>               Analog reading of 1023 = 100</div></div><div>Analog values between 200 and 800 will produce a result between 0 and 100.</div><div><br /></div><div>-------------------------------------------------------------------------------------<br /><br /><h3><span>If you wish to continue with this tutorial (stage 6 and above), please follow this link:  <a href="http://arduinobasics.blogspot.com/2012/07/arduino-basics-simple-arduino-serial_09.html">Serial Communication Stage 6 and above</a> </span></h3></div><div><br /></div><div><br /></div> <br />  <br />  <div> <p> <!--separator --> <img src="https://images-blogger-opensocial.googleusercontent.com/gadgets/proxy?url=http%3A%2F%2F1.bp.blogspot.com%2F-XQiwNpdqOxk%2FT_rKCzDh4nI%2FAAAAAAAAAQY%2FOfYBljhU6Lk%2Fs1600%2FSeparator.jpg&container=blogger&gadget=a&rewriteMime=image%2F*" /><br /> <br /> </p> </div> <p> <div> <p> If you like this page, please do me a favour and show your appreciation : <br /> <br />  <br /> Visit my <a href="https://plus.google.com/u/0/b/107402020974762902161/107402020974762902161/posts">ArduinoBasics Google + page</a>.<br /> Follow me on Twitter by looking for <a href="https://twitter.com/ArduinoBasics">ScottC @ArduinoBasics</a>.<br /> I can also be found on <a href="https://www.pinterest.com/ArduinoBasics/">Pinterest</a> and <a href="https://instagram.com/arduinobasics">Instagram</a>. <br /> Have a look at my videos on my <a href="https://www.youtube.com/user/ScottCMe/videos">YouTube channel</a>.<br /> </p></div> <div> <p>              <a href="http://arduinobasics.blogspot.com.au/p/arduino-basics-projects-page.html"><img src="http://2.bp.blogspot.com/-4b59S-y-Tws/VYeJtC1HNyI/AAAAAAAABk4/_CWyTKOPYOw/s320/ArduinoBasics_OpenLogo%2Bon%2BBlack.png" /></a> </p></div> <div> <p> <img src="https://images-blogger-opensocial.googleusercontent.com/gadgets/proxy?url=http%3A%2F%2F1.bp.blogspot.com%2F-XQiwNpdqOxk%2FT_rKCzDh4nI%2FAAAAAAAAAQY%2FOfYBljhU6Lk%2Fs1600%2FSeparator.jpg&container=blogger&gadget=a&rewriteMime=image%2F*" /><br /> <br /> </p></div> <div> <p> However, if you do not have a google profile... <br />Feel free to share this page with your friends in any way you see fit. </p></div></p>

    Jumper: Arduino controlled animation

    In this project, I have connected an Arduino to my computer and used a photoresistor to control an animation on the screen. Other sensors could have been used, but I chose a photoresistor because it feels like magic!!

    The photoresistor responds to changes in ambient light as my hand moves up and down. The Arduino sends the reading to a Processing sketch on the computer via a Serial command (through the USB cable). The processing sketch interprets the signal from the Arduino and selects the appropriate picture to display.

    I took a series of screenshots from the following YouTube video: http://www.youtube.com/watch?v=h6nE8m74kDg  And after borrowing a bit of code from these sites (1,2), the project was born.
    This idea is not new, nor my own. There are many people who have done this project before, but I thought to blog about how I have done it, just for fun.

    The Project Movie




    Components Required


    • Arduino Uno (and associated software), and USB cable
    • Photoresistor or Photocell
    • 10K resistor
    • Wires to put it all together
    • Processing IDE from http://processing.org
    • Computer/laptop


    The Arduino Sketch






    The Arduino Code:

    You can download the Arduino IDE from this site.
     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
    44
    45
    46
    47
    48
    49
    /* Jumper: Using an Arduino to animate:
    Written by ScottC on 02/06/2012 */

    int photoRPin = 0;
    int minLight;
    int maxLight;
    int lightLevel;
    int adjustedLightLevel;
    int oldLightLevel;

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

    //Setup the starting light level limits
    lightLevel=analogRead(photoRPin);
    minLight=lightLevel-10;
    maxLight=lightLevel;
    oldLightLevel=lightLevel;
    }

    void loop(){
    lightLevel=analogRead(photoRPin);
    delay(10);

    //auto-adjust the minimum and maximum limits in real time
    if(minLight>lightLevel){
    minLight=lightLevel;
    }
    if(maxLight<lightLevel){
    maxLight=lightLevel;
    }

    //Map the light level to produce a result between 1 and 28.
    adjustedLightLevel = map(lightLevel, (minLight+20), (maxLight-20), 1, 28);
    adjustedLightLevel = constrain (adjustedLightLevel, 1,28);

    /*Only send a new value to the Serial Port if the
    adjustedLightLevel value changes.*/
    if(oldLightLevel==adjustedLightLevel){
    //do nothing if the old value and the new value are the same.
    }else{
    //Update the oldLightLevel value for the next round
    oldLightLevel=adjustedLightLevel;

    /*Send the adjusted Light level result
    to Serial port (processing)*/
    Serial.println(adjustedLightLevel);
    }
    }

    The code above was formatted using this site.



    The Processing Code:

    You can download the Processing IDE from this site.

     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
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    /* Jumper: Using an Arduino to animate
    Written by ScottC on 02/06/2012

    Source code derived from :
    http://processing.org/learning/topics/sequential.html
    http://processing.org/discourse/beta/num_1267080062.html

    Pictures captured from:
    http://www.youtube.com/watch?v=h6nE8m74kDg

    ======================================================= */

    import processing.serial.*;
    Serial myPort;
    String sensorReading="";

    // Create the array that will hold the images
    PImage[] movieImage = new PImage[29];

    /* The frame variable is used to control which
    image is displayed */
    int frame = 1;



    /* Setup the size of the window. Initialise serial communication with Arduino
    and pre-load the images to be displayed later on. This is done only once.
    I am using COM6 on my computer, you may need replace this value with your
    active COM port being used by the Arduino.*/

    void setup(){
    size(700,600);

    myPort = new Serial(this, "COM6", 9600);
    myPort.bufferUntil('\n');

    for(int i=0;i<28;i++){
    movieImage[i] = loadImage("Jumper" + (i+1) + ".jpg");
    }
    }




    // The draw function controls the animation sequence.

    void draw(){

    //this draws the relevant image to the window
    image(movieImage[frame-1],0,0,width,height);
    }

    void serialEvent (Serial myPort){
    sensorReading = myPort.readStringUntil('\n');
    if(sensorReading != null){
    sensorReading=trim(sensorReading);
    if (sensorReading.length()<2){
    frame = integerFromChar(sensorReading.charAt(0));
    }else{
    frame = integerFromChar(sensorReading.charAt(0))*10;
    frame += integerFromChar(sensorReading.charAt(1));
    }
    }
    }



    /* This function used to convert the character received from the
    serial port (Arduino), and converts it to a number */

    int integerFromChar(char myChar) {
    if (myChar < '0' || myChar > '9') {
    return -1;
    }else{
    return myChar - '0';
    }
    }

    The code above was formatted using this site.


    The pictures 

    Captured from this YouTube Video: http://www.youtube.com/watch?v=h6nE8m74kDg






























    Comunikino, an Arduino based communication system

    Comunikino is a box, connected to a PC which runs a script in Python.  When receiving a mail, the subject will be printed to its LCD. You can then use one of three Comunikino’s buttons to send a mail back to say “Yes”,  “No” or “Readed”  (this button can also to be used to say: “Hey! I’m thinking of you”).

     

     

    The project has been developed by Eraticlux, check here the full project.

     

     

     

    Arduino Blog 31 May 19:26