Forum >Connecting Arduino to Iphone with WiFi
ArduinoGeneral

Connecting Arduino to Iphone with WiFi

userHead Jonczu 2011-06-20 22:07:44 11094 Views7 Replies
Hi

I have connected to iphone to the arduino and am sending info which looks like this in the serial monitor

11111013 (on)

11110210213 (off)

The sketch I am running is:



int incomingByte = 0;


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


}

void loop() {
if (Serial1.available()>0) {
incomingByte = Serial1.read();

Serial.print(incomingByte);
}
}

What I need to do is be able to switch an led on and off with these two commands (I have only started to learn how to program and don't know all the different functions of the arduino environment).

Thanks any help would be appreciated
Jon Czudek
2012-12-14 13:58:58 Hi Jonczu,

Thanks for the code. I'm trying to do the same.

As I read some tutorials and other posts I understood how to connect to a router using putty, but it didn't work to connect to my iphone... could you please describe how have you done it ??

And what about the objectiveC code; how could you send the UDP pack packets ??? i haven't found on the web...

It would help me a lot !!!

Thank you !!
userHeadPic emerson_afs
2011-07-14 00:42:47 Hi

I have managed to get the iphone controlled LEDs working.

iphone settings:
I am sending chars from the 'Mote' app (eg 'r' which is on red and 'R' which is of red). This is all through tcp/ip.

wifi sheild settings:
[url=https://www.dfrobot.com/community/index.php/2011/07/tutorial-dfrobot-wifi-shield-sku-tel0019/\]
https://www.dfrobot.com/community/index.php/2011/07/tutorial-dfrobot-wifi-shield-sku-tel0019/
[/url]

arduino code:

#define LEDGREEN 12
#define LEDRED 11
#define LEDYELLOW 10

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

  pinMode(LEDRED,OUTPUT);
  pinMode(LEDGREEN,OUTPUT);
  pinMode(LEDYELLOW,OUTPUT);
     

}

void loop() {
if (Serial.available()>0) {
  byte inByte = Serial.read();
 
 
 
  switch(inByte){
    case 'r':
    digitalWrite(LEDRED,HIGH);
    break;
   
    case 'R':
    digitalWrite(LEDRED,LOW);
    break;
   
    case 'g':
    digitalWrite(LEDGREEN,HIGH);
    break;
   
    case 'G':
    digitalWrite(LEDGREEN,LOW);
    break;
   
      case 'y':
    digitalWrite(LEDYELLOW,HIGH);
    break;
   
    case 'Y':
    digitalWrite(LEDYELLOW,LOW);
    break;
  }
}
}
   
The solution to my problem was simple (can't believe I didn't think of it earlier upper and lower case)  just send single chars which eliminates the need to store the incoming data and then pry the on and off strings out. This is very simple and probably won't be very useful in complex situations :-\.

For anyone out there with problems that they are having the arduino forum is also a great place to get advice.

Thanks
Jon Czudek


P.S. Sorry for the late reply as I haven't had the time to sit down and reply :).


userHeadPic Jonczu
2011-07-10 03:43:08 Hi

I am trying to do the same sort of thing as you but I have started by using a Mac sketch written in "Processing", which is very similar to the Arduino, to send UDP packets to the Arduino with the DFRobot Ethernet Shield which will then turn LEDs on and off and reply (using UDP) back to the Mac.

So far it all works fine but I then bought a WiFi shield from DFRobot and found that it is SOOOOO different to the Ethernet shield. Then I started hunting forums to find out why - and I still have no idea.

I have only been writing in C++ and the Arduino for about a month so I am no expert by a very long way.

Looking at your code I think your case statement fails because the char data type if inByte is only a byte in size and you are looking at strings not chars.

Here is all my code - it's a bit long !!

//This sketch receives UDP message strings, prints them to the 4x16 LDC Screen
//and sends an acknowledge string back to the sender
//it also updates the leds on 2 x daisy chained 74HC595 (serial to paralel chip with tristate & latch)

#include <LiquidCrystal.h>
#include <Ethernet.h>
#include <Udp.h>                                // UDP library from: [email protected] 12/30/2008
#include <SPI.h>

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);            // DFROBOT LCD Pin Assignment
int latchPin = 17;                              //Pin connected to ST_CP of 74HC595
int clockPin = 18;                              //Pin connected to SH_CP of 74HC595
int dataPin = 16;                                //Pin connected to DS of 74HC595
byte Hundreds;                                  //used to extract Hundreds from a byte
byte Tens;                                      //used to extract Tens from a byte
byte Units;                                      //used to extract Units from a byte
byte dataLO;                                    //Low order byte containing bits
byte dataHI;                                    //High order byte containing bits
byte dataWorkLO;                                //used to calculate bit position to set in LO Byte
byte dataWorkHI;                                //used to calculate bit position to set in HI Byte
byte mac[] = { 0x90, 0xA2, 0xDA, 0x00, 0x33, 0xAB }; // MAC address of shield but Im not sure why
byte ip[] = { 192,168,2,177 };                  // IP address of shield
unsigned int localPort = 8888;                  // local port to listen on
                                                // next variables set when a packet is received
