text:
Cast from uint8_t* to char - loses precision
I am trying to decode a received (via websocket) message (JSON) on my ESP8266.
The websocket library provides the data as uint8_t. The JSON library only understands char arrays. As far as I know uint8_t is basically char.
I am getting this error:
cast from 'uint8_t* {aka unsigned char*}' to 'char' loses precision [-fpermissive]
The websocket-function provides the payload as uint8_t:
void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length)

The JSON Decoder wants a char arr, as provides in the sample:
char json[] =
"{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}";

How to "convert" the uint8_t to char[]?
Here is my full code:
#include <ArduinoJson.h>
#include <ESP8266WiFi.h>
#include <WebSocketsServer.h>

WebSocketsServer webSocket = WebSocketsServer(81);
StaticJsonBuffer<200> jsonBuffer;

void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length) {

    switch(type) {
        case WStype_DISCONNECTED:
            Serial.printf("[%u] Disconnected!\n", num);
            break;
        case WStype_CONNECTED:
            {
                IPAddress ip = webSocket.remoteIP(num);
                Serial.printf("[%u] Connected from %d.%d.%d.%d url: %s\n", num, ip[0], ip[1], ip[2], ip[3], payload);

        // send message to client
        webSocket.sendTXT(num, "Connected");
            }
            break;
        case WStype_TEXT:
        {
            Serial.printf("[%u] get Text: %s\n", num, payload);
            JsonObject& root = jsonBuffer.parseObject((char)payload);
            // send message to client
            // webSocket.sendTXT(num, "message here");

            // send data to all connected clients
            // webSocket.broadcastTXT("message here");
        }
            break;
        case WStype_BIN:
            Serial.printf("[%u] get binary length: %u\n", num, length);
            hexdump(payload, length);

            // send message to client
            // webSocket.sendBIN(num, payload, length);
            break;
    }

}

void setup()
{
  Serial.begin(115200);
  Serial.println();
  IPAddress ip(192, 168, 178, 51);
  IPAddress gateway(192, 168, 178, 1);
  IPAddress subnet(255, 255, 255, 0);
  WiFi.config(ip, gateway, subnet);
  WiFi.begin("MyWifi!", "passpasspass");

  Serial.print("Connecting");
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println();

  Serial.print("Connected, IP address: ");
  Serial.println(WiFi.localIP());
  webSocket.begin();
  webSocket.onEvent(webSocketEvent);
}

void loop() {
   webSocket.loop();
  }

No, payload is a uint8_t*. Have you tried casting to char* yet?

Well, you are trying to cast pointer to uint8_t to one character, so it warns you about that. If you cast it to pointer to char, it should work:
JsonObject& root = jsonBuffer.parseObject((char *)payload);


text:
avr-gcc -D is ignored
Im trying to use XCode to compile avr program with arduino libs but seems like something wrong with my Makefile because it throws me warnings like
# warning "F_CPU not defined for <util/delay.h>"

but I use -D on CC and CXX which should define stuff I thought, here is my Makefile:
TARGET              = firmware
MCU                 = atmega32u4
F_CPU               = 16000000L
USB_VID             = 0x2a03
USB_PID             = 0x8036
USB_PRODUCT         = "USB Device"
USB_MANUFACTURER    = "Unknown"
ARDUINO_VERSION     = 107010

CC   =
CXX  = avr-g++
AR   = avr-ar
COPY = avr-objcopy
SIZE = avr-size
DUDE = avrdude

CFLAGS = -c -g -Os -w -ffunction-sections -fdata-sections -MMD -mmcu=$(MCU) -DF_CPU=$(F_CPU) -DARDUINO=$(ARDUINO_VERSION) -DARDUINO_AVR_LEONARDO -DARDUINO_ARCH_AVR -DUSB_VID=$(USB_VID) -DUSB_PID=$(USB_PID) -DUSB_MANUFACTURER=$(USB_MANUFACTURER) -DUSB_PRODUCT=$(USB_PRODUCT)

CXXFLAGS = -c -g -Os -w -fno-exceptions -fno-threadsafe-statics -MMD -mmcu=$(MCU) -DF_CPU=$(F_CPU) -DARDUINO=$(ARDUINO_VERSION) -DARDUINO_AVR_LEONARDO -DARDUINO_ARCH_AVR -DUSB_VID=$(USB_VID) -DUSB_PID=$(USB_PID) -DUSB_MANUFACTURER=$(USB_MANUFACTURER) -DUSB_PRODUCT=$(USB_PRODUCT)
all: compile

compile:

    $(shell $(CXX) $(CPPFLAGS) -I arduino -I arduino/variants/leonardo src/program.cpp -o build/program.cpp.o)

    $(shell $(CC) $(CFLAGS) -I arduino -I arduino/variants/leonardo arduino/hooks.c -o build/hooks.c.o)
    $(shell $(CC) $(CFLAGS) -I arduino -I arduino/variants/leonardo arduino/WInterrupts.c -o build/WInterrupts.c.o)
    $(shell $(CC) $(CFLAGS) -I arduino -I arduino/variants/leonardo arduino/wiring.c -o build/wiring.c.o)
    $(shell $(CC) $(CFLAGS) -I arduino -I arduino/variants/leonardo arduino/wiring_analog.c -o build/wiring_analog.c.o)
    $(shell $(CC) $(CFLAGS) -I arduino -I arduino/variants/leonardo arduino/wiring_digital.c -o build/wiring_digital.c.o)
    $(shell $(CC) $(CFLAGS) -I arduino -I arduino/variants/leonardo arduino/wiring_pulse.c -o build/wiring_pulse.c.o)
    $(shell $(CC) $(CFLAGS) -I arduino -I arduino/variants/leonardo arduino/wiring_shift.c -o build/wiring_shift.c.o)

    $(shell $(CPP) $(CPPFLAGS) -I arduino -I arduino/variants/leonardo arduino/abi.cpp -o build/abi.cpp.o)
    $(shell $(CPP) $(CPPFLAGS) -I arduino -I arduino/variants/leonardo arduino/CDC.cpp -o build/CDC.cpp.o)
    $(shell $(CPP) $(CPPFLAGS) -I arduino -I arduino/variants/leonardo arduino/HardwareSerial.cpp -o build/HardwareSerial.cpp.o)
    $(shell $(CPP) $(CPPFLAGS) -I arduino -I arduino/variants/leonardo arduino/HardwareSerial0.cpp -o build/HardwareSerial0.cpp.o)
    $(shell $(CPP) $(CPPFLAGS) -I arduino -I arduino/variants/leonardo arduino/HardwareSerial1.cpp -o build/HardwareSerial1.cpp.o)
    $(shell $(CPP) $(CPPFLAGS) -I arduino -I arduino/variants/leonardo arduino/HardwareSerial2.cpp -o build/HardwareSerial2.cpp.o)
    $(shell $(CPP) $(CPPFLAGS) -I arduino -I arduino/variants/leonardo arduino/HardwareSerial3.cpp -o build/HardwareSerial3.cpp.o)
    $(shell $(CPP) $(CPPFLAGS) -I arduino -I arduino/variants/leonardo arduino/HID.cpp -o build/HID.cpp.o)
    $(shell $(CPP) $(CPPFLAGS) -I arduino -I arduino/variants/leonardo arduino/IPAddress.cpp -o build/IPAddress.cpp.o)
    $(shell $(CPP) $(CPPFLAGS) -I arduino -I arduino/variants/leonardo arduino/main.cpp -o build/main.cpp.o)
    $(shell $(CPP) $(CPPFLAGS) -I arduino -I arduino/variants/leonardo arduino/new.cpp -o build/new.cpp.o)
    $(shell $(CPP) $(CPPFLAGS) -I arduino -I arduino/variants/leonardo arduino/Print.cpp -o build/Print.cpp.o)
    $(shell $(CPP) $(CPPFLAGS) -I arduino -I arduino/variants/leonardo arduino/Stream.cpp -o build/Stream.cpp.o)
    $(shell $(CPP) $(CPPFLAGS) -I arduino -I arduino/variants/leonardo arduino/Tone.cpp -o build/Tone.cpp.o)
    $(shell $(CPP) $(CPPFLAGS) -I arduino -I arduino/variants/leonardo arduino/USBCore.cpp -o build/USBCore.cpp.o)
    $(shell $(CPP) $(CPPFLAGS) -I arduino -I arduino/variants/leonardo arduino/WMath.cpp -o build/WMath.cpp.o)
    $(shell $(CPP) $(CPPFLAGS) -I arduino -I arduino/variants/leonardo arduino/WString.cpp -o build/WString.cpp.o)

    $(shell $(AR) rcs build/core.a build/hooks.c.o)
    $(shell $(AR) rcs build/core.a build/WInterrupts.c.o)
    $(shell $(AR) rcs build/core.a build/wiring.c.o)
    $(shell $(AR) rcs build/core.a build/wiring_analog.c.o)
    $(shell $(AR) rcs build/core.a build/wiring_digital.c.o)
    $(shell $(AR) rcs build/core.a build/wiring_pulse.c.o)
    $(shell $(AR) rcs build/core.a build/wiring_shift.c.o)
    $(shell $(AR) rcs build/core.a build/abi.cpp.o)
    $(shell $(AR) rcs build/core.a build/CDC.cpp.o)
    $(shell $(AR) rcs build/core.a build/HardwareSerial.cpp.o)
    $(shell $(AR) rcs build/core.a build/HardwareSerial0.cpp.o)
    $(shell $(AR) rcs build/core.a build/HardwareSerial1.cpp.o)
    $(shell $(AR) rcs build/core.a build/HardwareSerial2.cpp.o)
    $(shell $(AR) rcs build/core.a build/HardwareSerial3.cpp.o)
    $(shell $(AR) rcs build/core.a build/HID.cpp.o)
    $(shell $(AR) rcs build/core.a build/IPAddress.cpp.o)
    $(shell $(AR) rcs build/core.a build/main.cpp.o)
    $(shell $(AR) rcs build/core.a build/new.cpp.o)
    $(shell $(AR) rcs build/core.a build/Print.cpp.o)
    $(shell $(AR) rcs build/core.a build/Stream.cpp.o)
    $(shell $(AR) rcs build/core.a build/Tone.cpp.o)
    $(shell $(AR) rcs build/core.a build/USBCore.cpp.o)
    $(shell $(AR) rcs build/core.a build/WMath.cpp.o)
    $(shell $(AR) rcs build/core.a build/WString.cpp.o)

    $(shell $(CC) -w -Os -Wl,--gc-sections -mmcu=$(MCU) -o build/program.cpp.elf build/program.cpp.o build/core.a -Lbuild -lm)

    $(shell $(COPY) -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 build/program.cpp.elf build/program.cpp.eep)
    $(shell $(COPY) -O ihex -R .eeprom build/program.cpp.elf build/program.cpp.hex)

$(TARGET).bin: compile

    $(shell $(COPY) -O binary build/program.cpp.elf $(TARGET).bin)

clean:

Where did you read that you want to use $(shell ...) for all commands?

found in web, XCode show error " *** missing separator . Stop" if I not using shell

