Skip navigation
1 2 3 Previous Next

Raspberry Pi 2

32 posts

I've bought the new raspberry pie 2 and have installed noobs on it as is given on the pi community. But when I plug the device on, it displays a splash screen and some text after which the display shuts. I had noobs version 1.4.0 then. I downloaded and installed noobs version 1.4.1, after which the text panel shows the box where we can select the OS to be installed but crashes after that. I can't figure out the problem. Also, this is my first experience with the raspberry pi.

i-wrench

NO Network with Pi 2

Posted by i-wrench May 21, 2015

Hi,

I have a to me strange problem and could use some help. I have two raspberry Pi's a model B+ and a model 2. I can hook up the B+ and every thing works just fine but if I connect the model 2 it does not show up in my home network. Like I said the model b+ works fine I can see it from my windows computer and I can add movies and music with no problems. But if I hook up the model 2 I see nothing yet I can connect to the internet using either one. I have them both set to the same IP address and subnet mask on my xfinity router the only difference is the Mac address.I have tried reformatting and reinstalling my Windows computer twice and same thing other pc's like Laptops and I Pads connect fine just not my raspberry Pi model 2.

Any thoughts would be much appreciated

 

               Thanks

                         Russ

Why build a radar?

If you have an interest in aircraft then a cheap and easy way to receive details of aircraft near to you is using a cheap USB TV tuner as a software defined radio to decode aircraft radar transponder transmissions. Modern transponders can transmit more than just a squawk code and altitude allowing you to see their identity, position, speed and direction, and a Raspberry Pi is cheap enough to dedicate to the task. Tuners can be had from eBay for less than £10. Here's the hardware I'm using to test:

Pi2Radar.jpg

Software setup

Starting with the latest raspbian image apply the latest updates, then we can install a few extra packages and compile the software we need:

sudo apt-get install libusb-1.0.0-dev libmysqlclient-dev cmake

git clone git://git.osmocom.org/rtl-sdr.git

cd rtl-sdr

cmake .

make -j4 (because we have lots of cores to play with on a Pi2)

sudo make install

cd

wget http://lee.smallbone.com/blog/wp-content/uploads/2014/03/dump1090-1.08.1003.14-mysql.tar.gz

tar xvfz dump1090-1.08.1003.14-mysql.tar.gz

cd dump1090-mysql

PREFIX=/usr/local make -j4

cat <<EOF > /etc/modprobe.d/rtl-sdr-blacklist.conf

# This system has librtlsdr0 installed in order to

# use digital video broadcast receivers as generic

# software defined radios.

blacklist dvb_usb_rtl28xxu

blacklist e4000

blacklist rtl2832

EOF

cp dump1090 view1090 /usr/local/bin/

cp -av public_html /usr/local/share/dump1090

At this point you have the software built, but linux will have loaded the tv drivers not the sdr drivers. The simplest solution to this is a reboot.

 

Actually receiving data

 

Once things are up and running again you can fire up dump1090:

dump1090 --interactive --net --modeac --phase-enhance --aggressive --net-http-port 8080

You should see something like this in your terminal:

Dump1090Output.png

This shows you any aircraft being received. For a more interesting view point your browser to port 8080 on your Pi and you should see something like this:

Dump1090GUI.png

So now you have a list of the local aircraft, and a map showing their position. Selecting an aircraft will cause its track to be recorded and displayed. The centre of the map and the range rings can be configured for your location - you need to edit the config.js file in /usr/local/share/dump1090

 

Pi or Pi 2?

I've been running this setup on an original Pi Model B for a number of months logging to a database and also supplying data to Flightradar24. The load average on an original Pi is around 1.05 and this causes it to slowly grind to a halt and eventually become completely unresponsive. A reboot solves this but is annoying if you're trying to collect long term data. Running the same software on a Pi 2 results in a loadaverage of 0.43 - so you could probably get away with running multiple receivers on a single system.

 

So is it worth an upgrade?

If you're just running dump1090 to see whats around you then an original Pi will just about cope. Once you want to actually do something with the data then a Pi 2 will really make a difference to the performance and stability of the system.

I received a Raspberry Pi2 from element14 and in this post i will share about my experience. Pi is really evolving and getting better with the time. Here are my experiences and observations.

1.BOOT TIME

The first difference you will find when you will make the Pi2 boot is there are 4 raspberries on the top of screen instead of 1 raspberry on B+ representing the quardcore nature of the processor. The time taken by Pi 2 to boot is significantly lesser than the B+.


2. NOOBS

If you have an older version of NOOBS you need to update it to run it on Pi2 since the ARM  architecture is different on the two boards.The new version of NOOBS is compatible with the B+ model and the Pi2. However the new Noobs have very few operating systems to select from. Future releases will definitely and should definitely have more options.

However i had a queer observation i ran the new noobs on B+ and on Pi2 using the same SD card. When i run it on Pi2 and boot into the desktop i get the following message on screen.

GDBus.Error.org.feedesktop.Policykit1.Error.Failed: Cannot determine user of subject. Apart from this the operating system works fine.

 

3. RESOLUTION

since there is no bios on the Pi there is pain in getting the resolution right.The GPU reads the config.txt file everytime it boots up. I connected my Pi on a LG LED TV.And when i swap the Pi2 and B+ keeping the same SD card resolutions get disturbed. Had to fix it time and again if you also have such problem it can be fixed by firing Sudo nano/boot/config.txt. in the LX terminal . Paste the config.txt in your SD card if it is not there ,the file can be found on the raspberry pi official website. You will need to change a few values.

 

4. GAMES AND APPLICATIONS

I ran minecraft and the game play is much smoother on the Pi 2. Also the game loads faster. Similarly mathematica loads much earlier on Pi2. I also found the webpages load much better on PI2


5. VIDEOS

Ran the sample video by using omxplayer /opt/vc/scr/hello_pi/hello_video/test.h264. The video runs great on both. Also ran a movie "book_of _life". To put the movie on pi i first put the file on the pendrive connected it to pi ,from the pendrive i copied it to the desktop.Changed the directory  using cd/home/pi/Desktop. Then used omxplayer -o local book_of _life.mp3  to play it and have the audio through the 3.5 mm jack.I couldn't see any difference in the video playback on both the pi.

 

 

I have also done a video about the Pi ecosystem and comparison of the two Pi boards i used. I have made the video with the view that anybody who is not familiar with the Pi is able to have a understanding of what it is and for those who are already familiar with it i have info about the new things we are likely to see in the Pi ecosystem. Hope you will enjoy the video.

 

 

WHAT I DON'T LIKE ABOUT PI :

1. while booting the pi. The pi asks for username and password. After you enter the user name as Pi and then when you will  try to enter the password  you will see nothing appearing on the screen when you will press the  keys on you keyboard.But actually if you have faith in yourself and you type raspberry and then if you will press enter you will find that you have successfully logged in. There should be  stars****** on key press.

2. Pi doesn't have a power on /off button. Usually most of us connect our pi's adapter  to a multisocket board but it is annoying to turn it off from there. It would be great if there is a button on pi to do this. Till it gets there on the board there is another solution for the people like me ,there comes a used cable that has a on/off button which can be used to as an alternate.

 

ABOUT  THE PERIPHERALS I USED:


I used a wireless keyboard and mouse for the first time,earlier i use to go with a wired one. For those who want to buy one ,Logitech MK220 works flawless on the pi,no hassel just plug and play. Moreover this is the cheapest one available right now.

For wireless connectivity i used  EDUP Mini Wireless N 11n Wi-Fi Nano USB Adapter. This is also just plug and play.

