Reference   Language | Libraries | Comparison | Changes

MKRNB : NBClient class

read()

Description

Read the next byte received from the server the client is connected to (after the last call to read()).

read() inherits from the Stream utility class.

Syntax

client.read()

Parameters

none

Returns

int - The next byte (or character), or -1 if none is available.

Example

/*
  Web client

 This sketch connects to a website through a MKR NB 1500. Specifically,
 this example downloads the URL "http://arduino.cc/" and prints it
 to the Serial monitor.

 Circuit:
 * MKR NB 1500
 * SIM card with a data plan

 created 8 Mar 2012
 by Tom Igoe

 http://arduino.cc/en/Tutorial/NBExamplesWebClient

 */


// libraries
#include <MKRNB.h>

// PIN Number
#define PINNUMBER ""

// initialize the library instance
NBClient client;
GPRS gprs;
NB nbAccess;

// URL, path & port (for example: arduino.cc)
char server[] = "arduino.cc";
char path[] = "/";
int port = 80; // port 80 is the default for HTTP

void setup()
{
  // initialize serial communications
  Serial.begin(9600);
  Serial.println("Starting Arduino web client.");
  // connection state
  boolean notConnected = true;

  // After starting the modem with NB.begin()
  // attach the module to the GPRS network with the APN, login and password
  while(notConnected)
  {
     if((nbAccess.begin(PINNUMBER)==NB_READY) &&
       (gprs.attachGPRS()==GPRS_READY))
     notConnected = false;
    else
    {
      Serial.println("Not connected");
      delay(1000);
    }
  }

  Serial.println("connecting...");

  // if you get a connection, report back via serial:
  if (client.connect(server, port))
  {
    Serial.println("connected");
    // Make a HTTP request:
    client.print("GET ");
    client.print(path);
    client.println(" HTTP/1.0");
    client.println();
  }
  else
  {
    // if you didn't get a connection to the server:
    Serial.println("connection failed");
  }
}

void loop()
{
  // if there are incoming bytes available
  // from the server, read them and print them:
  if (client.available())
  {
    char c = client.read();
    Serial.print(c);
  }

  // if the server's disconnected, stop the client:
  if (!client.available() && !client.connected())
  {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();

    // do nothing forevermore:
    for(;;)
      ;
  }
}

See Also

Reference Home

Corrections, suggestions, and new documentation should be posted to the Forum.

The text of the Arduino reference is licensed under a Creative Commons Attribution-ShareAlike 3.0 License. Code samples in the reference are released into the public domain.