body:
I'm taking a sample I found on the web about [how to get ROS and arduino to communicated together over serial][1]. I have the sample working and now I'm moving the idea of the sample into my OOP project and am running into some trouble.

My sketch works but when I move a certain global variable to a protected member it breaks my sketch.

How do I declare this global variable

    ros::Publisher chatter("chatter", &str_msg);

as a protected variable

    protected:
      ros::Publisher chatter("chatter", &str_msg);

without getting this error

    expected identifier before string constant

**sample .ino**

    /*
     * rosserial Publisher Example
     * Prints "hello world!"
     */

    #include <ros.h>
    #include <std_msgs/String.h>

    ros::NodeHandle nh;

    std_msgs::String str_msg;
    ros::Publisher chatter("chatter", &str_msg);

    char hello[13] = "hello world!";

    void setup()
    {
      nh.initNode();
      nh.advertise(chatter);
    }

    void loop()
    {
      str_msg.data = hello;
      chatter.publish( &str_msg );
      nh.spinOnce();
      delay(1000);
    }

**ROSController class**

    #include <ros.h>
    #include <std_msgs/String.h>

    class ROSController {
      protected:
        ros::NodeHandle _nh;
        std_msgs::String str_msg;
    //    ros::Publisher chatter("chatter", &str_msg);
        int _throttle;
        bool _is_on = false;
      public:
        void loop();
        ROSController();
        double* getAttitude();
        bool isOn() {
          return this->_is_on;
        }
        int getThrottlePerc() {
          return this->_throttle / ROSController::THR_MAX;
        }

        static const int THR_MAX;
    };

    const int ROSController::THR_MAX = 100;

    ROSController::ROSController() {
      this->_nh.initNode();
    //  this->_nh.advertise(chatter);
    }

    double* ROSController::getAttitude() {
      return new double[3]{0, 0, 0};
    }

    void ROSController::loop() {
    //  str_msg.data = new char[] {"hello"};
    //  chatter.publish( str_msg );
      this->_nh.spinOnce();
      delay(1000);
    }

  [1]: http://wiki.ros.org/rosserial_arduino/Tutorials/Hello World

title: How can I move these global variables to be

Answers: 2

body:
The problem you are having is you are trying to both define and declare a class member variable at the same time. You can't. Instead you need to split it:

    protected:
        ros::Publisher chatter;

    ROSController::ROSController() : chatter("chatter", &str_msg)
    {
        this->_nh.initNode();
    //  this->_nh.advertise(chatter);
    }

That is, set up the variable as a protected member, then have the constructor call the constructor for you with the right parameters.

(I think that is the right syntax off the top of my head).

body:
You can't call the constructor in the class definition. Example:

<!-- language: lang-c++ -->

    class foo
      {
      protected:
        String bar ("fubar");
      };

    void setup ()
      {
      }  // end of setup

    void loop ()
      {
      }  // end of loop

That gives this error:

<!-- language: lang-none -->

    sketch_sep08b:4: error: expected identifier before string constant
         String bar ("fubar");
                     ^
    sketch_sep08b:4: error: expected ',' or '...' before string constant
    exit status 1
    expected identifier before string constant

---

Instead declare the class (without the constructor) and call the constructor in the constructor for the parent class, like this:

<!-- language: lang-c++ -->

    class foo
      {
      protected:
        String bar;
      public:

        foo () : bar ("fubar") {};  // constructor
      };

    void setup ()
      {
      }  // end of setup

    void loop ()
      {
      }  // end of loop


body:
I want it running as a normal automatic door so both sensors work as a separate activate. The only problem I've seen is that the servo remains active waiting for another high read and you can hear the buzz of it trying to keep position.

It didn't used to do this before the code change. While its open, if it reads another high it will remember and rerun the open wait close after it closes.

Eg. The door activates and while open 3 people walk thru so when the door closes it will then run 3 more times with out anyone being there.

Edit: Code changed

        #include <Servo.h>

      Servo myservo;

      int pos = 0; //variable to store servo position

      //amount of time we give the sensor to calibrate(10-60 secs according to       the datasheet)

      int calibrationTime = 30;

      int pirPin = 12; //digital pin connected to the PIR's output
      int pirPos = 13; //connects to the PIR's 5V pin
      int pirPin2 = 6; //digital pin connected to the PIR's output
      int pirPos2 = 10; //connects to the PIR's 5V pin
      const int position_closed = 0;      // door closed position [deg]
      const int position_open = 90;      // door open position [deg]
      const uint32_t delay_step = 15;     // delay between servo steps [ms]
      const uint32_t delay_open = 60000;  // how long the door stays open [ms]

      void setup()

      {
          myservo.attach(4); //attaches servo to pin 4
    Serial.begin(9600); //begins serial communication
    pinMode(pirPin, INPUT);
    pinMode(pirPos, OUTPUT);
    digitalWrite(pirPos, HIGH);
    pinMode(pirPin2, INPUT);
    pinMode(pirPos2, OUTPUT);
    digitalWrite(pirPos2, HIGH);

    //give the sensor time to calibrate
    Serial.println("calibrating sensor ");
    for(int i = 0; i < calibrationTime; i++)
    {
        Serial.print(calibrationTime - i);
        Serial.print("-");
        delay(1000);
    }
    Serial.println();
    Serial.println("done");
      }

      void loop()
      {
    static enum { CLOSED, OPENING, OPEN, CLOSING } state;
    static int position;          // door position
    static uint32_t last_change;  // last time state or position changed
    uint32_t now = millis();

    // When presence is detected, switch to the OPENING state.
    if ((digitalRead(pirPin) == HIGH || digitalRead(pirPin2) == HIGH)
            && state != OPENING) {
        state = OPENING;
        last_change = now;
    }
    else switch (state) {
        case CLOSED:
            break;
        case OPENING:
            if (position == position_open) {
                state = OPEN;
                last_change = now;
            } else if (now - last_change >= delay_step) {
                myservo.write(++position);
                last_change = now;
            }
            break;
        case OPEN:
            if (now - last_change >= delay_open) {
                state = CLOSING;
                last_change = now;
            }
            break;
        case CLOSING:
            if (position == position_closed) {
                state = CLOSED;
                last_change = now;
            } else if (now - last_change >= delay_step) {
                myservo.write(--position);
                last_change = now;
            }
            break;
          }
      }

title: code for automatic door

Answers: 2

body:
Your code is looping 180 times, **EACH TIME** it :

 - Sets the servo to 180
 - Delays for 2 seconds
 - Sweeps the servo from 180 to 90 in single steps
 - Sets the servo to 90
 - Delays for 60 seconds
 - Sweeps the servo from 90 to 180 in single steps

**So you code will take *more than 3 hours* to complete.**

I think you would be better pulling the code that moves the servo out into its own function: Something like:

    void moveServo(servoStart, servoEnd, servoStep, servoInterval)
    {
      for(int servoPos = servoStart; servoStart < servoEnd; servoStep)
      {
         myservo.write(servoPos);
         delay(servoInterval);
      }
    }

then simply call it from your main loop, like this:

    void loop()
    {

        if((digitalRead(pirPin) == HIGH) && (digitalRead(pirPin2) == HIGH))
        {
          moveServo(0, 180, 1, 15);
          delay(2000);
          moveServo(180, 90, -1, 15);
          delay(60000);
          moveServo(90, 0, -1, 15);
        }
    }

body:
KennetRunner already explained what is wrong with your code. Here I will
try to give advice on the proper way to implement the automatic door.

First thing is to get rid of `delay()`. While your program is inside a
call to `delay()`, it can do _nothing_ but wait until the delay is over.
This is acceptable if the program has only one single task to perform,
like blinking an LED. As soon as you have two tasks, `delay()` is a
nuisance because it blocks _all_ the tasks.

Case in hand: after keeping the door open for one minute, your program
would close it, irrespective of whether there is someone in the way. It
could not see the person come because it was busy delaying the closing
of the door.

The standard way to get rid of `delay()` is to never wait inside
`loop()`. Instead, if there is something to do _right now_, do it; if
not, just don't do it, but do not wait. Pseudo-code:

    void loop()
    {
        if (it_is_time_to_do_foo()) {
            do_foo();
        }
        if (it_is_time_to_do_bar()) {
            do_bar();
        }
        /// etc...
    }

You would use the [millis()][] function to know when the time has
come to do some task, as explained in the [Blink Without Delay][]
Arduino tutorial. This is really the second tutorial every Arduino user
should read, right after learning how to blink an LED.

Next, you have to learn how to implement a [finite state machine][]. I
recommend the [Finite State Machine tutorial][FSM by Majenko] by Majenko,
a regular contributor to this site.

Your problem can be very naturally mapped into a machine with four
states: CLOSED, OPENING, OPEN and CLOSING. You then write the rules
about what to do in each state, and when to transition to another state.
For example:

- when the door is CLOSED
  - if the sensors detect someone, transition to the OPENING state
- when the door is OPENING
  - if it's time to move the servo by one step, do it
  - if we have already moved all the way to the open position, we can
    say the door is OPEN now
- when the door is OPEN
  - if it's time to close it, transition to the CLOSING state
  - if the sensors detect someone, reset the timer <<<< note this!
- when the door is CLOSING
  - if the sensors detect someone, transition to the OPENING state
  - if it's time to move the servo by one step, do it
  - if we have already moved all the way to the closed position, we say
    the door is now CLOSED

A few things to note here:

- See the line marked by “<<<<”: this will prevent the aforementioned
  problem of the door closing into someone.
- The first rule for the CLOSING state follows from a similar rationale.
- I made up some of these rules, as the job of your program was not
  completely specified in your question. Feel free to change those rules
  to your taste.

And here is my proposed implementation. **Warning**: not tested. As
usual with FSMs, it is based on a big `switch`/`case` statement going
through all the possible states. However, to avoid repeating rules, I
factored the “if there is someone, start OPENING” rule out of the
`switch`. I also folded “if there is someone, reset the timer” into the
same rule.

    const int position_closed = 0;      // door closed position [deg]
    const int position_open = 180;      // door open position [deg]
    const uint32_t delay_step = 15;     // delay between servo steps [ms]
    const uint32_t delay_open = 60000;  // how long the door stays open [ms]

    void loop()
    {
        static enum { CLOSED, OPENING, OPEN, CLOSING } state;
        static int position;          // door position
        static uint32_t last_change;  // last time state or position changed
        uint32_t now = millis();

        // When presence is detected, switch to the OPENING state.
        if ((digitalRead(pirPin) == HIGH || digitalRead(pirPin2) == HIGH)
                && state != OPENING) {
            state = OPENING;
            last_change = now;
        }
        else switch (state) {
            case CLOSED:
                break;
            case OPENING:
                if (position == position_open) {
                    state = OPEN;
                    last_change = now;
                } else if (now - last_change >= delay_step) {
                    myservo.write(++position);
                    last_change = now;
                }
                break;
            case OPEN:
                if (now - last_change >= delay_open) {
                    state = CLOSING;
                    last_change = now;
                }
                break;
            case CLOSING:
                if (position == position_closed) {
                    state = CLOSED;
                    last_change = now;
                } else if (now - last_change >= delay_step) {
                    myservo.write(--position);
                    last_change = now;
                }
                break;
        }
    }

[millis()]: https://www.arduino.cc/en/Reference/Millis
[Blink Without Delay]: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
[finite state machine]: https://en.wikipedia.org/wiki/Finite-state_machine
[FSM by Majenko]: https://hackingmajenkoblog.wordpress.com/2016/02/01/the-finite-state-machine/


body:
This problem is on an Arduino Due.
I am trying to populate a char array buffer that is receiving information over a serial port. I am reading the information off of the serial port and storing it into a buffer array and passing it back to the original function call.

First is the code that initializes the buffer and writes the data that the Serial requires in order to issue a response. This function compares many types of expected responses (`uint32_t expect`) and returns a confirmation as an `int`.

    //Receive a cmd to send over serial and expect a certain response
    int SendCommand(char * cmd, uint32_t expect){
      int cmdSuccess = 0, j=0;
      char buffer[500];
      memset(&buffer,0,sizeof(buffer)); //0 out the buffer
      Serial3.print(F(cmd));
      delay(500);

      Response(buffer);

      if (expect == EXPECT_OK){
        for(int i=0;i<sizeof(RESP_OK);i++){
          if(buffer[i]==RESP_OK[i]){ //RESP_OK is an example of a response of length 6
            j++;
        }
      }
        if(j==sizeof(expect)-1){Serial.print(F("\nGOOD RESPONSE!\n")); return 1;}
      }
      else{return 0;}
      delete [] buffer;
    }

    void Response(char buffer[500])
    {
      int index = 0; //message index;
      int count = 0; //used for timeouts
      while(1)
      {
      if(Serial3.available()) //Data will be coming across serial3
      {
        char data = Serial3.read();
        buffer[index]=data;
        index++;
      }
        count++;
        delay(100);
        if(count == 50){
        Serial.println(F("\nEnd of Response"));
        break;
      }

    }
Edit: fixed the braces.

Right now, this code is hanging at the last part of `Response` right before `break;`. Am I having memory issues by the time it reaches the `println` at the end?
That last `println` was actually working until I began passing the buffer as a pointer and not returning it a `char*` and declaring `void Response` as `char* Response`. But the problem with this approach was that the `buffer` would reduce to `sizeof(buffer) = 4` and would strip off the rest of the information when returned.

**Edit:** As Matt suggested down below, I declared a `static const size_t bufferSize` and pass it into the `Response()` call as well as passing in `buffer` as `char*`. Then I reset the buffer size by `buffer = (char*)malloc(bufferSize)`.

What I still don't understand curious is the `sizeof(buffer)` after `Response` which is returning 4. However, 6 characters are stored into the array during `Response`. I've changed the pointer call to `Response(char* buffer, const int size)` with the following:

      if(index<size){
      buffer[index]=data;
      index++;
      }
      else{Serial.print(F("Buffer length exceeded!"));}

Thanks so much for your time!

title: Arduino is freezing during Serial.Print() while passing a char array

Answers: 3

body: I am having difficulties to follow your code due to indentation and additional braces which don't pair up correctly, but to me you are breaking out of the `if(count == 50)` statement through to the whole function as the `while(1)` statement was already closed.

body:
Sorry, but there are quite a few issues with your code any of which may be contributing to your problem.

 1. `memset(&buffer,0,sizeof(buffer)); //0 out the buffer` you are taking the address of a pointer and passing it to memset().  `buffer` is already a pointer of type `char*`.  Its working, because address of the pointer is the same address as buffer[0], but it is wrong and won't always work.
 2. `Serial3.print(F(cmd));` I have never used the F macro, but my understanding is it tells the compiler to store the string in flash memory.  cmd is a variable on the stack, a parameter to the function, so my guess would be the compiler is ignoring the F macro.
 3. `500` using a literal value in more than one place is opening you up to problems.  I think you should declare `static const size_t BufferSize = 500;`
 4. `void Response(char buffer[500])` It would be better to pass in a pointer to a char and the size as the parameter, `(const char* pBuffer, const int& size)` you can treat it the same within your function or you could pass a pointer to the next available item and then return the updated pointer.
 5. 1for(int i=0;i<sizeof(RESP_OK);i++){` Assuming that RESP_OK is a char[] of some sort this code will cause a crash if the length of RESP_OK is longer than the length of buffer.  You have protected against it by making buffer massive, but you could also protect against it by checking the `strlen()` of both variables before you start the for loop, because `if (strlen(RESP_OK) > strlen(buffer))` then buffer can't contain RESP_OK (its quicker too).

Also the Response function won't compile, because you have too many closing braces (I assume its a copy and paste error).  This is the cause of you code hanging `if(Serial3.available())` is inside a while(1) and there is no way of breaking out.  So if you just fix that you code will run.

body:
Ok, thanks to the responses in this thread, I believe I have the solved the problem. There is a problem using `sizeof(char*)` when passing through arrays, so I used `strlen(char*)` instead. This code properly stores the messages of various sizes coming off of `Serial3` and correctly compares them to the expected responses. The F() macro in Arduino is very useful in keeping the buffer free and, in general, I use it to print constants during debugging.

    int SendCommand(char * cmd, bool resp_type, uint32_t expect){
    delay(500);
      int cmdSuccess = 0, j=0, msgSize = 0;
      char * buffer;
      Serial3.print(F(cmd));
      Serial.print(F(cmd)); //Print to serial for debug purposes only
      delay(500);
      buffer = (char *)malloc(bufferSize);
      msgSize = Response(buffer, bufferSize);

      Serial.println("Buffer is: ");
      if (expect == EXPECT_OK){
        for(int i=0;i<msgSize;i++){
          if(buffer[i]==RESP_OK[i]){
            Serial.print(buffer[i],HEX);
            j++;
          }
        }
        Serial.print("\n");
        if(j==sizeof(expect)-1){Serial.print(F("\nGOOD RESPONSE!\n")); return 1;}
      }

      return cmdSuccess;
    }

    int Response(char* buffer, const int size)
    {
      int index = 0; //message index;
      int count = 0; //used for timeouts
      while(1)
      {
      if(Serial3.available()) //Message will be coming across serial3
      {
        char data = Serial3.read();
          if(index<size){
            buffer[index]=data;
            index++;
          }
          else{Serial.print(F("Buffer length exceeded!"));}
      }
        count++;
        if(count == 50){
        Serial.println(F("\nEnd of Response"));
        break;
        }
      } return index;
    }


body:
I bought this VMA-02 audio shield: http://www.velleman.co.uk/contents/en-uk/p623_vma02.html

I want it to get the data from line-in to line-out but with reading it in my arduino scetch first (e.g. for analysis later).

There's a example project to download here: http://www.apogeekits.com/Zip_Files/ka02-sample-code.zip

But I don't know whether it's possible to get the sound input anyway and if yes, with which pins I can read the input / write the output?

title: Using VMA-02 / KA-02 Sound Shield to get line-in input on arduino

Answers: 0


body:
1. When I press the button once, sequence s1() plays.
2. When I press the button twice, sequence s2() plays.
3. When I press the button thrice, sequence s3() plays.
4. When I press the button 4 times, sequence s4() plays.

--------
    const int buttonPin = 10;
    int buttonState = 0;

    void setup(){
      Serial.begin(9600);
      //initialize pin 2 - 9 as output
      for(int i=2;i<=9;i++){
        pinMode(i,OUTPUT);
      }
      pinMode(buttonPin, INPUT);
    }

    void loop() {
      buttonState = digitalRead(buttonPin);
      if (buttonState == HIGH) {
        s1();
        s2();
        s3();
        s4();
      }
    }

    void s1() {
      int i = 2 ;
      for(int z=0;z<=1;z++) {
        for(int x=i;x<=9;x++) {
          digitalWrite(i,HIGH);
          digitalWrite(x-1,LOW);
          delay(500);
          i = i + 1;
        }
        i = 2;
        if(i = 2) {
          digitalWrite(9,LOW);
        }
      }
    }

    void s2(){
      int y = 9;
      for(int i=0;i<=1;i++) {
        for(int x=2;x<=5;x++) {
          if(y>=1) {
            digitalWrite(x,HIGH);
            digitalWrite(y,HIGH);
            delay(500);
            y = y - 1;
          }
        }
        off();
        y = 9;
        delay(500);
      }
    }

    void s3() {
      for(int i=0;i<=2;i++) {
        for(int z=2; z<=9;z++) {
          if(z % 2 == 0) {
            digitalWrite(z,HIGH);
          }
        }
        delay(500);
        for(int z=2; z<=9;z++) {
          if(z % 2 == 0) {
            digitalWrite(z,LOW);
          }
        }
        delay(500);
        for(int z=2; z<=9;z++) {
          if(z % 2 != 0) {
            digitalWrite(z,HIGH);
          }
        }
        delay(500);
        for(int z=2; z<=9;z++) {
          if(z % 2 != 0) {
            digitalWrite(z,LOW);
          }
        }
        delay(500);
      }
    }

    void s4() {
      for(int i=0;i<=2;i++) {
        for(int x=2;x<=9;x++) {
          digitalWrite(x,HIGH);
          delay(500);
        }
        off();
        delay(500);
      }
    }

    void off() {
      for(int i=2;i<=9;i++) {
        digitalWrite(i,LOW);
      }
    }

title: How to count the number of button presses then play a sequence?

Answers: 2

body:
That's not that complex, please have a look at the following code: not the most elegant solution ever, but should be working (I didn't compile it as I'm currently on launch break in the office)

    #define LONGEST_PAUSE 1000
    unsigned long lastClick;
    unsigned int counter;

    void loop() {
      if (digitalRead(buttonPin) == HIGH) {
        // button is pressed
        while(digitalRead(buttonPin) == HIGH)) {
          delay(1); // wait until button released
        }
        lastClick = millis();
        counter++;
      }
      if (counter > 0 && (millis() - lastClick) >= LONGEST_PAUSE) { // 1s passed since last click: let's play!
        switch(counter) {
          case 1:
            s1(); break;
          case 2:
            s2(); break;
          case 3:
            s3(); break;
          case 4:
            s4(); break;
          default:
            // what if I keep clicking?!?
        }
        counter = 0; // reset the counter
      }
    }

body:
I prefer you to use pinchange interrupt or simple INT0 interrupt for the buttons to count the press.
Check [this link][1].

  [1]: https://www.arduino.cc/en/Reference/AttachInterrupt

on ISR, you can count the press.

    int count=0;

    void setup() {
      pinMode(interruptPin, INPUT_PULLUP);
      attachInterrupt(digitalPinToInterrupt(interruptPin), countFn, CHANGE);
    }

    void loop() {
      switch(count){
          // all cases here
      }
      count=0;
      delay(2000); // this delay is important to give enough time for a number of presses for the user
    }

    void countFn() {
      count++;
    }


body:
I got a problem where pulse voltage from acceptor is about 20mV. How can I solve my problem? and I can't detect the pulse using arduino uno.
please any one can help ?

title: Coin Acceptor CH-925 Pulse

Answers: 1

body:
From [this Amazon review][1]:

> There are 'live' (12V), 'ground' and 'signal' wires coming out of the
> back. Live and ground are pretty self-explanatory, and need to be
> connected to a 12V supply - I bought a simple 1A DC one. The final
> wire says 'signal', and needs to be connected to your circuit as input
> into a GPIO pin in the case of a raspberry pi. It produces a pulsing
> 5V signal (Why not tell us it will be 5V somewhere in the
> documentation? Luckily I have a multimeter) as a way of encoding which
> type of coin it has encountered. However, raspberry pi's only want
> 3.3V signals as inputs, so you'll be wanting to make a voltage divider (With a couple of resistors - I used 33k and 18k) to safely bring that
> 5V pulse down to 3.3V. (http://en.wikipedia.org/wiki/Voltage_divider)
> You'll also want to connect the ground from the device to a ground on
> your Raspberry Pi, or the signal won't work. I did this by splicing
> the ground cable from the power supply so that it has 2 ends - 1 for
> the power supply to the unit, and one for the unit to the Raspberry Pi
> Circuit.

It seems that a 5v pulse is the expected output. How are you measuring the output? You'll need a 'scope rather than a multimeter measuring voltage...

Anyway, I would not try to 'amplify' the signal, I would look to check the connections are correct and if that's not the issue, I would return the unit as defective.

  [1]: https://www.amazon.co.uk/review/R3FIXHUBYXTWBI/ref=cm_cr_dp_title?ie=UTF8&ASIN=B00C16P03I&channel=detail-glance&nodeID=560798&store=electronics


body:
I am trying to upload my code to my new Arduino (Just got one today, so im very new).

I can compile my code with no problems, but uploading it gives me:

    [Arduino: 1.6.11 (Mac OS X), Board: "Arduino/Genuino Uno"

    Sketch uses 1,186 bytes (3%) of program storage space. Maximum is 32,256 bytes.
    Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes.
    chmod: Unable to change file mode on /private/var/folders/md/s6pczlkd6gq8ylyh13z_3z8r0000gn/T/AppTranslocation/0D981E7A-E386-4AFD-9AEC-35E9ED8DA180/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude_bin: Read-only file system
    /private/var/folders/md/s6pczlkd6gq8ylyh13z_3z8r0000gn/T/AppTranslocation/0D981E7A-E386-4AFD-9AEC-35E9ED8DA180/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude: line 6: /private/var/folders/md/s6pczlkd6gq8ylyh13z_3z8r0000gn/T/AppTranslocation/0D981E7A-E386-4AFD-9AEC-35E9ED8DA180/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude_bin: Permission denied
    /private/var/folders/md/s6pczlkd6gq8ylyh13z_3z8r0000gn/T/AppTranslocation/0D981E7A-E386-4AFD-9AEC-35E9ED8DA180/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude: line 6: exec: /private/var/folders/md/s6pczlkd6gq8ylyh13z_3z8r0000gn/T/AppTranslocation/0D981E7A-E386-4AFD-9AEC-35E9ED8DA180/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude_bin: cannot execute: Undefined error: 0
    /private/var/folders/md/s6pczlkd6gq8ylyh13z_3z8r0000gn/T/AppTranslocation/0D981E7A-E386-4AFD-9AEC-35E9ED8DA180/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude: line 6: exec: /private/var/folders/md/s6pczlkd6gq8ylyh13z_3z8r0000gn/T/AppTranslocation/0D981E7A-E386-4AFD-9AEC-35E9ED8DA180/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude_bin: cannot execute: Undefined error: 0

    This report would have more information with
    "Show verbose output during compilation"
    option enabled in File -> Preferences.

It doesn't matter what i upload (tried to upload some of the examples).

As said i am very new, so if you need any more information to help me just ask.

Thanks in advance!

title: Can't upload to Arduino UNO (kuman UNO)

Answers: 2

body:
Check your port to which your arduino is connected. The port name can be checked from Arduino IDE. Click Tools -> Port -> There you can find the port name.
Open Terminal and type the following command.

    sudo chmod 777 /dev/port_name

After this try to Recompile/Upload the code again.

body: Drag Arduino.app out of your ~/Downloads folder to /Applications or anywhere else that isn't where you downloads it to. The app is being subjected to Gatekeeper Path Randomization which means it is running on a read-only file system. The app is trying to chmod something inside the app bundle and thats not possible on a read-only file system.


body:
I have a SIM800L Module connected to my arduino Nano. I want to open a TCP connection from the sim800l module to my own server and send a text string. The connection is working however I am not able to send text, because there is an issue with the arduino write() function I think... Below is the code I am trying to execute. Right after the message is sent, I need to send the stop value 0x1A (byte 26) to tell the sim800l module that the message end is reached and to send out the message.
My problem is, that it is not working in the arduino IDE and I don't know why.

My arduino code:

    #include <SoftwareSerial.h>

    #define SIM800_TX_PIN 8
    #define SIM800_RX_PIN 7

    SoftwareSerial serialSIM800(SIM800_TX_PIN, SIM800_RX_PIN);

    void setup() {

    serialSIM800.println("AT");
    delay(500);

    serialSIM800.println("AT+CIPSTART=\"TCP\",\"IP-ADRESS-HERE\",\"9999\""); //connection works
    delay(500);

    serialSIM800.println("AT+CIPSEND");
    delay(500);

    serialSIM800.print("TEXT MESSAGE HERE");
    delay(500);

    serialSIM800.write(26);
    delay(500);

    serialSIM800.println("AT+CIPCLOSE");
    delay(500);
    }

    void loop() {
      //Empty
    }
On my server I am running this python script that opens a socket:

    import socket
    import sys

    HOST = ''   # all available interfaces
    PORT = 9999 # Arbitrary non-privileged port

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print 'Socket created'

    #Bind socket to local host and port
    try:
      s.bind((HOST, PORT))
    except socket.error as msg:
      print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
      sys.exit()

    print 'Socket bind complete'

    #Start listening on socket
    s.listen(10)
    print 'Socket now listening'

    #now keep talking with the client
    while 1:
      #wait to accept a connection - blocking call
      conn, addr = s.accept()
      print 'Connected with ' + addr[0] + ':' + str(addr[1])
      data = conn.recv(1024)
      print len(data)
      print data
    s.close()

Once I execute this, I see the connection is working because "Connected with IP:PORT" is printed on my console. However right after that "len(data)" is printed (0) and "data" is an empty string. I even upped the delay from 500 to 5000, still same result.

However, if I leave the arduino IDE and send the message using the program "HTerm", it is working! In HTerm I typed in the text message and hit enter. After that I switched from ascii to hex mode (there is a checkbox) and I just typed 1A and sent it. That way it worked. Anybody can help me? Why is it not working @arduino?

title: Trying to Serial.write RAW code properly

Answers: 1

body: Replace `serialSIM800.write(26);` with `serialSIM800.write(0x1A);`, also  change `serialSIM800.print("TEXT MESSAGE HERE");` with a `println` or add a carriage return `\n`.


body:
I have the following snippet that seems to be taking a total of 6 CPU cycles per invocation.

Can I speed this up somehow? `x`  is a byte with the 3 lowest bits set.

    #define SET_COLOR(x) PORTB = (PORTB & ~(7)) | x

title: Performance tuning PORTB manipulation - mask

Answers: 1

body:
4 cycles:

    IN Rd,PORTB
    CBR Rd,7
    ORI Rd,x
    OUT PORTB,Rd

Translation into proper GCC inline assembly syntax is left as an exercise for the reader.


body:
I am making a solar charge controller using Arduino. So for starting, I thought I should calibrate the voltage so that I am able to read the exact voltage of battery and solar charger. For testing purposes, I do not have any solar panel, so I used a 12V power supply and set its output voltage to 13.56. I used the following calculations for getting exact voltage:

    float solarData = 0;
    float batData = 0;
    float batScale = 0;
    float solarScale = 0;
    float batPinVolt = 0;
    float solPinVolt = 0;
    float batVolt = 0;
    float solVolt = 0;

    Vcc = readVcc()/1000.00;    //getting the exact voltage of arduino
    Serial.print(Vcc);
    solarScale = analogRead(A0);  //reading solar analog data
    batScale = analogRead(A1);    //reading battery analog data
    solPinVolt = (solarScale/1024.0) * Vcc;
    solVolt = solPinVolt * (9.80 + 2.168)/2.168;    //I used 10k & 2.2k so entered their exact value
    batPinVolt = (batScale/1024.0) * Vcc;
    batVolt = batPinVolt * (9.80 + 2.168)/2.168;

Initially, I faced few problem regarding the exact voltage of the Arduino which I used as a reference voltage to calculate voltage. But then I found a solution [here](https://hackingmajenkoblog.wordpress.com/2016/02/01/making-accurate-adc-readings-on-the-arduino/). So below is the code which calculate the voltage of Arduino

    long readVcc()
    {
      long result;
      // Read 1.1V reference against AVcc
      ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
      delay(2); // Wait for Vref to settle
      ADCSRA |= _BV(ADSC); // Convert
      while (bit_is_set(ADCSRA,ADSC));
      result = ADCL;
      result |= ADCH<<8;
      result = 1125300L / result; // Back-calculate AVcc in mV
      return result;
     }

Now when I uploaded the code, I got the exact values of the voltages.

Now I wrote a logic where if the battery voltage is less than 12V then start charging until it is above 13V. Following is the code:

    if((solVolt > batVolt)&& ( batVolt <= 12.00 ))
    {
    digitalWrite(chargePin,HIGH);  //enable charging
    digitalWrite(loadPin,LOW);     //load off
    }
    else if((solVolt > batVolt)&&(batVolt > 12.00)&& (batVolt <= 13.00 ))
    {
     digitalWrite(chargePin,HIGH);   //enable chargin
     digitalWrite(loadPin,LOW);      //load off
    }
    // // shut down when battery is fully charged or when sunlight is not enough
    else if ((batVolt > 13.00) or (solVolt < batVolt))
    {
     digitalWrite(chargePin,LOW);    //disable charging
     digitalWrite(loadPin,HIGH);     //load on
    }

But when I uploaded the code, the Arduino started showing wrong values of the voltages. Power supply was set to 13.5, but it showed 13.15 and battery voltage was 11.8, but it showed 12.7.

Now due to this what exactly happened was it started charging so the value of battery voltage 12.7 (which is wrong) started increasing. When it was above 13V, Arduino turned off the `chargePin`. So when the `chargePin` is low, it shows the exact battery voltage which is low so it again started charging it and this loop keeps on going. This is all because of the wrong values of voltages. Following is the schematic:

[![enter image description here][2]][2]

  [2]: https://i.stack.imgur.com/StYxn.png

I am following the article I found on Instructables. (cannot post more links due to reputation). I want to know why there is change in voltage. Can anyone please help me on what I am doing wrong.

title: Voltage increasing when charging a battery using arduino

Answers: 1

body:
In order to charge a battery you have to apply a voltage to the battery terminals that is higher than the batteries own internal voltage. That's pretty much the definition of charging a battery.

Basically you're trying to do the impossible, you can't measure the batteries off charge voltage while charging it because as soon as you start charging the voltage at that point changes.

When charging your supply is 3.5V and your supply measurement is 13.15. That means you're loosing 0.35V in battery cables and F1.
The battery voltage is 12.7V so that's 0.45V loss in D1 and Q1.

That first loss seems too high and the second one too low, D1 should drop typically drop 0.58V, so you may have some resistor tolerance or noisy reading issues. The total voltage drop seems reasonable but the split looks wrong.

The best solution to what your are trying to do is to measure the charge current.

Move D1 to the other side of R1 so there is no diode drop between your two voltage measurements and add a small resistor in series where D1 used to be. The difference between the two measured voltages and the resistance between those points now tells you the charge current. Stop charging when the current drops below a certain threshold. Larger resistors make it easier to measure accurately but have an obvious efficiency hit, make sure you check the resistors power rating.

You may be able to avoid adding the resistor and simply use the on resistance of Q1 as your resistor. This will be a little variable between devices so it's not suitable for mass production but for a one off it should be good enough as long as it's not too small for you to measure the current accurately.

One further note: With a supply of 13.5V you will never get the battery to 13V. You have a diode in there with a 0.6V drop so the highest you could get is 12.9V. On the plus side this means you can keep charging until the current drops to 0 with no risk of overcharging.
Or alternatively switch D1 for a schottky diode with a drop of around 0.2V


body:
I have Arduino Due and PCA9685.

I use this library:
https://github.com/adafruit/Adafruit-PWM-Servo-Driver-Library

The board does not do anything with servo connected. I tried to use SDA/SCL pins and SDA1/SCL1 pins, I tried to use or not use pullup resistors. The board does not react in any case.

The PCA9685 is 100% working, because it operates properly when I connect it to my Arduino Mega using the same library, it works without pullups.

Also I noticed the following indicium, when I tried to use  this scanner
http://playground.arduino.cc/Main/I2cScanner I have no detected devices on SCL1/SDA1 but have detected 2 devices at 0x40 and 0x70 when I connect the board SDA/SCL pins.

title: How to make PCA9685 work with Arduino Due?

Answers: 1

body:
I made it working by this way: despite PCA9685 datasheet recommendations, we do not need to connect OE pin to VCC. Also we do not need to connect OE to ground as it recommended in some instructions related to other Arduinos.

So we should leave OE pin unconnected.
Also we should use 4,7K pull-up resistors to connect SDA and SCL to VCC.

The board can be used without level converters.

No special program/libraries changes needed. So it was a hardware problem.


body:
What is the meaning of `BitSet = bitRead(numeral[number], segment);`?

    const byte numeral[10] = {
      //ABCDEFG /dp
      B11111100,  // 0
      B01100000,  // 1
      B11011010,  // 2
      B11110010,  // 3
      B01100110,  // 4
      B10110110,  // 5
      B00111110,  // 6
      B11100000,  // 7
      B11111110,  // 8
      B11100110,  // 9
    };

    // pins for decimal point and each segment
    //                          dp,G,F,E,D,C,B,A
    const int segmentPins[8] = { 5,9,8,7,6,4,3,2};

    void setup()
    {
      for(int i=0; i < 8; i++)
      {
        pinMode(segmentPins[i], OUTPUT); // set segment and DP pins to output
      }
    }

    void loop()
    {
      for(int i=0; i <= 10; i++)
      {
        showDigit(i);
        delay(1000);
      }
      // the last value if i is 10 and this will turn the display off
      delay(2000);  // pause two seconds with the display off
    }

    // Displays a number from 0 through 9 on a 7-segment display
    // any value not within the range of 0-9 turns the display off
    void showDigit( int number)
    {
      boolean isBitSet;

      for(int segment = 1; segment < 8; segment++)
      {
        if( number < 0 || number > 9){
          isBitSet = 0;   // turn off all segments
        }
        else{
          // isBitSet will be true if given bit is 1
          isBitSet = bitRead(numeral[number], segment);
        }
        isBitSet = ! isBitSet; // remove this line if common cathode display
        digitalWrite( segmentPins[segment], isBitSet);
      }
    }

title: 7-segment display code

Answers: 1

body:
`bitRead(x, y)` takes a value `x`, and looks at _bit number_ `y`.

So, if:

 * `y` is the number `2`;
 * `x` is `53` (binary number `0` `0` `1` `1` `0` ***`1`*** `0` `1`)
 <pre>                                       ^</pre>

it looks at bit #2. Bits are counted from the _right_ starting at ***`0`*** - I have indicated the bit in question above.

So, `bitRead(53, 2)` would return `1`, since bit #2 in 53 is a `1`.

In the above program, the clever programmer has coded whether to light or not light the LED for each segment of the display in a single byte for each possible number to display. The digit `8` has all seven of its LEDs lit up, so you'd expect the encoding for `8` to have lots of binary `1`s in it - and sure enough, it does (`B11111110`)! And the digit `7` has only three segments lit up, so you'd expect only 3 bits to be set. Sure enough, `B11100000`.

The comment at the top describes what each of the bits represent - the last bit is the decimal point, which is never set...


body:
I'm controlling a light bulb with my Arduino Nano from serial or RF (via nRF24L01+) and I'm passing the commands as a string. After I get all the variables (3 ints) I try calling the function `execOrder` but no matter what I put in there, the Arduino just hangs or resets. Code is as follows:

 #define SSR 3
 #define SW 4
 #define nanoID 1
 bool isPWM = false;
 int value;

 // Módulo RF
 #include <SPI.h>
 #include "nRF24L01.h"
 #include "RF24.h"
 #include "printf.h"
 RF24 radio(9,10);
 const uint64_t pipes[2] = { 0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL };
 #define PayLoad 20

 #include <MemoryFree.h>

 void setup() {
   pinMode(SSR, OUTPUT);
   pinMode(SW, INPUT_PULLUP);
   digitalWrite(SSR, LOW);
   value = 0;
   Serial.begin(9600);
   Serial.println("------ CEACI SAS -- Controller Module ------");
   Serial.println("Module No: " + String(nanoID));
   // Inicializar RF
   Serial.println("Inicializando RF");
   radio.begin();
   radio.setRetries(15,15);
   radio.setPayloadSize(PayLoad);
   radio.setPALevel(RF24_PA_MIN);
   radio.setDataRate(RF24_250KBPS);
   radio.setCRCLength(RF24_CRC_16);
   delay(100);
   radio.openWritingPipe(pipes[1]);
   radio.openReadingPipe(1,pipes[0]);
   radio.startListening();
   //radio.printDetails(); //RF Debug
   Serial.println("RF listo!");
   Serial.print("freeMemory()=");
   Serial.println(freeMemory());
 }

 void loop() {
   if (Serial.available()) {
  Serial.println("Rcvd Serial!");
  String msgRcvd = Serial.readString();
  int ID = msgRcvd.substring(4,5).toInt();
  int cmdCode = msgRcvd.substring(10,11).toInt();
  int cmdVal = msgRcvd.substring(16).toInt();
  //Serial.println("ID: "+String(ID)+", CMD: "+String(cmdCode)+", VAL: "+String(cmdVal));
  Serial.print("freeMemory()=");
  Serial.println(freeMemory());
  //execOrder(ID,cmdCode,cmdVal);
   } else if (radio.available()){
  int RFlen=0;
  char msgBuff[]="";
  RFlen = radio.getDynamicPayloadSize();
  delay(10);
  radio.read(&msgBuff, RFlen);
  String msgRcvd(msgBuff);
  int ID = msgRcvd.substring(4,5).toInt();
  int cmdCode = msgRcvd.substring(10,11).toInt();
  int cmdVal = msgRcvd.substring(16).toInt();
  //Serial.println("ID: "+String(ID)+", CMD: "+String(cmdCode)+", VAL: "+String(cmdVal));
  Serial.print("freeMemory()=");
  Serial.println(freeMemory());
  //execOrder(ID,cmdCode,cmdVal);
   } else {
  chkSwitch();
   }
 }

 void execOrder(int ID, int CMD, int VAL){
   if (ID == nanoID || ID == 0){
  switch(CMD){
    case 0:
   State();
   break;
    case 1:
   value = VAL;
   OnOff();
   break;
    case 2:
   value = VAL;
   PWM();
   break;
  }
   }
 }

I wanted to process the incoming string in a function, but it resets as well.

By the way, I'm using `MemoryFree` library to check if I'm out of memory, and there's plenty of it, so I don't really know where's the problem. Any help would be greatly appreciated!

EDIT:

For the serial part I can do the following (my original code):

 if (Serial.find("MOD=")) {
   int ID = Serial.parseInt();
   if (ID == nanoID || ID == 0) {
  Serial.find("CMD=");
  int command = Serial.parseInt();
  int cmdVal = 0;
  if (command != 0){
    Serial.find("VAL=");
    cmdVal = Serial.parseInt();
  }
  Serial.println("MOD: "+String(ID)+", CMD: "+String(command) + ", VAL: " + String(value));
  Serial.print("freeMemory()=");
  Serial.println(freeMemory());
  execOrder(ID,command,cmdVal);
   }
 }

And it works flawlessly. But I don't know how to achieve the same results with the RF input. The problem seems to be with using so many strings.

title: Nano resets or freezes on calling a function

Answers: 2

body:
Ok, I solved it like this:

 if (radio.available()){
  int RFlen=0;
  char msgBuff[]="";
  RFlen = radio.getDynamicPayloadSize();
  delay(10);
  radio.read(&msgBuff, RFlen);
  int ID = msgBuff[4] - '0';
  int cmdCode = msgBuff[10] - '0';
  int cmdVal = msgBuff[16] - '0';
  if (cmdCode == 2){
    cmdVal *= 100;
    cmdVal += 10*(msgBuff[17]-'0');
    cmdVal += (msgBuff[18]-'0');
  }
  execOrder(ID,cmdCode,cmdVal);
 }

The problem is with using strings, but I don't know why since there's plenty of memory. Anyway, I hope this helps anyone else with the same issue.

body:
Your problem is not due to memory shortage, but because you are erroneously using pointers.

Even with your _fix_ you are doing the same mistake, you are just not incurring into the same problem by luck as you are not addressing anything new after the bad definition of your variable `msgBuff`.

Putting all that into simple terms, you should change your code and probably read some articles on C pointers as it looks like you have a Java background (like me).

Your issue is in the `char msgBuff[]="";` statement which should be moved after the the call to obtain the payload size and turned into `char msgBuff[RFlen];`:

    int RFlen=radio.getDynamicPayloadSize();
    char msgBuff[RFlen];
    delay(10);
    radio.read(&msgBuff, RFlen);


body:
Basically, if I put a shield on my Arduino (mine is Uno, but I'm asking generally), can I freely use **all** the pins that are there on the shield?

I have an Ethernet shield and almost all of the pins that the original Uno has, are available on the Ethernet too.

The best results that I could get from googling are [this][1] and [this][2] which describe that if a shield uses a certain pin, putting **another shield** that uses the same pin causes conflict.

But what about using them myself? Can I use all the pins on a shield as Input/Output?

If some pins are unusable, then why are they available on the board? For example why doesn't the Ethernet have pins 10-13 blocked so you can't put any jumper wires in them?

Additional info:

 - There was also [this][3] article which didn't seem very credible to me.

 - Also I've tried using pins 10-13 to light an LED while the Ethernet was busy transferring data. The result was the LED connected to pin 10 was very dim, 11 was less dim and so on. So my guess is yes, they are unavailable. But the fact that this was so rarely mentioned on the internet and that the pins aren't physically blocked made me doubtful.

  [1]: http://playground.arduino.cc/Main/ShieldPinUsage
  [2]: https://arduino.stackexchange.com/questions/1413/if-i-put-a-shield-on-an-arduino-can-i-use-the-arduino-for-anything-else
  [3]: http://arduserver.com/a2ethpin.htm

title: Are all the pins on Arduino shields available for use?

Answers: 1

body:
Short answer: **NO**.

Each shield adds some feature to the base Arduino Uno board and to do that it's more than probably going to use some of the PINs.
I say *more than probably* because Arduino do have support for certain protocols which can share the same pins (I2C and OneWire just from the top of my mind), but they are not the most commonly used approaches for shields.

The only reason the shields expose the same set of pins is for _stackability_, but not every shield is compatible with any other: it depends on the used PINs.

Some shields provide some level of configuration, usually via jumpers, in order to make them usable in more contexts they would usually be.

[![shield jumper configuration][1]][1]

Documentation regarding the pins used by each shield is generally available along with the shield, but if you buy cheap clones it's no surprise you might have difficulties finding documentation...

The article you were pointing is somewhat creditable because most of what the author says is actually true and real, including the risk of short circuits.

As an example, the test you run with LEDs connected to the Arduino SPI interface (pins from 10 to 13 are used by `SPI`) could have damaged your board if you didn't use current limiting resistors.

  [1]: https://i.stack.imgur.com/g0kUp.jpg


body:
And first of all sorry for my bad English.

I am trying to write code that allows the user to change between continuous or manual mode, but I am having some issues getting it to work. The goal is to be able to switch from manual SOS (user pressing the button to SOS) and automatic SOS (the led automatically blinking SOS morse).

Currently, when I press down the button it loops once the automatic SOS and returns back to its normal state with LED on.

How would I make it, for an example switch the mode to manual when holding down button and giving user some sort of indication when changing the mode (etc blinking the led for X amount of time?)

What I am looking to achieve is:

 1. Turn LEDS on when pressing the button.
 2. Start looping automatic SOS signal
 3. Press or hold down the button to change mode.
   - Blink LEDS to indicate the mode change.
 5. Switch to manual SOS signal (user pressing the button to signal)
 6. Press or hold down the button to change mode.
    - Blink LEDS to indicate the mode change.
 7. Switch back to an automatic loop.

The code so far:

    // set pin numbers:
    const int buttonPin = 2; // the number of the pushbutton pin
    const int ledPin =  13; // the number of the LED pin
    int mode;

    // variables will change:
    int buttonState = 0; // variable for reading the pushbutton status

    void setup() {
      // initialize the LED pin as an output:
      pinMode(ledPin, OUTPUT);
      // initialize the pushbutton pin as an input:
      pinMode(buttonPin, INPUT);
    }

    void loop() {
      // read the state of the pushbutton value:
      mode = digitalRead(buttonPin);

      // Manual SOS mode.
      buttonState = mode;

      // check if the pushbutton is pressed.
      // if it is, the buttonState is HIGH:
      if (buttonState == LOW) {
        digitalWrite(ledPin, HIGH); // turn LED on:
      } else {
        digitalWrite(ledPin, LOW); // turn LED off:
      }

      // Automatic SOS mode.
      if (mode == HIGH) {
        // check if the pushbutton is pressed.
        // if it is, starts looping automatic SOS.
        int i = 0;
        for (i=0; i<3; i++) {
          digitalWrite(ledPin, HIGH);   // turn the LED on
          delay(300); // wait for a second
          digitalWrite(ledPin, LOW); // turn the LED
          delay(300); // wait for a second
        }

        for (i=0; i<3; i++){
          digitalWrite(ledPin, HIGH); // turn the LED on
          delay(1200); // wait for a second
          digitalWrite(ledPin, LOW); // turn the LED
          delay(1200); // wait for a second
        }

        for (i=0; i<3; i++){
          digitalWrite(ledPin, HIGH); // turn the LED on
          delay(300); // wait for a second
          digitalWrite(ledPin, LOW); // turn the LED
          delay(300); // wait for a second
        }
        digitalWrite(ledPin, LOW);
        // waits 3 seconds before starting the loop again
        delay(3000);
      }
    }

title: Changing the mode when pressing/holding down a buttton

Answers: 1

body:
Ok, I'll try to split the code into multiple sections for clarity, but all this goes into one single sketch.

First we define the PINs: defines are pre-processor macros, even better than `const` in terms of performance and space consumption:

    #define BTN_PIN 2
    #define LED_PIN 13

Let's initialize the board as per our requirements:

    void setup() {
      pinMode(BTN_PIN, INPUT);
      pinMode(LED_PIN, OUTPUT);
    }

Now we define the code which emits and SOS signal in morse code using the standard timing:

 1. a long pulse lasts 3 times a short one
 2. a space lasts 6 times a short pulse

That boils down to the following definitions considering a standard unit of 300ms:

    #define UNIT 300
    #define SHORT (UNIT)
    #define LONG (UNIT*3)
    #define PAUSE (UNIT*3)
    #define SPACE (UNIT*6)

I'm also going to define another macro to emit a generic light pulse, for simplicity I'll use the `delay(...)` function, but this will prevent detecting button presses while signalling:

    #define PULSE(TYPE) digitalWrite(LED_PIN, HIGH);delay(TYPE); digitalWrite(LED_PIN, LOW);delay(UNIT)

With the above in place we can define a function to send an SOS which should be both very compact and also readable:

    void sendSOS() {
      PULSE(SHORT);PULSE(SHORT);PULSE(SHORT);
      PULSE(PAUSE); // inter letter pause
      PULSE(LONG);PULSE(LONG);PULSE(LONG);
      PULSE(PAUSE); // inter letter pause
      PULSE(SHORT);PULSE(SHORT);PULSE(SHORT);
    }

Now, let's describe what the mode changing should be notified to the user:

    #define QUICK 100
    bool autoMode = true;

    void switchMode() {
      autoMode= !autoMode;
      for (unsigned int i = 0; i < 25; i++) {
        digitalWrite(LED_PIN, HIGH);
        delay(QUICK);
        digitalWrite(LED_PIN, LOW);
        delay(QUICK);
      }
    }

Now our main loop will have to check the button and act accordingly, right?

    #define LONGPRESS 500
    unsigned long elapsed;
    bool clicked = false;
    unsigned long duration;

    void loop() {
      if (autoMode) {
        sendSOS();
      }
      elapsed = millis();
      while(clicked || millis() - elapsed <= SPACE) {
        // keep waiting to emit a SPACE or until the button is released

        if (digitalRead(BTN_PIN)) {
          // button has been clicked: trace it and start counting time
          clicked = true;
          duration = millis();
        } else if (clicked) {
          // button has been released: stop tracing and verify click duration
          clicked = false;
          if (millis() - duration <= LONGPRESS) {
            // switch mode on long press
            switchMode();
          } else if (!autoMode) {
            // short press has a meaning only when not in auto mode
            sendSOS();
          }
        }
      }

The solution above has great space for improvement:

 - there is no de-bouncing on the button
 - the board is unresponsive while signalling
 - keeping the button pressed forever will prevent any signalling to occur in any mode
 - the code is afflicted by `millis()` rollover if you keep the button pressed for long periods (around 49 days)

**UPDATE**: I've added the inter-letter pause as suggested in the comments.

**UPDATE**: apparently `auto` is a reserved word, so I changed it to `autoMode`.


body:
I am getting exception 29 every time I make request to `HTTP` using `GET` function. I am requesting HTTP every 20-30ms but using `millis` I am only reading request at 100ms in order to avoid any overflow or incomplete close connection, but still I am getting an exception after reading some 100 request.
What should I do now?

Here is my code and my Exception Decoder result as well

    #include <ESP8266WiFi.h>
    #include <ESP8266WebServer.h>

    #define RED_LED     12

    WiFiServer server(80);

    const char* ssid = "Led_Downlight1";
    char GetString[100];
    unsigned int long RedValue;
    unsigned long previousMillis = 0;
    const long interval = 100;

    void setup()
    {

      Serial.begin(115200); //Start communication between the ESP8266-12E and the monitor window
      Serial.println();
      Serial.print("Configuring access point...");

      WiFi.mode(WIFI_AP);
      WiFi.disconnect();
      delay(100);
      WiFi.softAP(ssid);
      Serial.println("");
      Serial.println("WiFi connected");
      Serial.print("SoftAP IP: ");
      Serial.println(WiFi.softAPIP());

      server.begin();
      Serial.println("Server started");
    }

    void loop()
    {

      WiFiClient client = server.available();
      if (!client)
      {
        return;
      }

      unsigned long currentMillis = millis();
      if (currentMillis - previousMillis >= interval)
      {

      Serial.println("Somebody has connected :)");

      previousMillis = currentMillis;
      String incoming = client.readStringUntil('\r');
      Serial.println(incoming);
      client.flush();
      incoming.toCharArray(GetString, 100);

      char *get = strtok(GetString, " ");
      char *request = strtok(NULL, " ");
      char *rtype = strtok(NULL, " ");

      if (request != NULL)
      {
        char *part = strtok(request, "/");
        bool seenSTA = false;
        bool seenRGBW = false;

        while (part)
        {
          if (!strcmp(part, "RGBW"))
          {
            seenRGBW = true;
          }

          else if (seenRGBW)
          {
            if (!strncmp(part, "R=", 2))
            {
              RedValue  = atoi(part + 2);
              analogWrite(RED_LED, RedValue);
              Serial.print("\n");
              Serial.print("Red:");
              Serial.print(RedValue);

              client.println("HTTP/1.1 200 OK");
              client.println("Content-Type: text/html");
              client.println(""); //  do not forget this one
              client.println("<!DOCTYPE HTML>");
              client.println("");
              client.println("Red value: ");
              client.println(RedValue);
              client.println("

");
              client.println("");

              Serial.println("Client disonnected");
            }
          }
          part = strtok(NULL, "/");
        }
      }
     }
    }

[![enter image description here][1]][1]
[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/E6wOp.png
  [2]: https://i.stack.imgur.com/hWEsc.png

title: Exception 29 ESP12E Arduino

Answers: 0


body:
I am just wondering if it is possible to check a string for specific characters.  For example if my string is `String mystr = "test";` and I wanted to check for the letter ***t*** at the beginning and if it is NOT there do something how would I go about this?

I have read about `string.startsWith(string2);` however it returns true or false, I want to be able to do "XYZ" if "ABC" isn't satisfied, and it would seem that `string.contains` isn't a thing.

To paraphrase, I am trying to create an if statement that will evaluate if a string starts with a certain character(s) and will do something if this condition is NOT met.

title: check string for specific characters?

Answers: 1

body:
Have you tried the following?

    if(!actualString.startsWith(expectedString)) {
      // do whatever you have to
    }

BTW, that is what actually suggested in _@EdgarBonet_'s comment.


body:
My code runs perfectly as long as the serial port is open. However if I connect it to external power, or even if I just try to run it plugged into my computer with the Serial Monitor not open, nothing happens. My project doesn't need any serial interaction, it will operate on its own far from any computers. I have it in here to help me debug.

The sticking point appears to be with `if (morseInput.available())` on line 63.

Here is everything, including the libraries I am using:

Morse EnDecoder.h

<!-- language-all: lang-cpp -->

    #ifndef MorseEnDecoder_H
    #define MorseEnDecoder_H

    #if (ARDUINO <  100)
    #include <WProgram.h>
    #else
    #include <Arduino.h>
    #endif

    #define MORSE_AUDIO true
    #define MORSE_KEYER false
    #define MORSE_ACTIVE_LOW true
    #define MORSE_ACTIVE_HIGH false

    class morseDecoder
    {
    public:
    morseDecoder(int decodePin, boolean listenAudio, boolean morsePullup);
    void decode();
    void setspeed(int value);
    char read();
    boolean available();
    int AudioThreshold;
    long debounceDelay;     // the debounce time. Keep well below dotTime!!
    boolean morseSignalState;
    private:
    int morseInPin;         // The Morse input pin
    int audioSignal;
    int morseTablePointer;
    int wpm;                // Word-per-minute speed
    long dotTime;           // morse dot time length in ms
    long dashTime;
    long wordSpace;
    boolean morseSpace;     // Flag to prevent multiple received spaces
    boolean gotLastSig;     // Flag that the last received morse signal is decoded as dot or dash
    boolean morseKeyer;
    boolean lastKeyerState;
    boolean morseAudio;
    boolean activeLow;
    long markTime;          // timers for mark and space in morse signal
    long spaceTime;         // E=MC^2 ;p
    long lastDebounceTime;  // the last time the input pin was toggled
    long currentTime;       // The current (signed) time
    char decodedMorseChar;  // The last decoded Morse character
    };

    class morseEncoder
    {
    public:
    morseEncoder(int encodePin);
    void encode();
    void setspeed(int value);
    void write(char temp);
    boolean available();
    int morseSignals;       // nr of morse signals to send in one morse character
    char morseSignalString[7];// Morse signal for one character as temporary ASCII string of dots and dashes
    private:
    char encodeMorseChar;   // ASCII character to encode
    boolean sendingMorse;
    int wpm;                // Word-per-minute speed
    long dotTime;           // morse dot time length in ms
    long dashTime;
    long wordSpace;
    int morseSignalPos;
    int sendingMorseSignalNr;
    long sendMorseTimer;
    long lastDebounceTime;
    long currentTime;
    protected:
    int morseOutPin;
    virtual void setup_signal();
    virtual void start_signal(bool startOfChar, char signalType);
    virtual void stop_signal(bool endOfChar, char signalType);
    };

    #endif

Morse EnDecoder.cpp

    /*          MORSE ENDECODER

    - Morse encoder / decoder classes for the Arduino.

    Copyright (C) 2010-2012 raron

    GNU GPLv3 license:

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

    Details: http://raronoff.wordpress.com/2010/12/16/morse-endecoder/

    #include "MorseEnDecoder.h"

    // Morse code binary tree table (dichotomic search table)

    // ITU with most punctuation (but without non-english characters - for now)
    const int morseTreeLevels = 6; // Minus top level, also the max nr. of morse signals
    const int morseTableLength = pow(2,morseTreeLevels+1);
    const char morseTable[] PROGMEM =
    " ETIANMSURWDKGOHVF*L*PJBXCYZQ!*54*3***2&*+****16=/***(*7***8*90*"
    "***********?_****\"**.****@***'**-********;!*)*****,****:*******\0";

    morseDecoder::morseDecoder(int decodePin, boolean listenAudio, boolean morsePullup)
    {
    morseInPin = decodePin;
    morseAudio = listenAudio;
    activeLow = morsePullup;

    if (morseAudio == false)
    {
    pinMode(morseInPin, INPUT);
    if (activeLow) digitalWrite (morseInPin, HIGH);
    }

    // Some initial values
    wpm = 13;
    AudioThreshold = 700;
    debounceDelay = 20;
    dotTime = 1200 / wpm;       // morse dot time length in ms
    dashTime = 3 * 1200 / wpm;
    wordSpace = 7 * 1200 / wpm;

    morseTablePointer = 0;

    morseKeyer = LOW;
    morseSignalState = LOW;
    lastKeyerState = LOW;

    gotLastSig = true;
    morseSpace = true;
    decodedMorseChar = '\0';

    lastDebounceTime = 0;
    markTime = 0;
    spaceTime = 0;
    }

    void morseDecoder::setspeed(int value)
    {
    wpm = value;
    if (wpm <= 0) wpm = 1;
    dotTime = 1200 / wpm;
    dashTime = 3 * 1200 / wpm;
    wordSpace = 7 * 1200 / wpm;
    }

    boolean morseDecoder::available()
    {
    if (decodedMorseChar) return true; else return false;
    }

    char morseDecoder::read()
    {
    char temp = decodedMorseChar;
    decodedMorseChar = '\0';
    return temp;
    }

    void morseDecoder::decode()
    {
    currentTime = millis();

    // Read Morse signals
    if (morseAudio == false)
    {
    // Read the Morse keyer (digital)
    morseKeyer = digitalRead(morseInPin);
    if (activeLow) morseKeyer = !morseKeyer;

    // If the switch changed, due to noise or pressing:
    if (morseKeyer != lastKeyerState) lastDebounceTime = currentTime; // reset timer

    // debounce the morse keyer
    if ((currentTime - lastDebounceTime) > debounceDelay)
    {
      // whatever the reading is at, it's been there for longer
      // than the debounce delay, so take it as the actual current state:
      morseSignalState = morseKeyer;

      // differentiante mark and space times
      if (morseSignalState) markTime = lastDebounceTime;
      else spaceTime = lastDebounceTime;
    }
    } else {
    // Read Morse audio signal
    audioSignal = analogRead(morseInPin);
    if (audioSignal > AudioThreshold)
    {
      // If this is a new morse signal, reset morse signal timer
      if (currentTime - lastDebounceTime > dotTime/2)
      {
        markTime = currentTime;
        morseSignalState = true; // there is currently a Morse signal
      }
      lastDebounceTime = currentTime;
    } else {
      // if this is a new pause, reset space time
      if (currentTime - lastDebounceTime > dotTime/2 && morseSignalState == true)
      {
        spaceTime = lastDebounceTime; // not too far off from last received audio
        morseSignalState = false;     // No more signal
       }
     }
    }

    // Decode morse code
    if (!morseSignalState)
    {
      if (!gotLastSig)
      {
        if (morseTablePointer < morseTableLength/2-1)
        {
        // if pause for more than half a dot, get what kind of signal pulse (dot/dash) received last
        if (currentTime - spaceTime > dotTime/2)
        {
          // if signal for more than 1/4 dotTime, take it as a morse pulse
          if (spaceTime-markTime > dotTime/4)
          {
            morseTablePointer *= 2;  // go one level down the tree
            // if signal for less than half a dash, take it as a dot
            if (spaceTime-markTime < dashTime/2)
            {
               morseTablePointer++; // point to node for a dot
               gotLastSig = true;
            }
            // else if signal for between half a dash and a dash + one dot (1.33 dashes), take as a dash
            else if (spaceTime-markTime < dashTime + dotTime)
            {
               morseTablePointer += 2; // point to node for a dash
               gotLastSig = true;
            }
          }
        }
      } else { // error if too many pulses in one morse character
        //Serial.println("<ERROR: unrecognized signal!>");
        decodedMorseChar = '#'; // error mark
        gotLastSig = true;
        morseTablePointer = 0;
      }
    }
    // Write out the character if pause is longer than 2/3 dash time (2 dots) and a character received
    if ((currentTime-spaceTime >= (dotTime*2)) && (morseTablePointer > 0))
    {
      decodedMorseChar = pgm_read_byte_near(morseTable + morseTablePointer);
      morseTablePointer = 0;
    }
    // Write a space if pause is longer than 2/3rd wordspace
    if (currentTime-spaceTime > (wordSpace*2/3) && morseSpace == false)
    {
      decodedMorseChar = ' ';
      morseSpace = true ; // space written-flag
    }

    } else {
    // while there is a signal, reset some flags
    gotLastSig = false;
    morseSpace = false;
    }

    // Save the morse keyer state for next round
    lastKeyerState = morseKeyer;
    }

    morseEncoder::morseEncoder(int encodePin)
    {
      morseOutPin = encodePin;
      this->setup_signal();

    // some initial values
    sendingMorse = false;
    encodeMorseChar = '\0';

    wpm = 13;
    dotTime = 1200 / wpm;       // morse dot time length in ms
    dashTime = 3 * 1200 / wpm;
    wordSpace = 7 * 1200 / wpm;
    }

    void morseEncoder::setspeed(int value)
    {
    wpm = value;
    if (wpm <= 0) wpm = 1;
    dotTime = 1200 / wpm;
    dashTime = 3 * 1200 / wpm;
    wordSpace = 7 * 1200 / wpm;
    }

    boolean morseEncoder::available()
    {
    if (sendingMorse) return false; else return true;
    }

    void morseEncoder::write(char temp)
    {
    if (!sendingMorse && temp != '*') encodeMorseChar = temp;
    }

    void morseEncoder::setup_signal()
    {
    pinMode(morseOutPin, OUTPUT);
    digitalWrite(morseOutPin, LOW);
    }

    void morseEncoder::start_signal(bool startOfChar, char signalType)
    {
    digitalWrite(morseOutPin, HIGH);
    }

    void morseEncoder::stop_signal(bool endOfChar, char signalType)
    {
    digitalWrite(morseOutPin, LOW);
    }

    void morseEncoder::encode()
    {
    currentTime = millis();

    if (!sendingMorse && encodeMorseChar)
    {
    // change to capital letter if not
    if (encodeMorseChar > 96) encodeMorseChar -= 32;

    // Scan for the character to send in the Morse table
    int p;
    for (p=0; p<morseTableLength+1; p++) if (pgm_read_byte_near(morseTable + p) == encodeMorseChar) break;

    if (p >= morseTableLength) p = 0; // not found, but send a space instead

    // Reverse binary tree path tracing
    int pNode; // parent node
    morseSignals = 0;

    // Travel the reverse path from position p to the top of the morse table
    if (p > 0)
    {
      // build the morse signal (backwards morse signal string from last signal to first)
      pNode = p;
      while (pNode > 0)
      {
        if ( (pNode & 0x0001) == 1)
        {
          // It is a dot
          morseSignalString[morseSignals++] = '.';
        } else {
          // It is a dash
          morseSignalString[morseSignals++] = '-';
        }
        // Find parent node
        pNode = int((pNode-1)/2);
      }
    } else { // Top of Morse tree - Add the top space character
      // cheating a little; a wordspace for a "morse signal"
      morseSignalString[morseSignals++] = ' ';
    }

    morseSignalString[morseSignals] = '\0';

    // start sending the the character
    sendingMorse = true;
    sendingMorseSignalNr = morseSignals; // Sending signal string backwards
    sendMorseTimer = currentTime;
    if (morseSignalString[0] != ' ') this->start_signal(true, morseSignalString[morseSignals-1]);
    }

    // Send Morse signals to output
    if (sendingMorse)
    {
    char& currSignalType = morseSignalString[sendingMorseSignalNr-1];
    bool endOfChar = sendingMorseSignalNr <= 1;
    switch (currSignalType)
    {
      case '.': // Send a dot (actually, stop sending a signal after a "dot time")
        if (currentTime - sendMorseTimer >= dotTime)
        {
          this->stop_signal(endOfChar, currSignalType);
          sendMorseTimer = currentTime;
          currSignalType = 'x'; // Mark the signal as sent
        }
        break;
      case '-': // Send a dash (same here, stop sending after a dash worth of time)
        if (currentTime - sendMorseTimer >= dashTime)
        {
          this->stop_signal(endOfChar, currSignalType);
          sendMorseTimer = currentTime;
          currSignalType = 'x'; // Mark the signal as sent
        }
        break;
      case 'x': // To make sure there is a pause between signals
        if (sendingMorseSignalNr > 1)
        {
          // Pause between signals in the same letter
          if (currentTime - sendMorseTimer >= dotTime)
          {
            sendingMorseSignalNr--;
            this->start_signal(false, morseSignalString[sendingMorseSignalNr-1]); // Start sending the next signal
            sendMorseTimer = currentTime;       // reset the timer
          }
        } else {
          // Pause between letters
          if (currentTime - sendMorseTimer >= dashTime)
          {
            sendingMorseSignalNr--;
            sendMorseTimer = currentTime;       // reset the timer
          }
        }
        break;
      case ' ': // Pause between words (minus pause between letters - already sent)
      default:  // Just in case its something else
        if (currentTime - sendMorseTimer > wordSpace - dashTime) sendingMorseSignalNr--;
    }
    if (sendingMorseSignalNr <= 0 )
    {
      // Ready to encode more letters
      sendingMorse = false;
      encodeMorseChar = '\0';
    }
    }
    }

Morse.h

    #pragma once
    /**
    * Generate and send Morse Code on an LED or a speaker. Allow sending
    * in a non-blocking manner (by calling a 'continue sending' method
    * every so often to turn an LED on/off, or to call tone/noTone appropriately).
    *
    * All input should be lowercase. Prosigns (SK, KN, etc) have special
    * character values #defined.
    */

    // for malloc and free, for the new/delete operators
    #include <stdlib.h>

    // Arduino language types
    #if defined(ARDUINO) && ARDUINO >= 100
    #include "Arduino.h"
    #else
    #include "WProgram.h"
    #endif

    #define WPM_DEFAULT 12.0
    // PARIS WPM measurement: 50; CODEX WPM measurement: 60 (Wikipedia:Morse_code)
    #define DITS_PER_WORD 50
    // Pass to SpeakerMorseSender as carrierFrequency to suppress the carrier.
    #define CARRIER_FREQUENCY_NONE -1

    // Bitmasks are 1 for dah and 0 for dit, in left-to-right order;
    // the sequence proper begins after the first 1 (a sentinel).
    // Credit for this scheme to Mark VandeWettering K6HX ( brainwagon.org ).
    typedef int             morseTiming_t;
    typedef unsigned char morseBitmask_t; // see also MAX_TIMINGS
    #define MORSE_BITMASK_HIGH_BIT B10000000

    // sentinel
    #define END             0

    // the most timing numbers any unit will need; ex: k = on,off,on,off,on,end = 5
    #define MAX_TIMINGS     15

    // Punctuation and Prosigns
    #define PROSIGN_SK 'S'
    #define PROSIGN_KN 'K'
    #define PROSIGN_BT 'B'
    typedef struct {
 char c;
 morseBitmask_t timing;
    } specialTiming;
    const specialTiming MORSE_PUNCT_ETC[] = {
 {'.',  B1010101},
 {'?',  B1001100},
 {PROSIGN_SK, B1000101},
 {PROSIGN_KN, B110110},
 {PROSIGN_BT, B110001},
 {END,  B1},
    };

    // Morse Code (explicit declaration of letter timings)
    const morseBitmask_t MORSE_LETTERS[26] = {
 /* a */ B101,
 /* b */ B11000,
 /* c */ B11010,
 /* d */ B1100,
 /* e */ B10,
 /* f */ B10010,
 /* g */ B1110,
 /* h */ B10000,
 /* i */ B100,
 /* j */ B10111,
 /* k */ B1101,
 /* l */ B10100,
 /* m */ B111,
 /* n */ B110,
 /* o */ B1111,
 /* p */ B10110,
 /* q */ B11101,
 /* r */ B1010,
 /* s */ B1000,
 /* t */ B11,
 /* u */ B1001,
 /* v */ B10001,
 /* w */ B1011,
 /* x */ B11001,
 /* y */ B11011,
 /* z */ B11100,
    };

    /**
    * Define the logic of converting characters to on/off timing,
    * and encapsulate the state of one sending-in-progress Morse message.
    *
    * Subclasses define setOn and setOff for (for example) LED and speaker output.
    */
    class MorseSender {
    protected:
 const unsigned int pin;
 // The setOn and setOff methods would be pure virtual,
 // but that has compiler issues.
 // See: http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1167672075 .

 /**
  * Called to set put the output in 'on' state, during a dit or dah.
  */
 virtual void setOn();
 virtual void setOff();

 /**
  * Called before sending a message. Used for example to enable a
  * carrier. (Noop in the base class.)
  */
 virtual void setReady();
 virtual void setComplete();

    private:
 morseTiming_t DIT, DAH;
 String message;

 // on,off,...,wait,0 list, millis
 morseTiming_t timingBuffer[MAX_TIMINGS+1];

 // index of the character currently being sent
 unsigned int messageIndex;
 // timing unit currently being sent
 unsigned int timingIndex;

 // when this timing unit was started
 unsigned long lastChangedMillis;

 /**
  * Copy definition timings (on only) to raw timings (on/off).
  * @return the number of 'on' timings copied
  */
 int copyTimings(morseTiming_t *rawOut,
  morseBitmask_t definition);

 /**
  * Fill a buffer with on,off,..,END timings (millis)
  * @return the index at which to start within the new timing sequence
  */
 unsigned int fillTimings(char c);

    public:
 /**
  * Create a sender which will output to the given pin.
  */
 MorseSender(unsigned int outputPin, float wpm=WPM_DEFAULT);

 /**
  * To be called during the Arduino setup(); set the pin as OUTPUT.
  */
 void setup();

 /**
  * Set the words per minute (based on PARIS timing).
  */
 void setWPM(float wpm);

 /**
  * Set the duration, in milliseconds, of a DIT.
  */
 void setSpeed(morseTiming_t duration);

 /**
  * Set the message to be sent.
  * This halts any sending in progress.
  */
 void setMessage(const String newMessage);

 /**
  * Send the entirety of the current message before returning. See the "simple"
  * example, which uses sendBlocking to send one message.
  */
 void sendBlocking();

 /**
  * Prepare to send and begin sending the current message. After calling this,
  * call continueSending repeatedly until it returns false to finish sending
  * the message. See the "speeds" example, which calls startSending and
  * continueSending on two different senders.
  */
 void startSending();

 /**
  * Switch outputs on and off (and refill the internal timing buffer)
  * as necessary to continue with the sending of the current message.
  * This should be called every few milliseconds (at a significantly
  * smaller interval than a DIT) to produce a legible fist.
  *
  * @see startSending, which must be called first
  * @return false if sending is complete, otherwise true (keep sending)
  */
 boolean continueSending();

 void *operator new(size_t size);
 void operator delete(void* ptr);
    };

    /**
    * Adapt Morse sending to use the Arduino language tone() and noTone()
    * functions, for use with a speaker.
    *
    * If a carrierFrequency is given, instead of calling noTone, call tone
    * with a low frequency. This is useful ex. for maintaining radio links.
    */
    class SpeakerMorseSender: public MorseSender {
 private:
  unsigned int frequency;
  unsigned int carrFrequency;
 protected:
  virtual void setOn();
  virtual void setOff();
  virtual void setReady();
  virtual void setComplete();
 public:
  // concert A = 440
  // middle C = 261.626; higher octaves = 523.251, 1046.502
  SpeakerMorseSender(
   int outputPin,
   unsigned int toneFrequency=1046,
   unsigned int carrierFrequency=CARRIER_FREQUENCY_NONE,
   float wpm=WPM_DEFAULT);
    };

    /**
    * Sends Morse on a digital output pin.
    */
    class LEDMorseSender: public MorseSender {
 protected:
  virtual void setOn();
  virtual void setOff();
 public:
  LEDMorseSender(int outputPin, float wpm=WPM_DEFAULT);
    };

    /**
    * Sends Morse on an analog output pin (using PWM). The brightness value is
    * between 0 and 255 and is passed directly to analogWrite.
    */
    class PWMMorseSender: public MorseSender {
 private:
  byte brightness;
 protected:
  virtual void setOn();
  virtual void setOff();
 public:
  PWMMorseSender(int outputPin, float wpm=WPM_DEFAULT, byte brightness=255);
  void setBrightness(byte brightness);
    };

morse.cpp

    // Morse Code sending library

    #include <morse.h>

    // MorseSender
    int MorseSender::copyTimings(
 morseTiming_t *rawOut,
 morseBitmask_t definition)
    {
 int t = 0;
 boolean foundSentinel = false;
 for(morseBitmask_t mask = MORSE_BITMASK_HIGH_BIT;
  mask > 0; mask = mask >> 1)
 {
  boolean isDah = (mask & definition) > 0;
  if(!foundSentinel)
  {
   if (isDah) { foundSentinel = true; }
   continue;
  }
  rawOut[2*t] = isDah ? DAH : DIT;
  rawOut[2*t + 1] = DIT;
  t++;
 }
 return t;
    }
    unsigned int MorseSender::fillTimings(char c)
    {
 int t = 0;
 unsigned int start = 0;
 if (c >= 'a' && c <= 'z')
 {
  t = copyTimings(timingBuffer, MORSE_LETTERS[c-'a']);
 }
 else if (c >= '0' && c <= '9')
 {
  int n = c - '0';
  boolean ditsFirst = (n <= 5);
  if (!ditsFirst)
  {
   n -= 5;
  }
  while(t < 5)
  {
   timingBuffer[2*t] = ((t < n) == ditsFirst) ? DIT : DAH;
   timingBuffer[2*t + 1] = DIT;
   t++;
  }
 }
 else
 {
  int s = 0;
  while(MORSE_PUNCT_ETC[s].c != END)
  {
   if(MORSE_PUNCT_ETC[s].c == c)
   {
    t = copyTimings(timingBuffer,
     MORSE_PUNCT_ETC[s].timing);
    break;
   }
   s++;
  }
  if (MORSE_PUNCT_ETC[s].c == END)
  {
   start = t = 1; // start on a space
  }
 }

 timingBuffer[2*t - 1] = DAH;
 timingBuffer[2*t] = END;

 return start;
    }

    // see note in header about pure-virtual-ness
    void MorseSender::setOn() {};
    void MorseSender::setOff() {};

    // noop defaults
    void MorseSender::setReady() {};
    void MorseSender::setComplete() {};

    MorseSender::MorseSender(unsigned int outputPin, float wpm) :
 pin(outputPin)
    {
 setWPM(wpm);
    }

    void MorseSender::setup() { pinMode(pin, OUTPUT); }

    void MorseSender::setWPM(float wpm)
    {
 setSpeed((morseTiming_t)(1000.0*60.0/(max(1.0, wpm)*DITS_PER_WORD)));
    }

    void MorseSender::setSpeed(morseTiming_t duration)
    {
 DIT = max(1, duration);
 DAH = 3*DIT;
    }

    void MorseSender::setMessage(const String newMessage)
    {
 message = newMessage;

 // Force startSending() before continueSending().
 messageIndex = message.length();

 // If a different message was in progress, make sure it stops cleanly.
 if (timingIndex % 2 == 0) {
  setOff();
 }
    }

    void MorseSender::sendBlocking()
    {
 //Serial.println("Sending blocking: ");
 //Serial.println(message);
 startSending();
 while(continueSending());
    }

    void MorseSender::startSending()
    {
 messageIndex = 0;
 if (message.length() == 0) { return; }
 timingIndex = fillTimings(message[0]);
 setReady();
 if (timingIndex % 2 == 0) {
  setOn();
  //Serial.print("Starting with on, duration=");
 } else {
  //Serial.print("Starting with off, duration=");
 }
 lastChangedMillis = millis();
 //Serial.println((int)timingBuffer[timingIndex]);
    }

    boolean MorseSender::continueSending()
    {
 if(messageIndex >= message.length()) { return false; }

 unsigned long elapsedMillis = millis() - lastChangedMillis;
 if (elapsedMillis < timingBuffer[timingIndex]) { return true; }

 timingIndex++;
 if (timingBuffer[timingIndex] == END)
 {
  messageIndex++;
  if(messageIndex >= message.length()) {
   setOff();
   setComplete();
   return false;
  }
  timingIndex = fillTimings(message[messageIndex]);
 }

 lastChangedMillis += elapsedMillis;
 //Serial.print("Next is       ");
 if (timingIndex % 2 == 0) {
  //Serial.print("(on) ");
  setOn();
 } else {
  //Serial.print("(off) ");
  setOff();
 }
 //Serial.println((int)timingBuffer[timingIndex]);

 return true;
    }

    void *MorseSender::operator new(size_t size) { return malloc(size); }
    void MorseSender::operator delete(void* ptr) { if (ptr) free(ptr); }

    // SpeakerMorseSender

    void SpeakerMorseSender::setOn() { tone(pin, frequency); }
    void SpeakerMorseSender::setOff() {
 if (carrFrequency == CARRIER_FREQUENCY_NONE) {
  noTone(pin);
 } else {
  tone(pin, carrFrequency);
 }
    }
    void SpeakerMorseSender::setReady() { setOff(); }
    void SpeakerMorseSender::setComplete() { noTone(pin); }
    SpeakerMorseSender::SpeakerMorseSender(
 int outputPin,
 unsigned int toneFrequency,
 unsigned int carrierFrequency,
 float wpm)
 : MorseSender(outputPin, wpm),
 frequency(toneFrequency),
 carrFrequency(carrierFrequency) {};

    // LEDMorseSender

    void LEDMorseSender::setOn() { digitalWrite(pin, HIGH); }
    void LEDMorseSender::setOff() { digitalWrite(pin, LOW); }
    LEDMorseSender::LEDMorseSender(int outputPin, float wpm)
 : MorseSender(outputPin, wpm) {};

    // PWMMorseSender

    void PWMMorseSender::setOn() { analogWrite(pin, brightness); }
    void PWMMorseSender::setOff() { analogWrite(pin, 0); }
    void PWMMorseSender::setBrightness(byte bright) {
 brightness = bright;
    }
    PWMMorseSender::PWMMorseSender(
  int outputPin,
  float wpm,
  byte bright)
 : MorseSender(outputPin, wpm), brightness(bright) {};

And finally, here is my code:

    #include <avr/pgmspace.h>
    #include <MorseEnDecoder.h>
    #include <stdio.h>
    #include <morse.h>
    #define PIN_STATUS  13
    #define CPU_RESTART_ADDR (uint32_t *)0xE000ED0C
    #define CPU_RESTART_VAL 0x5FA0004
    #define CPU_RESTART (*CPU_RESTART_ADDR = CPU_RESTART_VAL);

    // Pin mapping
    const byte morseInPin = 7;
    const byte morseOutPin = 13;
    String check = "";
    String origin = "SOS";
    const int maxItems = 3;
    int x;
    char myArray[maxItems], curChar;
    char nextChar;
    int i;
    int y;

    // Instantiate Morse objects
    morseDecoder morseInput(morseInPin, MORSE_KEYER, MORSE_ACTIVE_LOW);
    morseEncoder morseOutput(morseOutPin);

    // Variables dealing with formatting the output somewhat
    // by inserting CR's (carriage returns)
    long lastTransmissionTime;
    long currentTime;
    boolean transmissionEnded = true; // Flag to mark old transmission is finished

    // Minimum transmission pause time to insert carriage returns (CR)
    // Adjust depending on Morse speed. IE 13 wpm = 646 ms between words (no CR).
    const long transmissionPaused   = 1000; // Suitable for 13 wpm?

    LEDMorseSender sender(PIN_STATUS);

    void setup()
    {
      Serial.begin(9600);
      Serial.println("Morse EnDecoder Geocache");

      // Setting Morse speed in wpm - words per minute
      // If not set, 13 wpm is default anyway
      morseInput.setspeed(5);
      morseOutput.setspeed(5);

      lastTransmissionTime = (long)millis();
    }

    void(* resetFunc) (void) = 0; //declare reset function @ address 0

    void loop()
    {
      currentTime = (long)millis();

      // Need to call these once per loop
      morseInput.decode();
      morseOutput.encode();

      // RECEIVE MORSE (INPUT)
      // If a character is decoded from the input, write it to serial port
      if (morseInput.available())
      {
        char receivedMorse = morseInput.read();
        Serial.print(receivedMorse);
        // A little error checking
        if (receivedMorse == '#') Serial.println("< ERROR:too many morse signals! >");
        morseOutput.write('#');
        morseOutput.encode();

        //Create Array out of receivedMorse Chars

        curChar = 0;
        nextChar = receivedMorse;
        curChar += nextChar;
        myArray[i] = curChar;
        check.concat(myArray[i]);
        Serial.println(check);

        //Check input and respond
        if (check == origin)      //GOOD JOB!!  Your reward is as follows
        {
          Serial.println("check = origin");
          Serial.println(check);
          sender.setup();
          sender.setWPM(5);
          sender.setMessage(String("help is coming"));
          sender.startSending();
        }
        else if (check == "S") {}
        else if (check == "SO") {}
        else if (check == " SOS") {}
        else if (check.length() > 4)
        {
          delay(100);
          Serial.println("resetting");
          delay(500);
          resetFunc();  //call reset
          delay(100);
        }
        else {}
      }
      sender.continueSending();
    }

title: Code will not run when Serial Monitor is not open

Answers: 1

body: It would appear that with this code, the serial.print commands were interfering with the code running as strange as that seems.  I was able to delete the offending serial commands and now the code works.  With a few tweaks, it should be flawless.


body:
So I recently built a small IFTT powered button using an ESP8266 for my boys to play with. Tonight during an intense Thunderstorm, I kept getting alerts that it had been pressed. They weren't in the basement at all. Then I realized, giant crack of lightening === SMS message.

Now I don't think this has anything to do with the button mechanism itself, but the shoddy way I hooked it up, and stuffed it into an enclosure. I'm just curious - is this possible? Could some sort of static electricity from a few nearby lightening strikes do something that would send a 'high' signal to the GPIO Pin on my Espee? I had to use a pull up resistor, and I feel like there's probably a few bare-ish wires in there, but nothing touching, or even close enough to 'arc'. Am I crazy?

title: Thunderstorm triggering button press?

Answers: 1

body:
You aren't crazy. I had a similar thing happen when an external hot-water system turned on at midnight (someone was having a shower) and one of my systems detected input unexpectedly (and rang a bell right next to my ear while I was trying to sleep).

My solution was to have something like this:

[![Input pin protection][1]][1]

The diodes clamp the input to acceptable ranges, and R1 is a current limit for the diodes. R2 and C1 are a filter that slows down the incoming signal (and thus eliminates sudden spikes). R3 is a pull-up resistor. In my case I had active-low. If you have active-high you could use a pull-down resistor instead.

Also see <https://arduino.stackexchange.com/a/13128/10794>

Further reference material:

* [10 Ways to Destroy An Arduino](http://www.ruggedcircuits.com/10-ways-to-destroy-an-arduino)

* [Protection](http://www.thebox.myzen.co.uk/Tutorial/Protection.html)

* [Microcontroller Input Protection Techniques](http://www.kevinmfodor.com/home/My-Blog/microcontrollerinputprotectiontechniques)

  [1]: https://i.stack.imgur.com/MRCZ8.png


body:
I am having a problem when using a `switch` statement to check for something inside an array. I am using an `int` as my switch, then I compare the character arrays using `strstr`. So it reads like this:
<!-- language-all: lang-cpp -->

    void function(char *buffer, uint32_t size){
      char *p=(char*)malloc(compareSize); //compareSize is the size of the text to be compared
      #define TXTCOMPARE1 (char*)"Sample Text 1"
      #define TXTCOMPARE2 (char*)"Sample Text 2"
      #define TXTCOMPARE3 (char*)"Sample Text 3"
      switch(intCompare){
        case COMPARE1 :
          p = strstr(buffer,TXTCOMPARE1); break;
        case COMPARE2 :
          p = strstr(buffer,TXTCOMPARE2); break;
        case COMPARE3 :
          p = strstr(buffer,TXTCOMPARE3); break;
      }
      if(p!=NULL) { Serial.println("Success!"); }
      else { Serial.println("No match"); }
        memset(&p,0,sizeof(p);
    }

This method does not work and `p` is always `NULL`. However, when I write it out without the `switch()` it compares just fine:

    //using the same p declaration as above
    p = strstr(buffer,TXTCOMPARE1);
    if(p != NULL) { Serial.print("Success:"); }
    else { Serial.print("No Match"); }

Why would the `switch` statement give me different results for what is basically the same function call?

**Edit:** Actually it seems to break everywhere when I set more than one call to `p = strstr(...)`. When there is only one `strstr` it works, when two or more are used, it does not...

title: Problem using an array inside a switch statement

Answers: 2

body:
I solved this problem, there were a few problems with the code that I found, so thanks for your comments.
Basically, it lies in the `#define#` statements.
First, in Arduino it's not such great practice to use `#define` for strings/chars, only for `int`. This is because the compiler applies the text every time they appear in the code, so it uses up a lot more memory. The problem here is solved by using
`static char TXTCOMPARE1 = {"Sample Text 1"};`

Another problem was that there was no `NULL` terminated character at the end of the `#define` statement, so the program kept looking to the end of the stack when using `strstr()` and finding no termination, I think I was just getting lucky that it worked occasionally at all.

Furthermore, there is no need to clear `p` using `memset`. It needs to be declared as `NULL` and then reset after the switch by
`if(p){p = NULL;}`.

And now it works!

body: One big problem is that you forgot the break statements for those cases.  So if it compares in the first one and finds it, you'll still get null because it is going to go look for the third one afterwards.


body:
I am using the following wiring diagram from a tutorial.  I need to follow this configuration because later tutorials build on this example.  I have looked at other solutions, but they follow a different pattern and I am still learning, so don't have the sophistication to adapt.  I've looked at:

[Hacktronics][1]
[StackExchange][2]

The picture shows Freeduino, but I am using an Arduino Uno (does that make a difference?)
[![Connection Diagram][3]][3]

Here is the code I am using:

    #include <LiquidCrystal.h>
    int rs = 3;
    int enable = 4;
    int d4 = 5;
    int d5 = 6;
    int d6 = 7;
    int d7 = 8;

    int rows = 2;
    int cols = 16;
    LiquidCrystal lcd (3, 4, 5, 6, 7, 8);

    void setup() {
      // put your setup code here, to run once:
      pinMode (rs, OUTPUT);
      pinMode (enable, OUTPUT);
      pinMode (d4, OUTPUT);
      pinMode (d5, OUTPUT);
      pinMode (d6, OUTPUT);
      pinMode (d7, OUTPUT);
      lcd.begin(cols, rows);
      lcd.clear();
    }

    void loop() {
      // put your main code here, to run repeatedly:
      lcd.setCursor(0,0);
      lcd.print("Hello World");
      delay(1000);
      lcd.setCursor(0,1);
      lcd.print("Goodbye World");
      delay(1000);
    }

Unfortunately, I am getting a blank screen (it is lit up, but blank).  So questions:

1. Is the diagram correct?

2. Is the code the problem?

3. What else should I look for?

  [1]: https://www.hacktronics.com/Tutorials/arduino-character-lcd-tutorial.html
  [2]: https://arduino.stackexchange.com/questions/3625/why-is-my-lcd-162-is-not-displaying-any-characters-although-all-the-wiring-is
  [3]: https://i.stack.imgur.com/bIdBX.jpg

title: LCD 16x2 Blank Display

Answers: 2

body:
1) Diagram seems to be fine. However we don't see pin numbering on LCD. Sometimes pins are like:  `15 16 1 2 3 4 ... 14` (at least pin 1 is usualy marked).

2) Library should take care of inputs or outputs. So you can remove pinModes for them. Also change variables to constant variables and use them for lcd initialization: `LiquidCrystal lcd(rs, enable, d4, d5, d6, d7);`

3) Potentiometer in diagram is contrast setting. You have to preset correct value for it. Start with everything is black and find value where this black is almost invisible. If you've something displayed on LCD, it would be even easier to find right position as text just shows up.

Edit: I've just tested it and it's working fine. With the same wiring and contrast pot adjusted to the right position

body:
Check the voltage. your LCD should get 5v to work properly.

if you are powering it through your computer USB, Arduino could be outputting less than 5v.

PS: it happened to me yesterday.