Pages: [1] 2   Go Down
Author Topic: analogWrite freeze the arduino  (Read 1349 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Jr. Member
**
Karma: 0
Posts: 67
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Hi,
    i'm trying to do a sketch that when receive string with 3 value R,G,B, it put the value on three pwn pin so that i could change the colors of my led strip with any browser. the sketche work like a charm, value is correctly displayed in the serial monitor but as soon as i put in the code
the three analogWrite, it freeze.

i put

Code:
analogWrite(redPin, r);
analoWrite(greenPin, g);
analogWrite(bluePin, b

here the partial of the code


Code:
EthernetClient client = Ledserver.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;
          //Serial.print(c);
        }

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

          client.println("HTTP/1.1 200 OK"); //send new page
          client.println("Content-Type: text/html");
          client.println();

          client.println("<HTML>");
          client.println("<HEAD>");
          client.println("<TITLE>Michael led server</TITLE>");
          client.println("</HEAD>");
          client.println("<BODY>");

          client.println("<H1>Michael test server</H1>");
         
          client.println("<a href=\"/?on\"\">ON</a>");
          client.println("<a href=\"/?off\"\">OFF</a>");

          client.println("</BODY>");
          client.println("</HTML>");
 
          delay(1);
          //stopping client
          client.stop();
         
readString = readString.substring(5, readString.length() - 11);
Serial.println(readString); //print to serial monitor for debuging

         
int commaIndex = readString.indexOf(',');
//  Search for the next comma just after the first
int secondCommaIndex = readString.indexOf(',', commaIndex+1);

String firstValue = readString.substring(0, commaIndex);
String secondValue = readString.substring(commaIndex+1, secondCommaIndex);
String thirdValue = readString.substring(secondCommaIndex+1); // To the end of the string

int r = firstValue.toInt();
int g = secondValue.toInt();
int b = thirdValue.toInt();

Serial.println(r);
Serial.println(g);
Serial.println(b);

          //clearing string for next read
          readString="";

        }
      }
    }
  }
}

Thanks in advance
Logged

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

Quote
here the partial of the code
Nope. We need to see all of the code. Which pins are you using for the LEDs?
Logged

Global Moderator
Boston area, metrowest
Offline Offline
Brattain Member
*****
Karma: 525
Posts: 26493
Author of "Arduino for Teens". Available for Design & Build services. Now with Unlimited Eagle board sizes!
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Isn't this the problem?

int r = firstValue.toInt();
int g = secondValue.toInt();
int b = thirdValue.toInt();

These are ints (0x0000 to 0xFFFF), while analogWrite expects bytes (0x00 to 0xFF)?
Logged

Designing & building electrical circuits for over 25 years. Check out the ATMega1284P based Bobuino and other '328P & '1284P creations & offerings at  www.crossroadsfencing.com/BobuinoRev17.
Arduino for Teens available at Amazon.com.

USA
Offline Offline
Full Member
***
Karma: 0
Posts: 238
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

... it freeze.

What does freeze mean in this context?

Isn't this the problem?

int r = firstValue.toInt();
int g = secondValue.toInt();
int b = thirdValue.toInt();

These are ints (0x0000 to 0xFFFF), while analogWrite expects bytes (0x00 to 0xFF)?

That should produce a compiler error.  I think freeze means the sketch doesn't work anymore.
Logged

Offline Offline
Jr. Member
**
Karma: 0
Posts: 67
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

here the code

Code:
//Michael sketche
//Arduino server for 8 relay, stove and RGB led strip
//for use with IDE 1.0
//open serial monitor to see what the arduino receives
//address will look like http://192.168.1.102:84 for the ledserver
//address will look like http://192.168.1.102:85 for the relayserver
//for use with W5100 based ethernet shields

#include <SPI.h>
#include <Ethernet.h>
boolean reading = false;

// Debug mode
#define DEBUG true

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //physical mac address
byte ip[] = { 192, 168, 2, 16 }; // ip in lan
EthernetServer Ledserver(84); //Led server port
EthernetServer Relayserver(85); //Relay server port

