text:
Arduino IDE won't upload sketches
I recently updated my Arduino IDE to 1.8.5 from 1.6.9. I am getting issues with uploading sketches. The sketch compiles, but when I try to upload it I get this message:
Arduino: 1.8.5 (Mac OS X), Board: "Arduino/Genuino Mega or Mega 2560,
ATmega2560 (Mega 2560)"

Sketch uses 642 bytes (0%) of program storage space. Maximum is 253952 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 8183 bytes for local variables. Maximum is 8192 bytes.
java.io.IOException: Cannot run program "___REMOVE___/bin/avrdude": error=2, No such file or directory
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
    at java.lang.Runtime.exec(Runtime.java:620)
    at java.lang.Runtime.exec(Runtime.java:485)
    at processing.app.helpers.ProcessUtils.exec(ProcessUtils.java:11)
    at cc.arduino.packages.Uploader.executeUploadCommand(Uploader.java:129)
    at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:207)
    at cc.arduino.UploaderUtils.upload(UploaderUtils.java:78)
    at processing.app.SketchController.upload(SketchController.java:713)
    at processing.app.SketchController.exportApplet(SketchController.java:686)
    at processing.app.Editor$DefaultExportHandler.run(Editor.java:2168)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.io.IOException: error=2, No such file or directory
    at java.lang.UNIXProcess.forkAndExec(Native Method)
    at java.lang.UNIXProcess.<init>(UNIXProcess.java:247)
    at java.lang.ProcessImpl.start(ProcessImpl.java:134)
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
    ... 10 more
An error occurred while uploading the sketch

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

I get this message whether or not an Arduino is connected. I also get the same message weather I connect my Arduino Mega or Uno. I tried my sketch, the blink sketch and a completely blank sketch, all with the same results.
Could I please get some help with this issue?

The sketch compiled but it could not be uploaded to the Arduino board.  While I suspect it is not the reason for the error, did you select the correct port and board in the IDE?

yes, I used the usb port and arduino/genuino mega board from the board menu.

You may be able to fix this by taking some drastic action. Be aware this is somewhat advanced and will remove any boards you have installed via Boards Manager:

Click the link on the line following File > Preferences > More preferences can be edited directly in the file. This will open the Arduino15 (or similar name depending on OS) folder.
Delete all files and folders under the Arduino15 folder except for preferences.txt. Please be very careful when deleting things from your computer. When in doubt, back up!
Restart the Arduino IDE.
Verify you can now upload before re-installing any boards via Boards Manager.

where could I find arduino 15 on a mac, I can't seem to find the file

Follow the first step of my instructions exactly.


text:
How to stop extra LEDs from lighting in LED cube
So I build LED cubes and the way I have it programmed is I use an analog pin for the ground layers and set them to high when i want an led on that layer lit up. So lets say I wanted the following LEDs lit

But in reality the LEDs light up in all the layers that are set to high obviously so this is what actually ends up lighting

What should I incorporate in order to avoid this happening. I am using an Arduino Nano, do I need to edit my code or is it hardware?

You turn on one, turn it off, then turn the next one on and turn it off. Do that very fast and it looks like they are both lit.

Doesnt work because im spinning the cube around fast so 1 millisecond is noticeable

Then you will need to change the circuit so each LED is directly wired, and not in a matrix. If you can't use matrix multiplexing then you can't use a matrix. Simple.

There has to be a better way that i can control parts of the leds and still have a sturdy design thats a cube

You don't have a cube, you have a square. And if you are spinning it then multiplexing won't, as you have noted, work well. You have the choice of multplexing (flicker, few wires) or non multiplexing (no flicker, lots and lots of wires).

You may need to go back to the drawing board. Maybe the way you are designing whatever it is you are designing is wrong.

I know a better way of designing what im making but it requires a lot more work. I was just wondering if there was a special way to control each LED but thank you for the help so i didnt waste more time finding a method that doesnt work haha

The only way you could use multiplexing would be to have the frequency really really high. I'm talking MHz range. You may be able to find a driver chip that does that.

Do you want to turn those comments into an answer and ill give you the dub

I have come up with another option - I'll detail it in my answer.

Your circuit design has to be used with multiplexing. Multiplexing introduces flicker. Since you seem to be wanting to move the grid of LEDs rapidly that flicker will translate into a very undesirable effect.
So you have a number of choices:

Re-design your system so that you don't use multiplexing. With each LED directly driven you get zero flicker, but you end up with as many wires and GPIO pins needed as you have LEDs (although shift registers could be used to move the bulk of the wiring closer to the LEDs). That's impractical.
Use multiplexing but have the frequency so high that flickering is no longer noticeable. We're talking thousands or millions of loops per second to keep it looking smooth (depending on how fast you are spinning the grid). You would need a high speed multiplex driver chip for this.
Time your multiplexing to the spinning of the grid.

The third option relies on quite a high rate of spin, since your multiplexing increments one column or row for each revolution. With 5 columns to work through it would take 5 revolutions to work through the entire grid.
You need some way of identifying the start of each revolution (e.g., a hall-effect sensor), and each time you start a new revolution you illuminate just one column of LEDs. The faster you spin the smoother the effect will be.
If you want to have LEDs on or off for just part of the revolution it's then down to you to work out when to turn them on or off for that one specific column. That's when the fun really begins.

Upvoted. Just a remark about 1: you can use e.g. 74HC595's (in daisy chain mode) to upto 32 LEDs with a few pins. Although you need to wire from those 74HC595's to each LED (lots of wires).

@MichelKeijzers Indeed. Plus of course you'd probably then be spinning those around really fast as well, which adds to the instability of the whole thing. Not ideal.

Not ideal indeed :-)

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Arduino uno shift register
I have shift register 74HC595. I added 7 push buttons from Q1-7 and the 8th to ground. On the other side which pin of the register will go to Arduino pin 2? And wich one to the 5v pin?
How can I read one button at a time in the code because on the Arduino it is just 1 pin?

my problem is that i have a lot off buttons 16 how can i do it a 4x4 buttons - do you have 7 buttons or 16 buttons?

You cannot.  The 74HC595 does not have parallel inputs, such as you would need to read from 7 switches.
You need a parallel-in, serial-out shift register, such as a CD4021B.  You can find details on how to use it with an Arduino here

How can I read one button at a time in the code because on the Arduino it is just 1 pin?

Basically you "clock in" the data by toggling a clock line - each toggle presents the next bit, which you read in using your one digital input.

Okay , my problem is that i have a lot off buttons 16 how can i do it a 4x4 buttons with there values to send them to windows form

And does it work with just the arduino pins?

How many unused digital pins do you have on your Arduino?

I think i just need the grnd and the 5v , i dont have anything attached to the arduino just the buttons , my goal is to play a game i created with those buttons

If you post another question, asking how to connect 8 switches to an Arduino, I'll answer it - since it's a different question and this one has already been answered.

Just one. I have a 4x4 labels in C# on each button press i want to change its color

Okay I'll post a new question

OK. If you want to encourage people to help you further, then if your question has been answered (never mind that it wasn't the question that you should have asked) you should accept one of the correct answers and optionally up-vote any which have been helpful.

I can 't post the question always the red box pop out

I don't know what that means. You could almost certainly Google for how to connect many switches to an Arduino, though - and you should do research before posting the question!

Thanks for the help man , i'm really paniking now tomorrow i have ti present my project

So i need to put multiple switches with just the arduino i can get a multiplexer now

You don't need a multiplexexer. Ask another question about how to connect 8 switches to an Arduino. Maybe you'll get lucky and someone will answer - I'm going to bed. If not, think how much you'll learn about planning :-)

A shift register is an output device. You won't be able to "Read" 7 push buttons in this way.
A shift register like that is for taking a "series" of bits on one wire and parallelizing them onto 8 wires.
It does not work in reverse. The reverse is called a multiplexer.

so using this shift register can i send data from C# to arduino code as bytes  ? I just want to compare values on my C# with values given when i press a button .

That's nonsense, jose.  See my answer re types of shift registers.

Shift registers are available in several flavors:
• Serial-in, Serial-out (SISO) units like 7491 have serial input and output.
• Serial-in, parallel-out (SIPO) units like 74164 have serial input, parallel output.
• Parallel-in, Serial-out (PISO) units like 74165 or 74166 (etc. – just search for shift register in a list of 7400 series integrated circuits or other series) have parallel input, serial output.
Other variations: The 7494, 7495, and 7499 have serial and parallel input, parallel output.  The 7499 also has serial output.  The 7494 and 7499 can shift right or left.  (Most of the models listed earlier only shift one direction.)
Anyhow, by using an appropriate shift register, along with a bunch of resistors and diodes, it is possible to read lots of switches.  As suggested in another answer, you might want to ask about how to do that.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Splitting a float into bytes for storage in FRAM (like EEPROM)
I'm trying to write floats to I2C FRAM (like I2C EEPROM) but without result. I tried with this function but I lose all number after the decimal. Thank's for replying.
This for writing:
float floatNumber = 123.123;
byte floatPt1 = 0;
byte floatPt2 = 0;
byte floatPt3 = 0;
byte floatPt4 = 0;
byte b1 = (floatNumber);
byte b2 = (floatNumber >> 8);
byte b3 = (floatNumber >> 16);
byte b4 = (floatNumber >> 24);

This is for reading:
long floatRicomposto = 0;
floatPt1 = fram.read8(3);
floatPt2 = fram.read8(4);
floatPt3 = fram.read8(5);
floatPt4 = fram.read8(6);
//float RECOMPOSITION
floatRicomposto = (uint32_t) floatPt1 <<  0
  | (uint32_t) floatPt2 <<  8
  | (uint32_t) floatPt3 << 16
  | (uint32_t) floatPt4 << 24;

I solved it with the use of UNION:
//---------------------------------------------------------
union Scomp_float {
  // si utilizza union x float
  float temp;
  char byte_s[4];
} S_float;

//---------------------------------------------------------
//-------------------------FLOAT--------------------------------
float mioFlo = 123456.29;
byte f0 = 0;  // contengono i byte del float
byte f1 = 0;
byte f2 = 0;
byte f3 = 0;
S_float.temp = mioFlo;
f0 = S_float.byte_s[0];
f1 = S_float.byte_s[1];
f2 = S_float.byte_s[2];
f3 = S_float.byte_s[3];
Serial.println(f0);
Serial.println(f1);
Serial.println(f2);
Serial.println(f3);
fram.writeEnable(true);
fram.write8(7, f0);
fram.writeEnable(false);
fram.writeEnable(true);
fram.write8(8, f1);
fram.writeEnable(false);
fram.writeEnable(true);
fram.write8(9, f2);
fram.writeEnable(false);
fram.writeEnable(true);
fram.write8(10, f3);
fram.writeEnable(false);
S_float.byte_s[0] = fram.read8(7); // si ricompone il float
S_float.byte_s[1] = fram.read8(8);
S_float.byte_s[2] = fram.read8(9);
S_float.byte_s[3] = fram.read8(10);
float masterFloat = S_float.temp;
Serial.println(masterFloat);
//-------------------------FLOAT--------------------------------

You are using an array in the S_float union but not for the variables f0.  you could use a loop for the fram writes.