@user840250 Do you have a tabs as indents? Four spaces won't work in Makefile.

You're confusing CPP (the C PreProcessor, avr-cpp when called from avr-gcc or avr-g++) with CXX (avr-g++) with disastrous results.

You are using $(CPPFLAGS) for *.cpp files but only $(CXXFLAGS) are defined.
This should be obvious from command line (if you enable showing executed commands for make)
And also:

CC =
using $(CPP) again only $(CXX) is defined

And don't forget Makefile needs tabs for indenting target commands (here you have four spaces, but it might be just replaced by SE)

oh... seems like I need some sleep :) thanks.

source: Stack Exchange

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

sort: votes


text:
Problem with simple sound detection circuit using a microphone
I am very new to this community. My first project with Arduino was using a LDR (light dependent resistor) in a circuit like this:

The input I got was as expected between 0 - 1023.
I then tried a similar project this time using a sound sensor like this:

My circuit is as follows:

A0 on mic to A0 on Arduino
GND to GND
+ve to 5V
LED along with resistor to digital pin 9 on Arduino

My program is as follows:
const int analogInPin = A0;
int sensorValue = 0;

void setup() {
  pinMode(analogInPin, INPUT);
  pinMode(9, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  sensorValue = analogRead(analogInPin);
  Serial.print("sensor = ");
  Serial.print(sensorValue);
  Serial.print("\n");
  if(sensorValue > 900)
    digitalWrite(9,HIGH);
  else
  digitalWrite(9,LOW);
}

The problem is the serial monitor gives a weird reading, randomly giving 1023 and 0 after regular intervals.
sensor = 124
sensor = 0
sensor = 1023
sensor = 39
sensor = 352
sensor = 1023
sensor = 142
sensor = 0
sensor = 1023
sensor = 44
sensor = 338
sensor = 1023
sensor = 163
sensor = 0
...
...

I can't figure out the problem myself so I came here.

Do you know what a sound wave looks like?

i understand it is made up of rarefactions and compressions . what i was expecting this device to do was show approx loudness though(intensity if i am correct) .

I mean electrically. When you view it on an oscilloscope, or as a WAV or MP3 file in, say, audacity. It's a long sequence of discrete voltages at different points in time. That is what you are seeing. Discrete voltages at different points in time. That "module" is a microphone and amplifier. Nothing more. It is up to you to process those values to do something meaningful with them.

could you recommend something to read . i was expecting to light the led above a certain loudness. i can see though the similarities between this and a wave ( periodical 1023 and 0s ).Also what am i getting as the input then ??

The one thing you are missing in your thinking is time. During what period must the volume rise above a certain loudness to be counted? Also, you should know that the opposite must be true - not only rising above a certain value but falling below a certain value is just as loud.

Another thing: you can't print to serial whilst at the same time monitor the audio. You are only seeing very short snatches of sound in between your serial prints. Like if you stick your fingers in your ears, then pull them out and put them back in again very quickly. You just get short snatches of sound that make no sense.

The presence of 0 or 1023 in the data indicates clipping, which is to say that signal (or noise or interference) has hit the limit of and probably exceeded the voltage range which the ADC can handle, so the gain needs to be reduced so that "normal" inputs only produce unclipped samples.  But as already pointed out, the sampling rate is really too low and inconsistent.

I plotted the values you got in a spreadsheet:

You must admit that looks a bit like a sound wave! If you want to know if it is a soft sound or a loud sound you really need to see the maximum values (1023 in your case). If the maximum was 512 then clearly the incoming sound isn't as loud.
An alternative, if you just want loudness would be to filter the incoming signal, eg.

simulate this circuit – Schematic created using CircuitLab
This would smooth the incoming voltage so that consecutive readings would be in a narrower range.

Warning: Judging by the graph, you may be getting negative input into A0. The Arduino pins are not designed for negative voltage. You may want to use a diode to eliminate the negative component.

Thanks for the analysis...it felt like a wave to me too. I am afraid though that the maximum is always 1023 and lowest 0 no matter how loud or soft the sound is ,therefore I can't really check the loudness by measuring the peak. Reading through other answers and comments it feels like I should have been expecting a wave like input (am I right in saying it?) .Does that mean the microphone atm is too sensitive(therefore I am always getting a peak of 1023).

Possibly there is a connection problem and you are getting random values. Or you might be right about it being sensitive. I would be measuring with an oscilloscope to see what is really happening.

This is severely mistaken.  First, the data you plot is probably severely undersampled, given the serial printing at 9600 baud in the sampling loop.  Next, it is as likely AC power line hum as intended audio.  Your comment on maximum values is quite mistaken as it ignores that the data is an AC signal centered at some intermediate value, to measure a meaningful maximum the DC component must be removed and the absolute value taken.  Your lowpass filter proposal is the opposite of what would be useful - it removes the AC that should be analyzed, and provides the DC part that should be ignored.

Chris is right about the sampling rate. A higher baud rate may help a bit (and remove the string "sensor = "). He may also be right about the hum - you would need to know when the samples were taken to know what frequency that signal is.

This is severely mistaken. - no doubt the OP would be grateful if you would post an answer showing how to go about solving his problem.

Based on your code, it looks like you are trying to use the analog signal to obtain a digital output (turn an LED on or off). The sound sensor board does this for you and has a digital output pin called "D0".
Heres a simple sketch using the serial monitor to show you what the sensor "D0" pin is putting out. Connect ground and 5 volts as you did before, and connect sensor D0 to Arduino pin 3.
const byte DigitalInputPin = 3;

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

void loop(){
  Serial.print("Digital Pin = " );
  Serial.println(digitalRead(DigitalInputPin));
  delay(50);
}

You don't have to connect the sensor to an Arduino to adjust it or test it. There are 2 LEDs on the sensor circuit board. The one closest to the potentiometer will turn on when the D0 pin is high and off when it's low. You use the potentiometer to set the "trigger point" based on the level of sound you want to make the output go high.

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


text:
keypad storing problem any idea store more than 11 numbers like phone number
#include <SoftwareSerial.h>
#include <LiquidCrystal.h>

SoftwareSerial mySerial(6,5);
int table[]={0,0,0};

#include <Keypad.h>
#include <Wire.h>

LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns

char keys[ROWS][COLS] = {
    {'1','2','3'},
    {'4','5','6'},
    {'7','8','9'},
    {'*','0','#'}
};
byte rowPins[ROWS] = {2, 3, 17, 16}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {15, 14, 13}; //connect to the column pinouts of the keypad
int count=0;
Keypad kpd = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
char entryStr[13];   // This can hold up to 4 digits
int i=0;
***char n1, n2 , n3;
char buf [15] ;// i put here***

void setup()
{
    Wire.begin();
    mySerial.begin(9600);
    Serial.begin(9600);
    lcd.begin(20, 4);
    ask();
}

void loop()
{
    Wire.requestFrom(2, 3);    // request 6 bytes from slave device #2
    for (int i = 0; i < 3; i++)
    {
        int c = Wire.read(); // receive a byte as character
        Serial.print(c);
        table[i] = c;
        Serial.print('\t');
        // print the character
    }
    Serial.print('\n');
    Serial.print(table[0]);
    Serial.print('\t');
    Serial.print(table[1]);
    Serial.print('\t');
    Serial.print(table[2]);
    Serial.print('\n');

    //if(table[0]<=8)
    //{
    //Serial.print("Flame Detected!");
    //Serial.println("Level1");
}

void ask()
{
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Enter no1.:");
    lcd.setCursor(0,1);
    lcd.print("(starts with 0)");
    lcd.setCursor(1, 2);
    n1 = GetNumber(buf, sizeof (buf) - 1);

    Serial.print(n1);

    delay(1);

    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Enter no2.:");
    lcd.setCursor(0, 1);
    lcd.print("(starts with 0)");
    lcd.setCursor(1, 2);
    n2 = GetNumber(buf, sizeof (buf) - 1);

    Serial.println(n2);
    delay(1);
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Enter no3.:");
    lcd.setCursor(0,1);
    lcd.print("(starts with 0)");
    lcd.setCursor(1,2);
    n3 = GetNumber(buf, sizeof (buf) - 1);

    Serial.println (n3);
    delay(1);
    Serial.println (n1);
    Serial.println (n2);
    Serial.println (n3);
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("list of numbers ");
    lcd.setCursor(0, 1);
    lcd.print("will be shown press");
    lcd.setCursor(1, 2);
    lcd.print("reset if wrong");

    delay(7000);
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Numbers Stored:");
    lcd.setCursor(0, 1);
    lcd.print("no1.:0");
    lcd.print(n1);
    lcd.setCursor(1, 2);
    lcd.print("no2.:0");
    lcd.print(n2);
    lcd.setCursor(2, 3);
    lcd.print("no3.:0");
    lcd.print(n3);
}

void GetNumber(char * result, const int maxLength)
{
    char key = kpd.getKey();
    int i = 0;   // how far through buffer we are
    while (key != '#')
    {
        switch (key)
        {
            case NO_KEY:
                break;

            case '0': case '1': case '2': case '3': case '4':
            case '5': case '6': case '7': case '8': case '9':
                lcd.print(key);
                if (i < maxLength)
                {
                    result [i++] = key;
                    result [i] = 0;  // terminating null
                }
                break;

            case '*':  // backspace
                if (i > 0)
                {
                    i--;
                    result [i] = 0;  // terminating null
                }
                break;
        }

        key = kpd.getKey();
    }
} // end of GetNumber

I changed it..it gave me this error

Did you look at your question before posting it? It is a mess. Select the code part, and then hit Ctrl+K to indent it by four spaces so it looks like code.

In my answer the number is not returned, it is passed back in the argument (buf). Thus you should not try to save it in nl.

 long GetNumber()

A long type (on this platform) can go up to 2^31 (that is 2,147,483,648). Large 10-digit numbers (ie. starting with "9") will not fit.
You could work with a 10-character string (or longer) instead of a long.

Make GetNumber deal with strings, like this:
void GetNumber(char * result, const int maxLength)
{
  char key = kpd.getKey();
  int i = 0;   // how far through buffer we are
  while (key != '#')
  {
    switch (key)
    {
      case NO_KEY:
        break;

      case '0' ... '9':
        lcd.print(key);
        if (i < maxLength)
          {
          result [i++] = key;
          result [i] = 0;  // terminating null
          }
        break;

      case '*':  // backspace
        if (i > 0)
          {
          i--;
          result [i] = 0;  // terminating null
          }

        break;
    }

    key = kpd.getKey();
  }
} // end of GetNumber

Now, to call GetNumber supply a char buffer and the maximum length (allowing for the 0x00 needed to terminate a string), like this:
  char buf [15];
  GetNumber (buf, sizeof (buf) - 1);

How can I convert long to string it gives me error if I put String GetNumber() and String n1, n2, n3; thanks for help :)

You don't use long at all. See my amended answer.

Use a string or a char. They store their numbers a character per character and not a huge number. A long can hold a max of around 2 000 000 000.
For example, 123 declared as an lon would be litteraly, mathematicly 123 (as 100 + 20 + 3). On the other side, a char will consider it as 1,2,3. It can store higher digits number.

