Connecting to a wireless network

Hello.

I am using an official R3 wifi shield and official R3 mega adk. Using Arduino 1.0.3.

I am having issues connecting to a wireless network, in the same sketch that writes to a SD card using the SDfat library.

This is my code to handle connecting to a network. I have tested this code by inserting the code into a slightly modified WifiWebClientRepeating and it works.

void ConnectToNetwork()
{
  String SecurityType = "WPA2";
  //String SSIDNAME = "SmartSocket";
  //String PASS = "goodpassword";
  char ssid[SSIDNAME.length() + 1];
  char pass[PASS.length() + 1]; 
  int index;
  
  SSIDNAME.toCharArray(ssid, SSIDNAME.length() + 1);
  PASS.toCharArray(pass, PASS.length() + 1);
  Serial.println(ssid); 
  Serial.println(pass);
  for ( int i = 0; i < 2; i++ )
  {
    if( status != WL_CONNECTED) 
    {
      // WPA2 
      if ( SecurityType == "WPA2" )
      {
            Serial.println("in here");
            status = WiFi.begin(ssid,pass);
      }
      // if no security
      if ( SecurityType == "None" ) 
      {
        
        status = WiFi.begin(ssid);
      }
      if ( SecurityType == "WEP" )
      {
        status = WiFi.begin(ssid,INDEX.toInt(),pass);
      }   
      delay(10000); //waits 10 seconds for connections
       
    }
  }
  printWifiStatus(); 
}

But placing the function in with the rest of my sketch, which can be found below, I am unable to connect to any type of wireless network.

Any suggestion or recommendations? I am completely stumped. Could there be a conflict with SDFat.h, such a pin assignments and dependencies?

Any suggestion or recommendations?

I suggest that you read the sticky at the top of the forum. Again, if necessary. Your code is not posted correctly.

You might want to take your snippets to http://snippets-r-us.com. I'm sure that they'll be more help that we can be.

The original post was change to be more in line with the sticky.

This is the entirety of my sketch.

#include <WiFi.h>
#include <SPI.h>
#include <String.h>
#include "RTClib.h"
#include <Wire.h>
#include <stdarg.h>
#include <EmonLib.h>
#include "SdFat.h"

DateTime time;
int currentTime;
RTC_DS1307 RTC;

int keyIndex;
int status = WL_IDLE_STATUS;
char server[] = "yoursmartsocket.com";
WiFiClient client;
int securityType; 
String SecurityType; 
String SSIDNAME;
String PASS; 
String INDEX;
String phpSend; 
// Sensor Reading Stuffs 
int voltageMains =1; 
double current ; 
int socketId; 
int deviceID = 1337;
int toggleState = 0; 
EnergyMonitor emon1; 
float currentCalibration = 59.7; 
// Establish output and input pins 
int voltagePin = A0;
int currentPin = A1; 



// file system object
SdFat sd;

// create Serial stream
ArduinoOutStream cout(Serial);

// store error strings in flash to save RAM
#define error(s) sd.errorHalt_P(PSTR(s))

const uint8_t chipSelect = 53;

String toggle; 
void setup() 
{
  Serial.begin(9600);
  pinMode(voltagePin, INPUT);
  pinMode(currentPin, INPUT);
  Serial.println("Test");
  pinMode(53, OUTPUT); 
  emon1.current(1, 59.7); 
  unsigned long start = millis(); 
  while (WiFi.status() == WL_NO_SHIELD )
  {
    if ((millis() - start) > 30000)
    {
      Serial.println("WiFi shield not Present");
      while(true);
    }
    delay(500);
  }
  
  
  cout << pstr("Type any character to start demo \n");
  while (Serial.read() <= 0) {}
  delay(400);  // catch Due reset problem
  if (!sd.begin(chipSelect, SPI_FULL_SPEED)) 
  {
    sd.initErrorHalt();
  }
  
  // Read Network Configuration from SD Card
  
  getConfiguration(); 
  // Demo
   pinMode(led, OUTPUT); 
   current =  emon1.calcIrms(1480); 
}