A pointer can be used to easily decompose and reconstitute any multi byte type, like a float.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
LED sequence control by button
I want to make sequential LED by using arduino that controlled by button.
If I press + button, LED will increase from L1 to (L1 and L2 is HIGH), then I press button again, L1, L2, and L3 will be HIGH. If I press again, all the LED (L1, L2, L3, L4) will be high.
Same case if I press “ – “ button, LED will be lower from the previous state. Which mean that if L1, L2, and L3 is HIGH. There will be L1 and L2 only HIGH if I press ‘ – ‘ button. I dont how to do it. This is code for increase but I dont know how to make it reverse flow.
const int buttonPin = 2; // the pin number of the pushbutton input pin
int ledPins[] = {3, 4, 5,};
 // variables will change:
 int buttonState = 0; // variable for reading the pushbutton status
 int buttonPressCount = 0;
 int numberOfLED = 3;
 void setup() {
  // initialize the LED pin as an output:
  for (int i = 0; i < numberOfLED; i++) {
   pinMode(ledPins[i], OUTPUT);
  }
  pinMode(buttonPin, INPUT);
 }
 void loop() {
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);
  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (buttonState == HIGH) {
   for (int i = 0; i < numberOfLED; i++) {
    if (buttonPressCount % numberOfLED == i) {
     // turn LED on:
     digitalWrite(ledPins[i], HIGH);
    } else {
     // turn LED off:
     digitalWrite(ledPins[i], LOW);
    }
   }
   buttonPressCount++;
   delay(400);
  }
 }

My original answer was probably over-kill....Just keep track of how many leds are lit:
int ledPins[] = {3, 4, 5,};
const int num_leds = sizeof(ledPins) / sizeof(ledPins[0]);  // 3 in this example
byte num_leds_lit = 0

void set_leds() {
    for (int i = 0; i < num_leds; i++) {
        digitalWrite(ledPins[i], i < num_leds_lit ? HIGH : LOW);
    }
}

Then, on button press, increase the count:
if (num_leds_lit < num_leds) {
    num_leds_lit += 1;
    set_leds();
}

Then to turn the leds off with the other button press:
if (num_leds_lit > 0) {
    num_leds_lit -= 1;
    set_leds();
}

------------------------- Original answer
There are a few ways to do it. One way would be to use a bitmask. I would write a function to turn the leds on/off
// Each bit represents the state of one LED (0 == off, 1 == on)
byte led_bits = 0;
int ledPins[] = {3, 4, 5,};
const int num_leds = sizeof(ledPins) / sizeof(ledPins[0]);  // 3 in this example
// Need a mask to make sure we don't set too many bits
const byte led_mask = 0xFF >> 8 - num_leds;   // 00000111B in this case

void set_leds() {
    for (int i = 0; i < num_leds; i++) {
        // Turn on/off based on state of bit
        digitalWrite(ledPins[i], (1 << i) & led_bits ? HIGH : LOW);
    }
}

Then, on button press, set the mask:
led_bits << = 1;          // Shift left (001 -> 010)
led_bits |= 1;            // Set lsb    (010 -> 011)
led_bits &= led_mask;     // Ensure max bits: (1111 -> 0111)
set_leds();

Then to turn the leds off with the other button press:
led_bits >>= 1;          // Shift right (011 -> 001)
set_leds();


text:
How to on/off light dimmer using another pin?
In recent project, I'm working with light dimmer.
Let me explain with example of fan. In switch board, we have a fan switch which can able to ON/OFF our fan & FAN REGULATOR which vary speed of our fan. Now, when our switch ON then our fan start and then with help of regulator we can vary speed of fan. And when we switch OFF then our fan stop and we can't do anything means not vary fan speed. Same things I want in my light dimmer. One push button pressed once then it's just start my light dimmer and vise versa operation. And When push button pressed again then it's just stop my light dimmer.
Here is my full code.
int kPinPWM = 9; // This pin provides PWM values

int kPinSW1 = 6; // PUSH BUTTON // This pin used for increase PWM values
int kPinSW2 = 7; // PUSH BUTTON // This pin used for decrease PWM values

int kPinSw = 10; // PUSH BUTTON // This pin used for ON/OFF PWM pin means ON/OFF pin 9

int i = 0;

int temp = 0; // Flag

void setup()
{
  pinMode(kPinPWM, OUTPUT);

  pinMode(kPinSW1, INPUT);
  pinMode(kPinSW2, INPUT);

  digitalWrite(kPinSW1, HIGH);
  digitalWrite(kPinSW2, HIGH);

  pinMode(kPinSw, INPUT);

  digitalWrite(kPinSw, HIGH);
}

void loop()
{
  if(digitalRead(kPinSw) == LOW && temp == 0) //If I pressed PUSH BUTTOPN(PIN 10) and temp = 0
  {
    temp = 1; // Change value to 1 // temp = 1

    digitalWrite(kPinPWM, HIGH); // Turn ON PWM pin (PIN 9)

    if(digitalRead(kPinSW1) == LOW) // Pressed PUSH BUTTON to increase PWM value
    {
      i++;

      if(i > 4)
      {
        i = 4;
      }

      while(digitalRead(kPinSW1) == LOW); //Until PUSH BUTTON pressed
    }

    if(digitalRead(kPinSW2) == LOW) // Pressed PUSH BUTTON to decrease PWM value
    {
      i--;

      if(i < 0)
      {
        i = 0;
      }

      while(digitalRead(kPinSW2) == LOW); //Until PUSH BUTTON pressed
    }

    switch (i)
    {
      case 0:
              analogWrite(kPinPWM, 0); // When Button pressed not pressed send 0 value
      break;

      case 1:
              analogWrite(kPinPWM, 64); // When Button pressed and i = 1 send 64 value
      break;

      case 2:
              analogWrite(kPinPWM, 128); // When Button pressed and i = 2 send 128 value
      break;

      case 3:
             analogWrite(kPinPWM, 192); // When Button pressed and i = 3 send 192 value
      break;

      case 4:
             analogWrite(kPinPWM, 255); // When Button pressed and i = 4 send 255 value
      break;
    }
  }

  if(digitalRead(kPinSw) == LOW && temp == 1) //If I pressed PUSH BUTTOPN(PIN 10) and temp = 1
  {
    temp = 0; // Change value to 0 // temp = 0

    digitalWrite(kPinPWM, LOW); Turn OFF PWM pin (PIN 9)
  }
}

Do you mean you want pins 9 and 10 to BOTH be able to dim and switch on/off a light?  If so you just need to wrap you code in a function and take the pin number as a parameter.

Do you mean you want to use pin 10 as an input to control the PWM output, or do you want to use pin 10 as an output to control if the PWM signal gets to the light or not?

@Matt Yes, exactly. Ok, I will try.

@Majenko I want to make pin 10 as input pin which just ON/OFF pwm pin 9. Not controlling the PWM just control PWM pin. Means using pin 10 just ON/OFF PWM pin 9. Suppose, I pressed PIN 10 then it's ON PWM pin 9 and I can able to dim and vise verse of my light. And when I pressed PIN 10 again then it's OFF PWM pin 9 and then no operation performed.

@Hasan - The way I read it, your answer to me and to Majenko say two different things.  I still have no idea what you want, sorry.

Please explain what you want the three buttons to do. Also explain what the code is doing. What the code is not doing. Or what the code is doing wrong. Also, the first if statement inside the loop function seems very odd. It looks like you need to keep the button pressed for any of the other buttons or code to work at all.

@matt Ok, let me explain some things.

@Gerben Ok, understand your things. Let me clear the things.

I've give you an upvote for the comments.  In future enum may help you right even clearer code (rather than using ints to define states).  I'm still looking into the code.

Finally I find out solution. Here, I detect when switch becomes pressed instead of  button is pressed. So, for that I used StateChangeDetection. So while loop just removed from code. And I made function to perform dimmer and vise versa operation.
k
So, now I'm able to ON/OFF the PWM pin. And also vary PWM pin. Thanks everyone for your effort.
Here, it's my full code.
const int buttonPin1 = 2;
const int buttonPin2 = 3;
const int buttonPin3 = 4;

const int pwmPin = 9;

const int onOffPin = 10;

int buttonState1 = 0;
int lastButtonState1 = 0;

int buttonState2 = 0;
int lastButtonState2 = 0;

int buttonState3 = 0;
int lastButtonState3 = 0;

int buttonPushCounter = 0;

int onOffCounter = 0;

void setup()
{
   pinMode(buttonPin1, INPUT);
   pinMode(buttonPin1, INPUT);

   pinMode(pwmPin, OUTPUT);

   pinMode(onOffPin, OUTPUT);

   Serial.begin(9600);
}

void loop()
{
   buttonState3 = digitalRead(buttonPin3);

   if(buttonState3 != lastButtonState3)
   {
     if(buttonState3 == HIGH)
     {
       onOffCounter++;
       Serial.println("Button 3 on");
       Serial.print("number of button 3 pushes:  ");
       Serial.println(onOffCounter);
     }
     else
     {
       Serial.println("Button 3 off");
     }
     delay(50);
   }

   lastButtonState3 = buttonState3;

   if(onOffCounter % 2 == 0)
   {
     Serial.println("Switch is OFF");

     analogWrite(pwmPin, 0);
   }
   else
   {
      PWM_fun();

      Serial.println("Switch is ON");
   }
}

void PWM_fun()
{
  buttonState1 = digitalRead(buttonPin1);

  if (buttonState1 != lastButtonState1)
  {
    if (buttonState1 == HIGH)
    {
      buttonPushCounter++;
      Serial.println("Button 1 on");
      Serial.print("number of button 1 pushes:  ");
      Serial.println(buttonPushCounter);

      if(buttonPushCounter > 4)
      {
         buttonPushCounter = 4;
      }
    }
    else
    {
      Serial.println("Button 1 off");
    }
    delay(50);
  }

  lastButtonState1 = buttonState1;

  buttonState2 = digitalRead(buttonPin2);

  if(buttonState2 != lastButtonState2)
  {
    if(buttonState2 == HIGH)
    {
      buttonPushCounter--;
      Serial.println("Button 2 on");
      Serial.print("number of button 2 pushes:  ");
      Serial.println(buttonPushCounter);

      if(buttonPushCounter < 0)
      {
         buttonPushCounter = 0;
      }
    }
    else
    {
      Serial.println("Button 2 off");
    }
    delay(50);
  }

  lastButtonState2 = buttonState2;

  switch (buttonPushCounter)
  {
      case 0:
              analogWrite(pwmPin, 0);
      break;

      case 1:
              analogWrite(pwmPin, 64);
      break;

      case 2:
              analogWrite(pwmPin, 128);
      break;

      case 3:
              analogWrite(pwmPin, 192);
      break;

      case 4:
              analogWrite(pwmPin, 255);
      break;
  }
}

Thank you for the clarification.
Here's some code which should do that:
int kPinPWM = 9; // This pin provides PWM values

int kPinSW1 = 6; // PUSH BUTTON // This pin used for increase PWM values
int kPinSW2 = 7; // PUSH BUTTON // This pin used for decrease PWM values

int kPinSw = 10; // PUSH BUTTON // This pin used for ON/OFF PWM pin means ON/OFF pin 9

// Startup settings:
int level = 0;          // Lowest level
boolean on = false;     // Off

