body:
So I have an issue that I can't really think of a reason why it would be happening. I have an Arduino Mega connected on Serial3 to a RS232 breakout board with a male DB9 connector on it. I then have two female breakout boards connected. One is connected to the RS232 breakout board and the other to a Cisco DB9 to roll over cable, which is connected to my Cisco Switch, or if it is, it is being ignored.

For some reason no data sent from the Arduino is making it to the Cisco switch that I can tell. I did confirm that it is sending data using a USB to DB9 adapter and PUTTY. I can send and receive data from both the Arduino and PUTTY correctly to the other.

I can receive data from the switch perfectly. Cisco's default settings are the same as the Arduino's, 9600, 8bits, no parity, 1 stop bit etc...

I can also connect the switch to the USB to DB9 adapter directly and send and receive fine through it / PUTTY as well.

Does anyone have any suggestions why I'd be able to send data to and from Putty, but only receive data from the switch, or why the data going to the switch is failing?

[![Arduino Setup][1]][1]

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

    void setup() {
      Serial.begin(9600, SERIAL_8N1);
      Serial3.begin(9600, SERIAL_8N1);
      Serial.println("Ready....");
      Serial.println();
    }

    void loop() {
      // read from Serial3, write to Serial
      if (Serial3.available()) {
        int inByte = Serial3.read();
        Serial.write(inByte);
      }
      // read from Serial, write to Serial3
      if (Serial.available()) {
        int inByte = Serial.read();
        Serial3.write(inByte);
      }
      Serial3.println(); // Added just to test if a cr could be passed
      Serial3.write(98); // Added just to test if a character could be directory passed
      Serial3.write(10); // Added just to test if a cr could be passed
    }

title: Cisco Switch not receiving serial communication from Arduino

Answers: 2

body:
Assuming this is a flow control problem:

> Is there such a thing as inb vs oob for a serial console connection?
> This isn't on the internal network of the switch in any way but the
> console port

It assumed this is a managed switch and the traffic on the console port has nothing to do with the traffic going through the switch. Rather this is likely a port to the computer inside the switch.  Such a port might be able to use RTS/CTS/DSR or X-on / and X-off.

If this is a flow control problem, consider first looking for thumb switches on the back of the switch to see if the method used for flow control over the console port can be selected. If that is not possible, consider simply hardwiring the out of band flow control pins to always allow for data to flow.  At 9600 baud, a dedicated Aruidno should be able to keep up.

Refer to the 9 pin connector in [this chart][1] to find the out of band flow control pins.

  [1]: https://en.wikipedia.org/wiki/Serial_port#Pinouts

body:
Could be a voltage problem. You're using an TTL->RS232 Adapter as far as I can tell from the picture, which is absolutely necessary. Arduino only gives out TTL Signal Level, which would not be "understood" by the Cisco Switch, which works on RS232 / Serial Voltage Level (which is a lot higher). However, maybe the RS232 Converter Module is faulty. You could check the output voltage level with a Multimeter and see if it actually is in the required range (http://www.radio-electronics.com/info/telecommunications_networks/rs232/signals-voltages-levels.php).

Also connecting ground correctly is important, but that should be ok on your setup :).


body:
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][1]:

    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();
      }

  [1]: https://github.com/bblanchon/ArduinoJson/blob/master/examples/JsonParserExample/JsonParserExample.ino

title: Cast from uint8_t* to char - loses precision

Answers: 1

body:
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);


body:
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:

title: avr-gcc -D is ignored

Answers: 1

body:
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)


body:
I am very new to this community. My first project with Arduino was using a LDR (light dependent resistor) in a circuit like this:

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

The input I got was as expected between 0 - 1023.

I then tried a similar project this time using a sound sensor like this:

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

My circuit is as follows:

 1. A0 on mic to A0 on Arduino
 2. GND to GND
 3. +ve to 5V
 4. 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.

  [1]: https://i.stack.imgur.com/Rxoi1.jpg
  [2]: https://i.stack.imgur.com/GiUuC.jpg

title: Problem with simple sound detection circuit using a microphone

Answers: 2