//For arduino input
#define Doorbelloff "76" //Scene for pin 2 LOW (door bell On)
#define Doorbellon "83" //Scene for pin 2 high (door bell OFF)
#define Phoneon "81" //Scene for pin 3 LOW (telephoe ring On)
#define Phoneoff "82" //Scene for pin 3 high (telephoe ring OFF)
#define Doorbell 2
#define Phone    3
boolean DoorbellState = false;
boolean PhoneState = false;
boolean Phonedelay = false;

//Variable for debonce phone ring
unsigned long pressed;
int pwrtime = 600;
unsigned long time;
unsigned long unpressed;


char serverName[] = "192.168.2.19"; //Vera ip address
EthernetClient client;

String readString;

//RGB led pin
const int redPin =   9;
const int greenPin = 10;
const int bluePin =  11;

//////////////////////

void setup(){
  //start Ethernet
  Ethernet.begin(mac, ip);
  Ledserver.begin();

  //Led pin
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(bluePin, OUTPUT);
  
  //input
  pinMode(Doorbell, INPUT);
  pinMode(Phone, INPUT);
  
  //relay pin
  pinMode(22, OUTPUT); //output relay pin
  pinMode(23, OUTPUT); //output relay pin
  pinMode(24, OUTPUT); //output relay pin
  pinMode(25, OUTPUT); //output relay pin
  pinMode(26, OUTPUT); //output relay pin
  pinMode(27, OUTPUT); //output relay pin
  pinMode(28, OUTPUT); //output relay pin
  pinMode(29, OUTPUT); //output relay pin
  pinMode(29, OUTPUT); //output relay pin
  
  Serial.begin(9600);
  Serial.println("Arduino starting"); // so I can keep track of what is loaded
   if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // no point in carrying on, so do nothing forevermore:
    while(true);
  }
  else{
    Serial.println("Ethernet ready local IP:");
    Serial.println(Ethernet.localIP());
  }
  // give the Ethernet shield a second to initialize:
  delay(1000);
}

void loop(){
  Led();
  Relay();
  DoorbellDetection();
  TelephoneDetection();
  }

void Led(){
  // Create a client connection
  EthernetClient client = Ledserver.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;
          //Serial.print(c);
        }

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

          client.println("HTTP/1.1 200 OK"); //send new page
          client.println("Content-Type: text/html");
          client.println();

          client.println("<HTML>");
          client.println("<HEAD>");
          client.println("<TITLE>Michael led server</TITLE>");
          client.println("</HEAD>");
          client.println("<BODY>");

          client.println("<H1>Michael test server</H1>");
          
          client.println("<a href=\"/?on\"\">ON</a>");
          client.println("<a href=\"/?off\"\">OFF</a>");

          client.println("</BODY>");
          client.println("</HTML>");
 
          delay(1);
          //stopping client
          client.stop();
          
readString = readString.substring(5, readString.length() - 11);
Serial.println(readString); //print to serial monitor for debuging

          
int commaIndex = readString.indexOf(',');
//  Search for the next comma just after the first
int secondCommaIndex = readString.indexOf(',', commaIndex+1);

String firstValue = readString.substring(0, commaIndex);
String secondValue = readString.substring(commaIndex+1, secondCommaIndex);
String thirdValue = readString.substring(secondCommaIndex+1); // To the end of the string

int r = firstValue.toInt();
int g = secondValue.toInt();
int b = thirdValue.toInt();

Serial.println(r);
Serial.println(g);
Serial.println(b);

          //clearing string for next read
          readString="";

        }
      }
    }
  }
}
    
}
Logged