void setup()
{
  pinMode(kPinPWM, OUTPUT);

  pinMode(kPinSW1, INPUT);
  pinMode(kPinSW2, INPUT);
  pinMode(kPinSw, INPUT);

  digitalWrite(kPinSW1, HIGH);
  digitalWrite(kPinSW2, HIGH);
}

void loop()
{
    // Read each button in turn
    if(digitalRead(kPinSW1) == LOW) // Pressed PUSH BUTTON to increase PWM value
    {
       level++;

       if(level > 4)
       {
         level = 4;
       }

       while(digitalRead(kPinSW1) == LOW); //Until PUSH BUTTON released
    }

    if(digitalRead(kPinSW2) == LOW) // Pressed PUSH BUTTON to decrease PWM value
    {
       level--;

       if(level < 0)
       {
         level = 0;
       }

       while(digitalRead(kPinSW2) == LOW); //Until PUSH BUTTON pressed
    }

    if(digitalRead(kPinSw) == LOW ) // Pressed PUSH BUTTON to switch on/off
    {
        // If we're already on, switch off.
        if (on) on=false;
        // If we're already off, switch on.
        else on=true;

        while(digitalRead(kPinSW1) == LOW); // Until button is released
    }

    // Now set the PWM output
    if (on)
    {
        // We're on, so set the level
        switch (level)
        {
            case 0:
                // Maybe you don't want this "off" level..?
                analogWrite(kPinPWM, 0);
            break;

            case 1:
                analogWrite(kPinPWM, 64);
            break;

            case 2:
                analogWrite(kPinPWM, 128);
            break;

            case 3:
                analogWrite(kPinPWM, 192);
            break;

            case 4:
                analogWrite(kPinPWM, 255);
            break;

            default:
                // This should never happen but we should
                // handle it "just in case"
                analogWrite(kPinPWM, 255);
        }
    }
    else
    {
        // We're off, so stop the PWM
        analogWrite(kPinPWM, 0);
    }
}

We hold two variables: the level, and on/off state.
Buttons 6 and 7 affect the level, and button 10 affects the on/off state.
As with a fan, this code lets us change the "level" even when it's switched off.  It has no immediate effect, but when you switch back on, the level will have changed.

Some things to say about the question in general:

Try to explain more clearly exactly what you want to achieve.  For example, what exactly do you want button 10 to do?  Switch the PWM on?  On to what value?  I've chosen mid-way, but you could possibly want the highest value, or the lowest value, or the value it was last time you pressed button 10.
There's no need to comment code so literally.  We know literally what if(temp==0) does.  What would be helpful is to give things proper names, and/or explain their meaning.  What are you trying to achieve with temp?  (It wasn't clear to me at all, so I removed it.)

Ok, Let me explain more. Let me update my question more clearly with brief description. I hope that's may be clear your all doubt.

Thanks for the edits, but again we can see what the code does. Please try to explain, clearly and without lots of unnecessary detail, what you want it to do - the behaviour you want. I think you should be able to explain it in 5 lines of text.

Ok, get your point. Let me explain with example of fan. In switch board, we have a fan switch which can able to ON/OFF our fan & FAN REGULATOR which vary speed of our fan. Now, when our switch ON then our fan start and then with help of regulator we can vary speed of fan. And when we switch OFF then our fan stop and we can't do anything means not vary fan speed. Same things I want in my light dimmer. One push button pressed once then it's just start my light dimmer and vise versa operation. And When push button pressed again then it's just stop my light dimmer. I hope you understand.

I tried out your code. But it's not working as I want. Thank you again for your effort. I find out the solution. I will upload code and explanation.

Feel free to explain how it differs from what you want.


text:
How do I write the codes in #define in an IR Receiver circuit?
So I'm trying to turn an ON LED OFF or an OFF LED ON using a TV Remote. In the #define line, I write the hex code received from pressing the designated button on the TV remote. However, during compilation, an error saying unable to find numeric literal operator 'operator""DE74847' appears. I've scoured the web and can't come up with a solution.
#include <IRremote.h>
#include <IRremoteInt.h>
int ledPin = 13;
int IRPin = 3;

#define code1 0575

IRrecv irrecv(IRPin);
decode_results results;
void setup()
{
  Serial.begin(9600);
  irrecv.enableIRIn();
  pinMode(ledPin, OUTPUT);
}
void loop()
{
  if (irrecv.decode(&results))
  {
  unsigned int value = results.value;
  int ledState  = digitalRead(ledPin);
  switch(value)
  {
    case code1:
    if (ledState = HIGH)
    {
      digitalWrite(ledPin, LOW);
    }
    else
    {
      digitalWrite(ledPin, HIGH);
    }
    break;
  }
  }
  else
  {
    digitalWrite (ledPin, LOW);
  }
   unsigned int value = results.value;
  Serial.println(value);
    irrecv.resume();
}

Here's the code. Please help.

Could you add in the full error you receive, please?

Try putting the #define line before the #include lines.  If the define is being used in the included files they wont see it as it is now.

From the error you give, I can't see why you'd think the problem is with the define. It also seems like the code you've provided is different from the code that gave the error.

Check the error line number. It might be that you have entered characters that are not allowed in a literal number.

You have to prefix HEX numbers with 0x so the compiler knows it's HEX. 0575 is an octal number, not a HEX number. DE74847 is a random string of characters that it can't understand. Use 0xDE74847 instead.

Your problem is that you don't know how to form hexadecimal numbers.
In your code (in future, if you have an error in the code please post the code that is causing the error, not something else entirely - it makes it nigh on impossible for people without my psychic abilities to answer your question) you have defined a macro containing what you think is a hexadecimal number. In fact it's just a random string of characters and the compiler doesn't know what to make of it:
#define code1 DE74847