One last thing, do use a good quality power adapter otherwise it might deter the quality of your experience,the B+ and pi2 has good brown out detection and the power LED blinks if there is not enough power available.

coolbox

My Pi 2 arrived

Posted by coolbox Apr 28, 2015

Sorry it's late.But I want to share some Pics here.Thanks element14Dave for appreciating me by sending this amazing thing.I am planning some interesting projects.I will post them soon.

IMG_20150426_212341.jpg

pi_pic.png

 

This technote covers setting up the Xfce desktop environment and session manager on a Raspberry Pi.  Folks who use a Linux distribution that make use of Xfce will find the Raspbian Xfce quite familiar.  I find that the look and feel of the desktop and the application menu organization is almost identical to that of Xubuntu which I use at home on Mini-ITX builds.


The latest Raspbian image (2015-02-16) from http://www.raspberrypi.org/downloads/ includes Openbox and LXDE as desktop environment options on top of LightDM.  Xfce also uses LightDM so I was not surprised that Xfce installed so easily and was immediately available for use without any “tweaks”.

Note that one can also install the MATE desktop session manager that Linux Mint users are quite familiar with.  Maybe other desktop session managers too although the gating factor would be that they should interoperate with LightDM in order to avoid a lot of re-tooling.

Start with the following and go have a snack or walk the dog while its running:

sudo apt-get -y install Xfce4 Xfce4-screenshooter