Can you give me idea how to do it in my code?Please elaborate thanks a lot

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


text:
Interfacing key-pad with arduino with 7 segment display
I have the following components:

Arduino Mega
7-segment display
12-digit key-pad

For my project, I would like to display on the 7-segment display the number that the user presses on the keypad.

Try this: please note that you have to fill in the last function in order to get an int value from your keypad. The 7-segments part of the code should be fine.
const int segment[7] = {2,3,4,5,6,7,8}; //pins for each segment

const int nums[10][7] = //declaring array
{
  {1,1,1,1,1,1,0}, //0
  {0,1,1,0,0,0,0}, //1
  {1,1,0,1,0,0,1}, //2
  {1,1,1,1,0,0,1}, //3
  {0,1,1,0,0,1,1}, //4
  {1,0,1,1,0,1,1}, //5
  {1,0,1,1,1,1,1}, //6
  {1,1,1,0,0,0,0}, //7
  {1,1,1,1,1,1,1}, //8
  {1,1,1,0,0,1,1}  //9
};

void setup() {
  for(int i=2; i<=8; i++) //shorcut for declaring a buch of pin modes
  {
    pinMode(i, OUTPUT);
  }
}

//=======================================================================

void loop() {
  number(keypadInput);
}

//=======================================================================

void number(int num) //num is the number to display
{
  for(int i=0; i<7; i++)
  {
    digitalWrite(segment[i], nums[num][i]);
  }
}

int (keypadInput)
{
  //code for getting the input of your keypad
}

Thank you for your answer. I will definitely add this code once I get my keypad.  Thanks a lot.