So in your switch construct, when code1 gets replaced with the content of the macro, you end up with:
switch (value) {
    case DE74847:
        ....

The compiler has no idea what a DE74847 is.
Numbers other than decimal numbers (0-9 and the decimal point) are identified by the use of a prefix:

0b... is binary
0 is octal (in your completely different code you have the number 0575, which is actually octal, and represents the decimal value 381)
0x is hexadecimal.

So adding 0x to the start of your hexadecimal value will tell the compiler to treat it as hexadecimal:
#define code1 0xDE74847


text:
I am making an easy game but something in my code is wrong
I am making a game where you need to push the button when the LED lights up but it is not registering the push at the right time. I need to push the button when LED is about to go off.
My code:
randNumber = random(2);

if(randNumber == 0){
  digitalWrite(9, HIGH);
  delay(1000);
  digitalWrite(9, LOW);
}

if (btnAddFirst.pressed() && randNumber == 0){
  Serial.println("You did it");
}
else {
  Serial.println("u failed");
}

Don't use delay(), since nothing can happen (not even reading a button) while that delay is running.
Instead use millis() as in the BlinkWithoutDelay example sketch.


text:
Connecting two analog multiplexers (CD4051b)
Is it possible to connect two CD4051b analog multiplexers together so that I can receive 14 analog inputs through  them? Just by using one analog pin and three digital pins on the Arduino UNO.

CD4051b is an analogue multiplexer, not a shift register.  Your question seems to suggest you want lots of analogue inputs, not a shift register.  Have you read (or seen) the data sheet?

Oh okay. Yes I need analog inputs. What is the best option I have.

Thanks -- I've edited your question to reflect what you really want. Can you tell us more about what signal(s) you're trying to multiplex (switch) please?

Okay the components I need to connect are - 5 LDR sensors. 5 PIR sensors and 3 ambient heat sensors.

I have used all my digital input pins and only have the 6 analog in pins left.

Each CD4052B multiplexes 8 input to one output, and you need three digial pins to control it.  You have the six analogue input pins available and those pins can also serve as digital outputs, so you should be able to use  them to do what you need.
I would do as follows:
Assign three of your spare pins to be digital outputs.  Use these three to address both CD4052Bs together -- so both devices will receive the same addressing.
Connect the output of one CD4052B to the fourth analogue pin, and the output of the second CD4052B to the fifth analogue pin.  These will be your inputs.
On both CD4052Bs, tie the INHIBIT pin low, so they are permanently on.  (If you want to be able to switch them off, for some reason, you an use your sixth pin to control the INHIBIT line on both devices.)
Now when you want to read from sensor 1, you set 000 on the address lines (A, B and C) and read from the first input.  At the same time you'll have sensor 9 on the second input.
It would be well worth reading the data sheet


text:
433mhz range optimization
I would like to get the best range possible from my 433MHz modules. After A LOT of searching and reading, I'm convinced I should be able to cover 10m indoors with free line of sight.
[update]
After some tips in the comments I changed a few things. It looks like with an Arduino receiving in stead of a Pi, I get an extra meter, 1,5m now so still terrible. And 'as a bang on the fire arrow' as we say in Dutch, I now use two whip antenna's parallel to each other.
Before moving to fix the reception on my Pi, I now first try to maximize the reception on the receiving Arduino. This makes it much more simple to investigate.
[update 2]
After some more tests I got to about 6 meters range. When the transmitter is behind 1cm of wood, this goes back to 30cm.
My current 433MHz modules are going into the garbage bin, I thank you all for your time. I will look for a more stable alternative and maybe try some other/better433MHz modules like these: http://www.ebay.com/itm/433MHz-Superheterodyne-RF-Link-kits-3400-ARM-MCU-Transmitter-and-Reveiver-/281169560721?hash=item4177030491:g:SUcAAOxyaTxTRKJn
[update 3]
The new modules made an enormous change. I can now send my data from across my house with no problems at all. No ground plane (will try that TwoD!) yet. Still on 5V transmitter voltage!
I've asked a question before about my 433MHz setup so for full disclosure:
433MHz sending not receiving
My current range is about 40/50cm, this is not much since I use a straight antenna ~17cm at the receiver and a coil antenna at the transmitter:
http://www.instructables.com/id/433-MHz-Coil-loaded-antenna/
These are the modules I use:
http://www.ebay.com/itm/-/221524421949?roken=cUgayN&soutkn=xKBBUo
And just FYI, I use these awesome working pumps:
http://www.ebay.com/itm/-/321779742264?roken=cUgayN&soutkn=hk1lrB
I have tried many antenna combinations and also upping the transmitter voltage to 12V but it doesn't help much. My aim is to reach 10m line of sight at the least.

I notice that my Pi outputs 4.77V to the receiver.
The 4 penlites now output around 5V so transmitter power is low.
What I also like to test is adding 10uF caps to the V and GND of the transmitter but I have to wait for them to get delivered.
I have the 10mw version of the transmitter, they may be just useless.
The receiver stands in front of a speaker and a subwoofer, I turn those off when I test.
The 433MHz modules came in pairs. I did not respect this and use any receiver with any transmitter, wonder if this is a problem. My end-goal is 3 transmitters on one receiver.
Since I have multiple Tx/Rx modules, I swapped them to exclude DOA modules.
Also tried these Helical antenna's, only made range worse; http://www.ebay.com/itm/-/171271811976?roken=cUgayN&soutkn=TmOnpH

My Arduino usses VirtualWire to send with 1000 baud to my Raspberry Pi, on the Pi side I use PIGPIO and the following code:
if __name__ == "__main__":

   import time
   import datetime
   import pigpio
   import vw
   import json
   import requests
   from requests.auth import HTTPDigestAuth

   # Setup receiving 433MHz port
   RX=27

   # Setup Baud rate 433MHz
   BPS=1000

   # Connect to local Pi.
   pi = pigpio.pi()

   # Specify Pi, rx gpio, and baud.
   rx = vw.rx(pi, RX, BPS)

   # Empty message
   msg = 0

   # Save the time
   start = time.time()

   # Run for 3 seconds
   while (time.time()-start) < 36000:

      # Count msg per cycle
      msg += 1

      # Sleep for .4 second
      time.sleep(0.4)

      # Run while receiver is ready
      while rx.ready():

         # String join received characters into message
         message = ("".join(chr (c) for c in rx.get()))

         # Print the received message to screen
         print(message)

         # Create data dictionary
         data = {}
         data['meting']    = message[8:11]
         data['bericht']   = message[4:7]
         data['plant']     = message[1:3]
         data['timestamp'] = str(datetime.datetime.utcnow().isoformat())

         # Print the data to the screen
         print(data)

         # Setup filename for local data backup
         filename = str('data/' + data['plant'] + data['bericht'] + data['meting'] + '.json')

         # Write JSON data file to disk
         with open(filename, 'w') as outfile:
            json.dump(data, outfile)

         # Sending data
         url = 'http://server:8000/v1/documents?database=plantjes&extension=json'

         # Setup headers
         headers = {
            'Content-Type': 'application/json'
         }

         # Execute request
         r = requests.post(url, json = data, auth=HTTPDigestAuth('plantje', 'password'))

         # Print request response
         print r

   # Cancel the receiving of data
   rx.cancel()

   # Stop PIGPIO listening on pins
   pi.stop()

This script sends the measurement of the Hygro sensor to a database in JSON. This works like a charm.
The Arduino uses this code:
#include <VirtualWire.h>
#include <Sleep_n0m1.h>

String pid = "p02";
const int led_pin = 11;
const int transmit_pin = 12;
const int hygroSensor = 0;
int hygroPower = 8;
const int pump_pin = 5;
int watering_level = 900;

int count = 0;
Sleep sleep;
unsigned long sleepTime;

void setup()
{
  // serial console setup
  Serial.begin(9600);
  Serial.println("setting up");

  // cycle sleep time in ms
  sleepTime = 10000;

  // virtualwire setup
  vw_set_tx_pin(transmit_pin);

  // setting of pin modes
  pinMode(hygroPower, OUTPUT);
  pinMode(led_pin, OUTPUT);
  pinMode(pump_pin, OUTPUT);

  // Bits per sec
  vw_setup(1000);
}

void loop()
{
  // delay to allow serial output to be ready after wake up
  delay(100);

  // cycle counter
  count++;

  // turn on hygro sensor module
  digitalWrite(hygroPower, HIGH);

  // wait a bit for hygro sensor to start
  delay(1000);

  // read the input on analog pin 0:
  int measure = analogRead(hygroSensor);

  // Start light to show transmitting
  digitalWrite(led_pin, HIGH);

  // log moment of sending
  Serial.println("Sending: " + String(measure));

  // create & send random message id
  String mid = "m" + String(random(100, 999));

  // Sending data
  String hygrodata = "d" + String(measure);
  dataSend(pid + mid + hygrodata);

  // Stop light to show transmitting
  digitalWrite(led_pin, LOW);

  // Wait a second
  delay(1000);

  // sleep code
  if(count >= 3)
  {
    // reset counter
    count = 0;

    // run pump routine
    //waterpump(measure, mid, pid);

    // log sleeping to serial console
    Serial.print("Going to sleep now..");

    // set sleep mode
    sleep.pwrDownMode();

    // turn off hygro module power
    digitalWrite(hygroPower, LOW);

    // sleep for: sleepTime
    sleep.sleepDelay(sleepTime);
  }
}

// Data sending funtion
int dataSend(String data) {
  // declare int for length of message
  int msglen;

  // set length of message +1
  msglen = data.length() + 1;

  // declare array of characters
  char envelope[msglen];

  // put string in array
  data.toCharArray(envelope, msglen);

  // log data to serial monitor
  Serial.println(data);

  // send data
  vw_send((uint8_t *)envelope, sizeof(envelope));

  // wait for sending to finish
  vw_wait_tx();

  // return 1 for succes
  return 1;
}

// Pump function
int waterpump(int measure, String mid, String pid) {
    // Log measure
    Serial.println(measure);

    // Water when needed
    if (measure > watering_level) {
      // Turn on pump 2 seconds
      digitalWrite(pump_pin, HIGH);
      delay(3000);
      digitalWrite(pump_pin, LOW);
      // Send pump data
      dataSend(pid + mid + "pump");
    }
}

This controls the sensing of the messages and also the water pump I use to water my plant automagically when needed. This also works like a charm.

That "helping hands" antenna stand is highly suspect - did you model that as part of the antenna?  It very much is, and probably not in a good way.  Try holding the board with the antenna projecting, and possibly an opposing ground wire of the same length, radials, or a ground plane - depending on what the theory of how your chosen antenna is supposed to work is.  That said, what is the usual range for these modules?

Have you tried receiving to an Arduino (with RX module) with serial printout to Pi? Just to compare the performance (assuming Pi is missing RX). I have several RF433/Arduino modules for sensor data transmitting over 5 m through up to three walls indoor (at 4000 bps, 3V7). This is with a modified version of VirtualWire with a Hamming(7,4) encoder with bit-error correction. Please see https://github.com/mikaelpatel/Cosa/blob/master/libraries/VWI/VWI.hh, https://github.com/mikaelpatel/Cosa/blob/master/libraries/HammingCodec_7_4/HammingCodec_7_4.hh and https://github.com/mikaelpatel/Cosa-Domotica.

the helping hands are just for the photo :) so I didn't have them there while testing. the usual range is 1 wall + 10 meters or 50m outside with two straight antenna's. but this is Google science...

Using an extra Arduino with the receiver I get messages further away. So this indicates that my Pi is the culprit. Now I'll try to dump the receiver on the Pi to the console to see what comes in..

I don't think you should combine helical and whip antennas. Also, building helical antennas requires a bit of precision in length, inner diameter, number of turns, spacing between turn, and probably more. I'd go with whip antennas on both sides, and make sure they are parallel to each other. I'd also experiment with the length of the antenna. Some people say you have to subtract the length of the little loop of wire already on the board. Just make it a bit to long, and keep cutting it shorter, and see what effects it has on range. Also more the units around; there may be dead spots.

The PI might be generating a lot of "background noise". Might need to protect the TX module from that.

You could've just made a loop like windings out of that antenna instead of that helping hands set-up. It really doesn't matter so much.

I've had the same problem, couldn't get past 2 meters range.
Until i noticed that the TX-Frequency was off by about 150kHz.
I adjusted the RX Frequency (the module has a trimmer) and now 40-50m is possible with a wall in between.

On the transmitting side (with cheap AC switches as receiver), I've actually had good results with the cheap green squares, and the equally cheap 5 for a dollar 'Helical antenna 433MHz' you find everywhere on ebay :)
I can reach all three levels of our house with that, and that's with only 5v supply on the green square, and it just sitting on a breadboard.
On request, picture of the antenna, soldered onto one of the cheap green  transmitters, this one works well for me on 5V:

This antenna was bought as a set of 5 from:
http://www.ebay.com/itm/171271811976
There's about 21 windings, with 5mm diameter, so that makes roughly 5mm * 3.14(=Pi) * 21 = 33 cm of wire in the coil.

could you please attach a picture of the antenna?

Done, see the answer

Keep in mind they're specific to a frequency, you want ones sold specifically for 433mhz :)

The wire length of the antena for 433mHz should be of 17.3 cm. There are online calculators for this, e.g.: https://m0ukd.com/calculators/quarter-wave-ground-plane-antenna-calculator/

The 433mhz modules can be sensible on the power lines, place a cap on the power input. Also a straight antenna works most of the times, but if you want some more distance, look into making a dipole antenna, there is a coil loaded diy antenna you can make that helps a little bit up from straight wire.

thanks! I was just reading about that cap on the power input, how and why it works. Wondering how much uF and why..

I've used anything from 10uF and up, it's for power smoothing so the value is not critical.

I have the same TX/RX modules and two Arduinos and can get pretty good transmission reliability all throughout my house but it took some experimenting to figure out the largest factors in play (for me).
Module pairs should not matter, I got my 5 pairs jumbled up in a plastic bag, think only one was DOA. I use them together with Nexa wireless electric outlets and remotes since they operate on the same frequency and give me a decent reference point.
One thing I've noticed about the [receiver] modules is that they tend to auto-adjust to the signal strength. Blast at them with a transmitter at close range for a while and they will become worse at picking out the signs, from the noise at long range for some time. This appears to be true of the 433Mhz Nexa devices too.
When starting to transmit from further away, it may take longer before the receiver figures out it's found a signal.
Remember, these modules output only 1 or 0, not an analog signal, so they have to decide which level of noise to accept as 0 and when there is a 1.
My first mistake was not using a well attached antenna. A simple piece of strong wire is good enough in itself, but only if it makes good contact with the module. Good soldering skills always  recommended.
My second mistake was not giving the transmitter enough power. It can handle 12V, so give it 12V (not on the data pin!). Only go lower after you got it to work at the needed distance.
Try with a large ground plane for both transmitter and receiver (no contact with the device itself!). I got a very good range with my receiver on my computer case and the transmitter on my fridge!
I could even get a reliable reading from a temp sensor from inside the garage 10m away from the house when getting about 2m off the ground, using 17cm plain straight wires as antennas with good ground planes. (Monopoles antennas need ground planes to bounce the signal off.)
Try visualizing the signal on the receiving side with an oscilloscope. If you gave an analog receiver it's probably easier to tell apart noise and real data. But if all you got is the RX module, hooking up the data pin to some kind of logged visualization will at least let you see how difficult it is to spot the data patterns.
Try increasing the length of your preamble before the actual data. It'll let the receiver adjust before it gets to the interesting bits.
Repeat your transmitted data. Include a piece of id data which changes with each message, but not with each repetition, and store the last received id for comparison before relaying it to wherever.

Have you ever tried the Nordic nRF24L01 based modules? They are available on eBay for very low cost, and operate in the 2.4 GHz band.  They should offer a range of at least tens of meters indoors.  I have had good success with these, and they are very easy to interface to Arduino.

I've ordered one of those to check it out! What I also have is an ESP8266 module but it seems to be more used as a stand-alone solution than as an Arduino module. Until the nRF24L01 is here, I'll be testing with that one.

Yes, ESP8266 is better suited to connecting to a wireless router.  The nRF chips are better suited to mesh-type networks.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Arduino Simple Task - sweeping a buzzer and led, not working as expected

Use of the tone() function will interfere with PWM output on pins 3 and 11 (on boards other than the Mega).