byte remoteIp[4];                                // holds received packet's originating IP
unsigned int remotePort;                        // holds received packet's originating port
                                                // buffers for receiving and sending data
char packetBuffer[UDP_TX_PACKET_MAX_SIZE];      //buffer to hold incoming packet,
char  ReplyBuffer[] = "UDP - Ack";              //Reply string in an array of that length **

void setup() {
  pinMode(latchPin, OUTPUT);                    //set latch pin to output
  Ethernet.begin(mac,ip);                      // start Ethernet
  Udp.begin(localPort);                        // start UDP
  Serial.begin(9600);                          // start Serial
  lcd.begin(16, 4);                            // start LCD
  lcd.setCursor(0,0);                          // set cursor to pos 1 line 1
  lcd.print("UDP Demo Program");                // print a simple message
  lcd.setCursor(0,1);                          // This is all printed on a 4 line x 16ch LCD
  lcd.print("90-A2-DA-00-33-AB");
  lcd.setCursor(-4,2);
  lcd.print("192.168.2.177");
  lcd.setCursor(-4,3);
  lcd.print("UDP Port 8888");
  delay(5000);
  lcd.clear();
  lcd.setCursor(0,1);
  lcd.print("Waiting for UDP");
  lcd.setCursor(1,2);
  lcd.print("Packet");
  dataLO = 0;
  dataHI = 0; 
}