text:
Is it possible to pass HIGH and LOW values as parameter in a function?
I've created the following function:
void runMotor(int _dir, int _step, int wait){
  digitalWrite(_dir, HIGH);
  for (int x = 0; x < 3200; x++) {
    digitalWrite(_step, HIGH);
    delayMicroseconds(wait);
    digitalWrite(_step, LOW);
    delayMicroseconds(wait);
  }

In the first line inside the function I used the value HIGH as a fixed value. I would like to know if there's a way to pass the values HIGH and LOW as a parameter in this function. Is it possible?
Or should I just create a new function to rotate my step motor to the other side?

HIGH is just an alias for the number 1. LOW is just an alias for the number 0. Anywhere you can use numbers you can use HIGH or LOW equally. You can even use them in math: HIGH + HIGH == 2. The same goes for things like INPUT, OUTPUT, RISING, FALLING, etc. They are just aliases to numbers.

digitalWrite expects the pin and value to be uint8_t type. So you can certainly pass LOW or HIGH to functions.
For example:
void runMotor(int _dir, int _step, int wait, uint8_t value){
  digitalWrite(_dir, value);

What about Analog pins? Are they expected to be uint8_t values as well?

I meant what about the analogRead() function...

What do you mean? You don't pass HIGH or LOW to analogRead. You mean the pin numbers? Yes the pin number is uint8_t as well.


text:
How to connect Flora 2 and nRF8001 BLE Breakout
I'm trying to get the nRF8001 BLE Breakout polling properly on Flora but Adafruit's tutorial and everything I've read and hunted around but I'm new to Arduino and not really sure how the Adafruit_BLE_UART library is handling I/O on the various pins. I'd appreciate it if anyone knows the proper pin configuration to get this working. I'm not in a position where I can easily change out to a better BLE device for my Flora.
So it's clear I have

SCK connected to SCK.
MISO to MISO, I've also tried it in D12 with the same outcome.
MOSI in MOSI, there's no D11 on this board so I couldn't try that.
REQ in D10.
RDY in SDA, which is supposed to correspond to D2 (besides SCL I don't think there are any other interrupt pins).
RST in D9, also tried it in the Reset SPI, doesn't seem to make any difference.

In short I'm using all the appropriate SPI pins and two of the data pins mentioned in the BLE tutorial, and I've tried a couple other configurations without much success.
And it appears to be powered properly.
using echoDemo, getState always returns the disconnected opcode. Polling apparently does nothing, setDeviceName does not set a name. I think either MISO or MOSI or both are the problem here. I can blink the LED, and other peripherals are working okay. (Crossposted to Adafruit forums.)
Some code:
#include <SPI.h>
#include "Adafruit_BLE_UART.h"

// Connect CLK/MISO/MOSI to hardware SPI
// e.g. On UNO & compatible: CLK = 13, MISO = 12, MOSI = 11
#define ADAFRUITBLE_REQ 10
#define ADAFRUITBLE_RDY 2
#define ADAFRUITBLE_RST 9

Adafruit_BLE_UART BTLEserial = Adafruit_BLE_UART(ADAFRUITBLE_REQ, ADAFRUITBLE_RDY, ADAFRUITBLE_RST);

void setup(void) {
  Serial.begin(9600);
  while(!Serial); // Leonardo/Micro should wait for serial init
  Serial.println(F("Adafruit Bluefruit Low Energy nRF8001 Print echo demo"));
  BTLEserial.setDeviceName("NEWNAME"); /* 7 characters max! */
  BTLEserial.begin();
}
aci_evt_opcode_t laststatus = {5};

void loop() {
  // Tell the nRF8001 to do whatever it should be working on.
  BTLEserial.pollACI();
  // Ask what is our current status
  aci_evt_opcode_t status = BTLEserial.getState();
  Serial.println(laststatus);
  Serial.println(status);
  Serial.println(ACI_EVT_DEVICE_STARTED);
  Serial.println(ACI_EVT_CONNECTED);
  Serial.println(ACI_EVT_DISCONNECTED);
  delay(1000);
  // If the status changed....
  if (status != laststatus) {
    // print it out!
    if (status == ACI_EVT_DEVICE_STARTED) {
        Serial.println(F("* Advertising started"));
    }
    if (status == ACI_EVT_CONNECTED) {
        Serial.println(F("* Connected!"));
    }
    if (status == ACI_EVT_DISCONNECTED) {
        Serial.println(F("* Disconnected or advertising timed out"));
    }
    // OK set the last status change to this one
    laststatus = status;
  }
}

The SPI bus can be accessed using a 6 pin header located next to the embedded processor.  Look at the embedded image below. Locate the 6 pin header just to the right of the processor.  Note the white dot indicating pin1 of the header.  Now look at the bottom of the embedded image to see the definitions of the 6 pins.  MISO, MOSI and several other SPI signals are listed.

I'm not sure what you're trying to get at. I mentioned in the post that I'm using the SPI bus pins, do you mean to say that I should be modifying the BLE library to (somewhere) reference different pin numbers for MISO, MOSI, SCK? On the SPI bus the datasheet marks them 1, 4, and 3, but I don't see anything else indicating a pin number. The image you talked about doesn't seem to be in your reply, so I can't really tell what document you're referencing.

The image is embedded in the stackexchange answer.  In your question you associated MISO with D12 and MOSI with D11.  On this page Adafruit says the SPI is on the 6 pin header on pin 1 (MISO) and 4 (MOSI).  I do not think you should modify the library.

I do see that I did not read the flora key correctly off the embedded image.  I will remove the pin suggestions from the answer.  Adafruit might have done a better job at documenting their product as it does not appear Adafruit consistently used Arduino Uno pin names on the Flora.

The image thing turned out just to be in my browser, I can see it just fine using a different one. I'll see what I can do using this sheet for reference.


text:
Compiles but doesn't print anything
Here is my code. It is suppose to read a couple of sensors and print them out in the serial monitor. Any help please? Note that I'm new to object orientated programming.
/* The Blue Box

   Project description:
   Arduino black box flight data recorder
   This projects acts like a little homemade black box. It records data of a flying object.

   Details about the code:
   Altitude is calculated in meters above sea level.
   Records: day of the week, year, month, day, hour, minute, second, time from activation, yaw, pitch, roll, altitude, temperature

   This code is subject to a lot of ameliorations.

   By: xxx
   Date: 2016/08/28

   Extra credits:

   GY-521 library:
   I2Cdev device library code is placed under the MIT license
   Copyright (c) 2012 Jeff Rowberg
   https://github.com/jrowberg/i2cdevlib

   MPL3115A2 library
   Adafruit Industries
   https://github.com/adafruit/Adafruit_MPL3115A2_Library

   SD card library
   Code from example by Tom Igoe
   Included in the Arduino IDE itself

   DS3231 library
   Rinky-Dink Electronics
   http://www.rinkydinkelectronics.com/library.php?id=73
*/

#include <SPI.h>                        //include the SPI library
#include <SD.h>                         //include the SD card library
#include <Wire.h>                       //include I2C library
#include "I2Cdev.h"                     //include another I2C library
#include "Wire.h"                       //include another I2C library (yes, again)
#include "MPU6050_6Axis_MotionApps20.h" //include the MPU6050 library
#include "SparkFunMPL3115A2.h"          //include the MPL3115A2 library
#include <DS3231.h>                     //include the DS3231 library

//==================================================

#define testtest                    //*** COMMENT THIS LINE BEFORE UPLOADING OFFICIAL CODE TO FINAL PROJECT ***

#define chipSelect 10               //pin for the CS/SS
#define led 2                       //led and/or buzzer

volatile bool mpuInterrupt = false; //some random bool

bool ledState = false;              //state of the led and/or buzzer
bool dmpReady = false;              //state of the mpu6050

int yprInt[3];                      //gyro data in a integer because the extra precision of the float is total bullshit
int altitude;                       //altitude above takeoff point in meters
int altitudeCalibration;            //calibration for the altimeter
int temperature;                    //temperature in degrees Celcius

float counter = 0;                  //time counter, a somewhat internal clock that starts when the module starts dataloging

uint8_t mpuIntStatus;               //holds actual interrupt status byte from MPU
uint8_t devStatus;                  //return status after each device operation
uint8_t fifoBuffer[64];             //FIFO storage buffer

uint16_t packetSize;                //expected DMP packet size (default is 42 bytes)
uint16_t fifoCount;                 //count of all bytes currently in FIFO

String day;                         //day of the week
String ymd;                         //date: year,month,day
String hms;                         //time: hour,minute,second

MPU6050 mpu;                        //change mpu's adress
Quaternion q;                       //quaternion container
VectorFloat gravity;                //gravity vector

MPL3115A2 myPressure;               //MPL3115A2 object declaration as myPressure
DS3231  rtc(A0, A1);                //DS3231 object declaration as

void dmpDataReady() {
  mpuInterrupt = true;
}

class MainLoop
{

    unsigned long previousMillis;

  public:
    MainLoop()
    {
      rtc.begin();            //start DS3231

      Wire.begin();
      myPressure.begin();                                         //start MPL3115A2 communication
      myPressure.setModeAltimeter();
      myPressure.setOversampleRate(7);
      myPressure.enableEventFlags();
      altitudeCalibration = myPressure.readAltitude();            //read altitude

#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE

      TWBR = 24;
#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE

      Fastwire::setup(400, true);
#endif

      mpu.initialize();
      devStatus = mpu.dmpInitialize();
      mpu.setXGyroOffset(0);
      mpu.setYGyroOffset(0);
      mpu.setZGyroOffset(0);
      mpu.setZAccelOffset(0);

      if (devStatus == 0)
      {
        mpu.setDMPEnabled(true);
        attachInterrupt(0, dmpDataReady, RISING);
        mpuIntStatus = mpu.getIntStatus();
        dmpReady = true;
        packetSize = mpu.dmpGetFIFOPacketSize();
      }

#ifdef testtest

      Serial.begin(115200); //start serial communication
#endif

#ifndef testtest

      if (SD.begin()); ();       //sd card
#endif

    }

    void go(  )
    {
      unsigned long currentMillis = millis();

#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE

      TWBR = 24;

#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE

      Fastwire::setup(400, true);
#endif

      mpu.initialize();
      devStatus = mpu.dmpInitialize();
      mpu.setXGyroOffset(0);
      mpu.setYGyroOffset(0);
      mpu.setZGyroOffset(0);
      mpu.setZAccelOffset(0);

      if (devStatus == 0)
      {
        mpu.setDMPEnabled(true);
        attachInterrupt(0, dmpDataReady, RISING);
        mpuIntStatus = mpu.getIntStatus();
        dmpReady = true;
        packetSize = mpu.dmpGetFIFOPacketSize();
      }

      else
      {
        return;
      }

      altitude = myPressure.readAltitude() - altitudeCalibration; //read altitude
      temperature = myPressure.readTemp();                        //read temperature

      day = rtc.getDOWStr();  //get day of the week
      ymd = rtc.getDateStr(); //get day, month, year
      hms = rtc.getTimeStr(); //get hour, minutes, seconds

#ifdef testtest

      Serial.print(day);
      Serial.print(" ");
      Serial.print(ymd);
      Serial.print(" -- ");
      Serial.print(hms);
      Serial.print(", ");
      Serial.print(counter);
      Serial.print(", ");
      Serial.print(yprInt[0]);
      Serial.print(", ");
      Serial.print(yprInt[1]);
      Serial.print(", ");
      Serial.print(yprInt[2]);
      Serial.print(", ");
      Serial.print(altitude);
      Serial.print(" ,");
      Serial.print(temperature);
      Serial.println();
#endif

#ifndef testtest

      if (altitude > 1) //if the device is higher then 1m, then we sstart recording everything
      {
        File dataFile = SD.open("datalog.txt", FILE_WRITE);

        if (dataFile)
        {
          dataFile.print(day);
          dataFile.print(" ");
          dataFile.print(ymd);
          dataFile.print(" -- ");
          dataFile.print(hms);
          dataFile.print(", ");
          dataFile.print(counter);
          dataFile.print(", ");
          dataFile.print(yprInt[0]);
          dataFile.print(", ");
          dataFile.print(yprInt[1]);
          dataFile.print(", ");
          dataFile.print(yprInt[2]);
          dataFile.print(", ");
          dataFile.print(altitude);
          dataFile.print(" ,");
          dataFile.print(temperature);
          dataFile.println();
          dataFile.close();
        }
      }
#endif

      counter = counter + 0.5;

    }
};

MainLoop main;

void setup() {
}

void loop()  {
  main.go();
}

Why are you using a class in the first place?

Save a bit of memory and trying to learn new things.

Move all that code out of the constructor and put it in a .begin() method to call from setup(). You are calling functions before the chip has been initialized and things are being undone.
It is only safe to use a constructor to initialize a few variables and the like. Simply because the call sequence is:

Constructors
System Init
Setup
Repeat forever:
-> Loop

System Init configures the timers, peripherals, IO pins, etc. Things which need to be done before the code in your constructor.

mind giving a small example. im really not familiar with class and constructors...

Just rename your constructor to void begin() and then call main.begin() in setup(). Incidentally, calling it main is not good since that could cripple the main() function. Call it myMain instead.

im really not familiar with class and constructors - when an instance of a class is created its constructor (if it has one) is called to do preliminary housework. The constructor is a function with the same name as the class (in your case: MainLoop). On the Arduino it is not useful or safe to do much in a constructor other than setting variables (eg. setting them to zero).

You might also want to learn about the Static Initialization Order Fiasco problem in C++. A good example is using Serial in your own statically initialized class constructor (as you attempted). Which comes first - the Serial or MainLoop constructor...? Who knows...?

mind giving a small example. I'm really not familiar with class and constructors

Here is an example of trying to do things in the constructor:
class foo
{
  public:
  foo () // constructor
    {
    Serial.begin (115200);
    Serial.println ("Hello, world.");
    }
}; // end of class foo

foo bar;  // make an instance of foo

void setup() { }
void loop() { }

On my setup that prints "Hel" and nothing else.

Now if we change things around it works:
class foo
{
  public:
  void begin ()
    {
    Serial.begin (115200);
    Serial.println ("Hello, world.");
    }
}; // end of class foo

foo bar;  // make an instance of foo

void setup()
  {
  bar.begin ();
  }

void loop() { }

Now we are doing things in the right order. "Under the hood" the main function provided by the IDE initializes the hardware (by calling init) and then calls setup. Now we can call the begin function in our class.

It would have worked if we created the class instance inside setup because that is after init is called, like this:
class foo
{
  public:
  foo () // constructor
    {
    Serial.begin (115200);
    Serial.println ("Hello, world.");
    }
}; // end of class foo

void setup()
  {
  foo bar;  // make an instance of foo
  }

void loop() { }

However now bar is not a global variable.

What is sometimes done is to make a function to return an instance of the class, which creates it the first time it is called, like this:
class foo
{
  public:
  foo () // constructor
    {
    Serial.println (F("Hello, world."));
    }
  void doSomething ()
    {
    Serial.println (F("Doing something"));
    }
}; // end of class foo

foo & getFoo ()
  {
  static foo myBar;  // make an instance of foo
  return myBar;
  }  // end of getFoo

void setup()
  {
  Serial.begin (115200);
  Serial.println (F("Program starting."));

  foo & bar = getFoo ();
  bar.doSomething ();
  }  // end of setup

void loop()
  {
  foo & bar = getFoo ();
  bar.doSomething ();
  delay (500);
  }  // end of loop

Now the function getFoo returns a reference to the instance of foo created as a static variable inside it. Thus, the first time it is called, the instance is created. Subsequent times just return the same instance.


text:
Serial communication doesn't work right after upload
I'm trying to communicate between a program on the Arduino Uno and a program on the PC via USB. I got it more or less working. Only problem is that it doesn't work when I run my PC program the first time after I upload the Arduino code via the Arduino IDE (version 2:1.0.5+dfsg2-4). It has some strange behaviour. Of course I could do some workaround, but I hope someone knows what the cause of this problem is and if there is a nice way to solve it.
This program should send back every byte it receives:
void setup () {
    Serial.begin(9600);
    while (!Serial) {}
}

void loop () {
    if (Serial.available()) {
        Serial.write(Serial.read());
    }
}

This program sends the bytes 0 to 255 to the Arduino twice and outputs every byte it receives. It is written in Scala and uses the Java RXTX library for serial communication. I'm using Debian Linux.
import gnu.io.CommPortIdentifier
import gnu.io.SerialPort

object SerialTest extends App
{
    val portId = CommPortIdentifier.getPortIdentifier("/dev/ttyACM0")
    val port = portId.open(getClass.getName, 0).asInstanceOf[SerialPort]
    port.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE)

    val in = port.getInputStream
    val out = port.getOutputStream

    for (i <- 0 until 512) out.write(i)

    while (true) print(in.read + " ")
}

Instead of the 512 bytes it should receive, only around the last 44 bytes are received. Also, the first bytes the program receives are usually wrong. When I run the program for a second time, I get the desired result.
  Try 1: 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
  Try 2: 186 58 93 157 221 29 151 167 183 199 215 231 247 7 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
  Try 3: 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
  Try 4: 221 29 151 167 183 199 215 231 247 7 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
Desired: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255

If I let the program wait for 2 seconds anywhere between val portId = ... and writing to the output stream, it works. But there is be a better way, right?
(related question)

If you say that another question "is more or less the same" then your question should be closed as a duplicate.  To have a new question, you need instead to explain how yours  is different.

It is not clear what exactly your problem is, but you might consider either putting several seconds delay between the opening of the serial port and the attempt to communicate in order to allow the bootloader to time out, or better looking for an echo of test data before real data, or changing the serial port configuration to disable the modem status line manipulation on open which triggers reset, or change the wiring of the board or remove the bootloader.  Also fully configure the advanced serial port settings, rather than merely hoping whatever last used it set what you want.

Why have <while(!Serial)> when you use an UNO??

The only "better way" than a delay is a delay followed by a positive verification of communication and repeate if necessary until success, as already mentioned.   Or else to prevent the reset in the first place, but that is chancy as it depends on a modification that might not be made in every case.

@ChrisStratton How about this "disable the modem status line manipulation"? I have no idea what you're saying and Google isn't my friend on this one. If it might work, how should I do that?

http://arduino.stackexchange.com/questions/4078/why-does-my-arduino-seem-to-reboot-every-time-that-i-open-serial-monitor or http://arduino.stackexchange.com/questions/640/arduino-serial-port-reset-in-serial-monitor-python or http://playground.arduino.cc/Main/DisablingAutoResetOnSerialConnection

The first time you open the serial port on the PC the Uno resets and enters the bootloader. Two seconds later your sketch starts running.
By then you have already sent a load of your data to the Uno which it ignores because it's not valid bootloader commands.
When your program exits it leaves the port in an different state (RXTX is crap and doesn't clean up after itself when you terminate a program). That state includes the DTR signal being disabled.
With the DTR signal disabled the Uno doesn't reset when you open the port. Thus when you run your program a second time the sketch is already running and everything works fine.
You can toggle the control of the DTR signal in Linux by setting or clearing the hupcl flag on the tty:
Disable DTR control:
$ stty -F /dev/ttyACM0 -hupcl

Enable DTR control:
$ stty -F /dev/ttyACM0 hupcl


text:
Switch between ntc resistor sensors time based for other device
We have a heating system that uses an ntc resistor to measure water temperature. I would like to replace that ntc resistor by a fixed one (low enough to disable heating) temporary on a 5 minute schedule, or any other.
It's to prevent the warm water using up all the heat and not leaving any for the central heating of the building. We got fooled by the contractor and a proper upgrade would now cost several thousands, so we just want to trick the system. ;p
The arduino is not supposed to measure anything, just to connect one of the two resistors to the heating system.
Is an arduino the right choice for that? If yes, which model? What extra elements would I need? Transistors? Relays? They shouldn't have too much own resistance to not influence the measuring of the heating system when the NTC is connected.
Just a simple connection of the extra resistor would work too because the resulting resistance would be lower and still indicate "water is hot enough" to the heating system.
Any help is welcome, even if it is not arduino based.

It sounds like what you want is a small SPDT relay (maybe a reed relay).

simulate this circuit – Schematic created using CircuitLab
Turn on the GPIO, the MOSFET (or NPN BJT if you choose - increase R1 if you do) turns on, which energises the relay. The relay then switches between the NTC and the resistor being connected into the circuit.

For the benefit of the OP, I suggest you clarify what M1 is - and suggested part numbers or specs.

@NickGammon That portion of the circuit is the standard relay switching circuit. There are a brazillian tutorials and examples citing parts and specs online. Why replicate it needlessly?

cool, think that is what i need! would you use the arduino or is it overkill in that simple scenario? 5 mins on, 5 mins off, repeat ..

Arduino is a good choice.


text:
Expected } at the end of input
I am getting the error in my title when I try to compile the following code:
#define char incomingByte; //Defines incomingByte
#define char sendBack = K;
#define char ?;
#define pollTime;

bool running = true;

void setup() {
Serial.begin(9600); //Set data rate.
}

void loop() {
for(Serial.available() > 0;)  { //Gets you the number of bytes that are available to be read from the serial port.
pollTime = delayMicroseconds(200); // Sets a poll time of 200 microseconds.
incomingByte  = Serial.read();
if(incomingByte = ?) {
Serial.print(sendBack);
  }
 }
}

Your code is completely wrong in almost every respect.

#define char incomingByte; //Defines incomingByte

That line means that the compiler will substitute incomingByte; whenever it sees char.

#define char sendBack = K;

Now it will substitute sendBack = K; when it sees char.

#define char ?;

Now it will substitute ?; when it sees char.

#define pollTime;

I don't know what you are thinking here. If you are trying to declare a variable you have to give a type, like this:
int pollTime;

bool running = true;

void setup() {
Serial.begin(9600); //Set data rate.
}
void loop() {

Those lines are OK.

for(Serial.available() > 0;)  { //Gets you the number of bytes that are available to be read from the serial port.

You don't want the semicolon there. A for loop is not written like that. You possibly mean while, ie.
while(Serial.available() > 0)

pollTime = delayMicroseconds(200); // Sets a poll time of 200 microseconds.

That is doing nothing of the sort. It is delaying 200 µs, it isn't setting anything.

incomingByte  = Serial.read();

That line is OK, assuming you declared incomingByte like this, and not the way you did:
char incomingByte;

if(incomingByte = ?) {

That needs to be in single quotes, as you are comparing a character. Also you compare with == not = ie.
if(incomingByte == '?') {

Serial.print(sendBack);

It looks from your earlier code you mean:
Serial.print('K');

  }
 }
}

These lines look OK.

I suggest you read a beginners page about C programming. This is just pure guesswork what you are doing here. For one thing, read up on how #define works. Here is one page: https://www.techonthenet.com/c_language/constants/create_define.php. And another: http://www.cprogramming.com/reference/preprocessor/define.html

Thank you. This was very helpful. I'll look into the links that you provided.

P.S. you should change "respect" to "aspect" in the first line

I'm not sure about that. See in all respects which means: entirely, outright, wholly, thoroughly, altogether, totally, utterly

[UPDATE]
Try this:
int question = 63; //in the ascii table, ? is 63

void setup() {
  Serial.begin(9600); //set baud rate.
}

void loop() {
  if (Serial.available())  { //Gets you the number of bytes that are available to be read from the serial port.
    if (Serial.read() == question) {
      Serial.println("OK");
    }
  }
}

When I run the code it gives the following error:

invalid conversion from 'const char*' to 'char' [-fpermissive]

refresh the page and test the new code

Thank you. This part worked. I forgot to mention that I also need it to turn off the LED if the condition is not met. When I run the code you have provided the LED is on.

There's really no reason to use the ascii code for a question mark here, it makes the program hard to understand.  Use '?'your earlier error was a result of using a string (double quotes) rather than a single character (single quotes).

"When I run the code you have provided the LED is on" - your question was nothing to do with LEDs, nor does your code make any attempt to turn them on or off.


text:
Can I use L293D driver as ESC for arduino controlled quadcopter
I recently thought that it would be fun to build an arduino quadcopter.
As I did some research I realized that the common L293D motor drivers aren't ever used.
Why is this? Could I still use them in my project?

Bipolar bridge drivers like the L293D, L298, etc have extremely high losses.  They are long out of date and a poor choice compared to modern FET chips even for surface vehicles, let alone something that needs a good power to weight ratio for flight.  Typically if you made a small robot with one and some AA cells, you'd have to have an extra cell in the pack just to cover the losses of the L293D.  An aircraft (and especially a vertical lift one) cannot afford that waste.  Also the wasted energy shows up as heat (though I suppose you could position the chip in the propwash).
Actual quadcopters use MOSFET drivers, typically discrete ones carefully selected for a low RDSon at a low enough threshold voltage to fully turn on when driven by an MCU output.  Either just one N FET per motor for unidirectional control of brushed motors, or H bridges made of an N FET and either a P FET or else an N FETs with special high side driver circuitry for bidirectional control of brushed motors, or similarly as a half-bridge for each of the three leads of a brushless motor.  The MOSFETs may be found either on the main board in a single board quadcopter, or else they may be packaged in modular speed controllers separated from it.
But providing current to drive the motors is the easy part - sequencing brushless motor commutation, and stabilizing a flight platform are the hard parts.
In that regard, an Arduino is a very poor choice as a flight controller.  A literal one means carrying around a lot of extra mass and connectors that aren't really fitting.  A work-alike on a custom board is possible, but most of the open source projects that started that way have long since moved on to other MCUs with more capability.  You do still see ATmega8's within brushless motor drivers though.


text:
Error Uploading Arduino Sketch to Arduino Pro Mini
I got an error "stk500_getsync() not in sync resp=0x00" when I tried to update an Arduino Pro Mini with an FTDI Basic Breakout 5V/3.3V - Micro USB. Maybe someone has instructions on how to resolve this issue. I use the last version of Arduino IDE.
All standard stuff like drivers, ports installed and configured.
I have communication with controller and I receive answers from it, but when I try to flash the firmware I get that error.

It's your COM port or your board selection.
I often use the Pro Mini and an Uno and when I forget to change either the COM port or the board to which I have to upload the sketch to, that error message happens.

I updated question.

Maybe wrong driver. There is only one FTDI driver.


text:
LED and Switch Compolation Error Arduino 101
I'm getting an error on line 9 for some reason, (digitalWrite(Sender, HIGH);), and I just cant figure out why. My goal is to have two sets of flashing patterns, one for each switch state. I don't know how important this is but I'm using an Arduino 101. This is also my first day programming so the answer could be staring me right in the nose, (in fact, I would prefer that haha). Thank you for your time!
// Starting this by declairing intigers
int Sender = 2; // Switch Out on pin two
int LedG = 10; // LED Green out on pin ten
int LedR = 11; // LED Red out on pin eleven
int Reader = 12;  // Switch Input on pin twelve
//configuring I/O
pinMode(Sender = OUTPUT); // Setting pin two to output
pinMode(Reader = INPUT); // Making pin 12 set to read switch data
digitalWrite(Sender, HIGH); //Making pin two hot
//main loop
void loop() {
  if (digitalRead (Reader) == HIGH) { // if Switch input is reading on than do pattern A
    digitalWrite(LedG, HIGH); //turning on green led
    delay(50); //delay next instruction
    digitalWrite(LedG, LOW); //turn green led off
    digitalWrite(LedR, HIGH); //turn red led on
    delay(50); //delay next instruction
    digitalWrite(LedR, LOW); //turn red led off
  }
  else { //if switch input is readion off than play pattern b
    digitalWrite(LedR, HIGH); //turn red led on
    delay(1000); //delay next instruction
    digitalWrite(LedR, LOW); //turn red led off
    digitalWrite(LedG, HIGH); //turning on green led
    delay(1000); //delay next instruction
    digitalWrite(LedG, LOW); //turn green led off
  }
}

I notice that your pinMode function calls are not quite correct:
pinMode(Sender = OUTPUT); // Setting pin two to output
pinMode(Reader = INPUT); // Making pin 12 set to read switch data

Should be:
pinMode(Sender, OUTPUT); // Setting pin two to output
pinMode(Reader, INPUT); // Making pin 12 set to read switch data

Refer to https://www.arduino.cc/en/Reference/PinMode for more information.
And the whole section where you configure your I/O should be wrapped inside the setup() function.
//configuring I/O
void setup()
{
    pinMode(Sender, OUTPUT); // Setting pin two to output
    pinMode(Reader, INPUT); // Making pin 12 set to read switch data
    digitalWrite(Sender, HIGH); //Making pin two hot
}

Incidentally, my if statement doesn't seem to be functioning correctly.  Is (if (digitalRead (Reader) == HIGH)) the correct way to check if an input is true?

Never mind, sorry.

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


text:
SerialUSB on Arduino Due
I'm starting fiddling with a Due but I can't seem to be able to communicate over USB with it. Here is my code:
int bauds = 9600;

void setup() {
    SerialUSB.begin(bauds);
}

void loop() {
    if (SerialUSB.available())
        serialUSBEvent();
}

void serialUSBEvent() {
    String str = SerialUSB.readString();
    SerialUSB.write(str.c_str());
}

As you can see, I try with the bare minimum but my output consoles (2 COM port for the 2 usb connections, just in case I messed up which is which) stay blanks, whatever I send them...

Have you tried resetting the board after sending the program? Or after having opened the terminal?
A few days ago I didn't have any results using SerialUSB, and today I have. The program has been sent trough the programming port, and SerialUSB is with native port. Uploading my program trough native port, it didn't worked until I reset!

authors: Сергей Аликин


text:
Formula for current through shift register

Hi
I am programmer that just started learning electronics and Arduino. I built this simple circuit on Autodesk Circuits earlier. Originally I used 220 ohm resistors. Then when I ran the simulation and turned on more than 4 of the leds the simulator warned that I exceeded the max current for the shift register.
I then upgraded to 560 ohm resistors which solved the problem.
What I would like to know is how can I calculate the current through the shift register for each n-number of leds I turn on? That way I can calculate the right resistor that I need before I burn out my electronics.
Thanks for the help on this.

Datasheet says?

It's just N×IL+IQ where N is the number of LEDs, IL is the current through each LED and IQ is the current the shift register needs to operate (quiescent current).
The current through each LED is just (VIN - VLED) ÷ R, where VIN is 5V, VLED is the forward voltage drop of the LED, and R is the value of your resistor.
So you can combine it to be a single formula, if all your LEDs are the same and your resistors are the same, to:
IT = N × ((VIN - VLED) ÷ R) + IQ

There's a voltage drop across the shift register, too, but that may not be worth worrying about.  VLED may be most simply measured in operation - or else, calculating based on VLED=0 would somewhat overestimate the current, which isn't really a bad thing to do when comparing against a limit, since it just builds in some margin.  But if the LED were blue with a high forward voltage, then VLED would be very large - if the supply were only 3.3v  it would actually be the majority of the voltage drop.

Of course, the correct thing to do is throw away the poxy shift register and use a proper LED driver with constant current sink... Many are identical in operation from a programming and interfacing perspective, and remove the need for all the resistors completely.

Thanks. I looked through the data sheet. Can find Iq only Icc and Io for each pin. I also have no idea what the specs are for the leds the simulator does not provide specs. I will just make sure I know the specs before I put together a real circuit.

Sorry meant I can't find Iq.

@HeinrichKruger 80µA


text:
Expected declaration before } token
Below is my code. The idea is it is supposed to wait for the ? character, print K, and turn on the LED. If it does not detect ? then it should keep waiting.
Below is my code:
incomingByte = Serial.read();
sendBack = K;
int pollTime = 200;

int ledPin = 9;

bool running = true;

void setup() {
Serial.begin(9600); //Set data rate.
}

void loop() {
while(Serial.available())  {
  if(Serial.read == '?')  {
  Serial.print(sendBack);
  pinMode(9,OUTPUT);
  else  {
   delayMicroseconds(pollTime);
  }
}
}
}

why do you declare 9 as an output in the void loop???

Try this:
void setup() {
  Serial.begin(9600); //set baud rate.
  pinMode(9, OUTPUT);
}

void loop() {
  if (Serial.available())  { //Gets you the number of bytes that are available to be read from the serial port.
    if (Serial.read() == '?') {
      Serial.println("OK");
      digitalWrite(9, HIGH);
      delay(1000);
    }
  }
  else
  {
    digitalWrite(9, LOW);
  }
}


text:
Is there a cheap relay that can control voltage from stuff like bulb lights with a 5 V control output?
I need to power a light bulb or something like 110 V or 220 V at normal amperage for TV or something at that range like a fan...
My micro-controller is an Arduino with 5 V out and 12 V max out trough transistor switch.
To my understanding a stepper motor drive could be a viable option to enable the relays... I can even control current, right?
Up to 8 channels
Could this work better?

Just remember SSRs are not good with fluorescent light bulbs as there is  a small current through the relay in closed state.

Which to use where
Ok, so I've narrow the 2 main choices that you have : either a MOSFET or a RELAY. For higher voltages, it is much safer to go with a relay but for higher current, you might as well use a power MOSFET.
Option 1 - Relays
They are mainly used to control already made stuff like a bulb using main's voltage. They are also used to control stuff like a fan (pre built), lamp, and many more. Relays are also simple to wire and don't quire much electronics skills. The main disadvantage of a relay is that they are not as good as MOSFETs when it comes to current handling.
Advantages: Light bulb, stuff bought from the sotre (TVs, fans, small heater), house automation, laundry, house heater, fridge
Opition 2 - MOSFETs
IMPORTANT NOTICE : YOU CANNOT USE A MOSFET WITH MAIN'S VOLTAGE
MOSFETs are great when it comes to kick some voltage in to your devices. I remember as a kid, I use to stock these in NERF guns. Motors will instantly start with MOSFETS!. For even higher current control. Try power mosfets, they are designed for high current. Also know that mosfets are bad in the way that they tend to warm up a lot (if the current is high).
Advantages: Neon light, motors, things that need to be responsive (drone motors), things that need to be precise (PWM)
In conclusion, relays master the world of high voltages and MOSFETs the world of high current!

MOSFETs have an intrinsic body diode between source and drain. You want this diode to be reverse-biased when the MOSFET is off. Hence MOSFETs are not good for switching AC, and mains is AC.

Well thats why I said that Relays are better for mains voltage. Shoud I modify anything?

Yes, make it crystal clear that a MOSFET is unsuitable for switching mains. It is absolutely not obvious from your answer as it stands now.

@EdgarBonet, I included the notice, aything else

It think it is clear enough.

More understandable but if you could give an example on AC relay handling and if an arduino is able to handle it without external modules I could accept this answer! Thanks

I know solid state relays are better but they are not cheap! I want to know if I can wire an 8 channel relay module to control 110v to 220v devices!! Like the one in the link provided

Quick link : https://www.youtube.com/watch?v=LLFQ8sBWc80. He uses a cheap 2-channel but a 8-channel should work. See how he does it and follow CAREFULLY. I can't insist on safety with relays!

So, yes you can use the one from the link that you provided.

You can use a 5V Solid-State Relay module to control light bulbs. They cost $4-6 from US-based suppliers and $1-3 from a Chinese supplier. Just hook up the supply to the center pin and the load to either the NO or NC pin. Supply 5V to the module and wire a digital pin to the module to control it.

Nice one and thanks but could you confirm if any of the ones I found on ebay works as well?? Check my edit

@DarkXDroid The seller did not include part numbers or manufacturer names so I couldn't lookup any datasheets. A relay with a max 250VAC and max 10A rating will be able to handle any standard light bulb. The main concern is how much current is required to trigger the relay. Arduino I/O pins can only supply (or source) ~20mA so if the relay draws more than that it will damage the board. The relays in the link might work but you can't know for sure without the datasheet. I know that Sainsmart relay modules are safe to use with Arduino digital pins.

I got ´´Omron 5V solid state relay 240V 2A, output with resistive fuse 240V 2A?´´
I think itś not enough so I´ll search for 250vac with an 10A, right?

Better Solution?
http://www.ebay.com/itm/ESP8266-2-Kanal-Channel-Relais-Modul-5V-10A-250VAC-10A-30VDC-Optokoppler-Arduino-/282185010711?hash=item41b3898e17:g:k~gAAOSw6n5Xuwl4

Another one? http://www.ebay.com/itm/8-channel-relay-module-optocoupler-isolated-relay-5V10A-opto-relay-board-SN513-2-/291140196745?hash=item43c94ed989:g:lTMAAMXQNo5TZwnw

Is there a way to use transistors as switches? Or are there any other better solution without frying pins or ic?

@DarkXDroid I was about to say transistors or better: mosfets. A mosfet is a good way to switch with Arduino because mosfets require voltage and not current to switch. Many mosfets are designed to trigger between 1~3 volts. You can then supply 5V from the Arduino 5V pin (which can give up to 1A current) and use that to switch the relay.

@Len I saw about mosfets but could understand if they were better options!! Thanks! Could you recommend me one of the option in my comments? I like to make sure If one of them is better than the other based on your exp

@Len This mosfet is a good option http://www.ebay.com/itm/Four-Channel-4-Route-MOSFET-Button-IRF540-V2-0-MOSFET-Switch-Module-Arduino-/200959373944?hash=item2eca1cb278:g:B1oAAOSwwo1Xdeup

You don't need a shield or something. Just get the single mosfet, make sure gate is pulled down and you're basically good to go.

Something like a IRF640 with TO-220 package should be good. Continuous drain can be as high as 18A, so no worries there. Just put 5V on the Gate and it turns on, if you don't put 5V on it, the pulldown resistor will ground Gate and that turns off the mosfet.

@Len can I simplify it by using a motor drive? Cos I have 2 in hands ... Check my edit... But I can change current on at least 4 pins per drive with the module I have without worry on frying the micro

@DarkXDroid I don't know about that. Never used a motor driver like that. I'd stick to mosfets.

The first one you have seems fine (in my opinion). Note though that relays are something not to be cheap with. They can cause dangerous accidents if you buy them from a cheap supplier (chinese). I'll always go for a local supplier (don't know where you live so I can't tell). Make sure to check Radioshack and stores like that.
Also make sure that you find one with a datasheet. No datasheet = no specs. No specs = you don't know the max of your relay which is BAD. The max of a relay should be known and respected or something bad can happen.

First or second option? I understand that low grade equip can cause a disaster but I already have a solution... besides this is prototyping and I want to understand the technology and limits. That why I put a range devices that I could control. But you got a valid point with security and end capacity

first option is the one that i prefer

I´m grateful for everything .... I´go with that at first

In my experience, the relays purchased from a local or US supplier are all made in China anyway.

My exp tells me the same lol the thing is that I should pay more to stay on the safe side

@ThatAintWorking, if you buy it from a US supplier and it fails, you can sue them for $ (only if the product is defective). Buy it from Chine, suffer the consequences...


text:
How do I clear sim800L buffer?
Let's say that I've tried sending an SMS directly from serial monitor or any kind of terminal. For whatever reason (syntax error, etc), my attempt fails. Now, I try sending it again, but this time by code (as seen on this site):
#include <SoftwareSerial.h>

//SIM800 TX is connected to Arduino D8
#define SIM800_TX_PIN 8

//SIM800 RX is connected to Arduino D7
#define SIM800_RX_PIN 7

//Create software serial object to communicate with SIM800
SoftwareSerial serialSIM800(SIM800_TX_PIN,SIM800_RX_PIN);

void setup() {
  //Begin serial comunication with Arduino and Arduino IDE (Serial Monitor)
  Serial.begin(9600);
  while(!Serial);

  //Being serial communication witj Arduino and SIM800
  serialSIM800.begin(9600);
  delay(1000);

  Serial.println("Setup Complete!");
  Serial.println("Sending SMS...");

  //Set SMS format to ASCII
  serialSIM800.write("AT+CMGF=1\r\n");
  delay(1000);

  //Send new SMS command and message number
  serialSIM800.write("AT+CMGS=\"07194XXXXX\"\r\n");
  delay(1000);

  //Send SMS content
  serialSIM800.write("TEST");
  delay(1000);

  //Send Ctrl+Z / ESC to denote SMS message is complete
  serialSIM800.write((char)26);
  delay(1000);

  Serial.println("SMS Sent!");
}

void loop() {
}

The code sends not only the SMS within the code ("TEST"), but also the unwanted junk / remains of the previously unsuccessful sending attempt.
Is there a way to clear the module's buffer before sending a new message?
I guess I could restart the module before sending messages, but I was wondering whether there's a cleaner solution.
P.S. I apologize for the slightly misleading and irrelevant tags, but I can not use the nonexistent sim800L, which would be better suited for my question.

Do you get "TEST[...AT COMMANDS...]TEST" in your SMS? I.e., does it appear that the previous SMS doesn't get terminated and everything sent for the second SMS gets appended to it and then sent?

Yes, that's exactly what I receive. Since the attempt fails, the AT commands and previous text stay, and I don't even get to send CTRL-Z, in order to denote message end. And everything that stays, gets picked up on the next try.

According to the SIM800 AT Command Set you can terminate the sending of an SMS part way through by sending ESC (character 27).
So you can begin your sketch by first sending a number of ESC to ensure that any pre-existing text input for an earlier SMS is abandoned.
serialSIM800.write(27);
serialSIM800.write(27);
serialSIM800.write(27);

Only one should be needed, but it is best to repeat it a couple of times in case the first one isn't taken. You should then do a CR/LF to make sure it's ready for the next command.
serialSIM800.print("\r\n");

However, your method of controlling the modem is crude at best and not particularly reliable. The modem sends back responses from all the commands you send it. You should be reading in those responses and checking that the commands you sent actually worked. That way you can know if a command hasn't been accepted because it is in SMS reading mode (no response within 1 second, say), and you can force an escape.

Works fine, thanks. I can't believe I didn't try that. In regards to the code, it is indeed crude. I've yet to define or implement any kind of error catching, and devise a proper response to it.


text:
Most memory efficient way to program
I currently know 3 ways to do a program. Which one of them is the most memory friendly. Note that the example code is simple (blinking a led) and the final code will be VERY VERY complex. Also, the way I code is not the best, so suggest any suggestions in the way to write things or where to put them please.
1- All in the loop. The most basic way of programming.
const int led = 2;
const int interval = 500;
bool ledState = false;

void setup() {
  pinMode(led, OUTPUT);
}

void loop() {
  ledState = !ledState;
  digitalWrite(led, ledState);
  delay(interval);
}

2- Functions. Similar to the loop but a little neither. Can be splitted into many tabs.
const int led = 2;
const int interval = 500;
bool ledState = false;

void setup() {
  pinMode(led, OUTPUT);
}

void loop() {
  blinkLed();
}

void blinkLed()
{
  ledState = !ledState;
  digitalWrite(led, ledState);
  delay(interval);
}

Then finnaly, objects. The most supreme of them all (and the one that I know the least). I like objects and classes because multitasking with it is much easier. It is more flexible too. Code taken from here.
class Flasher
{
  // Class Member Variables
  // These are initialized at startup
  int ledPin;      // the number of the LED pin
  long OnTime;     // milliseconds of on-time
  long OffTime;    // milliseconds of off-time

  // These maintain the current state
  int ledState;                 // ledState used to set the LED
  unsigned long previousMillis;   // will store last time LED was updated

  // Constructor - creates a Flasher
  // and initializes the member variables and state
  public:
  Flasher(int pin, long on, long off)
  {
  ledPin = pin;
  pinMode(ledPin, OUTPUT);

  OnTime = on;
  OffTime = off;

  ledState = LOW;
  previousMillis = 0;
  }

  void Update()
  {
    // check to see if it's time to change the state of the LED
    unsigned long currentMillis = millis();

    if((ledState == HIGH) && (currentMillis - previousMillis >= OnTime))
    {
      ledState = LOW;  // Turn it off
      previousMillis = currentMillis;  // Remember the time
      digitalWrite(ledPin, ledState);  // Update the actual LED
    }
    else if ((ledState == LOW) && (currentMillis - previousMillis >= OffTime))
    {
      ledState = HIGH;  // turn it on
      previousMillis = currentMillis;   // Remember the time
      digitalWrite(ledPin, ledState);   // Update the actual LED
    }
  }
};

Flasher led(2, 500, 500);

void setup()
{
}

void loop()
{
  led.Update();
}

So, which is the best out of those 3.

Which board are you targeting?Which version of the hardware core for that board are you using?

Arduino Pro Mini by Sparkfun (Atmega328P_smd)

Which version of Arduino AVR Boards? You can check at Tools > Board > Boards Manager...

its version 1.6.14

Compile each variant and present the memory foot-print together with basic code analysis (LOC, complexity). And please define what you think is better. For instance, the OOP Flasher variant can be reduced in footprint and still keep the abstraction by rewriting to a template class.

You could tell the compiler to inline the function using inline void blinkLed(). That way the actual machine code will be identical in the first two cases.

That is an incredibly hard question to give a definitive answer to.
In general using OO consumes more memory, but that is the price you pay for greater flexibility and ease of use. The difference is usually minor though. Variables within an object take the same amount of space as variables outside an object. It's just the overhead of instantiating the object itself that adds to the memory usage, and that can be quite small, depending of course on what the object does.
Calling functions increases memory use on the stack. Every time you call a function the return address and a number of the internal CPU registers, along with some of the parameters, get placed on the stack. The deeper your function calls go the bigger the stack gets. But that is all temporary - as you leave the functions the stack shrinks again.
However, this is where it gets more complex:
The compiler performs optimizations. One of them is to consider functions for inlining. This replaces the function call with the content of the function that is being called. It makes for a slightly larger program, but it's a program that runs faster and uses less stack.
In your first two examples, because there is only one call to the blinkLed() function, the compiler will see that as a good candidate for using inline. So your first and second programs may well both end up exactly the same.
There are times, as well, where variables that you declare don't actually ever exist. For instance, if you use a couple of temporary variables to do a few calculations in a function and then return the result the compiler may instead just use CPU registers to store the temporary values instead of allocating variable space in memory.
So it is very hard to say "this is better" or "that is better". Instead you should pay more attention to how and where you declare and use your variables.
In general there are two rules:

Keep your variables the smallest size possible for the contents (use 8 bit variables instead of int for storing smaller numbers).
Keep the scope of variables as small as possible.

The latter is often overlooked. The scope of a variable is the block (delimited by { and } for example) where the variable is declared. Anything inside that block, including sub-blocks, can see the variable. By keeping the variable in as small a scope as possible you increase the chances that the compiler will choose to use CPU registers instead of allocating memory.  For example:
int i;

for (i = 0; i < 1000; i++) {
    .... do something ....
}

.... other things ....

for (i = 30; i < 2000; i++) {
    .... do something else ....
}

That is pretty much guaranteed to allocate memory for i.  However:
for (int i = 0; i < 1000; i++) {
    .... do something ....
}

.... other things ....

for (int i = 30; i < 2000; i++) {
    .... do something else ....
}

With that method the variable i will only exist within the first loop, after which it disappears. It is then recreated as an entirely new variable for the second loop. It doesn't need to stay in memory in between. The compiler may just place it in internal registers, or it may reuse the same block of memory, etc.
Also by keeping scope as small as possible you increase the ability of the compiler to re-use the same bits of memory for different purposes. 10 integers in different scopes doesn't mean 20 bytes of memory - it may mean just 2 bytes for all 10 integers.
So as you can see managing memory effectively can be a bit of a black art at times.

One other note not directly related to the code in the question which may be relevant to your final project - keep an eye on your use of the standard libraries. e.g. std::string will take more memory than using a c style char* for a string, lists/vectors will take up more memory than an array etc...

Optimizing your first example into the second is one of the basic optimizations automatically done by the compiler... provided the two loops belong to the same function.

@EdgarBonet You're making assumptions about the compiler. Yes, avr-gcc 4.9.2 might do that. Other versions might not. Other compilers for other chips might not. It is highly likely that it might, but it's not something you should rely 100% on happening if you can give the compiler a helping hand with just simple things like keeping the scope to the absolute minimum.

If yours doesn't do this basic stuff, you should probably get a better one.

@EdgarBonet Unless a better one isn't available. Not all compilers are GCC. Some are incredibly basic. Some are little more than a direct conversion to equivalent assembly.

There are very good observations about coding with limited resources in this book:
https://www.amazon.com/Programming-Arduino-Next-Steps-Sketches/dp/0071830251
It covers the items you ask about and more besides, including some brought up in the comments.
As others indicate- there are some 'best' practices to consider but often the most efficient method is context-dependent.


text:
Arduino project list: What do I need?
Being new to Arduino I would like to know if I can build a project on this platform.
I want to connect Arduino to a few car parking sensors, a video camera and a mobile phone. The preferred language is JavaScript.

Is it something feasible?
Are there JavaScript libraries that can help with automation?
What version of Arduino should I use? Arduino UNO or something else?

Thanks,
George

Can't be answered: you don't give enough detail about what you want to do. However, the word "camera" when coupled with "Arduino" usually means "No. Get a Pi."

Arduino is in C/C++/a bit of Java Script. That's the normal IDE language so no you can't change it. Even other compiler mostly use one of the many C languages.
Car parking sensor question anwsered here.
For the hardware, use an UNO Rev3. It's the latest and most expandable board. It's also cheaper then others and easy to use.

Thanks a lot.
I have also found out about this JS library for Arduino and more:
http://johnny-five.io/


text:
Help Improving Debouncing
In short, I am attempting to debounce several buttons using something like a while loop instead of delays.
This code runs in a box with a series of buttons on it, if the correct sequence of buttons is pressed, then the arduino will run a flashing LED sequence and open a solenoid.  There are two correct sequences, a "right" answer (Green LED), and a master code (Blue LED).  Anything else results in the failed sequence (Red LED).  The problem I am currently having is that my current debouncing system is very finicky, I would like to implement something allowing more flexibility for speed of button press etc.
The problem currently is I am relying on delay to debounce.  If I delay long enough it becomes difficult to type the correct code in because the user has to know to wait a certain amount of time before pressing the next key.  If I do not delay long enough my combination is regularly corrupted  with extraneous button pushes.
Below is my code, The debouncing occurs on lines 128-160.  Below that is a lot of LED flashing.
#define CPU_RESTART_ADDR (uint32_t *)0xE000ED0C
#define CPU_RESTART_VAL 0x5FA0004
#define CPU_RESTART (*CPU_RESTART_ADDR = CPU_RESTART_VAL);

const int button5 = 2;    //fifth  button is on pin 2
const int button4 = 3;    //fourth button is on pin 3
const int button3 = 4;    //third  button is on pin 4
const int button2 = 5;    //second button is on pin 5
const int button1 = 6;    //first  button is on pin 6
const int systemLED = 7;  //Red LED on front of Box (Power Indicator)
const int redLed1 = 8;    //red LED is on pin 7
const int greenLed1 = 9;  //green LED is on pin 8
const int blueLed1 = 10;   //blue LED is on pin 9
const int redLed2 = 11;   //red LED is on pin 10
const int greenLed2 = 12; //green LED is on pin 11
const int blueLed2 = 13;  //blue LED is on pin 12
const int solenoid = 14;  //activates solenoid Relay Circuit
const int relay2 = 15;     // >:-}

int code[] = {1,2,3,4,5}; //the desired code is entered in this array, separated by commas

int entered[5]; //create a new empty array for the code entered by the user (has 4 elements)

void setup(){ //run once at sketch startup
  Serial.begin(9600); //begin Serial
  pinMode(systemLED, OUTPUT);
  pinMode(button1, INPUT); //button 1 is an input
  pinMode(button2, INPUT); //button 2 is an input
  pinMode(button3, INPUT); //button 3 is an input
  pinMode(button4, INPUT); //button 4 is an input
  pinMode(button5, INPUT); //button 5 is an input
  pinMode(redLed1, OUTPUT); //the red LED is an output
  pinMode(redLed2, OUTPUT); //the red LED is an output
  pinMode(greenLed1, OUTPUT); // the green LED is an output
  pinMode(greenLed2, OUTPUT); // the green LED is an output
  pinMode(blueLed1, OUTPUT);
  pinMode(blueLed2, OUTPUT);
  pinMode(relay2, INPUT_PULLUP); //enable relay outputs as input_pullup in order to prevent triggering when initial power is provided
  pinMode(solenoid, INPUT_PULLUP);

  delay(500);

  pinMode(relay2, OUTPUT);   //convert pinmode for relay back to operable mode
  pinMode(solenoid, OUTPUT);//this prevents the relay and relay2 from triggering at startup

  digitalWrite(relay2, HIGH);
  digitalWrite(solenoid, HIGH);

  digitalWrite(blueLed1, HIGH); //turn both
  digitalWrite(greenLed1, HIGH);
  digitalWrite(blueLed2, HIGH);
  digitalWrite(greenLed2, HIGH); //LEDs on
  delay(100); //wait
  digitalWrite(blueLed1, LOW); //turn both
  digitalWrite(greenLed1, LOW);
  digitalWrite(blueLed2, LOW);
  digitalWrite(greenLed2, LOW); //LEDs off
  digitalWrite(systemLED, HIGH); //turn the red LED on
  delay(75); //wait

  for (int i = 0; i < 5;i++){ //work through numbers 0-4
    Serial.println(code[i]); //print each digit of the code
    Serial.println(entered[i]); //print each element of the entered[] array (this was for me to check that it started at 0)
  }
}

void checkEntered1(int button /* define the 1,2,3 or 4 as an integer called button */){ //check the first element of the entered[] array
  if (entered[0] != 0){ //if it is not a zero, i.e. it has already been input
    checkEntered2(button); //move on to checkEntered2, passing it "button"
  }

  else if(entered[0] == 0){ //if it is zero, i.e. if it hasn't been defined with a button yet
    entered[0] = button; //set the first element as the button that has been pressed
    Serial.print("1: ");Serial.println(entered[0]); //for debugging
  }
}

void checkEntered2(int button){ //check the second element of the entered[] array
  if (entered[1] != 0){ //if it is not a zero, i.e. it has already been input
    checkEntered3(button); //move on to checkEntered3, passing it "button"
  }

  else if(entered[1] == 0){ //if it is zero, i.e. if it hasn't been defined with a button yet
    entered[1] = button; //set the second element as the button that has been pressed
    Serial.print("2: ");Serial.println(entered[1]); //for debugging
  }
}

void checkEntered3(int button){  //check the third element of the entered[] array
  if (entered[2] != 0){ //if it is not a zero, i.e. it has already been input
    checkEntered4(button); //move on to checkEntered4, passing it "button"
  }

  else if (entered[2] == 0){ //if it is zero, i.e. if it hasn't been defined with a button yet
    entered[2] = button; //set the third element as the button that has been pressed
    Serial.print("3: ");Serial.println(entered[2]); //for debugging
  }
}

void checkEntered4(int button){ //check the fourth element of the entered[] array
  if (entered[3] != 0){ //if it is not a zero, i.e. it has already been input
    checkEntered5(button); //set the final element as the button that has been pressed
  }

  else if (entered[3] == 0){ //if it is zero, i.e. if it hasn't been defined with a button yet
    entered[3] = button; //set the fourth element as the button that has been pressed
    Serial.print("4: ");Serial.println(entered[3]); //for debugging
  }
}

This is where I need help debouncing, as can be seen I have attempted to debounce with delay(75) originally I had delay(1000) as the debounce which worked but required the user to wait or break normal rhythm while entering the code due to the long delay between inputs being accepted.
void checkEntered5(int button){ //check the fifth element of the entered[] array
  if (entered[4] == 0){ //if it is zero, i.e. if it hasn't been defined with a button yet
    entered[4] = button; //set the final element as the button that has been pressed
    Serial.print("5: ");Serial.println(entered[4]); //for debugging
    delay(100); //allow time for processing
    compareCode(); //call the compareCode function
  }
}
void loop(){ //run repeatedly
  if (digitalRead(button1) == HIGH){ //if button1 is pressed
    checkEntered1(1); //call checkEntered and pass it a 1
    //delay(1000); //wait
    while( digitalRead(button1) == HIGH) { } // do nothing
    delay(75);//wait, needed for correct functioning, otherwise
              //buttons are deemed to be pressed more than once
  }
  else if (digitalRead(button2) == HIGH){ //if button2 is pressed
    checkEntered1(2); //call checkEntered1 and pass it a 2
    //delay(1000); //wait
    while( digitalRead(button2) == HIGH) { } // do nothing
    delay(75); //wait
  }
  else if (digitalRead(button3) == HIGH){ //if button3 is pressed
    checkEntered1(3); //call checkEntered1 and pass it a 3
    //delay(1000); //wait
    while( digitalRead(button3) == HIGH) { } // do nothing
    delay(75); //wait
  }
  else if (digitalRead(button4) == HIGH){ //if button4 is pressed
    checkEntered1(4); //call checkEntered1 and pass it a 4
    //delay(1000); //wait
    while( digitalRead(button4) == HIGH) { } // do nothing
    delay(75); //wait
  }
  else if (digitalRead(button5) == HIGH){ //if button4 is pressed
    checkEntered1(5); //call checkEntered1 and pass it a 5
    //delay(1000); //wait
    while( digitalRead(button5) == HIGH) { } // do nothing
    delay(75); //wait
  }
}

Everything below this point is included simply to provide context for the check entered code seen above.  Everything functions as is expected except that the debounce is imperfect.
void compareCode(){ //checks if the code entered is correct by comparing the code[] array with the entered[] array
  for (int i = 0; i<4;i++){
    Serial.write(entered[i]);
  }
  if ((entered[0]==code[0]) && (entered[1]==code[1]) && (entered[2]==code[2]) && (entered[3]==code[3]) && (entered[4]==code[4])){ //if all the elements of each array match the passcode

    //--. .-. . . -.

    digitalWrite(solenoid, LOW);
    digitalWrite(greenLed1, HIGH); //turn the green LED on
    digitalWrite(greenLed2, HIGH); //turn the green LED on
    delay(50); //wait for a bit
    digitalWrite(greenLed1, LOW); //turn the green LED off
    digitalWrite(greenLed2, LOW); //turn the green LED off
    delay(500);
    digitalWrite(solenoid, HIGH);
    delay(2500);

  }

  else if ((entered[0]==code[4]) && (entered[1]==code[2]) && (entered[2]==code[0]) && (entered[3]==code[3]) && (entered[4]==code[1])){

    //-... .-.. ..- .

    digitalWrite(blueLed1, HIGH);
    digitalWrite(blueLed2, HIGH);
    delay(1000);
    digitalWrite(solenoid, LOW);
    delay(4000);
    digitalWrite(blueLed1, LOW);
    digitalWrite(blueLed2, LOW);
    delay(50);
    digitalWrite(redLed1, HIGH);
    digitalWrite(redLed2, HIGH);
    delay(1000);
    digitalWrite(redLed1, LOW);
    digitalWrite(redLed2, LOW);
    delay(50);
    digitalWrite(solenoid, HIGH);
    delay(1000);
  }

  else { //if you (or the intruder) get the code wrong
    flash(); //call the flash function
    for (int i = 0; i < 4; i++){ //this next loop is for debugging
      entered[i] = 0;
      Serial.println(entered[i]);
    }
  }
}

void flash(){ // this is basically the blink example
  //.-. . -..

  digitalWrite(relay2, LOW);
  digitalWrite(redLed1, HIGH);
  digitalWrite(redLed2, HIGH);
  delay(50);
  digitalWrite(redLed1, LOW);
  digitalWrite(redLed2, LOW);
  delay(250);
  digitalWrite(redLed1, HIGH);
  digitalWrite(redLed2, HIGH);
  delay(50);
  digitalWrite(redLed1, LOW);
  digitalWrite(redLed2, LOW);
  digitalWrite(relay2, HIGH);
  delay(2500);
  CPU_RESTART;

If you want to solve the denouncing problem, make a simpler sketch that only accepts input, and maybe outputs the result to the serial monitor.  On the other hand if you can accept input in isolation and the issue seems more in the interaction with your input vs. display code, see if you can make a simpler case (fewer outputs, etc) that illustrates the interaction.  At present this is still too big to be readily understood, but is it possible you may have a situation where each distinct user input triggers a time-consuming sequence of output operations?

I believe I understand you, however I may have phrased my question poorly, I am simply looking to see if anyone knows of a simple method of debouncing which is more reliable than the delay function.  This code is adapted from someone else's which I found a long time ago, I do not entirely understand the intricacies of it to simplify on my own.

The simplest means of debouncing is that once you have any input you will accept, you ignore all inputs for some fraction of a second.  If you also trigger time consuming operations from the inputs is when that gets complicated - simplest there is to not accept new input until they are done, but the user may not enjoy that.  Or if you need to recognize a different button immediately and only have a debounce delay to the same button. Or if you want to have auto-repeate if a button is held down long enough.

    while( digitalRead(button2) == HIGH) { } // do nothing

Doing that right after a digital read assumes there is only one bounce, That's highly unlikely. I would put the delay right after the read and before the delay. Depending on the type of switch bouncing varies, but shouldn't be over 150mS. Less for the little tactile push button used on pcboards.
    // read button
    delay(75); //wait
    while( digitalRead(button2) == HIGH) { } // do nothing

You can always use an RC filter to debounce each button, then you don't have to worry about the difficult key presses, just the extra parts and expense.

Many of the lines shown in the program box are superfluous – totally redundant and unnecessary.  I suggest that you revise it [see (a)-(d) below], then replace all the stuff in the program box with the revised version.
(a) Use more subroutine parameters.  In cases where you have four or five otherwise-identical routines that differ only in some constants, pass those values into one routine as parameters.  Don't write out long lists of nearly-identical routines.
(b) Don't create artificial dependencies.  Your code in the five checkEntered- routines is obscure, so I can't say without taking more time than I care to spend, but it appears that you have made tests for button 2 depend on tests for button 1, and so on down the line.  That makes no sense.  Test each button separately and in an identical manner, using a parameterized subroutine.  To enforce an order of button presses, create an array P of 5 bytes (or however many you like) and initialize a counter Q to zero.  Whenever your debounce routine detects a valid button press, if Q is small enough store the button number in P[Q] and then increase Q.  (If Q is (size P) or more, don't store.)
(c) Don't nest subroutine calls more deeply than necessary.  Your checkEntered1() can call checkEntered2(), which can call checkEntered3(), and so forth.  Besides not making sense, that series of calls uses five times as much stack memory as necessary.  (Generally, RAM is a scarce resource on AVR microcontrollers.)  Just use five calls, one after another, to a properly parameterized subroutine.
(d) For repetitious sequences like the following,
digitalWrite(greenLed1, HIGH); //turn the green LED on
digitalWrite(greenLed2, HIGH); //turn the green LED on
delay(1000); //wait for a bit
digitalWrite(greenLed1, LOW); //turn the green LED off
digitalWrite(greenLed2, LOW); //turn the green LED off
delay(250); //wait for a bit

which seem to recur with minor variations about a dozen times, write a properly parameterized subroutine and call it as necessary.  For example:
void flashPair(byte L1, byte L2, int del1, int del2) {
  digitalWrite(L1, HIGH);   // turn the green LED on
  digitalWrite(L2, HIGH);   // turn the green LED on
  delay(del1);          // wait a little
  digitalWrite(L1, LOW);    // turn the green LED off
  digitalWrite(L2, LOW);    // turn the green LED off
  delay(del2);          // wait a little
}
...
flashPair(greenLed1, greenLed2, 1000, 250);
flashPair(redLed1,   redLed2,     50, 2500);
...

There are, of course, other ways of handling those dozen tedious repetitions.  For example, one could write a for loop that gets pin numbers and delays from an array and turns LEDs on or off as needed.
For example, see an answer to question 17453 for a method of treating multiple buttons systematically using information in arrays along with a for loop.

I have used and know of many others who use the Bounce2 Library to provide an easy way to debounce the switch without using any delays so the user wouldn't have to pause between presses. Behind the scenes it uses the Millis function to provide the debounce which doesn't interrupt the sketch running at all. You could also write the Debounce with Millis function yourself.