void loop()
{
  // Read Voltage
  ConnectToNetwork(); 
  voltageMains = 120;
  // Read Current
  current =  emon1.calcIrms(1480);   
  
  Serial.print("Irms is: ");
  Serial.println(current);
  if ( 1 != sendData( current, voltageMains, currentTime, toggleState))
  {

    saveUnSentData( 1 , current, voltageMains, toggleState); 
  }
  else 
  {
    // Connection worked 
    Serial.println("Data is Sent"); 
   // sendLoggedData();
  }
  toggleState = getToggleState(); 
  
  // Toggle the Relay

  Serial.print("Toggle State ");
  Serial.println(toggleState); 

}

// Reads WiFi network configuration from SD card  
void getConfiguration() {
  const int line_buffer_size = 64;
  char buffer[line_buffer_size];
  ifstream sdin("Config.TXT");
  int line_number = 0;
  Serial.println("test");
  while (sdin.getline(buffer, line_buffer_size, '\n')) 
  {
    ++line_number;
   if ( line_number == 1)
   {
   
   SecurityType = buffer; 
   }
      if ( line_number == 2)
   {
   
   SSIDNAME = buffer; 
   }
      if ( line_number == 3)
   {
  
   PASS = buffer; 
   }
   if ( line_number == 4)
   {
  
   INDEX = buffer; 
   }
    

  }
  
}


void ConnectToNetwork()
{
 // String SecurityType = "WPA2";
  //String SSIDNAME = "SmartSocket";
  //String PASS = "goodpassword";
  char ssid[SSIDNAME.length() + 1];
  char pass[PASS.length() + 1]; 
  int index;
  
  SSIDNAME.toCharArray(ssid, SSIDNAME.length() + 1);
  PASS.toCharArray(pass, PASS.length() + 1);
  Serial.println(ssid); 
  Serial.println(pass);
  for ( int i = 0; i < 2; i++ )
  {
    if( status != WL_CONNECTED) 
    {
      // WPA2 
      if ( SecurityType == "WPA2" )
      {
            Serial.println("in here");
            status = WiFi.begin(ssid,pass);
      }
      // if no security
      if ( SecurityType == "None" ) 
      {
        
        status = WiFi.begin(ssid);
      }
      if ( SecurityType == "WEP" )
      {
        status = WiFi.begin(ssid,INDEX.toInt(),pass);
      }   
      delay(10000); //waits 10 seconds for connections
       
    }
  }
  printWifiStatus(); 
}

// This function will send the PHP request 
int sendData(int currentScaled, int voltageScaled, int Time, int toggleState) 
{
      String phpStart = "PUT /SmartSocket/arduino_readings?id=";
        phpSend = phpStart; 
	//Make connection with server
        if (client.connect(server, 80)) 
        {
        Serial.println("connected to server to send data");
        char c[4];
        dtostrf(current, 4, 2, c);
        
        // Send readings to server  
        client.println(phpSend + deviceID + "&I=" + c +  "&V=" + (String)voltageScaled +  "&time=" + "2013071318" + (String)random(0, 59) + (String)random(0, 59) + "&state=" + (String)toggleState);
        client.println(F("Host: www.yoursmartsocket.com"));
        client.println(F("Connection: close"));
        
        client.println();


        } 
        Serial.println("Unable to make connection");
        client.flush(); 
        client.stop(); 
}

// This function will send all the logged data to the server
// Then clear the data once it is all sent. 
// While data is on card 
	// Read Data from card
	// Send Data to server 
// Once done overwrite file to clear it