This installs the desktop environment and session manager, the related applications, and a screen-shot application that is the best that I have ever used [(-:].

To try out Xfce once,

    • Logout.
    • At the login prompt, select “Xfce Session” in place of “Default Xsession”.
    • Login.

Note that the next time that you reboot/logout and come back, you will be back to whatever desktop session manager that you were using before.  To make use of Xfce from now on as the default, execute the following:

sudo update-alternatives --config x-session-manager

This will bring up a menu that should look like the following (or similar, depending on what you have been tinkering with):

   Selection    Path                      Priority   Status
------------------------------------------------------------
  0            /usr/bin/startlxde-pi      90        auto mode
  1            /usr/bin/lxsession         49        manual mode
  2            /usr/bin/openbox-session   40        manual mode
  3            /usr/bin/startlxde         50        manual mode
  4            /usr/bin/startlxde-pi      90        manual mode
  5            /usr/bin/startXfce4        50        manual mode
  6            /usr/bin/Xfce4-session     40        manual mode

Assuming your #6 looks like the above, select 6 to make Xfce the default session from now on.

Reboot.  That's it!  Feel free to comment or mail me if you have issues with installing or using Xfce.

Intro

In this blog post I will describe how I used the SPI interface of the Raspberry Pi 2 (and Raspberry Pi) to communicate with an Arduino board.

Both the RPi and Arduino are connected to a nRF24L01+ chip to communicate with each other via the SPI interface.

I will describe the practical details of the setup and will also share the sources which were used.

The GPIO usage on the Raspberry Pi 2 is exactly the same as on the Raspberry Pi B(+). In practice it might be that some expansion boards which fit on the Raspberry Pi B do not fit on the RPiB+ or RPi2 because pins 27,28 are right next to pins 25,26.

 

Setup

To use the GPIO pins on the Raspberry Pi 2 I used some (additional) electronic parts. I did the same tests with Raspberry Pi B Rev. 2.0 and Raspberry Pi 2 B.

The most important parts I used:

2x nRF24L01+

1x Raspberry Pi 2 / 1x Raspberry Pi B

1x Arduino UNO R3

2x Capacitor 220uF(*) (for the power to the nRF24L01+ chip)

 

To connect to the nRF24L01+ chip I used a straight 20 pin ribbon cable and for connecting to the GPIO pins of the Raspberry Pi an old IDE40 cable. (Note that if you try this yourself, you should pay attention that you have 40 pin cable without any shorts, a 80-wire / 40 pin cable will most likely have shorts to reduce crosstalk.)


(*) I still had this capacitor laying around, probably 10uF would have been sufficient.


Raspberry Pi (2) GPIO PINs

For both Raspberry Pi's the pins that I use are the same.

P01 : 3.3V : dark orange (*)
P25 : GND : black

P15 : GPIO22 : white (CE)

P19 : MOSI : yellow

P21 : MISO : green

P23 : SCLK : orange (*)

P24 : CSN  : blue


We connect the pins from the RPi(2) to the nRF24L01+ chip. Vcc is 3.3V and for CE we use pin 15 (GPIO22) on the RPi(2). (For the rest we connect the MOSI of the RPi to the MOSI of the nRF24L01+ chip, ... )

In the test setup I used an old IDE40 cable. On both the RPi2 and RPi, pin 1 and 2 are at the edge of the board. Since some pins of the IDE cable are next to the board you will see that the wires on the other side of the IDE cable are inserted in a different position.

(*) It might not be that easy to see the difference between dark orange and orange in the pictures, but the dark orange is the "lonely" cable (7 pins next to the white cable).

 

IDE40 color
RPi(2) function
RPi(2) pinnRF24L01+ pinnRF24L01+ function20-pin color
dark orange3.3V012Vcc / 3.3Vyellow
blackGND251GNDwhite
whiteGPIO22153CEwhite
yellowMOSI196MOSIyellow
greenMISO217MISOgreen
orangeSCLK235SCKorange
blueCSN244CSNblue

 

Raspberry Pi 2 B:

The following table tries to show the relation between the pins on the RPi2 and the pins on the IDE40 cable:

__________________------__________________
403836343230282624222018161412108642
39373533312927252321191715131197531

The "---" in the middle represents the notch in the midlle of the IDE cable (see pictures "RPi2: IDE40 ribbon cable / dupont wires").

 

{gallery} Raspberry Pi 2 IDE40

RPi2B_IDE40.jpg

RPi2: IDE40 ribbon cable

RPi2B_IDE40_dupont.jpg

RPi2: IDE40 ribbon cable / dupont wires

 

Raspberry Pi B:

The following table tries to show the relation between the pins on the RPi and the pins on the IDE40 cable (xx means not used; pins sticking out next to the board):

__________________------__________________
2624222018161412108642xxxxxxxxxxxxxx
252321191715131197531xxxxxxxxxxxxxx

 

 

{gallery} Raspberry Pi IDE40

RPiB_IDE40.jpg

RPi: IDE40 ribbon cable

RPiB_IDE40_dupont.jpg

RPi: IDE40 ribbon cable / dupont wires

nRF24L01+

"Top" view of the nRF24L01+ chip

|__|__|__|__|--
|___________
|||
|||
|||
2468
1357

 

1 : GND

2 : VCC (3.3V)

3 : CE    : white

4 : CSN  : blue

5 : SCK  : orange

6 : MOSI : yellow

7 : MISO : green

8 : IRQ : xx

 

The following table tries to show the relation between the nRF24L01+ pins and the pins on the 20-pin ribbon cable (xx means not used):

________------________
2468xxxxxxxxxxxx
1357xxxxxxxxxxxx

 

{gallery} nRF24L01+

nRF24L01_180.jpg

nRF24L01+: chip

nRF24L01_dupont_180.jpg

nRF24L01+: dupont

 

Software

By default SPI is not enabled on Raspbian to load it during the boot process execute sudo raspi-config then select Advanced and then enable the SPI kernel module.

You can also do sudo modprobe spi-bcm2708.

For both the RPi and Arduino, I used the TMRh20 library available on github (some RPi specific info).

If you download the library and do not follow the installation procedure, then you'll need to do sudo make and sudo make install to install the library.

The modified sources are just to transmit data between RPi and Arduino. By default this Arduino sketch will start in transmit mode, by pressing d it will go in "dump" mode, where it will dump the contents of the data array when it's received.

 

Arduino Sketch:

/*
2015-04-06 : Johan Boeckx - Arduino/RPi(2) nRF24L01+ : Arduino UNO R3 code
  Tested on Arduino UNO R3 and Raspberry Pi B Rev. 2.0 and Raspberry Pi 2 B


TMRh20 2014
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
version 2 as published by the Free Software Foundation.
*/
/** Reliably transmitting large volumes of data with a low signal or in noisy environments
* This example demonstrates data transfer functionality with the use of auto-retry
and auto-reUse functionality enabled. This sketch demonstrates how a user can extend
the auto-retry functionality to any chosen time period, preventing data loss and ensuring
the consistency of data.

This sketh demonstrates use of the writeBlocking() functionality, and extends the standard
retry functionality of the radio. Payloads will be auto-retried until successful or the
extended timeout period is reached.
*/
#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
#include "printf.h"
/*************  USER Configuration *****************************/
RF24 radio(7,8);                        // Set up nRF24L01 radio on SPI bus plus pins 7 & 8
unsigned long timeoutPeriod = 3000;     // Set a user-defined timeout period. With auto-retransmit set to (15,15) retransmission will take up to 60ms and as little as 7.5ms with it set to (1,15).
                                        // With a timeout period of 1000, the radio will retry each payload for up to 1 second before giving up on the transmission and starting over
/***************************************************************/
const uint64_t pipes[2] = { 0xABCDABCD71LL, 0x544d52687CLL };   // Radio pipe addresses for the 2 nodes to communicate.
byte data[32] = {"_This is a message via NRF24L+!"};                           //Data buffer
volatile unsigned long counter;
unsigned long rxTimer,startTime, stopTime, payloads = 0;
//bool TX=1,RX=0,role=0, transferInProgress = 0;
bool transferInProgress = 0;
unsigned int TX=1,RX=0,role=1,lastrole=0,SKIP=2,RXPRINT=3,RXDUMP=4;
unsigned int offset=0;
void setup(void) {
  Serial.begin(57600);
  printf_begin();
  radio.begin();                           // Setup and configure rf radio
  radio.setChannel(1);                     // Set the channel
  radio.setPALevel(RF24_PA_HIGH);
  radio.setDataRate(RF24_250KBPS);
  //radio.setDataRate(RF24_2MBPS);
  radio.setAutoAck(1);                     // Ensure autoACK is enabled
  radio.setRetries(2,15);                  // Optionally, increase the delay between retries. Want the number of auto-retries as high as possible (15)
  radio.setCRCLength(RF24_CRC_16);         // Set CRC length to 16-bit to ensure quality of data
  if (role == RX)
  {
    radio.openWritingPipe(pipes[0]);         // Open the default reading and writing pipe
    radio.openReadingPipe(1,pipes[1]);

    radio.startListening();                 // Start listening
  }
  else{
    radio.openWritingPipe(pipes[1]);         // Open the default reading and writing pipe
    radio.openReadingPipe(1,pipes[0]);
    radio.stopListening();
  }
  radio.printDetails();                   // Dump the configuration of the rf unit for debugging

  printf("\n\rRF24/examples/Transfer Rates/\n\r");
  printf("*** PRESS 'T' to begin transmitting to the other node\n\r");

  /*
  randomSeed(analogRead(0));              //Seed for random number generation
  for(int i=0; i<32; i++){
     data[i] = random(255);               //Load the buffer with random data
  }
  */
  radio.powerUp();                        //Power up the radio

}
void showData(void)
{
      printf("Data: ");
      for(int i=0; i<32; i++){
         if(isprint(data[i]))
           printf("%c", data[i]);
         else
           printf(".");
      }
      printf("\n\r");
}
void loop(void){
  if(role == TX){
    delay(500);                                              // Pause for a couple seconds between transfers
    printf("Initiating Extended Timeout Data Transfer\n\r");
    unsigned long cycles = 1000;                              // Change this to a higher or lower number. This is the number of payloads that will be sent.

    unsigned long transferCMD[] = {'H','S',cycles };          // Indicate to the other radio that we are starting, and provide the number of payloads that will be sent
    radio.writeFast(&transferCMD,12);                         // Send the transfer command
    if(radio.txStandBy(timeoutPeriod)){                       // If transfer initiation was successful, do the following

        startTime = millis();                                 // For calculating transfer rate
        boolean timedOut = 0;                                 // Boolean for keeping track of failures

        for(int i=0; i<cycles; i++){                          // Loop through a number of cycles
          data[0] = i;                                        // Change the first byte of the payload for identification
          if(!radio.writeBlocking(&data,32,timeoutPeriod)){   // If retries are failing and the user defined timeout is exceeded
              timedOut = 1;                                   // Indicate failure
              counter = cycles;                               // Set the fail count to maximum
              break;                                          // Break out of the for loop
          }
        }


        stopTime = millis();                                  // Capture the time of completion or failure

       //This should be called to wait for completion and put the radio in standby mode after transmission, returns 0 if data still in FIFO (timed out), 1 if success
       if(timedOut){ radio.txStandBy(); }                     //Partially blocking standby, blocks until success or max retries. FIFO flushed if auto timeout reached
       else{ radio.txStandBy(timeoutPeriod);     }            //Standby, block until FIFO empty (sent) or user specified timeout reached. FIFO flushed if user timeout reached.

   }else{                                      
       Serial.println("Communication not established");       //If unsuccessful initiating transfer, exit and retry later
       counter = cycles+1;
   }
   if (counter <= cycles )
   {
     float rate = cycles * 32 / (stopTime - startTime);         //Display results:

     Serial.print("Transfer complete at "); Serial.print(rate); printf(" KB/s \n\r");
     Serial.print(counter);
     Serial.print(" of ");
     Serial.print(cycles); Serial.println(" Packets Failed to Send");
     //if (counter == 0)
     showData();
   }
   counter = 0;
   Serial.print("------------------------------------------------------------\r\n\r\n");
}

if(role == RX){

  if(!transferInProgress){                       // If a bulk data transfer has not been started
     if(radio.available()){
        //Serial.print("Rx\r\n");
        //Serial.print(".");
        radio.read(&data,32);                    //Read any available payloads for analysis
        if(data[0] == 'H' && data[4] == 'S'){    // If a bulk data transfer command has been received
          payloads = data[8];                    // Read the first two bytes of the unsigned long. Need to read the 3rd and 4th if sending more than 65535 payloads
          payloads |= data[9] << 8;              // This is the number of payloads that will be sent
          counter = 0;                           // Reset the payload counter to 0
          transferInProgress = 1;                // Indicate it has started
          startTime = rxTimer = millis();        // Capture the start time to measure transfer rate and calculate timeouts
        }
     }
  }else{
     if(radio.available()){                     // If in bulk transfer mode, and a payload is available
       //Serial.print("Rx\r\n");
       radio.read(&data,32);                    // Read the payload
       rxTimer = millis();                      // Reset the timeout timer
       counter++;                               // Keep a count of received payloads
     }else
     if(millis() - rxTimer > timeoutPeriod){    // If no data available, check the timeout period
       Serial.println("Transfer Failed");       // If per-payload timeout exceeeded, end the transfer
       transferInProgress = 0;
       //Serial.print("!\r\n");
     }else
     if(counter >= payloads){                   // If the specified number of payloads is reached, transfer is completed
      //Serial.print("!\r\n");
      startTime = millis() - startTime;         // Calculate the total time spent during transfer
      float numBytes = counter*32;              // Calculate the number of bytes transferred
      Serial.print("Rate: ");                   // Print the transfer rate and number of payloads
      Serial.print(numBytes/startTime);
      Serial.println(" KB/s");
      printf("Payload Count: %d (%c)\n\r", counter, (char* )data[1]);
      showData();
      transferInProgress = 0;                   // End the transfer as complete
    }
  }
}
if(role == RXDUMP){
     if(radio.available()){
        radio.read(&data,32);                    //Read any available payloads for analysis
        showData();
     }
}
if(role == RXPRINT){
  if(!transferInProgress){                       // If a bulk data transfer has not been started
     if(radio.available()){
        //Serial.print("Rx\r\n");
        Serial.print(".");
        radio.read(&data,32);                    //Read any available payloads for analysis
        if(data[0] == 'H' && data[4] == 'S'){    // If a bulk data transfer command has been received
          payloads = data[8];                    // Read the first two bytes of the unsigned long. Need to read the 3rd and 4th if sending more than 65535 payloads
          payloads |= data[9] << 8;              // This is the number of payloads that will be sent
          counter = 0;                           // Reset the payload counter to 0
          transferInProgress = 1;                // Indicate it has started
          startTime = rxTimer = millis();        // Capture the start time to measure transfer rate and calculate timeouts
        }
     }
  }else{
     if(radio.available()){                     // If in bulk transfer mode, and a payload is available
       Serial.print(".");
       radio.read(&data,32);                    // Read the payload
       rxTimer = millis();                      // Reset the timeout timer
       counter++;                               // Keep a count of received payloads
     }else
     if(millis() - rxTimer > timeoutPeriod){    // If no data available, check the timeout period
       Serial.println("Transfer Failed");       // If per-payload timeout exceeeded, end the transfer
       transferInProgress = 0;
       Serial.print("!\r\n");
     }else
     if(counter >= payloads){                   // If the specified number of payloads is reached, transfer is completed
      Serial.print("!\r\n");
      startTime = millis() - startTime;         // Calculate the total time spent during transfer
      float numBytes = counter*32;              // Calculate the number of bytes transferred
      Serial.print("Rate: ");                   // Print the transfer rate and number of payloads
      Serial.print(numBytes/startTime);
      Serial.println(" KB/s");
      printf("Payload Count: %d (%c)\n\r", counter, (char* )data[1]);
      showData();
      transferInProgress = 0;                   // End the transfer as complete
      delay(500);
    }
  }
}
if(role == SKIP){
}

  //
  // Change roles
  //
  if ( Serial.available() )
  {
    char c = toupper(Serial.read());
    printf("*** SERIAL : %c %d\n\r", c, c);
    if ( c == 'C' && role == SKIP)
    {
      role = lastrole;
      printf("*** CONTINUING PREVIOUS ROLE\n\r");
    }
    else if ( c == 'D' && (role != RXDUMP ))
    {
      radio.openWritingPipe(pipes[0]);
      radio.openReadingPipe(1,pipes[1]);
      radio.startListening();
      printf("*** CHANGING TO RECEIVE DUMP ROLE -- PRESS 'T' TO SWITCH BACK\n\r");
      role = RXDUMP;                // Become the primary receiver (pong back)
    }
    else if ( c == 'T' && (role != TX ))
    {
      printf("*** CHANGING TO TRANSMIT ROLE -- PRESS 'R' TO SWITCH BACK\n\r");
      radio.openWritingPipe(pipes[1]);
      radio.openReadingPipe(1,pipes[0]);
      radio.stopListening();
      role = TX;                  // Become the primary transmitter (ping out)
    }
    else if ( c == 'P' && (role != RXPRINT ) )
    {
      radio.openWritingPipe(pipes[0]);
      radio.openReadingPipe(1,pipes[1]);
      radio.startListening();
      printf("*** CHANGING TO RECEIVE PRINT ROLE -- PRESS 'T' TO SWITCH BACK\n\r");
      role = RXPRINT;                // Become the primary receiver (pong back)
    }
    else if ( c == 'R' && (role == RX) )
    {
      radio.openWritingPipe(pipes[0]);
      radio.openReadingPipe(1,pipes[1]);
      radio.startListening();
      printf("*** CHANGING TO RECEIVE ROLE -- PRESS 'T' TO SWITCH BACK\n\r");
      role = RX;                // Become the primary receiver (pong back)
    }
    else if ( c == 'S' && role != SKIP)
    {
      lastrole = role;
      role = SKIP;
      showData();
      printf("*** WAITING -- PRESS 'C' TO CONTINUE\n\r");
    }
    else if ( c == 'M' ){
      offset = 1;
      while ( c != 13 )
      {

        if ( Serial.available() )
        {
          c = Serial.read();
          if ( c != 13 ){
          offset++;
          if (offset>=32)
            offset = 1;
          data[offset] = c;
          printf("*** SERIAL : %c data[%d]=(%c)\n\r", c, offset, data[offset]);
          }
        }
      }
    }
  }
}








 

Raspberry Pi (2) c code:

/*
2015-04-06 : Johan Boeckx - Arduino/RPi(2) nRF24L01+ : Raspberry Pi (2) code
  Tested on Arduino UNO R3 and Raspberry Pi B Rev. 2.0 and Raspberry Pi 2 B

 Copyright (C) 2011 J. Coliz <maniacbug@ymail.com>

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
version 2 as published by the Free Software Foundation.

 03/17/2013 : Charles-Henri Hallard (http://hallard.me)
              Modified to use with Arduipi board http://hallard.me/arduipi
                          Changed to use modified bcm2835 and RF24 library
TMRh20 2014 - Updated to work with optimized RF24 Arduino library

*/

#include <cstdlib>
#include <iostream>
#include <sstream>
#include <string>
#include <RF24/RF24.h>

using namespace std;
//
// Hardware configuration
// Configure the appropriate pins for your connections

/****************** Raspberry Pi ***********************/

// Radio CE Pin, CSN Pin, SPI Speed
// See http://www.airspayce.com/mikem/bcm2835/group__constants.html#ga63c029bd6500167152db4e57736d0939 and the related enumerations for pin information.

// Setup for GPIO 22 CE and CE0 CSN with SPI Speed @ 4Mhz
//RF24 radio(RPI_V2_GPIO_P1_22, BCM2835_SPI_CS0, BCM2835_SPI_SPEED_4MHZ);

// NEW: Setup for RPi B+
//RF24 radio(RPI_BPLUS_GPIO_J8_15,RPI_BPLUS_GPIO_J8_24, BCM2835_SPI_SPEED_8MHZ);

// Setup for GPIO 15 CE and CE0 CSN with SPI Speed @ 8Mhz
//RF24 radio(RPI_V2_GPIO_P1_15, RPI_V2_GPIO_P1_24, BCM2835_SPI_SPEED_8MHZ);

// RPi generic:
RF24 radio(22,0);

/*** RPi Alternate ***/
//Note: Specify SPI BUS 0 or 1 instead of CS pin number.
// See http://tmrh20.github.io/RF24/RPi.html for more information on usage

//RPi Alternate, with MRAA
//RF24 radio(15,0);

//RPi Alternate, with SPIDEV - Note: Edit RF24/arch/BBB/spi.cpp and  set 'this->device = "/dev/spidev0.0";;' or as listed in /dev
//RF24 radio(22,0);


/****************** Linux (BBB,x86,etc) ***********************/

// See http://tmrh20.github.io/RF24/pages.html for more information on usage
// See http://iotdk.intel.com/docs/master/mraa/ for more information on MRAA
// See https://www.kernel.org/doc/Documentation/spi/spidev for more information on SPIDEV

// Setup for ARM(Linux) devices like BBB using spidev (default is "/dev/spidev1.0" )
//RF24 radio(115,0);

//BBB Alternate, with mraa
// CE pin = (Header P9, Pin 13) = 59 = 13 + 46
//Note: Specify SPI BUS 0 or 1 instead of CS pin number.
//RF24 radio(59,0);

/********** User Config *********/
// Assign a unique identifier for this node, 0 or 1
// 0 Rx / 1 Tx
bool radioNumber = 0;
unsigned long timeoutPeriod = 3000;     // Set a user-defined timeout period. With auto-retransmit set to (15,15) retransmission will take up to 60ms and as little as 7.5ms with it set to (1,15).

/********************************/

// Radio pipe addresses for the 2 nodes to communicate.
// const uint8_t pipes[][6] = {"1Node","2Node"};
const uint64_t pipes[2] = { 0xABCDABCD71LL, 0x544d52687CLL };   // Radio pipe addresses for the 2 nodes to communicate.
char data[32] = {"_A message from RPi w/ NRF24L+!"};            //Data buffer

void showData(void)
{
      printf("Data: ");
      for(int i=0; i<32; i++){
         if(isprint(data[i]))
           printf("%c", data[i]);
         else
           printf(".");
      }
      printf("\n\r");
}

int main(int argc, char** argv){

  const int role_rx=0, role_tx=1;
  int role=role_rx;
/********* Role chooser ***********/

  printf("\n ************ Role Setup ***********\n");
  string input = "";
  char myChar = {0};

  cout << "Choose a role: Enter 0 for Rx, 1 for Tx (CTRL+C to exit) \n>";
  getline(cin,input);

  if(input.length() == 1) {
    myChar = input[0];
    if(myChar == '0'){
        cout << "Role: Rx " << endl << endl;
    }else{  cout << "Role: Tx " << endl << endl;
        role = role_tx;
    }
  }
  switch(role) {
      case role_rx :
        radioNumber=0;
        break;

      case role_tx :
        radioNumber=1;
        break;
  }

/***********************************/
  // Setup and configure rf radio
  radio.begin();

  // optionally, increase the delay between retries & # of retries
  radio.setRetries(15,15);
  // Set the channel
  radio.setChannel(1);
  // Set the data rate
  //radio.setDataRate(RF24_2MBPS);
  radio.setDataRate(RF24_250KBPS);
  //radio.setPALevel(RF24_PA_MAX);
  radio.setPALevel(RF24_PA_MIN);

    if ( !radioNumber )    {
        radio.openWritingPipe(pipes[0]);
        radio.openReadingPipe(1,pipes[1]);
        memset(&data,'\0',sizeof(data));
        radio.startListening();
    } else {
        radio.openWritingPipe(pipes[1]);
        radio.openReadingPipe(1,pipes[0]);
        radio.stopListening();
    }
    // Dump the configuration of the rf unit for debugging
    radio.printDetails();
    printf("Start loop:\n");
    // forever loop
    while (1)
    {
        if (radioNumber) {
            if (radio.writeBlocking(&data,sizeof(data),timeoutPeriod)) {
                printf(".");
            }
            else {
                printf("?");
            }
            fflush(stdout);
            //printf("\n");
        }
        else {
        //
        // Receive each packet, dump it
        //
            if(radio.available()){
                // Read any available payloads for analysis
                radio.read(&data,32);
                // Dump the printable data of the payload
                showData();
                fflush(stdout);
            }
        }
        delay(5);
    } // forever loop

  return 0;
}









 

Raspberry Pi (2) output

Receive mode

When we receive a message, dump the data.

************ Role Setup ***********

Choose a role: Enter 0 for Rx, 1 for Tx (CTRL+C to exit)

>0

Role: Rx

 

================ SPI Configuration ================

CSN Pin       = CE0 (PI Hardware Driven)

CE Pin       = Custom GPIO22

Clock Speed     = 8 Mhz

================ NRF Configuration ================

STATUS         = 0x0e RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=7 TX_FULL=0

RX_ADDR_P0-1     = 0xabcdabcd71 0x544d52687c

RX_ADDR_P2-5     = 0xc3 0xc4 0xc5 0xc6

TX_ADDR         = 0xabcdabcd71

RX_PW_P0-6     = 0x20 0x20 0x00 0x00 0x00 0x00

EN_AA         = 0x3f

EN_RXADDR     = 0x02

RF_CH         = 0x01

RF_SETUP     = 0x21

CONFIG         = 0x0f

DYNPD/FEATURE     = 0x00 0x00

Data Rate     = 250KBPS

Model         = nRF24L01+

CRC Length     = 16 bits

PA Power     = PA_MIN

Start loop:

Data: H...S...........................

Data: .This is a message via NRF24L+!.

Transmit mode

If the write succeeds write a "." else a "?".

************ Role Setup ***********

Choose a role: Enter 0 for Rx, 1 for Tx (CTRL+C to exit)

>1

Role: Tx

 

================ SPI Configuration ================

CSN Pin       = CE0 (PI Hardware Driven)

CE Pin       = Custom GPIO22

Clock Speed     = 8 Mhz

================ NRF Configuration ================

STATUS         = 0x0e RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=7 TX_FULL=0

RX_ADDR_P0-1     = 0x544d52687c 0xabcdabcd71

RX_ADDR_P2-5     = 0xc3 0xc4 0xc5 0xc6

TX_ADDR         = 0x544d52687c

RX_PW_P0-6     = 0x20 0x20 0x00 0x00 0x00 0x00

EN_AA         = 0x3f

EN_RXADDR     = 0x03

RF_CH         = 0x01

RF_SETUP     = 0x21

CONFIG         = 0x0e

DYNPD/FEATURE     = 0x00 0x00

Data Rate     = 250KBPS

Model         = nRF24L01+

CRC Length     = 16 bits

PA Power     = PA_MIN

Start loop:

...????................................................................................................................................................................................................................................................................................................^C

Arduino Output

By default the Arduino starts in Transmit mode. When you press "d" it goes to "dump" mode, which means just dump the packet which is received.

STATUS           = 0x0e RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=7 TX_FULL=0

RX_ADDR_P0-1     = 0x544d52687c 0xabcdabcd71

RX_ADDR_P2-5     = 0xc3 0xc4 0xc5 0xc6

TX_ADDR          = 0x544d52687c

RX_PW_P0-6       = 0x20 0x20 0x00 0x00 0x00 0x00

EN_AA            = 0x3f

EN_RXADDR        = 0x03

RF_CH            = 0x01

RF_SETUP         = 0x25

CONFIG           = 0x0e

DYNPD/FEATURE    = 0x00 0x00

Data Rate        = 250KBPS

Model            = nRF24L01+

CRC Length       = 16 bits

PA Power         = PA_HIGH

 

Transmit mode

The Arduino sketch which was taken as basis, was meant to send a header packet and then x times a payload packet.

When we stop listening on the RPi to the packets coming from the Arduino, we will see errors on the serial output of the Arduino:

Initiating Extended Timeout Data Transfer

Transfer complete at 5.00 KB/s

0 of 1000 Packets Failed to Send

Data: .This is a message via NRF24L+!.

------------------------------------------------------------

 

Initiating Extended Timeout Data Transfer

Communication not established

------------------------------------------------------------

Dump mode

Data: _A message from RPi w/ NRF24L+!.

 

 

Sources

 

Github : https://github.com/TMRh20/RF24

Class documentation : Optimized High Speed NRF24L01+ Driver Class Documenation: Optimized High Speed Driver for nRF24L01(+) 2.4GHz Wireless Tr…

Raspberry Pi info : Optimized High Speed NRF24L01+ Driver Class Documenation: Raspberry Pi

Ethernet library : RF24Ethernet - TCP/IP over RF24Network: RF24Ethernet library: TCP/IP over RF24Network

A few folks seem to have stumbled over network set up and using SSH in OpenELEC on Pi 2.  So this technote shares my experience in hopes that it might help others clear those hurdles.  Also, I added overclocking here because I found that it eliminated some video playback anomalies.

 

Topics covered in detail where I had put in effort beyond what I saw written up elsewhere:

 

  1. Setting up wireless with or without a static IP address
  2. Setting up SSH service
  3. Overclocking for Higher Performance

 

1. Setting up wireless with or without a static IP address

 

There are a number of reasons why one might (at least, initially) set up a wireless connection for OpenELEC.  In my case, my Pi went from sitting in my dining room (no Ethernet) to sitting in my kitchen breakfast nook (no Ethernet) with its power adapter plugged into the same electric wall plate as my coffee machine [(-:].  My home is currently another project (long story).

 

In the OpenELEC home menu, select:

 

    PROGRAMS > Openelec Configuration

 

In Network, select Wireless and

 

    Turn off Wired Network

    Turn on Wireless Network

 

In Connections, select your router and enter the usual network pass-code for connecting.

 

A static IP address for a server such as OpenELEC is convenient for using client service requesters such as SSH (the next subject in this technote).  If a static IP address is desired, select the router's connection entry > Edit > IPv4 and enter the values that make sense for your home network.  My Pi (an example) is configured as follows:

 

        IP Address Method              Manual

        IP Address                     192.168.1.102

        Netmask                        255.255.255.0

        Default Gateway                192.168.1.1 (router)

 

Note that the above static address scheme would also work for a wired Ethernet connection (default IP Address Method = dhcp).

 

2. Setting up SSH service

 

Sometimes, it is useful to get a command line terminal on the OpenELEC Pi.  Some examples of use are as follows:

 

  • Future system update operations.
  • Trouble-shooting using the contents of /var/log.
  • Modifying the config.txt system configuration file (E.g. overclocking).

 

To set this up, in the OpenELEC home menu, select:

 

    PROGRAMS > Openelec Configuration

 

In Services, enable SSH.

 

3. Overclocking for Higher Performance

 

See the discussion at http://wiki.openelec.tv/index.php/Raspberry_Pi_FAQ#Overclocking and the overclocking settings under the paragraph, "How do I overclock my PI?".

 

I have no issues doing this for myself or my family.  Other people might feel differently.  My Pi is still running cool, even while throwing up an MKV video at 1080p.  And, the normal-clocking Pi occasionally stuttered video and audio and video horizontal line anomalies were occasionally visible.  Maybe that was my hardware.  In any case, after overclocking, the anomalies have not yet re-appeared.

 

The following is what my OpenELEC file system list looks like through the eyes of `ssh`:

 

ssh root@192.168.1.102

root@192.168.1.102's password:

##############################################

# OpenELEC - The living room PC for everyone #

# ...... visit http://www.openelec.tv ...... #

##############################################

 

OpenELEC (official) Version: 5.0.8

raspy:~ # df -k

Filesystem           1K-blocks      Used Available Use% Mounted on

devtmpfs                371968         0    371968   0% /dev

/dev/mmcblk0p1          261868    107508    154360  41% /flash

/dev/mmcblk0p2        60139035     34254  60100685   0% /storage

/dev/loop0               96640     96640         0 100% /

tmpfs                   377168         0    377168   0% /dev/shm

tmpfs                   377168      5048    372120   1% /run

tmpfs                   377168         0    377168   0% /sys/fs/cgroup

tmpfs                   377168         4    377164   0% /tmp

tmpfs                   377168       224    376944   0% /var

 

As you can see, OpenELEC does not mount /boot on /dev/mmcblk0p1.  It mounts /flash on that device as read-only; the config.txt file is filed under /flash.

 

You can edit config.sys by either (a) editing config.txt on another computer or (b) ssh to OpenELEC Pi and change the config.txt there.

 

If you choose (a), the instructions for Windows are on the OpenELEC wiki page referenced earlier; Linux users can probably figure out the equivalent.

 

If you choose (b) as I did, the instructions can be found here: http://wiki.openelec.tv/index.php/Config.txt

OpenELEC is a special Linux distribution because it runs a single specialized application: Kodi.  As a consequence of being understandably cautious, there are limitations to what a user can do in terms of administration in this environment.

 

For example, many of the Debian Linux utilities found in Raspbian are not present in OpenELEC.  Examples include the `dpkg*` and `apt*` families for system update and maintenance.  I don't mind those limitations at all.  However, one irksome situation concerns time synchronization.  While the user has full ability to configure the local time zone, we seem to have been left to our own devices for setting and updating the clock time.  Note that `ntpd` (network time protocol daemon) is installed but it is not configured nor started - at least in Raspberry Pi OpenELEC version 5.0.8.

 

So, I just finished a band-aid which will probably work for you if you are also observing time drift issues like I have (E.g. after powering off for a bit). Hopefully, at some time in the future, OpenELEC will include automatic periodic execution of `ntpd`.

 

1. ssh to the OpenELEC Pi 2 server as the root.  The remaining steps (2-7) take place in the ssh window.

 

2. Edit /storage/.config/autostart.sh with your favorite Linux text editor.  If you have never added anything to this file before, it will not yet exist.  Don't worry, just create it.

 

3. Append the following 2 lines to autostart.sh:

#!/bin/sh

(sleep 10; /sbin/ntpd -p pool.ntp.org; )&


The URL pool.ntp.org points to a global pool of time servers.  You can also address a continent-specific or country-specific pool of time servers.  See http://www.pool.ntp.org/zone/@ for details.


Do not use the -q command line option of `ntpd` or the daemon will execute once on OpenELEC startup and then quit (unless, of course, that is what you want). 


The sleep parameter of 10 seconds is a delay to allow networking to be established before trying to fetch network time.


4. Save and exit the editor.  If in doubt of your editing, cancel (E.g. `vi` :q!), exit, and go back to step 2.

 

5. Make sure that autostart.sh is executable:

chmod +x /storage/.config/autostart.sh

 

6. Test:

sh /storage/.config/autostart.sh

sleep 10; date

echo 'How does the time display look in the command line?'

 

7. When okay to do so, execute:

reboot

 

How does the time display look now on the GUI?

 

Afterthought: I would have thought that the contents of /storage/.config would have been under /etc where they usually are in Unix and Linux.  Also, an autostartup.sh would have been /etc/rc.local (Debian-sh) or some other "rc" mechanism.  Maybe the OpenELEC folks are trying to remind us that this distribution is different.  No worries.

A couple of months ago, while visiting the element14 community blog, I chanced upon the “Tis the Season for Inventing” contest announcement. The challenge was to submit innovative ideas using either the Arduino, Raspberry-Pi or BeagleBone Black platforms.

Element 14 Package

I had just wrapped up my desktop CNC ShapeOko build and set it up at the Makers’ Asylum garage. This build used the Raspberry-Pi as the control computer for the CNC. It was hooked to the network via WiFi, and we could SSH in to it remotely from other computers. This made life easier as it meant we didn’t have to have a computer kept in close proximity of the CNC and muck it up with dust from the mill. On top of the Raspberry-Pi sat the AlaMode Arduino clone, that I had helped design along with my buddies at WyoLum. The ShapeOko itself was paid for by WyoLum. Since the build used both – a Raspberry-Pi and an Arduino Clone, I could have entered it in either category. I settled for the Raspberry-Pi category, since most existing CNC controllers already used an Arduino hooked up to an external Computer.

I pretty much forgot about this once I submitted my idea. So it was with great surprise (and a fair amount of dis-belief ) that I read the mail from element14 informing me that I’d won the first prize ! Woot ! Me and my friends at WyoLum decided to gift the Shopping Spree prize to the Makers’ Asylum to help kit up our makerspace with useful items.

I ordered out a bunch of stuff via the local retailer of element14 – CrazyPi – and cool hawtness just landed on my desk a few days later. $1000 worth of goodies for  Makers to use at the Asylum. Let’s get Makin’ !

Here’s some pictures of what’s in the Box :

  • An 11″ HDMI display
  • Four Raspberry-Pi’s
  • Two BeagleBone Black’s
  • One Intel Edison
  • Eight Arduino UNO’s
  • One Arduino Mega
  • A Robot Kit
  • Some Power adapters, cables and breakout boards and odds and ends.

DSCN0759-1024x768.jpg?resize=1024%2C768?w=660

 

DSCN0757-1024x768.jpg?resize=1024%2C768?w=660

But that's not the end of it. A few days after we received the goddies, came news about the new Raspberry Pi 2 Model B. It seems we missed getting those for the Makers Asylum ! Drat


But Providence shined on us again. The Community Lead at Element14 got in touch with me and asked if I would like to receive a Raspberry Pi 2 Model B. whoa! That just made my day. Once again, I sent in my address, and pretty much forgot about it. Many weeks later, the package landed on my desk exactly on April 1st, 2015. This is what arrived on my desk today.

DSCN0921

Opening it up, and out popped a delicious Pi ! As with the earlier prize, this one too goes to the Makers’ Asylum.

DSCN0930

The discerning viewer will instantly recognize the all new, yummy, Raspberry Pi 2 Model B 1GB.

  • 6X Faster
  • Broadcom BCM2836 ARMv7 Quad Core Processor powered Single Board Computer running at 900MHz
  • 1GB RAM so you can now run bigger and more powerful applications
  • Identical board layout and footprint as the Model B+, so all cases and 3rd party add-on boards designed for the Model B+ will be fully compatible.
  • Fully HAT compatible
  • 40pin extended GPIO to enhance your “real world” projects
  • 10/100 Ethernet Port to quickly connect the Raspberry Pi to the Internet

We plan to use it to build some kick ass project. One of the projects we are working on at the Makers Asylum is a DIY Book Scanner. The Raspberry-Pi 2 coupled to the Ras Pi Cam looks like an ideal solution instead of using an expensive Camera.

Here’s a closer look at the board itself :

 

 

For a look at the improvements compared to the previous models, check out “Specifications” on this Wikipedia page. Besides this, the provision of four mounting holes is a nice improvement, as is the use of a micro SD card. If you’d like to play around with this delicious board, or any of the other interesting stuff we have at the Asylum, do get in touch with us.




 

Jeffery Moss

I am a New Member

Posted by Jeffery Moss Mar 30, 2015

Interested in several applications; integrate the system into my home security system; Inside and Outside cameras; Color and Night UV. Connect to Smart Phones... Application to Locate and Price Items in stores such as; Walmart, Home Depot, Lowes, Sears, Albertsons, Sam's Club, Cosco... and Many more applications... Just starting and don't know where to begin... I worked in a Chemical Laboratory for 44 years and I am now retired and on disability, due to spinal surgery, still have sciatica pain and Restless Leg Syndrome

Sorry if this is a dumb question but I am trying to find the schematics for the Pi 2?

 

Are they available?

 

Ta

Rod

couchie

Concept layout...

Posted by couchie Mar 29, 2015

Ok, so I've attempted to do a layout/flowchart of the project I'm working on. I've printed it in PDF format hoping to make it more visible.

 

I don't know if this clears up my though process or not, but...

 

I'm thinking, use the Arduino to scan the RFID, pass the data to the RPi which will then transmit the data to the SQL DB on a centralized server. The server sends back which team the player is on to  the RPi. The RPi then tells the Arduino which color to illuminate the LED's at the room's door. The player's can join different teams in each game, therefore the centralized DB will keep track of all that.

 

Make sense? And am I overthinking/working this? Do I need to use both the Arduino AND RPi or can this be accomplished with just one of these devices.... and if so, which one?

How amazing the things you can do with RPi2!

 

 

EDIT: Sorry I forgot to say the video was made by the guys of Possibly Unsafe

pi2.jpg

 

In this blog post, I’m going to use a new Raspberry Pi 2 with Node.JS with Sock.JS and Angular.JS to create a chat page. We’ll start from the basics with a simple “Hello World” web page and slowly build upon that to create a powerful chat page.

 

Installing Node.JS

The package of Node.JS that you will get if you run “apt-get install nodejs” is fairly out of date. So, in order to get something more recent, I built the latest from source.  In order to do that, navigate over to:

 

http://nodejs.org/dist/latest/

 

That will have the latest version of Node.JS.  What you are really looking for is the latest version number.  In my case it is v0.12.0.  Once you have that, you can download the source code by doing:

Once that is downloaded, unzip it and build it with the following commands:

After that is complete, we can test and make sure that Node.js is installed and working by having it print out the version number:

 

node –version

 

That should return 0.12.0.

NodeVersion.png

Hello World – Node.JS Style

Now that we have all of the necessary software, let’s start out with the simplest Node.JS program:

The first line loads the module that lets us create an HTTP server.  The second line defines the port that we are going to be listening on.  In this case we are setting it to 1337.

 

The next line creates the HTTP server.  The function that we pass into the createServer method will be called every time someone navigates to our HTTP server.  In this case, all we want to do is to write back a simple response.  The simple response comes in two parts: the header and the body.  In the header we specify two things: a status code (200) and a content-type (text/plain). The status code of 200 means that everything went well.  The content type just tells the client that we are sending over plain text.  For the body of the response, we are just going to give it the string “Hello World\n”. (In case you were wandering, the “\n” is just a code for a new line – much like hitting enter.)

 

With the last line of the program, we start up the HTTP server and have it listen on the port that we already set up.

 

Now to test the program, copy the code into a text file called helloWorld.js and run it by doing:

 

node helloWorld.js

 

This should be pretty uneventful.  It should start up the program, but it will appear as though nothing is happening:

CommandLine.png

In order to see the real excitement, open up a browser and point it to:

 

127.0.0.1:1337

 

The 127.0.0.1 is an IP address.  It happens to be a special one that points to the computer that you are currently using. The 1337 is the port that we typed into the program earlier.  When you navigate there, you should see something like this:

HelloWorld.png

As a side note, you can also view it from another computer.  Just change the IP address to point to the IP address of your Raspberry Pi:

HelloWorld2.png

Hello World – Web Page

Now we weren't really sending back a web page in the previous example.  We were just sending back a phrase and the browser was kind enough to show it to us.  If you view the source for the web page (in chrome – right click and select ‘View page source’), you’ll see that there really isn’t much there:

ViewSource.png

So, now let’s upgrade this so that it returns a real web page, and not just some text.

 

To help turn this into a website, we need to install a Node.JS package called Express.JS.  To do this, just execute the following command:

 

npm install express

 

Once Express.JS is installed, create a file called helloWebsite.js and put the following code in there:

This code is fairly similar to the first version.  We are still importing and using the HTTP module on the first line.  With the second line, we import the Express.JS module. On the third line, we create a new express application, and then set how it responds with lines 4 - 6.  So, when the user asks for our base page (‘/’) we will respond with the ‘helloWebsite.html’ file.

 

The last two lines just define the port that we are going to run on and starts up the http server.

 

Finally, we need to create the helloWebsite.html file that we are going to return:

This creates a fairly simple web page that just displays “Hello Website” to the user.  Here’s what the website looks like now:

HelloWebsite.png

And if we view the source again, we’ll see that this time it is the same information that we put in helloWebsite.html

HelloWebsiteSource.png

Sock.JS + Angular.JS

Now, let’s step it up one more notch.  Let’s get the hello message from a WebSocket.  To do this, we need to install the Sock.JS module:

 

npm install sockjs

 

Once that completes, create a file called helloWebsocket.js and put the following code in there:

Hopefully by now the code is starting to look familiar.  The first three lines just import some modules that we are going to use.  The next block of code sets up the Express.JS application.  This is very similar to the previous example, except this time we add an additional file (client.js).  This is the code that is going to run on the client’s machine to receive the message that we send.

 

The next block of code sets up the WebSocket using Sock.JS.  The first line creates a new WebSocket server.  The next three lines define what happens when a new connection is established. In this case, all we do is respond back with the text “Hello WebSockets!”.

 

The last block of code sets up the HTTP server with the Express.JS application and the Sock.JS WebSocket server.  Most of this is the same as the last time.  Now we just make sure to install the WebSocket server handler.  Here we set it up to response to the ‘/message’ relative path, so the full location would be ‘http://192.168.1.8:1337/message’.

 

Next we’ll create the webpage that will display the message to the user.  Copy and paste this into a file called hello.html:

At first glance, this website looks very similar to the one before.  It’s got basically the same structure, but this time we include some javascript code with the <script> tag.  This is very similar to the “require” statements that we saw before on the server.  It is a way to reference javascript libraries.

 

The next thing that jumps out is the {{message}} part in the body of the webpage.  This is Angular.JS’s way of saying: put whatever is in the message variable here.  So, now we aren’t hard coding the message that will be displayed to the user.  We are going to get that from the server over a WebSocket connection.

 

The last differences are a little more subtle.  There are two new attributes: ng-app and ng-controller.  These tell Angular.JS where to find the code that is associated with this web page.  Angular.JS is built for large websites with lots of javascript, so these help organize and isolate the code that backs the website.

 

Finally, we’ll write the code that is going to be executed on the client’s machine.  Copy and paste this into a file called client.js:

This code starts out with the Angular.JS attributes that we just saw in the web page.  The first line creates an Angular.JS application called myApp. The empty square brackets near the end of the line indicate that this application doesn’t have any dependencies. (Another way that Angular.JS helps manage the large amounts of code that back modern websites.)

 

The next line defines a controller.  A controller contains the interaction for a piece of a website.  The next line tells specifies what variables we want passed to us. In this case, we want the $scope variable which contains information about the current scope within the controller.

 

The next line defines a function that contains the logic for our controller and takes as an input the $scope variable that we said that we wanted earlier.  (It might seem like we are repeating ourselves here a bit, and well we are.  However, this is for good reason.  Most websites use minification for their javascript code.  When this happens, all of the variable names are changed to single letters, so our $scope function parameter will be renamed.  When this happens, Angular.JS will have no way of knowing what we want.  Since strings do not get minified, ‘$scope’ will not change.  This is what Angular.JS will use to figure out what variable you want to get passed in.)

 

Inside our controller logic function, the first thing that we do is create a WebSocket connection to the server.  We pass it in the full address of the WebSocket server.  Then we define what should happen when a new message is received. In this case we want to update the message variable (within the current $scope) to the data that is sent from the server.  The $scope.$apply function tells Angular.JS that one of the variables that it is concerned with is changing and that it should update the web page accordingly.

 

Here is what the web page looks like now:

HelloWebsocket.png

Chat

Now that we have played with all of the important pieces and gotten a feel for how they work, let’s leverage their power to create a chat web page.  It will be a simple page that just broadcasts all of the messages that are posted to all of the people participating in the conversation.

 

Let’s start with the server code; copy and paste this into a file called chatServer.js:

The vast majority of the code should look very familiar from the previous examples.  The only part that is new and different is the code that is related to the WebSocket.  The first addition is a method called broadcast that sends a given message to all of the clients that are currently connected.  The code for this method should be fairly self-explanatory.

 

Handling the WebSocket connections is also fairly straight forward.  When a new person connects, we add them to the clients object.  When a new messages is sent, we broadcast that message to all currently connected clients.  Finally, when a person leaves (closes the connection), we delete them from the clients object.

 

Next let’s look at the HTML code; copy and paste this into a file called client.html:

Ok, so the <head> part of the page just includes a bunch of libraries that we are going to be using.  The new one is ng-dialog.  We are going to use this to pop a dialog box up to the user when they first navigate to the page in order to get their user name.  The page is going to look like this:

dialog.png

Looking at the <body> of the HTML, there are three distinct sections: sending a message, displaying messages, and getting the user name.

 

The first section contains a <form> that is used to get the message that the user would like to send.  The first thing specified is the method that will be called (sendMessage) when the user submits the form.  This allows the user to press enter and submit the current message.  Wiring this up is done by the Angular attribute ng-submit. The first <input> is a text box where the user can type in a message to send.  We use the ng-model attribute to tell Angular what variable to write the text within the text box to, so that we can access it in javascript. The second <input> is a button to click to send the message.  This is the same thing as pressing enter within the text box.  Notice that we call the same method (sendMessage) in both cases.

 

The next section displays the messages that have been received.  Angular has a lot of power in this respect.  We can use the ng-repeat attribute to display everything that is in a list.  In this case, we want to display every message within the messages object.  The “track by $index” part is in case a duplicate message is sent.  By default Angular suppresses duplicates, so this part just forces the duplicates to be displayed.

 

The final section is the dialog that will be displayed to the client in order to get their user name. If you look at the <form> inside, it should look very similar to the previous <form> that got the message to be sent.

 

The last part is the client side javascript; copy and paste this into a file called client.js:

The basic structure of this file should look familiar after the previous examples.  This time, when we receive a new message (sock.onmessage), we first parse the JSON object that is sent to us.  The JSON object will look like this:

So, the object is fairly simple.  In order to go from text to a Javascript object, we use the JSON.parse method. Once it is an object, we can add (push) the content of that message on to the messages object.  If you remember, we saw that the messages object was used in the HTML code to display all of the messages in the web page.

 

The next section deals with getting the username from the client.  A dialog box is created with the template that we specified in the HTML code earlier.  We also create a separate Angular controller just for this dialog box.  The controller is fairly simple in that it just defines the method selectUserName.  When this method is called, it saves off the username that was typed in and it closes the dialog.

 

The last section defines a method called sendMessage that handles sending the message to the server.  First we check to make sure that there really is a message.  (Make sure that the user didn’t click the send button without typing in a message.)  If there is a message, then we package it up into a Javascript object.  This object has the format that we saw earlier when we were parsing the message that we received from the server.  Once we have created this object (msg), we then turn it into a string using JSON.stringify (the opposite of the JSON.parse) and send it over the WebSocket to the server.  Last but not least, we clear the message in the input text box.

 

Here’s a quick video of the chat application in action:

Conclusion

In this blog post, we create a chat web page using Node.JS, Express.JS, Sock.JS and Angular.JS.  We were able to combine these extremely powerful frameworks together to create a chat web page very quickly.  We just brushed the surface of the capabilities of these libraries but hopefully this was a nice easy introduction into what they can offer.