UPDATE: IT seems that there is a problem using pin 11 and 13 together but if I use a different pwm pin like pin 5. It's okay. I'm guessing that the timers used at pin 11 is connected to tone() but not sure...
I’ve encountered a weird problem with an Arduino with this simple task. It involves just a buzzer and LED and a very simple custom library that I made.
I wanted the buzzer to sweep back and forth with a specified frequency range (f1, f2), the led will also display a specific brightness (0, 50) based on the frequency being played.
The buzzer works perfectly on its own, and also the LED, but when you put them together, it malfunctions.
A more detailed explanation can be found here: https://tilarduino.wordpress.com/2015/11/27/weird-arduino-problem-buzzer-led-brightness/
And i've included all the files i've used here: https://gist.github.com/mithi/09ae419a3c7eba285221
Using this code below, commenting out line 19 with line 18 uncommented-out will make the buzzer work, and commenting out line 19 with line 18 back in will make the led work as expected. But together, the code malfunctions. buzzer is attached to pin 13 and led is attached to pin 11.
#include "SimplestLibrary.h"

Sweeper sweeper;
Buzzer buzzer;
AnalogLED led;

int f1 = 3000;
int f2 = 4500;
int f = 0;

void setup() {
    sweeper.New(f1, f2, BACKANDFORTH);
    buzzer.New(13);
    led.New(11);
}

void loop() {
    f = sweeper.Update(1);
    buzzer.Play(f, 4, 2);
    led.NewBrightness(map(f, f1, f2, 0, 50));
    delay(1);
}

From Arduino.cc:

Use of the tone() function will interfere with PWM output on pins 3 and 11 (on boards other than the Mega).

Simple solution is to use a PWM that isn't an output from Timer2 :
Timer      OCxA pin    OCxB pin
  0           6        5
  1           9        10
  2           11       3


text:
Simple compiler design help: Variable length arrays in Arduino?
I'm trying to write a simple compiler in the Arduino language that I am making up for my lab.  The compiler will have to be able to turn a string like this:
"do command_one 3 times"

into a data structure that represents this:
<command_one>, <command_one>, <command_one>

it should also be able to turn something more complicated like this:
"do do c_one do c_two 2 times 2 times c_thr 2 times"

into a data structure that represents this:
<c_one> <c_two> <c_two> <c_one> <c_two> <c_two> <c_thr> <c_one>
                <c_two> <c_two> <c_one> <c_two> <c_two> <c_thr>

Another function will then read the commands out one by one.
These examples show all of the functionality that I would want from the compiler.
I'm having design issues for the compiler that I want to create.  Initially, I just wanted to do some string manipulation and turn the input string into an array of integers representing commands.  However, since the compiler will be outputting an arbitrarily large number of commands, and since arrays in Arduino need to be initialized with a length, this could be a problem.
I am not fluent in Arduino so I am hoping that an Arduino whiz can show me a quick solution.  I have already come up with the suggested solution on my own in Python, however, my solution in Python has to do with the ability to change the length of lists on the fly.
You will also notice that I posted the same question in the C++ stackexchange.  I am trying to write the same code for an Arduino and in C++.  I know that Arduino code is based on C++, if the answer is the same in Arduino as it is in C++ that would be very helpful.

Arduino has full c++ language support, but does not have the standard library, so if your c++ answer is "use std::vector" you will need to find or write a separate vector implementation. Outside of implementation, the answers should be the same.

That's the only answer I've gotten so far.  If that continues to be the only answer then I'll have to find something else for the Arduino

Do you want to run your compiler on the Arduino ? That seems a bit odd.

Yes I do.  I want to be able to insert an SD card with the code and I want the arduino to compile it.

Posting the same question on multiple sites is not permitted.  Arduino is C++, but beware you have fairly extreme memory limitations.  Ordinarily one would want to do any compiling on the device where the text is being provided, and put only the distilled result into the limited resources of the traditional Arduino board.

Do you want the arduino to run the code afterward? You can't edit code memory while running on an AVR. What you may want instead is to write a very simple interpreter for some language you write to the SD card.

If you want to compile and run code from Arduino to Arduono, then the answer is simple: you can't. What you can potentially do however is parse a command line and get a series of lower-level instructions (a kind of bytecode like in Java) and then interpret them. But that's quite complex work, though.

I'm curious now: does Arduino support dynamic memory allocation with pointers like in standard C++?

@jfpoilpret, I don’t think the answer is that clear cut: First, every Arduino boot loader can and does modify program memory. Second, a compiler could compile to byte code in RAM, instead of machine code.

@AnnonomusPenguin yes it does, but because RAM is so scarce, the use of dynamic allocation is extremely rare. I think there might be only a single malloc in all Arduino libraries: https://github.com/arduino/Arduino/blob/3a8ad75bcef5932cfc81c4746a87ddbdbd7e6402/libraries/SD/File.cpp

@microtherion only code in the bootloader are can write code to the rest of the Flash (I think there are some ugly tricks to work around that but it is NOT advised, event by Atmel I believe). Regarding intermediate bytecode writing to SRAM, actually this is exactly what I was saying!

@microtherion, there are more locations in Arduino libraries that use dynamic allocation, the first that comes to my mind is String, which is why I avoid using String like the plague.

@jfpoilpret sorry about the byte code thing. Should not post when fatigued. I believe you're right about the bootloader restriction, but who says a compiler can't live (at least in part) in the bootloader section. Besides, OP was talking about Arduino Due, to which rather different rules may apply.

You may have more luck investigating standard C ways of dealing with this issue, instead of the common C++ methods.
Although it is typically not advised, you can use malloc and free on the Arduino. This allows you to dynamically use memory. I would provide a more detailed code example than below but when using dynamic memory it can be hard to troubleshoot what is going on without the use of a library to simplify the process. I would strongly advise doing a little study and understanding both dynamic memory management, and the repercussions of doing so on the Arduino platform. A solid foundation in this will pay off tenfold in time saved when debugging.
Note that you should check each time that you call malloc that it is successful
These resources might help:

Dynamic Arrays
Check Malloc Succeded
Malloc and Free on Arduino Discussion
Is it a bad idea?

Simple Example:
// Make a pointer to your array
someType *A;

// The size of your array, may be changed programmatically.
int arraySize = 5;

// Reserve memory for your array.
A = malloc(arraySize * sizeof(someType));

// Use Array
A[0] = someData;

// Release A's memory when complete.
free(A);

The Arduino IDE features nearly full C++ language support (at least for C++03 features).
library support is limited, but any standard component you need, you should be able to get an open source implementation that compiles.
That said, you have 2K of RAM to work with on an Arduino, so the kind of C++ code you would write for a general purpose computer just won’t get you very far.
I could be wrong, but I very much doubt there are full Python implementations for Arduino.

Edit: Thanks to Mr. Penguin for pointing out that we’re dealing with an Arduino Due, not an Uno (I had overlooked the OP’s tag). 96K of memory is actually a decent amount to play with, so grab a library implementation like this one and use the C++ techniques you wish to use.

You have 96 KB of RAM on the Due if I remember right, 2K is on the Uno. That still doesn't make it better...

You probably also have hardware capability to execute-from-ram.  It really changes the whole story.

You question isn't totally clear to me, so this is just a pile of advice:

I think that you might be looking for a run() type of command, where you can run any function in code. However, since C++ is a compiled language, this is not possible. You can only do this in scripting languages.
Besides that, you want a variable length array? I haven't been able to confirm that this works with Arduino, but I know in standard C++ it is called dynamic memory allocation and you can do this with a pointer.
As for the string to store your data, where you're heading is wrong if you care about efficiency. I'd go with an array of integers (unsigned int myData[2] = {1, 290};) since you can store a lot more data in two bytes than you could typing out the function names.

For the "multiple run" function of your language, a simple for loop might work better to save space:
for(int x = 5; x <3; x++) {
  //Code here
}

Another thing you might want to do is store this "code" on a SD card encoded in two characters to yield a number like this:
byte valOne = SD.read();
byte valTwo = SD.read();
int outputVal = (valOne << 8) + valTwo;

This would solve the whole variable array crisis in the first place.
End of unorganized thoughts...

For a while, "New" wasn't implemented, but it is now. "malloc" and "free" and the like have always been available on arduino for dynamic memory management. I don't use it often because with such a small amount of RAM I'm always worried about memory fragmentation, but I have used it.

@Brett nice to know! The OP is using a Due, so RAM should be sufficient for most cases.