body:
I plotted the values you got in a spreadsheet:

[![Microphone input][1]][1]

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.

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/TVylT.png)

<!-- End schematic -->

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.

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

body:
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.


body:
```c++
#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

[![void value not ignored as it ought to be][1]][1]

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

title: keypad storing problem any idea store more than 11 numbers like phone number

Answers: 2

body:
>      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:

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

    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:

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

      char buf [15];
      GetNumber (buf, sizeof (buf) - 1);

body:
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.


body:
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.

title: Interfacing key-pad with arduino with 7 segment display

Answers: 1

body:
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
    }


body:
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?

title: Is it possible to pass HIGH and LOW values as parameter in a function?

Answers: 1

body:
`digitalWrite` expects the pin and value to be `uint8_t` type. So you can certainly pass LOW or HIGH to functions.

For example:

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

    void runMotor(int _dir, int _step, int wait, uint8_t value){
      digitalWrite(_dir, value);


body:
I'm trying to get the [nRF8001 BLE Breakout][1] polling properly on [Flora][2] 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][1] 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;
      }
    }

  [1]: https://learn.adafruit.com/getting-started-with-the-nrf8001-bluefruit-le-breakout/software-uart-service
  [2]: https://learn.adafruit.com/getting-started-with-flora/flora-pinout-diagram

title: How to connect Flora 2 and nRF8001 BLE Breakout

Answers: 1

body:
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.

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

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


body:
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();
    }

title: Compiles but doesn't print anything

Answers: 2

body:
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:

1. Constructors
2. System Init
3. Setup
4. Repeat forever:
5. -> Loop

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

body:
> 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.


body:
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)][1]

  [1]: https://arduino.stackexchange.com/questions/25263/serial-available-doesnt-work-right-after-upload

title: Serial communication doesn't work right after upload

Answers: 1

body:
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


body:
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.

title: Switch between ntc resistor sensors time based for other device

Answers: 1

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

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/bebYw.png)

<!-- End schematic -->

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.


body:
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);
      }
     }
    }

title: Expected } at the end of input

Answers: 2

body:
[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");
        }
      }
    }

body:
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>


body:
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?

title: Can I use L293D driver as ESC for arduino controlled quadcopter

Answers: 1

body:
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.


body:
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.

title: Error Uploading Arduino Sketch to Arduino Pro Mini

Answers: 1

body:
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.


body:
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
      }
    }

title: LED and Switch Compolation Error Arduino 101

Answers: 1

body:
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
    }


body:
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...

title: SerialUSB on Arduino Due

Answers: 1

body:
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!


body:
[![shift register with leds][1]][1]

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

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.

title: Formula for current through shift register

Answers: 1

body:
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


body:
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);
      }
    }
    }
    }

title: Expected declaration before } token

Answers: 1

body:
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);
      }
    }


body:
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][1]

[Could this work better?][2]

  [1]: http://www.ebay.com/itm/5V-1-2-4-6-8-Channel-Relay-Board-Module-Optocoupler-LED-for-Arduino-PiC-ARM-AVR-/371642356980?var=&hash=item56879c54f4:m:mgnWPfoXCbjWi3z8ochdzrw
  [2]: http://www.ebay.com/itm/5V-8-Channel-Low-Level-Trigger-Arduino-Solid-State-Relay-Module-with-Fuse-250V2A-/191963613200?hash=item2cb1ec4810:g:fc8AAOSwwPhWlcTF

title: Is there a cheap relay that can control voltage from stuff like bulb lights with a 5 V control output?

Answers: 3

body:
You can use a [5V Solid-State Relay module][1] 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.

  [1]: https://www.amazon.com/Tolako-Module-Arduino-Official-Boards/dp/B00VRUAHLE/ref=pd_lpo_107_lp_t_4?ie=UTF8&psc=1&refRID=K5X5T6967S4XKE4P14S6

body:
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.

body:
**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!


body:
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][1]):

    #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.

  [1]: http://www.ayomaonline.com/programming/quickstart-sim800-sim800l-with-arduino/

title: How do I clear sim800L buffer?

Answers: 1

body:
According to the [SIM800 AT Command Set](https://cdn-shop.adafruit.com/datasheets/sim800_series_at_command_manual_v1.01.pdf) 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.


body:
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][1].

    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.

  [1]: https://learn.adafruit.com/multi-tasking-the-arduino-part-1/a-classy-solution

title: Most memory efficient way to program

Answers: 2

body:
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:

1. Keep your variables the smallest size possible for the contents (use 8 bit variables instead of `int` for storing smaller numbers).
2. 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.

body:
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.


body:
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

title: Arduino project list: What do I need?

Answers: 1

body:
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][1].

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.

  [1]: https://arduino.stackexchange.com/questions/29997/sensor-for-detect-there-is-a-car-or-not/29998#29998


body:
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;

title: Help Improving Debouncing

Answers: 3

body:
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](https://arduino.stackexchange.com/questions/17453/arduino-sending-keystrokes-via-push-buttons-proper-bouncing-and-manually-settin/17462#17462) for a method of treating multiple buttons systematically using information in arrays along with a `for` loop.

body:
        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.

body:
I have used and know of many others who use the [Bounce2][1] 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][2] function yourself.

  [1]: https://github.com/thomasfredericks/Bounce2
  [2]: https://www.arduino.cc/en/Tutorial/Debounce


body:
So I have a project where I need to run pthreads (coded in C) on an Arduino Uno. I've written and compiled the code and the output is what we need when I use a C compiler. But I'm having trouble running it on the board. I've installed the Pthreads library in the libraries folder of the Arduino, but it still gives me erroneous errors.

I'm jumbling back and forth without finding a solution, can anyone give me any tips?  It's become so annoying that I'm thinking of buying a Pi.

Any help is much appreciated.

Edit: let me rephrase: the professor wants us to implement pthreads on an Arduino or Pi. I didn't decide pthreads is the solution, it is the requirement.

title: Running Pthreads (POSIX) on an Arduino

Answers: 1

body:
> I need to run pthreads ...

You probably don't *need* to run pthreads. This sounds like an [X-Y problem](http://xyproblem.info/).

What you are probably saying is "I need to do multiple things at once" (such as flashing LEDs whilst taking ADC readings, or play sounds at the same time as moving a vehicle forwards).

You could get better answers if you described the project (X) and not your proposed solution (Y) which you think is pthreads.

I have a web page about [How to do multiple things at once ... like cook bacon and eggs](http://www.gammon.com.au/blink) which goes into this sort of thing in some detail.

Some example code from that page which blinks different LEDs at different rates is:

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

    // Which pins are connected to which LED
    const byte greenLED = 12;
    const byte redLED = 13;

    // Time periods of blinks in milliseconds (1000 to a second).
    const unsigned long greenLEDinterval = 500;
    const unsigned long redLEDinterval = 1000;

    // Variable holding the timer value so far. One for each "Timer"
    unsigned long greenLEDtimer;
    unsigned long redLEDtimer;

    void setup ()
      {
      pinMode (greenLED, OUTPUT);
      pinMode (redLED, OUTPUT);
      greenLEDtimer = millis ();
      redLEDtimer = millis ();
      }  // end of setup

    void toggleGreenLED ()
      {
       if (digitalRead (greenLED) == LOW)
          digitalWrite (greenLED, HIGH);
       else
          digitalWrite (greenLED, LOW);

      // remember when we toggled it
      greenLEDtimer = millis ();
      }  // end of toggleGreenLED

    void toggleRedLED ()
      {
       if (digitalRead (redLED) == LOW)
          digitalWrite (redLED, HIGH);
       else
          digitalWrite (redLED, LOW);

      // remember when we toggled it
      redLEDtimer = millis ();
      }  // end of toggleRedLED

    void loop ()
      {

      // Handling the blink of one LED.
      if ( (millis () - greenLEDtimer) >= greenLEDinterval)
         toggleGreenLED ();

      // The other LED is controlled the same way. Repeat for more LEDs
      if ( (millis () - redLEDtimer) >= redLEDinterval)
        toggleRedLED ();

    /* Other code that needs to execute goes here.
       It will be called many thousand times per second because the above code
       does not wait for the LED blink interval to finish. */

    }  // end of loop

---

>  It's become so annoying that I'm thinking of buying a Pi.

Sure you can do that. You can buy a Mac or a Windows PC. You can buy 5 Arduinos. But if you want to learn how to do multiple things on an Arduino you can learn how to manage a "state machine" and do it all on $5 of hardware.

---

As an example of what *can* be done see [this post](http://www.gammon.com.au/forum/?id=12623) about a retro arcade game called Toorum's Quest written by Petri Häkkinen and run on an Atmega328P (same chip as in the Arduino Uno).

Hardware and screenshots:

[![Toorum's Quest][1]][1]

In his code (which I compiled using the Arduino IDE to test it) he has:

* Multiple sprites on a TV screen with a resolution of 104x80 with 256 colors.
* Sprites are multiplexed so you can have as many as you want on the screen.
* He moves them around according to game logic
* He plays music and sound effects at the same time
* He reads from a game controller

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


body:
I want to simply switch a relay like Majenko describes it for [my last question][1]. (time based switching of a relay)

That's the code I came up with based on the documentation:

    int relayPin = 2; // pin where relay is attached
    long mins = 5L;

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

    void loop() {
        digitalWrite(relayPin, HIGH);
        delay(mins * 60L * 1000L);
        digitalWrite(relayPin, LOW);
        delay(mins * 60L * 1000L);
    }

Now I want to use a real device and have been looking around, but there are tons of different boards, so some shopping advice would be really great. What I would like if possible:

- Closed casing to reduce risk of people touching stuff. (also for a "professional" look)
- Built in power supply from 220V AC.
- Outputs strong enough to work without external logic, just connect the relay and go.
- Small size and low cost, in case I start using these everywhere in the house i don't need to reevaluate. :)

  [1]: https://arduino.stackexchange.com/a/30250/27435

title: Which arduino should i use for a very simple one pin "blinking led" type project?

Answers: 2

body:
For beginners, use an Arduino Uno. It is ready to use and quite expendable with shields. They have the USB to SERIAL chip on the board. Only week point is that it is sometimes large from space sensitive projects.

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

For more advanced users, I would suggest the Pro Mini (my personnal favorite). It is small, powerful and even has more pins then the UNO. The main disadvantage is that it requires an FTDI connector for the USB to SERIAL. Note that this NOT recommended if you use a lot of I2C.

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

Finaly, there is the overkill option. Only use this if you are considering to get one Arduino to rule them all!. It's the Arduino Mega 2560. It is the overkill of the overkill. So many GPIOs and ANALOG inputs. It is also unique for its core which is different the then normal ATmega328.

[![enter image description here][3]][3]

Then finaly there is the most easy to use one, the Red Board by Sparkfun. It combines the best of each Arduino in one. Note that this one is not manifactured and backed by Arduino.

[![enter image description here][4]][4]

That is pretty much a summary of all of the most popular types of Arduino that there is.

**[EDIT]**

Note that none of them has an included case and a circuit that can reduce 220V to 5V. If you really want a case, get an UNO. There are many cases for it. For transforming 220V to 5V, use an 5V wallplug. If you have something like a 12V wallplug, you can also connect it to the Arduino but you have to make sure you connect it to the Vin port.

  [1]: https://i.stack.imgur.com/89Mpc.png
  [2]: https://i.stack.imgur.com/7bpj1.png
  [3]: https://i.stack.imgur.com/pfAjp.png
  [4]: https://i.stack.imgur.com/0VaLB.png

body:
Personally I would recommend a chip from the ATtiny series (ATtiny85 for example - it has 5 programmable pins and costs about $1 - $3).

Even though it is not really an Arduino board - it is really great  as you can easily program it from another board from within the Arduino IDE, and it is really lightweight and cheap.

Watch this
[Youtube video][1]
for a guide to set it up - it is really useful.

Otherwise you can simply give "*attiny85 arduino setup*" a google

  [1]: https://youtu.be/30rPt802n1k


body:
I am sending data from ESP8266 (NodeMCU) to Arduino using serial and 9600 baud rate on both sides. Since it is uni-directional and from NodeMCU to Arduino, I am not using a voltage regulator and I have connected tx (Software Serial) of NodeMcu to Rx of Arduino. I've connected the usb of nodeMCU to my computer. I've done the same thing to power Arduino.

Here is some sample code on NodeMCU:

    #define Arduino_RX 4 // D2
    #define Arduino_TX 5 // D1
    SoftwareSerial ArduinoSerial(Arduino_RX, Arduino_TX); // RX | TX

    void setup() {
      Serial.begin(115200);
      ArduinoSerial.begin(9600);
      delay(10);

      // Connect to WiFi network
      Serial.print("Connecting to ");
      Serial.println(ssid);

      WiFi.begin(ssid, password);
      WiFi.config(ip, gateway, subnet);

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

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

    void loop()
    {
        ArduinoSerial.println("hi");
        Serial.println("hi");
        delay(1);
    }

Code on Arduino

    #define ESP8266_RX   2
    #define ESP8266_TX   3
    #include <SoftwareSerial.h>
    SoftwareSerial ESPserial(ESP8266_RX, ESP8266_TX); // RX | TX

    void setup() {
      // put your setup code here, to run once:
        Serial.begin(9600);     // communication with the host computer
        ESPserial.begin(9600);
        Serial.println("Ready");

    }

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

title: Uni-directional communication between NodeMCU and Arduino spits out garbage

Answers: 1

body:
1. https://www.pjrc.com/teensy/td_libs_AltSoftSerial.html

2. Do you GND them via your PC USB? Try connecting their GND as well.

3. External power could be an issue as well, I am not aware of power consumption of ESP when they do stuff with their WiFi.


body:
I'm trying to run a sample sketch on my Genuino 101 but the following error shows up. Here is a verbose version.

    Starting download script...
    Args to shell: [/home/userk/.arduino15/packages/Intel/tools/arduino101load/1.6.9+1.28/x86/bin /tmp/buildc2bfbabdb2df5b87204fdf9941c899a2.tmp/Blink.ino.bin /dev/ttyACM0 verbose ATP1BLE000-1541C5635 141312]
    Serial Port: /dev/ttyACM0
    BIN FILE /tmp/buildc2bfbabdb2df5b87204fdf9941c899a2.tmp/Blink.ino.bin
    Waiting for device...
    Waiting for device...
    Waiting for device...
    Waiting for device...
    Waiting for device...
    Flashing is taking longer than expected
    Try pressing MASTER_RESET button
    Waiting for device...
    Waiting for device...
    Waiting for device...
    Waiting for device...
    Waiting for device...
    ERROR: Timed out waiting for Arduino 101 on /dev/ttyACM0

I have installed the Intel Curie package with the Boards Manager and tried to press the Master Reset button, the reset and a combination of both. Nothing.

I have also tried the suggestions provided in this [question] [1] but they did not work. I am using Ubuntu 16.04. Do you have any advice?

EDIT: Same problem with Windows 10/8/7.

  [1]: https://arduino.stackexchange.com/questions/18959/error-timed-out-waiting-for-arduino-101-anything-i-can-do

title: Genuino 101 - Can't upload my sketch - Timeout Error

Answers: 3

body:
Is the Genuino 101 board been recognized by the OS? Sounds like your board is not being recognized by the system.

For windows, open up your device manager before plugging into the PC. After plugging in, the device manager should refresh and display the board in the COM Port section.

For Linux (in your case Ubuntu), you can use the *dmesg | tail* cmd to check whether your board is being detected when you plug in the Genuino 101 board.

body:
I have the same problem while uploading sketches ,
when i uploading the sketch and press  `MASTER_RESET` button solved my problem .
when it shows `Waiting for device...` just press the `MASTER_RESET` .

or try to update Firmware

    Select Tools >> Programmer >> Arduino 101 Firmware Updater
    Select Tools >> Burn Bootloader

body: Problem solved with a downgrade of the Arduino 101 core. Try with all available versions.