// Check if data is logged on SD CARD 
// Send all logged data to server
// clear file once all data is sent
void sendLoggedData()
{
  char * p;
  char * str;
  int i = 0;  
  int time;
  double current;
  int voltage;
  int togglestate;
  const int line_buffer_size = 64;
  char buffer[line_buffer_size];
  ifstream sdin("Unsent.csv");
 // sendData(int currentScaled, int voltageScaled, int Time, int toggleState)
  while (sdin.getline(buffer, line_buffer_size, '\n')) 
  {
    p = buffer; 
    
    while ( (str = strtok_r(p, ";", &p)) != NULL ) 
    {
      if ( i == 0 ) // str is time
      {
     
        time = atoi(str); 
        //Serial.print(str);
      }
      else if ( i == 1 ) // str is current 
      {
        current = atoi(str); 
      //  Serial.print(str);
      }
      else if ( i == 2 ) // str is voltage
      {
        voltage = atoi(str); // voltage is faked see report
    //    Serial.println(str);
      }
      else if ( i == 3 ) // str is togglestate
      {
        togglestate = atoi(str);
  //      Serial.println(str); 
      }
      i++; 
    }
    i = 0;
   // sendData( current, voltage, time, togglestate); 
  }
  // Deletes file then creates a new empty verision
  SdFile myFile;
  myFile.open("Unsent.csv", O_RDWR | O_CREAT | O_AT_END);
  myFile.remove(); 
  myFile.open("Unsent.csv", O_RDWR | O_CREAT | O_AT_END);
  myFile.close();
}

// This logs data that could not be sent to the server
// Appends to a files 
void saveUnSentData(int time, double current, int voltage, int togglestate)
{
// Stores Data to SD card 
  Serial.println("starting"); 
  char name[] = "Unsent.csv"; 
  if (!sd.begin(chipSelect, SPI_FULL_SPEED)) 
  {
    sd.initErrorHalt();
  }

  ofstream sdout(name, ios::out | ios::app);
  if (!sdout)
  {
    error("open failed");
  }
   sdout << time << ";" << current << ";" << voltage << ";" << togglestate <<endl; 
  sdout.close();
  if (!sdout)
  {
    error("append data failed");
  }
  Serial.println("done");
}

// Gets the toggle state from the server
// Sends a http get request to the server
int getToggleState()
{
  String phpToggleStart = "GET /SmartSocket/arduino_state?id="; 
  client.stop();
  // 1 = on 2 = USE scheduler  0 = OFF 
   phpSend = phpToggleStart; 
  if (client.connect(server, 80) || status == WL_CONNECTED ) // CHange back to &&
  {
       
        Serial.println("connected to server to get toggle state");
  
        client.println("GET /SmartSocket/arduino_state?id=1337");
        client.println("Host:www.yoursmartsocket.com");
        client.println("Connection: close");
        client.println();
   delay(50); 
      int count = 0;
      char c; 
      while(client.connected() && !client.available() && count < 10000 ) 
      {
        delay(1); 
        count++; 
      }
      if (client.connected() || client.available())
      { //connected or data available
        c = client.read(); //gets byte from wifi buffer
        Serial.println(c); //prints byte to serial monitor 
      }
      client.flush(); 
      client.stop(); 
      return (int(c));   
  }
  return 0; 
}   


// Only for debuging 
void printWifiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);
}

// Saves data to a csv file and appends to the end
void LogData(int time, double current, int voltage)
{
    SdFile myFile;
  myFile.open("datalog.csv", O_RDWR | O_CREAT | O_AT_END);
  myFile.close(); 
  char name[12] = "dataLog.csv"; 
  if (!sd.begin(10, SPI_FULL_SPEED)) 
  {
    sd.initErrorHalt();
  }

  ofstream sdout(name, ios::out | ios::app);
  if (!sdout)
  {
    error("open failed");
  }
   sdout << time << "," << current << "," << voltage << endl; 
  sdout.close();
  if (!sdout)
  {
    error("append data failed");
  }
  Serial.println("done");
}

Serial.println("test");

Why? Perhaps you should print something useful, like what you read from the file.

Perhaps you could show your serial output.

Perhaps you could consider using Tools + Auto Format, to fix the horrid indenting in your sketch.

      String phpStart = "PUT /SmartSocket/arduino_readings?id=";

Perhaps you could consider spelling GET correctly. This looks like a GET request.