Offline Offline
Jr. Member
**
Karma: 0
Posts: 67
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Code:
[code]void Relay(){

  EthernetClient client = Relayserver.available();

  if (client) {

    // an http request ends with a blank line
    boolean currentLineIsBlank = true;
    boolean sentHeader = false;

    while (client.connected()) {
      if (client.available()) {

        if(!sentHeader){
          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println();
          sentHeader = true;
        }

        char c = client.read();

        if(reading && c == ' ') reading = false;
        if(c == '?') reading = true; //found the ?, begin reading the info

        if(reading){
          Serial.print(c);

           switch (c) {
            case '1':
              //relay pin 22 on
              digitalWrite(22, HIGH);
              Serial.println("Relay 1 on");
              break;
            case '2':
              //relay pin 22 off
              digitalWrite(22, LOW);
              Serial.println("Relay 1 off");
              break;
            case '3':
              //relay pin 23 on
              digitalWrite(23, HIGH);
              Serial.println("Relay 2 on");
              break;
            case '4':
            //relay pin 23 off
              digitalWrite(23, LOW);
              Serial.println("Relay 2 off");
              break;
            case '5':
              //relay pin 24 on
              digitalWrite(24, HIGH);
              Serial.println("Relay 3 on");
              break;
            case '6':
            //relay pin 24 off
              digitalWrite(24, LOW);
              Serial.println("Relay 3 off");
              break;
            case '7':
              //relay pin 25 on
              digitalWrite(25, HIGH);
              Serial.println("Relay 4 on");
              break;
            case '8':
            //relay pin 25 off
              digitalWrite(25, LOW);
              Serial.println("Relay 4 off");
              break;
              case '9':
              //relay pin 26 on
              digitalWrite(26, HIGH);
              Serial.println("Relay 5 on");
              break;
            case '0':
              //relay pin 26 off
              digitalWrite(26, LOW);
              Serial.println("Relay 5 off");
              break;
            case 'a':
              //relay pin 27 on
              digitalWrite(27, HIGH);
              Serial.println("Relay 6 on");
              break;
            case 'b':
            //relay pin 27 off
              digitalWrite(27, LOW);
              Serial.println("Relay 6 off");
              break;
            case 'c':
              //relay pin 28 on
              digitalWrite(28, HIGH);
              Serial.println("Relay 7 on");
              break;
            case 'd':
            //relay pin 28 off
              digitalWrite(28, LOW);
              Serial.println("Relay 7 off");
              break;
            case 'e':
              //relay pin 29 on
              digitalWrite(29, HIGH);
              Serial.println("Relay 8 on");
              break;
            case 'f':
            //relay pin 29 off
              digitalWrite(29, LOW);
              Serial.println("Relay 8 off");
              break;
              case 'g':
              //relay pin 29 on
              digitalWrite(30, HIGH);
              Serial.println("Foyer on");
              break;
            case 'h':
            //relay pin 29 off
              digitalWrite(30, LOW);
              Serial.println("Foyer off");
              break;
          
          }

        }

        if (c == '\n' && currentLineIsBlank)  break;

        if (c == '\n') {
          currentLineIsBlank = true;
        }else if (c != '\r') {
          currentLineIsBlank = false;
        }

      }
    }

    delay(1); // give the web browser time to receive the data
    client.stop(); // close the connection:
 }
 }
 
 void DoorbellDetection(){
      ////
      // Arduino input detection code
      ////
      if (digitalRead(Doorbell) == HIGH && DoorbellState == false) // switch on pinDevid1 is ON
      {
        if(DEBUG){Serial.println("Doorbell off");}
        DoorbellState = true;
        //Sending request to Vera
        sendToVera(Doorbelloff);
      }
       if (digitalRead(Doorbell) == LOW && DoorbellState == true) // switch on pinDevid1 is OFF
      {
        if(DEBUG){Serial.println("Doorbell on");}
        DoorbellState = false;
        //Sending request to Vera
        sendToVera(Doorbellon);
      }
 }
 
 void TelephoneDetection (){
      time = millis();
      ////
      // Listening for the pin3 state
      ////
       if (digitalRead(Phone) == HIGH && PhoneState == false) // switch on pinDevid1 is ON
      {
        PhoneState = true;
         if(DEBUG){Serial.println("Phone off");}
        sendToVera(Phoneoff);
      }
        
       if (digitalRead(Phone) == LOW && PhoneState == true) // switch on pinDevid1 is OFF
      {
      pressed = time,
      PhoneState = false;}
        
       if ((PhoneState == false) && ((time - pressed) > pwrtime))
       {
        if(DEBUG){Serial.println("Phone on");}
        Phonedelay = true;
        sendToVera(Phoneon);
        }
     }
    
 void sendToVera(String devid){

  if (client.connect(serverName, 49451)) {
    if(DEBUG){Serial.println("connected to Vera");}

    if(DEBUG){Serial.println("sendind request");}
    client.print("GET /data_request?id=lu_action&output_format=xml&serviceId=urn:micasaverde-com:serviceId:HomeAutomationGateway1&action=RunScene&SceneNum=");
    client.print(devid);
    client.println(" HTTP/1.1");
    client.print("Host: ");
    client.println(serverName);
    client.println("User-Agent: Arduino");
    client.println();
  }
  else {
    if(DEBUG){Serial.println("connection failed");}
  }
  
  // if there are incoming bytes available
  // from the server, read them and print them:
  if(DEBUG){
    if (client.available()) {
    char c = client.read();
    Serial.print(c);
    }
  }

    if(DEBUG){Serial.println();}
    if(DEBUG){Serial.println("disconnecting.");}
    client.stop();
    if (Phonedelay == true)
    {
     delay(1500);
     Phonedelay = false;
     }
    
}
[/code]
Logged

Offline Offline
Jr. Member
**
Karma: 0
Posts: 67
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

yes i'm able to compile it, as soon as i send a http request and i compile it with the analogwrite, it freeze. but if the analogwrite isn't there, it's ok and i'm able to see the three value r,g,b in the serial. the rest of the sketches work like charm.

thanks
Logged

USA
Offline Offline
Full Member
***
Karma: 0
Posts: 238
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

You maybe running out of RAM.  Insert the following code into the sketch and print (Serial.println()) the result of StackCount().  Also, what board are you using?

Code:
#define STACK_CHECK_BUILT

#ifdef STACK_CHECK_BUILT
extern uint8_t _end;
extern uint8_t __stack;
#define STACK_CANARY 0xc5
void StackPaint(void) __attribute__ ((naked)) __attribute__ ((section (".init1")));
void StackPaint(void)
{
#if 0
   uint8_t *p = &_end;
   while(p <= &__stack) {
      *p = STACK_CANARY;
       p++;
   }
#else
    __asm volatile ("    ldi r30,lo8(_end)\n"
                    "    ldi r31,hi8(_end)\n"
                    "    ldi r24,lo8(0xc5)\n" // STACK_CANARY = 0xc5
                    "    ldi r25,hi8(__stack)\n"
                    "    rjmp .cmp\n"
                    ".loop:\n"
                    "    st Z+,r24\n"
                    ".cmp:\n"
                    "    cpi r30,lo8(__stack)\n"
                    "    cpc r31,r25\n"
                    "    brlo .loop\n"
                    "    breq .loop"::);
#endif
}
//---------------------------------------------------------------------------

uint16_t StackCount(void)
{
   const uint8_t *p = &_end;
   while(*p == STACK_CANARY && p <= &__stack)
      p++;
   return p - &_end;
}
//---------------------------------------------------------------------------
#endif
Logged

Offline Offline
Jr. Member
**
Karma: 0
Posts: 67
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

the board is a mega2650

thanks
Logged

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

Code:
const int greenPin = 10;
With the Ethernet shield in use? I don't think so.
Logged

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

To paraphrase your problem:
My sketch is doing weird things. It uses the String class a lot.

Stop using the String class. It can cause memory corruption which can make your sketch do weird things.
Logged

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

Offline Offline
Jr. Member
**
Karma: 0
Posts: 67
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Yes i use the ethernet shield,  Don't know how to extract the rgb value without using the string, cause when the server receive a data, it look like
(get/ 255,255,255 / HTTP1.1) So could you point me on how to extrat 255,255,255 and put them individually to r = 255 g = 255 b = 255 without using string.

Thanks again
Logged

Offline Offline
God Member
*****
Karma: 17
Posts: 723
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

You can use a string.  What you can't use is the String class.

If the data will look basically the same every time, then store it in a char array and then do the same thing you're doing now, find the commas and the numbers in between. 
Logged

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

So could you point me on how to extrat 255,255,255 and put them individually to r = 255 g = 255 b = 255 without using string.

Use c-strings (not Strings) and the standard 'C' runtime library functions to manipulate them. The Arduino runtime environment includes a reasonably complete AVR 'C' runtime library and the Arduino reference section contains a link to the AVR documentation for it. The functions you want are declared in string.h. Since these standard 'C' runtime library functions are common to a huge number of platforms, there is an enormous quantity of documentation and tutorials on the internet explaining how to use them. To give you a start, the strtok() function lets you divide a string into tokens separated by defined characters, and there are many functions such as atoi() to parse a numeric string into the corresponding number.
Logged

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

Offline Offline
Jr. Member
**
Karma: 0
Posts: 67
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

thanks guys i will make a shot
Logged

Pages: [1] 2   Go Up
Jump to: