Pages: [1]   Go Down
Author Topic: Beginner needing help with code!  (Read 478 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Newbie
*
Karma: 0
Posts: 5
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

As stated in the topic, I am a beginner to arduino.  Recently I've been working on a private project to construct an ambient weather light using the arduino.  Unfortunately, there are still a couple things I am stuck on and I need it done by Wednesday.  Explaining my own incompetence aside, I obviously need some help.

The hardware is simple enough, so I won't get into that, and I know there are some answers out there, but as a beginner every tutorial and answer I have found was one I just can't wrap my head around as I don't have enough experience to understand everything they are referring to, so when answering it is not required but I'll still ask for your patience and would be eternally grateful if you could simplify your answer to something a beginner can understand and especially if you could endure my questions.  Also, if my code seems painfully messy I apologize as I have not been working with this language for very long.

Anyway, I have two questions:

First, how do you get the arduino to read incoming information as a string rather than individual characters.  I was testing my RGB LED's response to the logic statements using the serial port, however I have yet to figure out how I can get it to read '72' instead of '7' '2'.

Here's my current code for reference (which I'll admit I have been using multiple resources to "Frankenstein" this together) :
Code:

//Ethernet Settings//

//#include <SPI.h>
//#include <Ethernet.h>
//#include <TextFinder.h>

  //Change to match current computer//

//byte mac[] = { 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x01 };
//IPAddress ip(192, 168, 10, 00);
//IPAddress server(000, 000, 000, 000);

  //Initializing the Ethernet Client Library//
 
//Client client;

//boolean requested;
//long lastAttemptTime = 0;




//Back To Normal//



const int redPin = 9;   
const int grnPin = 10; 
const int bluPin = 11;

const int button1Pin = 2;

const int button2Pin = 3;

int tempToday = 0;

int tempTonight = 0;


void setup () {

  //Ethernet Settings//
    //Start the Ethernet Library// 
//Ethernet.begin(mac, ip);
    //Start the Serial Library//
Serial.begin(9600);



// Normal //



pinMode(redPin, OUTPUT);

pinMode(grnPin, OUTPUT);

pinMode(bluPin, OUTPUT);

pinMode(button1Pin, INPUT);

pinMode(button2Pin, INPUT);


analogWrite(redPin, 127); 
analogWrite(grnPin, 127);   
analogWrite(bluPin, 127); 

Serial.println("Enter Testing Temperature :");

    //Allow the Ethernet Shield the time to Initialize//
//delay(1000);
    //Connect to server//
//connectToServer();

}



void loop () {

//Ethernet//

  //If you're connected to the client, save any incoming bytes to the input string
//  if (client.connected()) {
//    if (!requested) {
//      requested = makeRequest();
//    } else {
//      //Utilize the TextFinder to search the response
//      TextFinder response(client);
//      //See if the response contains the Temperature Value
//      if (response.find("Today's Temperature:")) {
//        temp1 = response.getValue(); //Converts remaining into an integer
//      }
//    }
//  }
//  else if (millis() - lastAttemptTime > requestInterval() {
//    client.stop();
//    connectToServer();
//  }
 
//  setLEDs();
 

// Normal //


  String content = "";
  char character;

while(Serial.available() <=0);
 
  if (Serial.available() >= 1) {
    int tempr = Serial.read();
  character = Serial.read();
  content.concat(character); 

//Temperature Logic Statements//

  tempr-=48;
//   For basic RGB color testing
//  tempr*=10;
  Serial.print(tempr);
   
 if (tempr >= 75) {

    Serial.print("Hot");

    analogWrite(redPin, 255);

    analogWrite(grnPin, 0);

    analogWrite(bluPin, 0);

    delay (2000);

   

    }


else if(tempr >= 50 && tempr <= 74){

    Serial.print("Warm");

    analogWrite(redPin, 255);

    analogWrite(grnPin, 165);

    analogWrite(bluPin, 0);

    delay (2000);


    }


else if(tempr <= 49 && tempr >= 35){

    Serial.print("Mild");

    analogWrite(redPin, 0);

    analogWrite(grnPin, 255);

    analogWrite(bluPin, 0);

    delay (2000);


}


else if(tempr <= 34 && tempr >= 20){

    Serial.print("Chilly");

    analogWrite(redPin, 127);

    analogWrite(grnPin, 0);

    analogWrite(bluPin, 255);

    delay (2000);


}


else if(tempr <= 19){

    Serial.print("Cold");

    analogWrite(redPin, 0);

    analogWrite(grnPin, 0);

    analogWrite(bluPin, 255);

    delay (2000);


}
 
 
}


  if (content != "") {
    Serial.println(content);
  }
 
}
 

//void connectToServer() {
//  Serial.println("Connecting to Server ...");
//  if (client.connect(server, 80)) {
//    requested = false;
//  }
//  lastAttemptTime = millis();
// 
//}

//boolean makeRequest() {
 
//client.println("GET /~emeryk/Robotics/robot3.php HTTP/1.1\n");
//client.print("HOST:ctstudents.smccme.edu\n\n");
//client.println();
//return true;
 
//}



I should put it in right now that I do intend for this to be compatible with incoming information from a php script that will parse the html I need.  The only reason everything is commented out mostly has to do with the fact I need it to be able to read the information as a string first.  And apologies if there might be some spare code I forgot to scrape up from my prior attempts to get this thing to work correctly.

Second Part: As more experienced coders do you think the following code is a good method to go about something like this and/or do you know of any good resources for this type of project that can tell me the information in plain and simple terms?
Logged

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

Quote
First, how do you get the arduino to read incoming information as a string rather than individual characters. 
It's best if you don't go there. Read the characters, one at a time, storing then in an array, until you get the end of packet marker (something that indicates that the sender's message is complete).

Quote
Second Part: As more experienced coders do you think the following code is a good method to go about something like this and/or do you know of any good resources for this type of project that can tell me the information in plain and simple terms?
That depends on what the PHP script is sending to the Arduino. Some stuff is easier to parse/deal with than other stuff.
Logged

Global Moderator
UK
Offline Offline
Brattain Member
*****
Karma: 302
Posts: 26273
I don't think you connected the grounds, Dave.
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Before posting this topic (twice), did you read the sticky thread at the top of the section that ask you, politely, to read it before posting?

Why not?

DO NOT CROSS-POST, IT WASTES TIME.
Logged

"Pete, it's a fool looks for logic in the chambers of the human heart." Ulysses Everett McGill.
Do not send technical questions via personal messaging - they will be ignored.

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

Quote
First, how do you get the arduino to read incoming information as a string rather than individual characters. 
It's best if you don't go there. Read the characters, one at a time, storing then in an array, until you get the end of packet marker (something that indicates that the sender's message is complete).

Quote
Second Part: As more experienced coders do you think the following code is a good method to go about something like this and/or do you know of any good resources for this type of project that can tell me the information in plain and simple terms?
That depends on what the PHP script is sending to the Arduino. Some stuff is easier to parse/deal with than other stuff.

First, thank you very much for replying~! smiley-kitty

Second: The array idea sounds good.  How would I be able to set it up to convert it?

Third: Currently my PHP script looks like this:

Code:
<?php

$url
='http://weather.cnn.com/weather/forecast.jsp?locCode=USME9976&zipCode=04093
$checkForValue = false;
$temp1 = -1;
$filePath = fopen($url, "r");
        while(!feof($filePath))
                {
                $line = fgetss($filePath, 4096);
                if (preg_match('
/&deg/', $line))
                        {
                        $checkForValue = true;
                        }
                if ($checkForValue == true)
                        {
                        $temp1 = $line;
                        $checkForValue = false;
                        }
                }


echo "Today'
s Temperature:". $temp1;

?>



Which I need help with as well, although I figured people not might be happy if I asked questions about php on an arduino forum.  Still, I use my second php located Here as reference (Viewing the source code making it much easier to find the specific lines I need)  Currently it just posts temperature, but I would also like to get it to grab a weather condition once I improve it.
Logged

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

Before posting this topic (twice), did you read the sticky thread at the top of the section that ask you, politely, to read it before posting?

Why not?

DO NOT CROSS-POST, IT WASTES TIME.

I apologize.  I honestly had not meant to be a nuisance.  When I posted it originally in the Project Guidance section it was kind of with the idea of the second question still in mind and then I realized my first question (and admittedly the dominating one of the post) belonged in this section, so I was more or less confused as to where to put it.
Logged

UK
Offline Offline
Shannon Member
****
Karma: 223
Posts: 12631
-
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

It looks to me as if you are using the same sketch as a learning tool and also trying to evolve it into your final solution. That isn't a good way to work. It is far better to write small test sketches that are just for you to learn or test a particular feature of your code - for example, handling serial input. Once you have worked out the best way to do it, you can then incorporate that feature into your project.

Make sure you back up your work as you go. By that I mean keep a copy of old versions of your source code somewhere. If you don't already have any scheme in place for this, I recommend File Hampster as a good, simple automated versioning system.

Get used to deleting code that you no longer use, rather than keeping it commented out 'just in case'. You can always retrieve it from your backup/versioning system if you find you need it again, or just copy+paste it into a separate file that you save somewhere. But don't leave it cluttering up your working code since it makes it harder to see the real code.

Get used to indenting and spacing your code properly. I recommend putting each { and } on separate lines with matching pairs indented by the same amount and ythe lines between them indented one extra level. If you put the { and } on separate lines, the Tools / Auto Format command will sort out the indentation for you.

You have (IMO) far too many blank lines in your code, which means you can only see a small part of your code at a time. The more of your code you can physically fit on the monitor at the same time, the easier it will be to understand. I suggest you delete any blank line which is next to a {, or next to a }, or next to another blank line. Get rid of blank lines between statements that are similar/related. Blank lines are useful as a way to visually separate pieces of code that are logically distinct, and also to separate inline comments from unrelated code. However, you can have too much of a good thing.

There are two approaches to handling serial input as a string.

The first one is to buffer the incoming string in a c-string. A c-string is a char array with a null value after the last character. This is the approach I recommend. With this approach, each time your received a new character you would append it to the buffer by writing it to the next entry in the array and putting a null terminator after it. You need a scheme to recognise when the input string is complete. With textual input, the most obvious way to do that is by putting a newline character at the end of each message. It is good practice to also make sure you don't overflow the array, in case you receive a message that is much longer than you expect. The code could look similar to this:

Code:
// incomplete, untested

const int BUFF_SIZE = 32; // make this big enough for the biggest message you need to handle
char buffer[BUFF_SIZE + 1]; // +1 allows space for the null terminator
int length = 0; // number of characters stored in the string

void loop()
{
    handleSerialInput();
}

void handleSerialInput()
{
    if(Serial.available())
    {
        char c = Serial.read();
        if((c == '\n') || (c == '\r'))
        {
            // end-of-message received
            if(length > 0)
            {
                handleReceivedMessage(buffer);
            }
            length = 0; // reset the buffer ready for the next message
        }
        else
        {
            // received character is not end-of-message marker
            if(length < BUFF_SIZE)
            {
                buffer[length++] = c; // append the received char to the buffer
                buffer[length] = 0; // append null terminator
            }
            else
            {
                // buffer is full - discard received char
            }
        }
    }
}

void handleReceivedMessage(char *msg)
{
    // your code here
    if(strcmp(msg, "27") == 0)
    {
        // handle "27"
        etc
    }
}

The alternative approach uses the String class. The code would look broadly similar but appending to the string would be done using the '+' operator and string comparisons would be done using the '==' operator. However, the String class exposes a memory leak which can cause stability problems on Arduino versions prior to 1.0.4, and introduces potential memory fragmentation problems in all versions; I don't recommend using it.
Logged

I only provide help via the forum - please do not contact me for private consultancy.

0
Offline Offline
Tesla Member
***
Karma: 143
Posts: 9577
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Quote
First, how do you get the arduino to read incoming information as a string rather than individual characters.  I was testing my RGB LED's response to the logic statements using the serial port, however I have yet to figure out how I can get it to read '72' instead of '7' '2'.

You can put the individual characters together like below.

Code:
// zoomkat 7-30-11 serial I/O string test
// type a string in serial monitor. then send or enter
// for IDE 0019 and later

String readString;

void setup() {
  Serial.begin(9600);
  Serial.println("serial test 0021"); // so I can keep track of what is loaded
}

void loop() {

  while (Serial.available()) {
    delay(2);  //delay to allow byte to arrive in input buffer
    char c = Serial.read();
    readString += c;
  }

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

    readString="";
  }
}

Logged

Consider the daffodil. And while you're doing that, I'll be over here, looking through your stuff.   smiley-cool

Pages: [1]   Go Up
Jump to: