Pages: [1]   Go Down
Author Topic: Please modify this code  (Read 799 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Newbie
*
Karma: 0
Posts: 6
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Hi,

Could someone modify below code to get 2 values from a text-field and split them into two(using indexOf to find where the comma is) and assign them into 2 variables and convert the values of 2 variables into int.

assume my string will look something like "145,384".

I want to split it like
int 145
int 384


a function that will take the string and convert it to an INT.

Code:
// Function to convert a string into an int
// Accepts a string variable (not CHAR!)
// Returns an INT
int ConvertStringToInt(string convertString){
    char convert_buffer[convertString.length() + 1];
    convertString.toCharArray(convert_buffer, sizeof(convert_buffer));
    int convert_integer_data = atoi(convert_buffer);
    return convert_integer_data;
}


Code:

Code:
#include <SPI.h>
#include <Ethernet.h>

byte mac[] = {
  0x5c, 0x26, 0x0a, 0x78, 0x12, 0x85 };  // mac
byte ip[]  = {
  192, 168, 20 , 2 };                  // ip in lan
byte gateway[] = {
  192, 168, 20, 1 };               // internet access via router (Gateway)
byte subnet[]  = {
  255, 255, 255, 0 };        // subnet mask

EthernetServer server(80);      // server port

String readString, servo1, servo2;

int lux_v1;
int lux_v2;


void setup(){

  //start Ethernet
  Ethernet.begin(mac, ip, gateway, subnet);
  server.begin();

  //enable serial data print
  Serial.begin(9600);
  int lux_v1.attach(7);
  int lux_v2.attach(6);
  Serial.println("initialize..."); // so I can keep track of what is loaded
}

void loop(){
  // Create a client connection
  EthernetClient client = server.available();
  if (client) {
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();

        //read char by char HTTP request
        if (readString.length() < 100) {

          //store characters to string
          readString += c;
        }

        //if HTTP request has ended
        if (c == '\n') {

          ///////////////
          Serial.println(readString);

          if (readString.length() >0) {
            Serial.println(readString);

            int lux_v1 = readString.substring(7, 11);
            int lux_v1 = readString.substring(12, 16);

            Serial.println(lux_v1);
            Serial.println(lux_v2);

            int n1;
            int n2;

            char carray1[6];
            lux_v1.toCharArray(carray1, sizeof(carray1));
            n1 = atoi(carray1);

            char carray2[6];
            lux_v2.toCharArray(carray2, sizeof(carray2));
            n2 = atoi(carray2);

            readString="";
          }

          //now output HTML data header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println();

          client.print("<html><head>");
          client.print("<title></title>");
          client.println("</head>");
          client.print("<body>");

          client.print("<form method=get>LUX:<input type=text size=3 name=L value=");
          client.print(">&nbsp;<input name=H type=submit value=submit></form>");

          client.print("<body>");
          client.println("</html>");

          break;
        }
      }
    }
    //clearing string for next read
    readString="";
    client.stop();
    Serial.println("client stoped");
  }
}

I hope someone will help me on this. Pls I really appreciate your kind help.

Regards,
Udesh
Logged

Seattle, WA USA
Offline Offline
Brattain Member
*****
Karma: 615
Posts: 49388
Seattle, WA USA
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Quote
a function that will take the string and convert it to an INT.
But, you don't have a string. You have a String. Completely different beasts.

Otherwise, that function is overly complex for dealing with a String, since String has a toInt() method.
Logged

nr Bundaberg, Australia
Offline Offline
Tesla Member
***
Karma: 129
Posts: 8530
Scattered showers my arse -- Noah, 2348BC.
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

If the string is always three chars, comma, three chars you can do this

Code:
char x[] = "123,456";

x[3] = '\0';  // split string into two separate strings

int y = atoi (x);      // convert first number
int z = atoi (&x[4]); // convert second number

______
Rob
Logged

Rob Gray aka the GRAYnomad www.robgray.com

Offline Offline
Full Member
***
Karma: 2
Posts: 219
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Code:
String s = "123,456";               // string
int i = s.indexOf(",");
int l = s.length();
int a = int(s.substring (0,i-1));  //result in a
int b = int(s.substring (i+1,l));  //result in b

ps check for typos, as i didnt  
Sorry lazy.. but maybe you where too ?
Or maybe not, your new to coding, well then i gave a sample.
Logged

Seattle, WA USA
Offline Offline
Brattain Member
*****
Karma: 615
Posts: 49388
Seattle, WA USA
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Quote
ps check for typos, as i didnt 
Also perform some error checking. Given the initialization of s, i will have a valid value. Given your data, i may not.

Given the initialization of s, l will have a valid value. Given your data, l may be 0.

Creating substrings using invalid indices is rarley a good idea.
Logged

Offline Offline
Newbie
*
Karma: 0
Posts: 6
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Code:
String s = "123,456";               // string
int i = s.indexOf(",");
int l = s.length();
int a = int(s.substring (0,i-1));  //result in a
int b = int(s.substring (i+1,l));  //result in b

ps check for typos, as i didnt 
Sorry lazy.. but maybe you where too ?
Or maybe not, your new to coding, well then i gave a sample.


Quote
ps check for typos, as i didnt 
Also perform some error checking. Given the initialization of s, i will have a valid value. Given your data, i may not.

Given the initialization of s, l will have a valid value. Given your data, l may be 0.

Creating substrings using invalid indices is rarley a good idea.

How to get 2 integer values from the text-field and assign it to 2 variables(val1 and val2). Then I don't need to manually change the value in the below code. @PGTBOOS has given how to do it but the string is predefined in the code(String s = "123,456") but I want let user to input the value in the text-field and read that value and assigned it to val1 and val2.

Like this:

Code:

Code:
    if (lux < val1)
    {
      digitalWrite(Pin3, HIGH);
      digitalWrite(Pin5, LOW);
    }
    if ((lux >= val1) && (lux < val2))
    {
      digitalWrite(Pin3, LOW);
      digitalWrite(Pin5, LOW);
      digitalWrite(Pin9, LOW);
    }
    if (lux >= val2)
    {
      digitalWrite(Pin3, LOW);
      digitalWrite(Pin5, HIGH);
    }

Please help me on this one. I'm sorry for bothering you. I can't code it due to my little knowledge. I also want the client.prinln code since I am new to this. Pls hope you will help me on this.
Logged

Offline Offline
Full Member
***
Karma: 2
Posts: 219
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

oh your realy new to code.. well ehmm you should dive into it why else you have an arduino?.
I dont have the ethernet shield so i cannt really rewrite and test your code.
Well maybe i still can help you, and give you guidance
As a general note type correctly
As i see in your code
Code:
int lux_v1 = readString.substring(7, 11);
int lux_v1 = readString.substring(12, 16);// lux_v2 = readString.substring(12, 16)
i added some marked command  // is for marking
in you code you give lux_v1 a value and the next line does the same to the same value
But most likely you wanted it to assign to lux_v2

Are those perhaps the values you would like to work with ?
Because there you took parts of string called readString
For strings, a string = "text like this"
The first character is counted as zero
So the command substring, takes from readstring the 0123456 7th  character till the 11th
However by nature if you take part of a string it will returned as a string to you.
There is a function to convert a number inside a string to an int
Code:
// put this in the setup part
int A = 0; 
int B = 0;
now you program knows of two variables A and B
You also had lux_v1 and lux_v2 who where not int's but strings
This how you get their text numbers into an int, place it in your main program below after where i spoted your typo.
Code:
A = int(lux_v1);
B = int(lux_v2);

Instead of A you might also name them like Lux_v1_AsNumber  perhaps more easy?