text:
How to make timed loops after switch / case?
I am working on a code, which is running a function once a second:
switch (gearbox1) {
  case 1:
    //manually close
    Serial.println("Closing1");
    digitalWrite(gear1OpenPin, OFF);
    t.setTimer(1000, Close1, 1);

    break;

  case 2:
    //manually open
    Serial.println("Opening1");
    digitalWrite(gear1ClosePin, OFF);
    t.setTimer(1000, Open1, 1);

    break;

This part is working fine. But then i want at case 10: call function autoClose() which would work in 10 second cycles.
Struggle is, as my first function is called once a second, it is starting function autoClose() once a second as well. How can I overcome this please?
At the moment I have current, non working code:
  case 10:
    //automatic close
    Serial.println("A Close1");
    digitalWrite(gear1ClosePin, OFF);
    digitalWrite(gear1OpenPin, OFF);

    t.enable(autoClose);
    autoClose();
    break;

Edit: Added minimal possible code. I want autoOpen() and autoClose() to loop in 10 sec. intervals.
#include <SimpleTimer.h>
SimpleTimer t;
int gearbox1;

#define gear1OpenPin 44
#define gear1ClosePin 46

int OFF = HIGH;  // states for relays
int ON = LOW;

byte gear1Open = 0;
byte gear1Close = 0;

void setup() {

  t.setInterval(1000, Control1);
  int autoOpen = t.setInterval(10000, autoOpen);
  int autoClose = t.setInterval(10000, autoClose);
}

void loop() {

  t.run();
}

void Control1() {
  //*****************************************
  switch (gearbox1) {
    case 1:
      //manually close
      Serial.println("Closing");
      digitalWrite(gear1OpenPin, OFF);
      t.setTimer(1000, Close1, 1);

      break;

    case 2:
      //manually open
      //   Serial.println("Opening");
      digitalWrite(gear1ClosePin, OFF);
      t.setTimer(1000, Open1, 1);

      break;

    case 5:
      //stop
      Serial.println("Stopping");
      digitalWrite(gear1ClosePin, OFF);
      digitalWrite(gear1OpenPin, OFF);

      break;

    case 10:
      //automatic close

      digitalWrite(gear1ClosePin, OFF);
      digitalWrite(gear1OpenPin, OFF);
      if (t.isEnabled(autoClose)) {
        autoClose();
      } else {
        t.restartTimer(autoClose) ; t.enable(autoClose);
        autoClose();
      }
      break;

    case 20:
      //automatic open

      digitalWrite(gear1ClosePin, OFF);
      digitalWrite(gear1OpenPin, OFF);
      t.restartTimer(autoOpen); t.enable(autoOpen);
      autoOpen();
      break;
 }
}

void Open1() {
  digitalWrite(gear1OpenPin, ON);
}
//**********************************************
void Close1() {
  digitalWrite(gear1ClosePin, ON);
}
//**********************************************
void autoOpen() {

  if (gear1Open == ON) {
    gear1Open = OFF;
  } else {
    gear1Open = ON;
  }
  digitalWrite(gear1OpenPin, gear1Open);
}
//**********************************************
void autoClose() {
  if (gear1Close == ON) {
    gear1Close = OFF;
  } else {
    gear1Close = ON;
  }
  digitalWrite(gear1ClosePin, gear1Close);
}

You don't show Auto() function being called at all, yet you state it is starting once per second. Show all your code, or at least a complete working example that demonstrates the problem.

Sorry, function is autoClose. And t.enable is part of SimpleTimer library.

Create a new variable to hold the state of whether or not you are in autoClose mode:
uint8_t inAutoClose=0;

Then, add a line in your switch statement to set that flag when you enter that state, but not call the function if you were already in that state:
case 10:
  //automatic close
  Serial.println("A Close1");
  digitalWrite(gear1ClosePin, OFF);
  digitalWrite(gear1OpenPin, OFF);
  if (!inAutoClose) {
    inAutoClose = 1;
    t.enable(autoClose);
    autoClose();
  }
  break;

Add a line in your other switch branches to clear that flag:
case 1:
  //manually close
  inAutoClose = 0;
  [...]

If you want autoClose() to be called every 10 seconds repeatedly as the "idle" state, then you need to clear inAutoClose (set it to zero) at the end of every 10 second period. How and where you do that depends on other factors you haven't shown, like what autoClose() does, or what the timer you enable does.
Side note: avoid naming your timer name (autoClose) and your function name autoClose() the same! Does your code compile that way? It ought to throw an error.
ANSWER 2 (based on comments)
Your auto-close state is described as

Turns on for 10 seconds, after that off for 10 seconds.

This can be accomplished with a similar structure to what you have now, with a few changes. (These are my suggestions, but by no means the best or worst way.)
Edit your open and close functions:
void Open1() {
  digitalWrite(gear1OpenPin, ON);
  if (isAutoOpen) {
    t.setTimeout(10000UL, Close1); // Sets a timer to call closer in 10s
   }
}

void close1() {
  digitalWrite(gearClosePin, ON);
  if (isAutoOpen) {
    t.setTimeout(10000UL, Open1); // Sets a timer to call opener in 10s
  }
}

When you call either Open1() or Close1(), if your auto-open flag is set, then 10s later, the opposite function is called, and this keeps chaining together, every 10s.
Whenever it's time to stop this, you clear the isAutoOpen flag and disable the timers. You may wish to keep track of the timer ID that is created with the setTimeout() function, so you can disable it at any time to avoid the system going through the cycle one more time after you clear the flag.

Thank you a lot. One step closer.

If you want autoClose() to be called every 10 seconds repeatedly as the "idle" state, then you need to clear inAutoClose (set it to zero) at the end of every 10 second period.

This is little bit difficult, as all i do in that loop, changing states from HIGH to LOW.

Take a look at the setTimeout() function of SimpleTimer -- it's like the setInterval(), but is a one-shot. You can set a timeout at just under 10s and have it call a function that un-sets inAutoClose. As in t.setTimeout(9900UL, endAutoClose); where endAutoClose() is a function that just sets inAutoClose=0; You would call this setTimeout() function just before enabling the timer.

I tried that in separate simple sketch. The output was unpredictable .

In your updated example code, your switch statement switches on gearbox1, but you don't show how that value gets set to the various states. Could you update it again so that you show code that demonstrates your problem?

gearbox1 is value read from Nextion screen   gearbox1=myNextion.getComponentValue("G1");    What i am trying to achieve is, when case 10 (witch is checked once a second) run a 10 second loop turning output on and off. And the same with case 20, but different output. Tried different ways, one result is outputs changing in 1 second intervals or output blinks short on 10 second intervals. I don`t know how to post a code in comments, sorry.

Please explain "run a 10 second loop turning output on and off". The output turns on when? Stays on how long? Turns off when? "run a 10 second loop" is not clear.

Turns on for 10 seconds, after that off for 10 seconds. But i think, i have a solution, will try in couple of minutes. Could be easier than i think.


text:
How to make RGB LED blink rapidly one color using FOR or WHILE loop
I found a code that turns on different RGB colors but I would like it to blink rapidly one color once called. I dont want to use void loop function to make this possible. My RGB is a cathode. Any help?
int redPin = 8;
int greenPin = 9;
int bluePin = 10;

//uncomment this line if using a Common Anode LED
//#define COMMON_ANODE

void setup()
{
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(bluePin, OUTPUT);
}

void loop()
{
    for (int j = 0; j <= 10; j++) //LED simply stays on. No blinking occuring
     {
      setColor(255, 0, 0);
      delay(100);
      setColor(0, 0, 0);
        }
}

void setColor(int red, int green, int blue)
{
  #ifdef COMMON_ANODE
    red = 255 - red;
    green = 255 - green;
    blue = 255 - blue;
  #endif
  analogWrite(redPin, red);
  analogWrite(greenPin, green);
  analogWrite(bluePin, blue);
}

You need another delay as the last line in the for loop.  Currently it is turning it off and then immediately turning it on at the top of the loop.

give another delay after setColor(0,0,0).

Simply do this:
int redPin = 8;
int greenPin = 9;
int bluePin = 10;

//uncomment this line if using a Common Anode LED
//#define COMMON_ANODE

void setup()
{
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(bluePin, OUTPUT);
}

void loop()
{
  blinkLed();
}

void setColor(int red, int green, int blue)
{
#ifdef COMMON_ANODE
  red = 255 - red;
  green = 255 - green;
  blue = 255 - blue;
#endif
  analogWrite(redPin, red);
  analogWrite(greenPin, green);
  analogWrite(bluePin, blue);
}

void blinkLed()
{
  setColor(255, 0, 0);  // red
  delay(1000);
  setColor(0, 0, 0);  // off
  delay(1000);
}

This snippet will blink your led in the red color. Put it in your void loop and you are ready to go.
NOTE: Erase the rest of the void loop before putting this in. Don't delete the function though.
EDIT
FULL CODE ADDED

Is there a way to do this without using loop function? Say with a while or for loop? I'm actually using this function within a code.

Yes you can, simply insert it in whatever loop you want

I tried but the LED stays on

I've included the FULL code. If it doesn't work, describe in detail what happens.


text:
Button state issue
Let me preface this by saying I'm a beginner, and I know my code must have some logic errors. I need some fresh eyes on this, I have been messing with it a few days and am just running in circles at this point.
I'm trying to use buttons and button states to set hours and minutes of an alarm clock so I am trying to save the state of the buttons so after being pushed so it will remember the state rather than being changed on release.
I am trying to get it so pushing button A in my code goes into the alarm clock set procedure, then until button C is pressed it will loop to set hours then minutes (I havent added minutes procedure yet) So button A starts procedure and button C completes it, while button B increases the hours/minutes variable by one.
I have thoroughly confused myself. I have two "lastButtonState" variables which may be unnecessary but it was the only thing I could think of.
Right now with my code it goes into the button C while loop but doesn't come out of it on button press. My logic for that was that the while loop should exit when button C is pressed, so I don't think I need anything within the loop to break out of it.
I have the button B setting hours part working, it just isn't exiting the button C loop.
I'm eventually going to put this code in its respective function and add in the set minutes area after set hours area.
Here is my code:
#include <LiquidCrystal.h>

LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
//Constants
//const int buttonPin = 9;
const int buttonApin = 3;
const int buttonBpin = 2;
const int buttonCpin = 5;
int buttonState = 0;
int buttonState2 = 0;
int buttonState3 = 0;
//int flag = 0;
int alarmHoursInner = 1;
int lastButtonState = 0;
int lastButtonState3 = 0;
void setup() {
  // put your setup code here, to run once:
  lcd.begin(16, 2);
  Serial.begin(9600);
  //Input or output?
  pinMode(buttonApin, INPUT_PULLUP);
  pinMode(buttonBpin, INPUT_PULLUP);
  pinMode(buttonCpin, INPUT_PULLUP);
}

void loop() {
  // put your main code here, to run repeatedly:
  buttonState = digitalRead(buttonApin);
  buttonState2 = digitalRead(buttonBpin);
  buttonState3 = digitalRead(buttonCpin);

  if (buttonState == HIGH) {
    while (buttonState3 == LOW) {

      buttonState2 = digitalRead(buttonBpin);
      if (lastButtonState != buttonState2) { // last button state starts at 0 (or OFF) this line tests current state against last state
        if (buttonState2 == LOW) { // if buttonState is HIGH it went from OFF to ON
          // Serial.print("Button B works!");
          ++alarmHoursInner; // increments variable for hours
          Serial.print(alarmHoursInner); // prints hours
          Serial.println("  "); // blank line
          delay(50); // delay
        }
        else {

          Serial.print("Please push button B");
          Serial.println("  ");
        }
      }

      lastButtonState = buttonState2;
    }
      lastButtonState3 = buttonState3;
  }
}

start by renaming the buttons to some useful names that describe the function.... instead of buttonA, buttonB, buttonC call them something like mode, advance, exit .... modeButton, etc.

research Arduino state machine

Ok your input about renaming is noted, thanks! I have already looked at state changes pretty thoroughly. Could you point me in the direction of something specific about state machines that would help? I googled it and looked at a few links but what part of state machines should I focus on? So far, It looks like its what I have already known about states when I developed my code. What exactly is wrong with my code?

lastButtonState3 = buttonState3;  .... this line is indented too far, which makes it look like it is part of the if statement .... it is at the end of the while loop  ..... buttonState3 will always be LOW when this line executes


text:
A coding problem or improper interrupt usage?
As I should expect(?), the PIR on pin#2 should trigger the trigsensor state at any time the board is running. However, I may get one trigger then nothing else. I have a GSM shield on top of a UNO. I know that I still have some tweaking to do, but I'm trying to solve one issue at a time. Thanks for any insight. The other functions seem to perform correctly. When I enter an incorrect code, the alarms operates properly. When the interrupt is triggered, the alarm response should be the same.
///////////////////////// initialize & includes //////////////////////////
#include "SIM900.h"
#include "sms.h"
#include "Keypad.h"
#include <GSM.h>
SMSGSM sms;

boolean started = true;
int PIR_SensorPin = 2;
int Alarm_OutPin = 11; //green
int Light_OutPin = 12; //red
int alarm_count;
boolean volatile trigsensor = false;
const byte interruptPin = 2;
int z = 0;
int i = 0;

//////////////////////////// setup keyPad //////////////////////////
const byte ROWS = 4; // four rows
const byte COLS = 4; // four columns
char keys[ROWS][COLS] =
{
  {
    '1', '2', '3', 'A'
  }
  ,
  {
    '4', '5', '6', 'B'
  }
  ,
  {
    '7', '8', '9', 'C'
  }
  ,
  {
    '*', '0', '#', 'D'
  }
};
byte rowPins[ROWS] = {
  6, 7, A2, A3 // row pin# on keypad to Arduino pin#, ie Row Pin #1 goes to Arduino Pin #6, etc.
}; // connect to the row pinouts of the keypad
byte colPins[COLS] = {
  3, A0, A1, A4
}; // connect to the column pinouts of the keypad
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS );
const char PIN[5] = {
  '9', '6', '7', '9', '#'
}; // PIN number
char key_input[5] = {
  0, 0, 0, 0, 0
}; // used for comparison

//////////////////////////////// setup ///////////////////////////////////
void setup() {
  Serial.begin (9600);  // Establish Serial connection.
  pinMode (Alarm_OutPin, OUTPUT);   // Set pinMode.
  pinMode (Light_OutPin, OUTPUT);   // Set pinMode.
  pinMode (PIR_SensorPin, INPUT);   // Set pinMode.
  digitalWrite (Alarm_OutPin, LOW); // Set output pins to LOW for start.
  digitalWrite (Light_OutPin, LOW); // Set output pins to LOW for start.
  digitalWrite (PIR_SensorPin, LOW);
  Serial.println ("GSM Shield testing."); // Serial message that GSM shield is starting up
  if (gsm.begin(4800)) {    // Set GSM shield to recommended 4800 baud rate.
    Serial.println ("Status = READY");
    digitalWrite (Alarm_OutPin, HIGH);
    // PIR as interrupt
    attachInterrupt (digitalPinToInterrupt (2), trigger, RISING);
    //attachInterrupt ((0), trigger, RISING);
  }
  //  started = false; //////////////////////////////////////////////////////////////
  Serial.println ("System Ready, at the keypad loop!");
}

//////////////////////////////// void loop ///////////////////////////////////
void loop() {
  readKeypad();
}

////////////////////////////// void trigger ///////////////////////////////////
void trigger() {
  trigsensor = true;
  started = true;
}

//////////////////////////////// void alarm ///////////////////////////////////
void alarm() {
  Serial.println (started); Serial.println (trigsensor);
  //  digitalWrite (trigsensor, LOW);
  Serial.println("at Alarm");
  // while ((timedelay - time) > 0); Serial.println (time);  time++;
  if ((started == true) && (trigsensor == true)) {
    // (sms.SendSMS("**********", "***Motion Detected in Studio!***"));
    Serial.println ("MOTION detected: SMS Sent");
    for (alarm_count = 0; alarm_count < 5; alarm_count++) { // Cycle outputs if triggered
      digitalWrite (Alarm_OutPin, HIGH); delay (2000); // On/Off/On/Off/Off
      digitalWrite (Alarm_OutPin, LOW);
      digitalWrite (Light_OutPin, HIGH); delay (2000);
      digitalWrite (Light_OutPin, LOW); // End by turning off light
    }
    digitalWrite (Alarm_OutPin, HIGH);
  }
  else { }
  readKeypad();
}

//////////////////////////////// read Keypad ///////////////////////////////////
void readKeypad() {
  char key = keypad.getKey();
  if (key != NO_KEY) { // if a keypad input
    key_input[z] = key;
    Serial.print("Key_input["); Serial.print(z); Serial.print("] = "); Serial.println(key);
    z++;
    if (z >= sizeof(key_input)) {
      z = 0;
    }
    switch (key) {
      case '*': // resets key_inputs to "0"
        z = 0;
        break;
      case '#': // pressed to "enter"
        z = 0;
        for ( i = 0;   i < 4 ;  i++ ) {
          Serial.print(key_input[i]);
        }
        Serial.println ("-------");
        delay(100); // for extra de-bounce
        checkPIN();
        break;
    }
  }
}

//////////////////////////////// check PIN ///////////////////////////////////
void checkPIN() {
  Serial.println ("@ checkPIN ");
  int correct = 0;
  int i;
  for ( i = 0;   i < (sizeof(PIN) - 1) ;  i++ ) {
    if (key_input[i] == PIN[i]) {
      correct++;
    }
  }
  if (correct >= sizeof(PIN) - 1) {
    Serial.print ("# correct = "); Serial.println (correct); Serial.println (sizeof(PIN) - 1);
    correctPIN();
  }
  else {
    incorrectPIN();
  }
}

//////////////////////////////// correct PIN ///////////////////////////////////
void correctPIN() {              // do this if correct PIN entered
  Serial.println ("@ correct PIN ");
  started = false;
  digitalWrite (Alarm_OutPin, HIGH);
  readKeypad();
}

///////////////////////////// incorrect PIN ///////////////////////////////////
void incorrectPIN() {           // do this if incorrect PIN entered
  Serial.println ("@ incorrect PIN ");
  started = true;
  // add time delay before alarm, via keypad??
  alarm();
}

None of the code you posted ever sets trigsensor to false, besides the initial value.

Thanks, you are right. But I'm not sure where it should be placed, and why??

You are correctly doing little in the ISR: set a flag telling the main program to handle something. You should unset that flag when you are done doing handling the something you needed to handle.  Guessing from your code: in the alarm() function.

It seems as if the interrupt on pin 2 is not triggering the function. Not sure what is wrong.

I did make the change in the alarm function, but still not getting the interrupt to trigger.
}
trigsensor = false;
readKeypad();
}

What does the signal on the interrupt pin look like? You initialize it to trigger on a rising edge -- is that what is happening with the actual signal?

I have actually tried RISING and CHANGE, with no difference. The PIR is the sensor, and it is working OK. I don't have a scope to see the signal, but it reads 5vdc on a meter. And I can get the a Serial.print to show that it is "true". The problem that I am having, referring to the original sketch posted, is that the trigger is not being seen by the "alarm" function. I am still playing around with it and may find the problem. Thanks.

You never call the alarm() function in your code. Your loop() is only calling readKeypad() and readKeypad() never looks at trigsensor. Your ISR is only changing trigsensor and started. You need to add code in your loop() function to check trigsensor and if true, call alarm() or something.

THANKS! You nailed it! Not sure how I overlooked that, but thanks for your pair of eyes. On to debugging the rest.

Mark the question as answered so that it can be useful to others!

Maybe another problem for your eyes. I seem to get the alarm to cycle regardless of the state of trig sensor and away (they should both need to be true in order for the alarm to run after an incorrect code is entered):


text:
Arduino pins always reading HIGH (1)
I have tried changing pinModes and I/O declarations but still getting erratic or unexpected pin readings (HIGH), even though, I think, that I have set them LOW during setup. I read elsewhere that this is not uncommon, but I have not found a similar situation or a suitable explanation/solution. I can only believe that it is a basic misunderstanding (still learning). Thanks for any support. By the way, I had deleted the use of the keypad for trial purposes. My code is below:
//////////////////////////// Initialize & Includes //////////////////////////
#include "SIM900.h"
#include "sms.h"
#include "Keypad.h"
#include <GSM.h>
SMSGSM sms;
boolean pir_SensorPin = 2;
int led_OutPin = 11; // green
int alarm_OutPin = 12; // red
int alarm_count = 0;
boolean switchPin = 4; // alarm on test
boolean keypadPIN;
int z = 0;
int i = 0;
int waitTime = 5000;

//////////////////////////// Setup Keypad //////////////////////////
const byte ROWS = 4; // four rows
const byte COLS = 4; // four columns
char keys[ROWS][COLS] =
{
  {
    '1', '2', '3', 'A'
  }
  ,
  {
    '4', '5', '6', 'B'
  }
  ,
  {
    '7', '8', '9', 'C'
  }
  ,
  {
    '*', '0', '#', 'D'
  }
};
byte rowPins[ROWS] = {
  6, 7, A2, A3 // row pin# on keypad to Arduino pin#, ie Row Pin #1 goes to Arduino Pin #6, etc.
}; // connect to the row pinouts of the keypad
byte colPins[COLS] = {
  3, A0, A1, A4
}; // connect to the column pinouts of the keypad
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS );
const char PIN[5] = {
  '9', '6', '7', '9', '#'
}; // PIN number
char key_input[5] = {
  0, 0, 0, 0, 0
}; // used for comparison

//////////////////////////////// Setup ///////////////////////////////////
void setup() {
  Serial.begin (9600);  // Establish Serial connection;
  pinMode (switchPin, INPUT);       // Set pinMode.
  pinMode (led_OutPin, OUTPUT);     // Set pinMode.
  pinMode (alarm_OutPin, OUTPUT);   // Set pinMode.
  pinMode (pir_SensorPin, INPUT);   // Set pinMode.
  digitalWrite (led_OutPin, LOW);   // Set output pins to LOW for start.
  digitalWrite (alarm_OutPin, LOW); // Set output pins to LOW for start.
  digitalWrite (switchPin, LOW);
  digitalWrite (pir_SensorPin, LOW);
  Serial.println ("Studio Alarm starting up."); // Serial message that GSM shield is starting up
  if (gsm.begin(4800)) {    // Set GSM shield to recommended 4800 baud rate.
    Serial.println ("Status = Network READY");
    digitalWrite (led_OutPin, HIGH);
  }
  //  attachInterrupt (digitalPinToInterrupt (2), trigger, CHANGE); // PIR as interrupt
  Serial.println ("System Ready");

}

//////////////////////////// State Setup //////////////////////////
enum STATE {
  armed, // system acknowledges trigger
  unarmed, // system unarmed via keypad entry setting keypadPIN = LOW
  justActivated, // PIR-triggered
  alarm // confirm system unarmed then goto unarmed state else start alarm
};

STATE systemState = unarmed;
long timeGettingArmed;

/////////////////////////// Trigger ///////////////////////////////
//void trigger() {
//  systemState = alarm;

//////////////////////////// State Machine //////////////////////////
void loop() {
  check(); Serial.print ("switchPin = "); Serial.println (switchPin);
  Serial.print ("pir_SensorPin ="); Serial.println (pir_SensorPin);
  switch (systemState) {
    case armed:
      Serial.println ("armed");
      if (digitalRead (pir_SensorPin == HIGH)) {
        systemState = alarm;
      } else if (digitalRead (keypadPIN == LOW)) {
        systemState = unarmed;
      }
      break;
    case unarmed:
      if (digitalRead (pir_SensorPin == HIGH)) {
        Serial.println ("unarmed");
        timeGettingArmed = millis(); // Or just do a delay here.
        systemState = justActivated;
      }
      break;
    case justActivated:
      Serial.println ("juatActivated");
      if (timeGettingArmed + waitTime < millis()) {
        systemState = armed;
      }
      break;
    case alarm:
      Serial.println ("alarm");
      if (digitalRead (keypadPIN == LOW)) {
        systemState = unarmed;
      } else {
        beep();
      }
      break;
  }
}

//////////////////////////// Alarm //////////////////////////
void beep() {
  Serial.println("at beep");
  // (sms.SendSMS("**********", "*** Motion Detected in Studio! ***"));
  Serial.println ("MOTION detected: SMS Sent");
  for (alarm_count = 0; alarm_count <= 5; alarm_count++) { // Cycle outputs if triggered
    digitalWrite (alarm_OutPin, HIGH); delay (1000); // On/Off/On/Off/Off
    digitalWrite (alarm_OutPin, LOW); delay (500);
    digitalWrite (led_OutPin, HIGH); // delay (1000);
    Serial.println (alarm_count);
  }
  systemState = armed;
}

void check() {
  if (digitalRead (switchPin == HIGH)) { // manual test in lieu of keypad attached
    (keypadPIN = LOW); // unarmed
  }
  else {
    (keypadPIN = HIGH); // armed
  }
  Serial.print ("switchPin = "); Serial.println (switchPin);
  Serial.print ("keypadPIN = "); Serial.println (keypadPIN);
}

Serial output shows:
pir_SensorPin =1
switchPin = 1
keypadPIN = 1
switchPin = 1

Your code to read from the pins is incorrect. You write
if (digitalRead (pir_SensorPin == HIGH)) {

However, this compares pir_SensorPin == HIGH, (which is 2 == HIGH), producing a true or false that it then passes as the argument to digitalRead, which will try to interpret that as a pin number. Fix your parentheses:
if (digitalRead(pir_SensorPin) == HIGH)  {

(This problem occurs throughout your code.)
You also are writing an input pin in your setup, which is not necessarily wrong (it is one way of enabling or disabling the pullup resistor), but you should understand why you're doing it:
pinMode (pir_SensorPin, INPUT);   // Set pinMode.
...
digitalWrite (pir_SensorPin, LOW);

The effect of writing to an input pin enables or disables (disables in this case) the internal pullup resistor. In earlier versions of the Arduino API there was no INPUT_PULLUP mode, so writing to the input pin was common. I suppose there are still plenty of examples and tutorials that still tell you to do that.

Thanks to you both. I am in the process of implementing its changes and my parentheses issues.

Majenko, thanks for the useful explanation. I really do need to finish reading that whole data sheet and then the library source....

Still not able to get a functioning operation, as I expect. I have since grounded my two input pins, with no success. I am getting the following outputs:switchPin = 1
PIRtriggerCheck = 0
switchPin = 1
1
The PIRtriggerCheck doesn't seem to get triggered. Code follows:

Write the simplest possible program that sets up two pins as input pins and then, in a loop, reads them and prints out their values. Tie one to 5V and the other to ground, and ensure you're getting the right readouts. If it doesn't work, edit the question to include the simpler code that's not working. If it does work, gradually add bits to the program to bring it closer to the final version, testing after each small change.


text:
3D printer firmware version
Is there a way to determine which version of a Marlin firmware I would have installed onto my printer? I am trying to modify the existing arduino sketch rather than starting all over with a wrong, earlier version. Thanks.

First, check to see if the printer itself yields this information, either on LCD display if present, or by reporting it to a host computer upon connection (ie, try enabling verbose output in your printing software).
While it's not guaranteed to be supported, in practice many Arduino Mega based 3d printers have bootloaders capable of readback of the flashed contents, and the chips themselves are unlocked.  Even if the bootloader does not support this, an ISP connection might.
If you are able to read out the contents, you can have avrdude write them to a flat binary file, and examine it with the strings program or a hex editor.  If you end up with a hex file instead, there are tools for converting this to a flat binary.
Your goal would be to look through the file for version strings, and other messages which might indicate specifics, especially on which side of various points of change or configuration options it falls.
Making such a backup is a good idea before loading a new firmware anyway.  Ideally after verifying that you obtained meaningful contents, you would also readback a few distinct copies of the file and use something like diff to verify that they are all the same.  You can grab the EEPROM contents too, if your firmware may be storing things there.

Thanks. I can see the Marlin fw version in the lcd but not my arduino sketch version/name.

That may well not be saved.  Still, if you have a finite number of candidates you can try to look at details that would differentiate them.  Rebuilding and doing some kind of percentage fuzzy match comparison could work, but could also easily get confused by different compiler versions or build options.

Yeah, that’s what I assumed my option was. Thanks.


text:
Multiply char with float
I have a value for led brightness that is stored as an unsigned char (0-255)
unsigned char* colors[3];
colors[0] = 255;
colors[1] = 0;
colors[2] = 0;

I want to multiply a brightness percentage to that value.
float percent = 0.5;
auto red_brightness = colors[0] * percent

Since colors[0] is of type char and percent is of type float. It gives error Invalid operands of types 'unsigned char*' and 'float' to binary 'operator*'
unsigned char brightness;
float percent;
unsigned char* colors[3];

void setup() {
  Serial.begin(9600);
  colors[0] = 255;
  colors[1] = 0;
  colors[2] = 0;
}

void loop() {
    brightness = 127;
    float percent = (float)brightness / 255;
    float newRed = (float)colors[0] * percent;

    Serial.println(percent);
    Serial.print("red ");
    Serial.print(newRed);
    Serial.println("");
    delay(1000);
}

How can I multiply colors[0] (255) by 0.5 to get 127?

What I've tried

Cast colors[0] to a float or int

    # invalid cast from type 'unsigned char' to type 'float'

    float newRed = (float)colors[0] * percent;

strtod

Using this conversion website, I've tried converting like so:
    float tempColor = (float)strtod(colors[0],NULL);
    float newRed = tempColor * percent;

While this compiles, it always returns 0 (not 127 like I expect)
unsigned char brightness;
float percent;
unsigned char* colors[3];

void setup() {
  Serial.begin(9600);
  colors[0] = 255;
}

void loop() {
    brightness = 127;
    float percent = (float)brightness / 255;
    float tempColor = (float)strtod(colors[0],NULL); // <- returns 0.00

    Serial.print("tempColor");
    Serial.println(tempColor);
    delay(1000);
}

How can I multiply 255 by 0.5 to get ~127 ?

Solution
Thanks to the pointer by st2000 and this sparkfun article on datatypes
I avoided floating point and char arrays and converted everything to byte and now my code works as expected. Thank you
byte brightness;
byte percent;
byte colors[3];

void setup() {
  Serial.begin(9600);
  colors[0] = 255;
}
void loop() {
      percent = 50;
      auto foobar = colors[0] * percent / 100;
      Serial.print("foobar: ");
      Serial.println(foobar);

11:12:19.833 -> foobar: 127

Using "floats" is expensive both in required space and execution time.  Consider avoiding the problem entirely and use uint8_t or byte for everything.
Then just assume
percent = 50;

... is 50%.  Then try:
tempColor =  colors[0] * percent / 100;

... where all variables are of type uint8_t or byte.

@spuder, please follow  up to let us know if the above code suggestion works.  I think C uses type int for intermediate values in which case the worst expected case (255*100) should not exceed the limits of a type int variable.  Otherwise casting one of the variables to a type uint16_t would likely make the code more portable / less likely to break.

You wrote:

I have an led brightness that is stored as an unsigned char (0-255)
unsigned char* colors[3];

This is not an array of unsigned char, this is an array of
pointers to unsigned char. If you instead write
unsigned char colors[3];

Everything should work as expected.
But then, st2000 has very good advice on how to avoid expensive floating
point operations.

Oooo, good catch @edgar!


text:
Not waking up more than once?
I'm trying the following code on an Uno. I'm pulling the high side of a pull down 10K resistor to 5V, but it can only be woken once. Just once. Does anyone know why this might be the case?
It works fine if I use LOW for attachInterrupt along with a pull-up resistor though. Just not with RISING and a pull-down.
#include <avr/sleep.h>
#include <avr/power.h>

int pin2 = 2;

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

  /* Setup the pin direction. */
  pinMode(pin2, INPUT);

  Serial.println("Initialisation complete.");

}

void pin2Interrupt(void)
{
  /* This will bring us back from sleep. */

  /* We detach the interrupt to stop it from
   * continuously firing while the interrupt pin
   * is high.
   */
  detachInterrupt(digitalPinToInterrupt(pin2));
}

void enterSleep(void)
{

  sleep_enable();

  /* Setup pin2 as an interrupt and attach handler. */
  attachInterrupt(digitalPinToInterrupt(pin2), pin2Interrupt, RISING);
  delay(100);

  set_sleep_mode(SLEEP_MODE_PWR_DOWN);

  sleep_mode();

  /* The program will continue from here. */

  /* First thing to do is disable sleep. */
  sleep_disable();
}

int seconds=0;
void loop()
{
  delay(1000);
  seconds++;

  Serial.print("Awake for ");
  Serial.print(seconds, DEC);
  Serial.println(" second");

  if(seconds >= 3)
  {
    Serial.println("Entering sleep");
    delay(200);
    seconds = 0;
    enterSleep();
  }
}

I think I have seen somewhere in the past a problem with detaching an interrupt from within an interrupt handler.  You shouldn't need to detach and attach the interrupt handler all the time - just leave it attached.

@Majenko But you wouldn't want interrupts to keep firing whilst it's going to sleep, right?

I don't understand that question.  What do you mean by "going to sleep"? It's either asleep or awake. You need interrupts enabled while it's asleep so you can wake up. Does it really matter to you if an empty interrupt handler gets triggered if you press the button while it's awake?

Based on the examples here, it says "In the interrupt service routine (ISR) for a level interrupt, the interrupt must be detached otherwise the interrupt will keep happening and the ISR will be repeatedly called until the pin changes state." So it sounds like it's essential to detach - no?

Read the last word in your attachInterrupt call.  What does it say?

You mean RISING? Yeah, I'm trying to pull the pin high rather than low.

That means that the pin has to transition from low to high to trigger the interrupt.  It only does it at the moment the pin changes, not all the time it's HIGH. You have an EDGE interrupt, not a LEVEL interrupt. It will only trigger once per press of the button (discounting bounces).

Indeed. However, AFAIK, the Uno doesn't not support the HIGH argument. Is there an alternative? My chip pulls the interrupt high, so I thought LOW wouldn't be appropriate.

You are using the alternative! RISING means TRIGGER ONCE WHEN IT RISES which is what you want WITHOUT having to manually disable the interrupt!

I'm pulling the high side of a pull down 10K resistor to 5V, but it can only be woken once.  - you mean you are pulling it up, right?

@NickGammon Sorry. Yes, that's right.

So, really on a rising interrupt you want to put the 10k resistor to ground, yes? That's what I did in my test below.

For a RISING interrupt you never need to disconnect the interrupt to prevent repeat triggering.
A RISING interrupt specifically only triggers the once when the input pin transitions from LOW to HIGH rather than all the time it's in a state like a level interrupt.
Attach the interrupt once in setup() and leave it alone after that.  Your interrupt handler routine can be completely empty.  It will only ever be triggered at the exact moment you press the button.  To trigger it again you will just need to press the button again.

Probably your switch is bouncing and giving two interrupts. The first wakens it, and the second is lying there waiting until you attach the interrupt again. Then it fires, detaches the interrupt, then you go to sleep, never to awaken.
Clear any pending interrupt before doing the attachInterrupt:
EIFR = bit (INTF0);  // clear flag for interrupt 0

See Interrupts.
It is also wise to have interrupts off while setting up for sleep.

Example code:
#include <avr/sleep.h>

const byte LED = 13;

// interrupt service routine in sleep mode
void wake ()
{
  sleep_disable ();         // first thing after waking from sleep
}  // end of wake

void sleepNow ()
{
  set_sleep_mode (SLEEP_MODE_PWR_DOWN);
  noInterrupts ();          // make sure we don't get interrupted before we sleep
  sleep_enable ();          // enables the sleep bit in the mcucr register
  EIFR = bit (INTF0);       // clear flag for interrupt 0
  attachInterrupt (0, wake, RISING);  // wake up on rising edge
  interrupts ();           // interrupts allowed now, next instruction WILL be executed
  sleep_cpu ();            // here the device is put to sleep
  detachInterrupt (0);      // stop this interrupt until next time
}  // end of sleepNow

void setup ()
  {
  pinMode (LED, OUTPUT);
  }  // end of setup

void loop ()
  {
  sleepNow ();
  digitalWrite (LED, HIGH);
  delay (1000);
  digitalWrite (LED, LOW);
  }  // end of loop

Tested and works OK.

Note: Since this is a rising interrupt you should have a pull-down resistor on the pin, and you trigger the interrupt by connecting the pin to +5 V.