void loop() {
  int packetSize = Udp.available();            // note that this includes the UDP header
  if(packetSize)                                // if there's data available, read a packet
  {
    packetSize = packetSize - 8;                // subtract the 8 byte header
    lcd.clear();                                // clears LDC and moves Cursor to Pos 1 line 1
    lcd.print("Packet Size:");
    lcd.print(packetSize);                      //Number of bytes in the UDP Packet
                                                // read packet into packetBufffer - senders IP and port no
    Udp.readPacket(packetBuffer,UDP_TX_PACKET_MAX_SIZE, remoteIp, remotePort);
    lcd.setCursor(0,1);                        // move Cursor to Pos 1 line 2
//    lcd.print("Data:");
    lcd.print(packetBuffer);
    lcd.setCursor(-4,2);                        //move Cursor to Pos 1 line 3
    lcd.print(remoteIp[0],DEC);                  //IP address byte displayed as decimal
    lcd.print('.');
    lcd.print(remoteIp[1],DEC);                  //IP address byte displayed as decimal
    lcd.print('.');
    lcd.print(remoteIp[2],DEC);                  //IP address byte displayed as decimal
    lcd.print('.');
    lcd.print(remoteIp[3],DEC);                  //IP address byte displayed as decimal
    lcd.setCursor(-4,3);                        //move Cursor to Pos 1 line 4
    lcd.print("Remote Port:");
    lcd.print(remotePort,DEC);                  //Remote Port byte displayed as decimal
// Start filling the dataHi or dataLO acording to the packetBuffer contents dataHI & dataLO

      if (packetBuffer[0] == 'H' || packetBuffer[0] == 'L') {  //UDP Data Packet starts with H or L then 1-8 then 1 or 0
          if (packetBuffer[0] == 'H') {
            dataWorkHI = (1<<packetBuffer[1]-49); //Takes the 2nd Char and raises 2 to the power of 2nd
            dataWorkLO = 0;     
          }
          else {
            dataWorkLO = (1<<packetBuffer[1]-49); //Takes the 2nd Char and raises 2 to the power of 2nd
            dataWorkHI = 0;
          }
          if( packetBuffer[2] == '1') {          //turn on pin with a bitwise OR
            dataHI = dataHI | dataWorkHI;
            dataLO = dataLO | dataWorkLO;
          }
          else {                                //turn off a pin Bitwise & to test for already on and the bitwise xor
            dataHI = (dataHI & dataWorkHI) ^ dataWorkHI;
            dataLO = (dataLO & dataWorkLO) ^ dataWorkLO;
          }
    }
    if (packetBuffer[0] == 'A') {                //UDP Date Packet starts with AL then 1 or 0
        if( packetBuffer[2] == '1') {            //turn on all pins
        dataHI = 255;
        dataLO = 255;
        }
        else {                                  //Turn off all pins
        dataHI = 0;
        dataLO = 0;
      }       
    }
    if (packetBuffer[0] =='H' || packetBuffer[0] == 'L' || packetBuffer[0] == 'A') {
    if (packetSize = 3) {
      ReplyBuffer[0] = packetBuffer[0];          //Fill the ReplyBuffer with the sent data + Ack
      ReplyBuffer[1] = packetBuffer[1];
      ReplyBuffer[2] = packetBuffer[2];
      ReplyBuffer[3] = ' ';
      ReplyBuffer[4] = '-';
      ReplyBuffer[5] = ' ';
      ReplyBuffer[6] = 'A';
      ReplyBuffer[7] = 'c';         
      ReplyBuffer[8] = 'k';
    }
    else {
      ReplyBuffer[0] = 'B';                      //Short data received so bad reply sent back
      ReplyBuffer[1] = 'A';
      ReplyBuffer[2] = 'D';   
      ReplyBuffer[3] = ' ';
      ReplyBuffer[4] = '-';
      ReplyBuffer[5] = ' ';
      ReplyBuffer[6] = 'U';
      ReplyBuffer[7] = 'D';   
      ReplyBuffer[8] = 'P';
    }
    }
    if (packetBuffer[0] == 'S') {                //Pin Status sent back to sender STA
      Hundreds = 0;
      Tens = 0;
      Units = 0;
      if (dataHI > 99) {
        Hundreds = (dataHI/100);
      }
      if (dataHI-(Hundreds * 100) > 9) {
        Tens = ((dataHI-(Hundreds*100))/10);
      }
      Units = (dataHI-(Hundreds*100)-(Tens*10));
      Hundreds = Hundreds + 48;
      Tens = Tens + 48;
      Units = Units + 48;
      ReplyBuffer[0] = 'H';
      ReplyBuffer[1] = Hundreds;
      ReplyBuffer[2] = Tens;
      ReplyBuffer[3] = Units;
      ReplyBuffer[4] = '-';
      Hundreds = 0;
      Tens = 0;
      Units = 0;
      if (dataLO > 99) {
        Hundreds = (dataLO/100);
      }
      if (dataLO-(Hundreds * 100) > 9) {
        Tens = ((dataLO-(Hundreds*100))/10);
      }
      Units = (dataLO-(Hundreds*100)-(Tens*10));
      Hundreds = Hundreds + 48;
      Tens = Tens + 48;
      Units = Units + 48;   
      ReplyBuffer[5] = 'L';
      ReplyBuffer[6] = Hundreds;         
      ReplyBuffer[7] = Tens; 
      ReplyBuffer[8] = Units;
    }
    remotePort = 6000;                          // forced return port
    remoteIp[0] = 192;                          // forced return IP Address
    remoteIp[1] = 168;                          // forced return IP Address
    remoteIp[2] = 2;                            // forced return IP Address
    remoteIp[3] = 211;                          // forced return IP Address
    Udp.sendPacket( ReplyBuffer, remoteIp, remotePort);
   
// end of filling the dataHI and dataLO
    digitalWrite(latchPin, 0);                  //ground latchPin during transmitting
    shiftOut(dataPin, clockPin, dataHI);        //move Upper byte first
    shiftOut(dataPin, clockPin, dataLO);        //move out lower byte
    digitalWrite(latchPin, 1);                  //return the latch pin high to Latch the data out 

    lcd.setCursor(-4,2);                        //move Cursor to Pos 1 line 3 because my 4 line LCD is a bit odd
    lcd.print("                ");
    lcd.setCursor(-4,2);                        //move Cursor to Pos 1 line 3 because my 4 line LCD is a bit odd
    lcd.print(dataHI,BIN);                      //HI Byte as bits
    lcd.setCursor(-4,3);                        //move Cursor to Pos 1 line 4 because my 4 line LCD is a bit odd
    lcd.print("                ");
    lcd.setCursor(-4,3);
    lcd.print(dataLO,BIN);                      //LO Byte as bits
  }
  delay(10);
}
// This function shifts 8 bits out MSB first, on the rising edge of the clock, clock idles low
void shiftOut(int myDataPin, int myClockPin, byte myDataOut) {
  int i=0;                                      //internal function setup
  int pinState;                                //internal function setup
  pinMode(myClockPin, OUTPUT);                  //setup Clock pin as digital output
  pinMode(myDataPin, OUTPUT);                  //setup Data pin as digital output
  digitalWrite(myDataPin, 0);                  //serial data pin low
  digitalWrite(myClockPin, 0);                  //clock pin low
                                                //for each bit in the byte myDataOut in our for loop
  for (i=7; i>=0; i--) {                        //loop 8 times for the 8 bits from 7 to 0
    digitalWrite(myClockPin, 0);                //Set clock pin low
    if ( myDataOut & (1<<i) ) {                //Test the i bit AND - Bit Shift left by "i" places
      pinState= 1;
    }
    else {
      pinState= 0;
    }
    digitalWrite(myDataPin, pinState);          //Sets the pin to HIGH or LOW depending on pinState
    digitalWrite(myClockPin, 1);                //register shifts bits on upstroke of clock pin
    digitalWrite(myDataPin, 0);                //zero the data pin after shift to prevent bleed through
  }
  digitalWrite(myClockPin, 0);                  //stop shifting
}





If you have a full list of your WiFi sketch and how you have set up the WiFi shield that would be good to see and try and understand


userHeadPic Paul
2011-07-01 03:23:13 Hi

Here is another piece of code. With this code I get a an error: ???

IPHONE_WIFI_ARDUINO__experiment.cpp: In function 'void loop()':
IPHONE_WIFI_ARDUINO__experiment:30: error: duplicate case value
IPHONE_WIFI_ARDUINO__experiment:22: error: previously used here
IPHONE_WIFI_ARDUINO__experiment:34: error: duplicate case value
IPHONE_WIFI_ARDUINO__experiment:26: error: previously used here
:
[code]

#define LEDGREEN 12
#define LEDRED 11




void setup() {
  Serial.begin(9600);
  Serial1.begin(9600);
  pinMode(LEDRED,OUTPUT);
  pinMode(LEDGREEN,OUTPUT);
     

}

void loop() {
if (Serial1.available()) {
  char inByte = Serial1.read();
 
  Serial.print(inByte);
 
  switch(inByte){
    case 'redon':
    digitalWrite(LEDRED,HIGH);
    break;
   
    case 'redoff':
    digitalWrite(LEDRED,LOW);
    break;
   
    case 'greenon':
    digitalWrite(LEDGREEN,HIGH);
    break;
   
    case 'greenoff':
    digitalWrite(LEDGREEN,LOW);
    break;
  }
}
}

[/code]

Any help would be appreciated :)
Jon Czudek
userHeadPic Jonczu
2011-07-01 02:16:44 Hi

Running into issues as I am a noob and don't fully understand programming (probably a to big project for me) but if someone puts me on the right track I am sure Ill be able to make it work.

Commands that I receive from my Iphone via the wifi sheild are a string of ascii characters if I use int/String not byte (eg  11111013)
I was wondering on how to compare this to a set value.

I can switch one led on and off but when I try to control multiple leds it seems that arduino sees two different commands as the same (eg redon switches both leds on and greenon switches both leds on same thing for redoff and greenoff ).

Here is my code: 

[code]
#define LEDGREEN 12
#define LEDRED 11

byte inByte='0';
byte ReOn = 'redon'; 
byte ReOff = 'redoff';
byte GrOn = 'greenon';
byte GrOff = 'greenoff';

void setup() {
  Serial.begin(9600);
  Serial1.begin(9600);
  pinMode(LEDRED,OUTPUT);
  pinMode(LEDGREEN,OUTPUT);
     

}

void loop() {
if (Serial1.available()>0) {
  inByte = Serial1.read();
  Serial.print(inByte);
}
if (inByte==ReOn){
  digitalWrite(LEDRED, HIGH);
}
if (inByte==ReOff){
  digitalWrite(LEDRED,LOW);
}
if (inByte==GrOn){
  digitalWrite(LEDGREEN, HIGH);
}
if (inByte==GrOff){
  digitalWrite(LEDGREEN,LOW);
}
}
[/code]


Any help with this would be much appreciated (I'm willing to learn anything I can).

Jon Czudek
userHeadPic Jonczu
2011-06-21 07:22:39 Excellent!  Lots of our customers have problem with wifi shield.

But I think it is because of the lack of tutorial.  If you can post a tutorial about your project, we will be very thankful and probably reward you some voucher.
userHeadPic R2D2C3PO
2011-06-20 23:13:50 Hi

Update: managed to get it working using byte instead of int. :)


#define LED 12

byte incomingByte=0;
byte On = 'on';
byte Off = 'off';

void setup() {
  Serial.begin(9600);
  Serial1.begin(9600);
  pinMode(LED,OUTPUT);
 

}

void loop() {
if (Serial1.available()>0) {
  incomingByte = Serial1.read();
  Serial.print(incomingByte);
}
if (incomingByte==On){
  digitalWrite(LED, HIGH);
}
if (incomingByte==Off){
  digitalWrite(LED,LOW);
}
}


I would rather use the switch and case method but don't know how, I would also like to be dealing with hex or decimal values.  ;D

Thanks
Jon Czudek
userHeadPic Jonczu