I also note that you use a function called    atoi()  as far as i know this is not part of the arduino language, i couldnt find a reference of it (there is no atoi here : http://arduino.cc/en/Reference/HomePage but perhaps its a function that was part of Spi or Ethernet includes ? well perhaps might be.

Oh nextyou have serial output... and web output.
So you should also upate your webpage with A and B i suppose ?
Take a look at your seccond usage of your  <body> statement ... that should be </body>
But just above that line you might write
Code:
client.println (<br>);  // in html web page language that is a new line
client.print ( "First value :");
client.print ( lux_v1 );  // yes we can keep the string, you might try int version too
client.print (<br>);
client.print ( "Second value :");
client.print ( lux_v2 );


I hope you will manage with this help, i cannt test your solutions.
What's always a good approach to programming is to divide your problems into smaller ones. Or slowly extend your program, with a lot of file saves in between. so your working code extends, until you reach a problem. so then you know its there. then try to solve it in small parts, look perhaps how other people solved similar c++ coding problems, hang around c++ forums, or place newbie questions at   "stack overflow"  >> google it.
You can also slowly extend the sample programs its a good way to learn how to code.
Books are nice too,  (but borring too) just try to code, thats where it all starts..
Logged

Offline Offline
Full Member
***
Karma: 2
Posts: 219
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

a small extra note
if you want a function to go from a string to number it goes like this

Code:
 
int ConvertStringToInt(string S)
 {
   return int(s);
 }


As mentioned earlier there is always one answer to a function so you could repeat it
If you have this function you can write

Code:
A = ConvertString(lux_v1);
B = ConvertString(lux_v2);

in this case its more typing work, but often functions are good to repeat complex computer math programming, so using functions is a good thing just to let you know  smiley-grin

Logged

Finland
Offline Offline
Sr. Member
****
Karma: 1
Posts: 270
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

a small extra note
if you want a function to go from a string to number it goes like this

Code:
 
int ConvertStringToInt(string S)
 {
   return int(s);
 }


A small typo here (capital S swapped place), but what is the point of this? Assuming that the String class implements cast to int (haven't use it, but as your code indicates), why bother writing  a function (and justify the extra run time overhead)  when  it does nothing but the cast.


As mentioned earlier there is always one answer to a function so you could repeat it
If you have this function you can write

Code:
A = ConvertString(lux_v1);
B = ConvertString(lux_v2);
in this case its more typing work, but often functions are good to repeat complex computer math programming, so using functions is a good thing just to let you know  smiley-grin


Wouldn't this be better?
Code:
A = int(lux_v1);
B = int(lux_v2);

Logged

Offline Offline
Full Member
***
Karma: 2
Posts: 219
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

yes in this case its more handy to write it like that, less typing is better.

But suppose you wanted a more complex function to create a complex string for HTML formatting.
Based on the value of A the text color is red or green, and if A is below or above a treshold it should be bold too.
Things like that require longer peaces of code.

As i am not sure how good you are in coding, i just noted it could also be written as your function, with a name you like to add to it.
If your learning c++ from other languages, it might be confusing to see how functions are made.
Without words like "Function" , well c++ is a bit barebones syntax , compared to languages like python  or java or basic, or ...etc

Essentially   int() is a build in function for arduino its allready there.
Logged

Finland
Offline Offline
Sr. Member
****
Karma: 1
Posts: 270
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

yes in this case its more handy to write it like that, less typing is better.

But suppose you wanted a more complex function to create a complex string for HTML formatting.
Based on the value of A the text color is red or green, and if A is below or above a treshold it should be bold too.
Things like that require longer peaces of code.

Yes, that is a better example where functions should be used. I just posted my comment because I didn't want udeshplus to think that he (or she) should actually implement the ConvertStringToInt function you presented. ConvertStringToInt wont simplify the code a bit and it brings in a lot of overhead. For example, you passed the param "s" as value. It means that calling the function will allocate a new String object from stack and execute its copy constructor.

Quote
As i am not sure how good you are in coding, i just noted it could also be written as your function, with a name you like to add to it.
If your learning c++ from other languages, it might be confusing to see how functions are made.
Without words like "Function" , well c++ is a bit barebones syntax , compared to languages like python  or java or basic, or ...etc

Essentially   int() is a build in function for arduino its allready there.

int() is actually not a function but a build in type conversion (or cast). Its equivalent of:
Code:
A = (int) lux_v1;
If lux_v1 is an instance of the String class, it will invoke  String's cast operator.


Logged

Pages: [1]   Go Up
Jump to: