message:
How to repair or work around a damaged usb port on the Arduino?

While unplugging the usb cable from the Arduino, the plastic piece in the center of the port (the part that separates the pins) broke off and lodged into the end of the usb cable. I didn't notice that it broke off and when I plugged the cable back into the Arduino it bent one of the pins back onto itself.

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

How would you go about repairing this?

If I fail to repair it is there an alternate method to programming the board?

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

body:
You would need to replace the whole socket in order to repair it. For that you would need:

* Soldering iron
* Solder sucker
* Solder wick
* Patience and experience

Or you just connect an FT232 breakout board to TX, RX and RESET as if you were making a breadboard arduino and program the board through that.


sender: user

sender: assistant

body:
You could try bending the pin back, removing the white part from your cable, and gluing it back in.

Second option is to replace the USB socket on the Arduino board. You might be able to salvage a socket from some old electronics you still have lying around.

Third option is to cut one end of a spare USB cable, and solder the 4 wires inside the cable directly to the corresponding pads on the bottom of the broken socket. Add some glue to provide some strain-relieve to the cable.

Fourth option is an external USB to serial converter, like @Majenko suggested.


body:
I would suggest to actually remove the whole thing and resolder it. There are many tutorials out there is you're new to soldering. This way, it is less probable that it creates a short or data loss during compilation.

If you don't want to solder, then you might be able to use an FTDI connector. FT232s are quite cheap.

Tx > Rx

Rx > Tx

Reset > Reset

Vcc > Vcc

GND > GND


message:
Arduino Uno Wifi Module ESP8266 AT Command Test error

When i Connected Rx>Rx (Rx Of module To Pin 0 Of Arduino) And Tx>Tx ( Tx Of Module To Pin 1 Of Arduino), The AT Command Test shows The Following error With Scrambled Words, but when I Connect Rx>Tx (Rx Of Module To Pin 1 Of Arduino) And Tx>Rx(Tx Of Module To Pin 0 Of The arduino), The AT Command Test Shows a Blank Screen. I Connected VCC, CHPD and RST Of Module to 3v Of Arduino and GND Of Module To GND Of Arduino. So How Do I Connect Arduino To Wifi Module which passes the at command test, Btw i Have an Intermediate, ie Motor Shield, I Connected Motor Sheild To Arduino And Then I connected Wifi Module To Motor Shield. Listen So  I need To Connect Wifi Module To Arduino, such that there isnt any error. what do i do?[![RX>Rx and Tx>Tx Pair][1]][1]

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

body:
The first connection you made between arduino and esp which resulted in some random data means both are communicating whereas the second connection where the screen shows blank means communication hasnt been established on account of incorrect wiring. So your first connection tx>tx and rx>rx is **correct**.

 The only two area which you need to check is the baud rate and the mode of return. Some Esps work at 115200 with mode carriage return. So you can try different combinations of baud rate and mode to check which one does your Esp support.


message:
The best signal source for a path-finding robot

Newbe question - I'm thinking of creating a simple robot that heads to a signal source.

Ie, when you press a button on some remote control - the robot will head towards its source.

What would be the best choice of signal? A strength of a wifi, sound?

AD

body:
IR sensor in combination with an ultrasonic distance sensor would work great.

You can mimic a radar with an IR sensor so that it can detect from where the IR source from your remote is comming from. Then from there, process the angles and make you robot go towards it.

The ultrasonic distance sensor can be used a "fail" prevention system. In the sense that if it detects an object in front of the robot, it will stop, go around it and then continue towards the target


body:
I like @Canadiancyborg's IR solution, but the same theory can be applied to any other emitter, and RF emitters may be preferable to an IR emitter since IR light can be blocked by intermediate objects. Also an omnidirectional RF transmitter is easier to arrange than an omnidirectional IR transmitter.

The basic theory is that you need to work out which direction a signal is coming from. In order to do that you need to "look around you" and find at which angle the signal is strongest.

A highly directional receiver (parabolic dish, IR receiver with lens, etc) will allow you to sense the signal strongest when the receiver is pointing directly at the source. By then rotating the receiver (either on its own independent rotational system, such as a servo motor, or by rotating the entire robot using the wheels) you can "lock on" to the direction where the signal is strongest and drive towards it.


message:
Attiny85 code on Attiny84

I made OLED timer/watch using Attiny85, but as internal clock isnt accurate i need external crystal. On Attiny85 im short on pins so i am switching to Attiny84 but i have problems to compile/upload same code to Attiny84. Even if i stay on Attiny84 8mhz internal clock as on Attiny85 i still cant compile.
Im using Arduino UNO as ISP.

Error what i have:

    WDT_Time.cpp: In function 'void setup_watchdog(uint8_t)':
    WDT_Time.cpp:272: error: 'WDTCR' was not declared in this scope
    WDTCR |= (1 << WDCE) | (1 << WDE);
    ^
    In file included from c:\program files (x86)\arduino\hardware\tools\avr\avr\include\avr\io.h:99:0,
                 from c:\program files (x86)\arduino\hardware\tools\avr\avr\include\avr\pgmspace.h:88,
                 from C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Arduino.h:28,
                 from WDT_Time.cpp:12:
    WDT_Time.cpp:276: error: 'PCIE' was not declared in this scope
       sbi(GIMSK, PCIE); // Turn on Pin Change interrupts (Tell Attiny85 we want to use pin change interrupts (can be any pin))
                  ^
    WDT_Time.cpp:276:3: note: in expansion of macro 'sbi'
       sbi(GIMSK, PCIE); // Turn on Pin Change interrupts (Tell Attiny85 we want to use pin change interrupts (can be any pin))
       ^
    WDT_Time.cpp:277: error: 'PCMSK' was not declared in this scope
       sbi(PCMSK, PCINT3);
           ^
    WDT_Time.cpp:277:3: note: in expansion of macro 'sbi'
       sbi(PCMSK, PCINT3);
       ^
    'WDTCR' was not declared in this scope

body:
There are slight differences between registers, register names and registers bit names:

- `WDTCR` is named `WDTCSR`
- `PCIE` doesn't exist in `GIMSK` as there are two IO ports, so there are two pin change channels: `PCIE0` and `PCIE1`
- and `PCMSK` is similar to `PCIE`. There'll be two of them too.

Basically you have to look into both datasheets and compare what you are using and check if it's correct.


message:
Serial loop stopped after a while, I don't know why

I am very new to Arduino. I wrote a program in order to read some registers in a I2C device. I receive HEX datas.

So the Arduino LEONARDO is connected to the external board using the 2-wires-bus.
Then informations are sent to my computer by using Serial.println.

My problem is my Arduino stops working after a while, maybe 25 or 30 loops. Sometimes I loose communication and I have to reboot the Arduino.

I guess it's an overflow issue or I'm loosing connection randomly :

    int dt = 500;
    int dt2 = 1000; // used for delay duration
    #include "Wire.h"
    #include <Process.h>
    #define pot_address 0x25 // each I2C object has a unique bus address, the MCP40

    void setup() {
      // put your setup code here, to run once:
      Wire.begin();
      Serial.begin(9600);

    }

    void loop() {
      // put your main code here, to run repeatedly:

      Wire.beginTransmission(pot_address);
      Wire.write(0); //
       Wire.endTransmission();
      Wire.requestFrom(pot_address,8);
      byte b = Wire.read();

      Wire.beginTransmission(pot_address);
      Wire.write(1); //
       Wire.endTransmission();
      Wire.requestFrom(pot_address,8);
     byte c = Wire.read();

       Wire.beginTransmission(pot_address);
      Wire.write(2); //
       Wire.endTransmission();
      Wire.requestFrom(pot_address,8);
     byte d = Wire.read();

      Wire.beginTransmission(pot_address);
      Wire.write(3); //
       Wire.endTransmission();
      Wire.requestFrom(pot_address,8);
     byte e = Wire.read();

      Wire.beginTransmission(pot_address);
      Wire.write(4); //
       Wire.endTransmission();
      Wire.requestFrom(pot_address,8);
     byte f = Wire.read();

      Serial.print("b");
      Serial.println(b, HEX);
      Serial.println("-");
      Serial.print("c");
      Serial.println(c, HEX);
      Serial.println("-");
      Serial.print("d");
      Serial.println(d, HEX);
      Serial.println("-");
      Serial.print("e");
      Serial.println(e, HEX);
      Serial.println("-");
      Serial.print("f");
      Serial.println(f, HEX);
      Serial.println("-");

     delay(dt2);

    }

body:
Add:

    while(!Serial) ;

I'll make sure the Leonardo is in sync with the Serial communication.

It is the case because the Leonardo is USB native thus the Serial communication works differently.


message:
Amplified piezo sensor wiring problem

I am trying to amplify the signal from an Adafruit Small enclosed piezo.  The piezo is working using the Arduino Knock example but I want to increase the sensitivity using an amplifier.  The wiring shown below does not work using the Knock sketch and I am assuming it is a problem with the wetware and the wiring(NOOB here).
Any advice in amplifying the piezo is appreciated.[![enter image description here][1]][1]

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

body:
You don't seem to understand how to wire an OP-AMP. Here is a quick tutorial on their basics:

https://www.youtube.com/watch?v=kqCV-HGJc6A

The thing is that you are missing a LOT of resistors. An usual OP-AMP circuit contains many resistors to determine the amount of amplification and more...

The tutorial explains quite well what resistor and where do you need to put them in order for your circuit.


message:
Returning an int array from a function

I have a function that needs to return 3 int values. I currently use an array declared in the global scope and I ask the function to write into them. Is there a way to make a function return an array?

Here is what I want to do:

    int function()
    {

    int array[3];

    array[0] = 19;  //these are just random numbers

    array[1] = 7;

    array[2] = 69;

    return array[]; //is this possible??

    }

body:
There are 2 ways to do what you want in C. One relies on the function caller managing memory, the other on the "library" code managing the memory. If you go with the caller-managed memory, your function accepts a buffer and fills it. For "library" managed memory, you provide additional functions to allocate and release the buffer that the caller then calls

If you want to use C++ idioms, you can make a class (possibly static) that allocates the memory and provides access to the data.


body:
There are several ways to achieve what you want:

## The way that does not work

Did you try to compile the code you gave in the question? Then you
probably noticed it does not compile. I tried and got: “error: expected
primary-expression before ‘]’ token”, meaning the compiler expected
`return array[some_index];`.

## The way that almost works

Remove the brackets and just return `array`:

    int *function()
    {
        int array[3];
        array[0] = 19;
        array[1] = 7;
        array[2] = 69;
        return array;
    }

This may work, or not, depending on the surrounding code, on how the
optimizer processes your program, and on how lucky you are when you test
it. It is called “undefined behaviour” and is something you should
always avoid.

Here is what happens: in C (and C++) you cannot return an array. The
identifier `array` “decays” to a pointer pointing at its first element.
Then `return array` is essentially equivalent to `return &array[0]`. The
problem is that, since the array is allocated in the function's stack
frame, it ceases to exist when the function returns, thus the caller
gets a pointer to an area of memory that is not allocated anymore.
Likely memory corruption ahead. The compiler warned me when I tried to
do that: “warning: address of local variable ‘array’ returned”. It's a
very serious warning that should never be ignored.

## The simplest fix: make the array static

As suggested by Chris Stratton in a comment, you can make the array
static, so it will be allocated for the whole life of the program:

    int *function()
    {
        static int array[3];
        array[0] = 19;
        array[1] = 7;
        array[2] = 69;
        return array;
    }

The only catch is that the function is now not _reentrant_, meaning that
every time you call it it will clobber the same array it returned on the
previous calls. Depending on your use case, this may not be an issue,
but it's something you need to be aware of.

## Have the caller manage the allocation

A safer (reentrant) way is to have the caller provide the memory needed
for the array. This is a very common method in C, and is suggested both
by Harper Shelby's answer and Chris Stratton's comment:

    int *function(int array[3])
    {
        array[0] = 19;
        array[1] = 7;
        array[2] = 69;
        return array;
    }

The caller can allocate in static memory, or in it's own stack frame, or
on the heap... but you do not care, the allocation is the caller's
problem now.

A couple of things to note here:

* The prototype is equivalent to `int *function(int *array)`: the
  function receives only a pointer. Writing `array[3]` instead of
  `*array` has the sole effect of _documenting_ that the function
  expects the pointer to point to somewhere with room for 3 values. You
  could document that in a comment instead.
* The function could return `void`, since the caller presumably knows
  the address it is giving you. Returning that same address is just for
  convenience, as it can help you chain calls like
  `another_function(function(array))`.

## Return the array in a struct

One may wonder: why can't we return an array in the first place. I do
not know for sure why the authors of the language made this choice, but
one possible explanation is that it is expensive to return a big array
by value, as it involves copying the whole of it. Now, if your array is
_really_ only three ints, then that argument does not apply, and you may
reasonably want to really return the whole array by value. This can be
done by embedding it inside a struct:

    // Struct definition.
    struct Array3 {
        int array[3];
    };

    Array3 function()
    {
        Array3 a;
        a.array[0] = 19;
        a.array[1] = 7;
        a.array[2] = 69;
        return a;
    }


body:
> I have a function that needs to return 3 int values.

In the interests of completeness I'll suggest another method. Let's assume that you really need 3 values and not 300.

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

    void foo (int & a, int & b, int & c)
    {
      a = 19;  //these are just random numbers
      b = 7;
      c = 69;
    }

    void setup() {
      Serial.begin (115200);
      int x, y, z;
      foo (x, y, z);
      Serial.println (x);
      Serial.println (y);
      Serial.println (z);
    }

    void loop() {
    }

This conceivably will use less memory because the compiler may be able to optimize all 3 values into registers. In fact in that specific example, it has optimized away the entire function call:

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

    000000be <setup>:
      public:
        inline HardwareSerial(
          volatile uint8_t *ubrrh, volatile uint8_t *ubrrl,
          volatile uint8_t *ucsra, volatile uint8_t *ucsrb,
          volatile uint8_t *ucsrc, volatile uint8_t *udr);
        void begin(unsigned long baud) { begin(baud, SERIAL_8N1); }
      be: 26 e0        ldi r18, 0x06 ; 6
      c0: 40 e0        ldi r20, 0x00 ; 0
      c2: 52 ec        ldi r21, 0xC2 ; 194
      c4: 61 e0        ldi r22, 0x01 ; 1
      c6: 70 e0        ldi r23, 0x00 ; 0
      c8: 82 e2        ldi r24, 0x22 ; 34
      ca: 91 e0        ldi r25, 0x01 ; 1
      cc: 0e 94 64 01  call 0x2c8 ; 0x2c8 <_ZN14HardwareSerial5beginEmh>
      d0: 4a e0        ldi r20, 0x0A ; 10
      d2: 50 e0        ldi r21, 0x00 ; 0
      d4: 63 e1        ldi r22, 0x13 ; 19  <---------- x
      d6: 70 e0        ldi r23, 0x00 ; 0
      d8: 82 e2        ldi r24, 0x22 ; 34
      da: 91 e0        ldi r25, 0x01 ; 1
      dc: 0e 94 4d 03  call 0x69a ; 0x69a <_ZN5Print7printlnEii>
      e0: 4a e0        ldi r20, 0x0A ; 10
      e2: 50 e0        ldi r21, 0x00 ; 0
      e4: 67 e0        ldi r22, 0x07 ; 7   <---------- y
      e6: 70 e0        ldi r23, 0x00 ; 0
      e8: 82 e2        ldi r24, 0x22 ; 34
      ea: 91 e0        ldi r25, 0x01 ; 1
      ec: 0e 94 4d 03  call 0x69a ; 0x69a <_ZN5Print7printlnEii>
      f0: 4a e0        ldi r20, 0x0A ; 10
      f2: 50 e0        ldi r21, 0x00 ; 0
      f4: 65 e4        ldi r22, 0x45 ; 69  <---------- z
      f6: 70 e0        ldi r23, 0x00 ; 0
      f8: 82 e2        ldi r24, 0x22 ; 34
      fa: 91 e0        ldi r25, 0x01 ; 1
      fc: 0c 94 4d 03  jmp 0x69a ; 0x69a <_ZN5Print7printlnEii>

    00000100 <loop>:
     100: 08 95        ret


message:
Cisco Switch not receiving serial communication from Arduino

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
    }

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


message:
Cast from uint8_t* to char - loses precision

I am trying to decode a received (via websocket) message (JSON) on my ESP8266.

The websocket library provides the data as uint8_t. The JSON library only understands char arrays. As far as I know uint8_t is basically char.

**I am getting this error:**
cast from 'uint8_t* {aka unsigned char*}' to 'char' loses precision [-fpermissive]

The websocket-function provides the payload as uint8_t:

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

The JSON Decoder wants a char arr, as provides in the [sample][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

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


message:
avr-gcc -D is ignored

Im trying to use XCode to compile avr program with arduino libs but seems like something wrong with my Makefile because it throws me warnings like

    # warning "F_CPU not defined for <util/delay.h>"

but I use -D on CC and CXX which should define stuff I thought, here is my Makefile:

    TARGET              = firmware
    MCU                 = atmega32u4
    F_CPU               = 16000000L
    USB_VID             = 0x2a03
    USB_PID             = 0x8036
    USB_PRODUCT         = "USB Device"
    USB_MANUFACTURER    = "Unknown"
    ARDUINO_VERSION     = 107010

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

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

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

    compile:

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

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

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

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

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

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

    $(TARGET).bin: compile

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

    clean:

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)


message:
Problem with simple sound detection circuit using a microphone

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

[![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

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.


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

```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

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.


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

I have the following components:

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

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

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
    }


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

I've created the following function:

    void runMotor(int _dir, int _step, int wait){
      digitalWrite(_dir, HIGH);
      for (int x = 0; x < 3200; x++) {
        digitalWrite(_step, HIGH);
        delayMicroseconds(wait);
        digitalWrite(_step, LOW);
        delayMicroseconds(wait);
      }

In the first line inside the function I used the value `HIGH` as a fixed value. I would like to know if there's a way to pass the values `HIGH` and `LOW` as a parameter in this function. Is it possible?

Or should I just create a new function to rotate my step motor to the other side?

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


message:
How to connect Flora 2 and nRF8001 BLE Breakout

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

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


message:
Compiles but doesn't print anything

Here is my code. It is suppose to read a couple of sensors and print them out in the serial monitor. Any help please? Note that I'm new to object orientated programming.

    /* The Blue Box

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

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

       This code is subject to a lot of ameliorations.

       By: xxx
       Date: 2016/08/28

       Extra credits:

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

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

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

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

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

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

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

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

    volatile bool mpuInterrupt = false; //some random bool

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

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

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

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

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

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

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

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

    void dmpDataReady() {
      mpuInterrupt = true;
    }

    class MainLoop
    {

        unsigned long previousMillis;

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

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

    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE

          TWBR = 24;
    #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE

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

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

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

    #ifdef testtest

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

    #ifndef testtest

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

        }

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

    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE

          TWBR = 24;

    #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE

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

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

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

          else
          {
            return;
          }

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

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

    #ifdef testtest

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

    #ifndef testtest

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

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

          counter = counter + 0.5;

        }
    };

    MainLoop main;

    void setup() {
    }

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

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.


message:
Serial communication doesn't work right after upload

I'm trying to communicate between a program on the Arduino Uno and a program on the PC via USB. I got it more or less working. Only problem is that it doesn't work when I run my PC program the **first time after I upload** the Arduino code via the Arduino IDE (version 2:1.0.5+dfsg2-4). It has some strange behaviour. Of course I could do some workaround, but I hope someone knows what the cause of this problem is and if there is a nice way to solve it.

This program should send back every byte it receives:

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

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

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

 import gnu.io.CommPortIdentifier
 import gnu.io.SerialPort

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

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

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

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

Instead of the 512 bytes it should receive, only around the last 44 bytes are received. Also, the first bytes the program receives are usually wrong. When I run the program for a second time, I get the desired result.

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

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

[(related question)][1]

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

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


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

We have a heating system that uses an ntc resistor to measure water temperature. I would like to replace that ntc resistor by a fixed one (low enough to disable heating) temporary on a 5 minute schedule, or any other.

It's to prevent the warm water using up all the heat and not leaving any for the central heating of the building. We got fooled by the contractor and a proper upgrade would now cost several thousands, so we just want to trick the system. ;p

The arduino is not supposed to measure anything, just to connect one of the two resistors to the heating system.

Is an arduino the right choice for that? If yes, which model? What extra elements would I need? Transistors? Relays? They shouldn't have too much own resistance to not influence the measuring of the heating system when the NTC is connected.

Just a simple connection of the extra resistor would work too because the resulting resistance would be lower and still indicate "water is hot enough" to the heating system.

Any help is welcome, even if it is not arduino based.

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.


message:
Expected } at the end of input

I am getting the error in my title when I try to compile the following code:

    #define char incomingByte; //Defines incomingByte
    #define char sendBack = K;
    #define char ?;
    #define pollTime;

    bool running = true;

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

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

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>


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

I recently thought that it would be fun to build an arduino quadcopter.

As I did some research I realized that the common L293D motor drivers aren't ever used.

Why is this? Could I still use them in my project?

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.


message:
Error Uploading Arduino Sketch to Arduino Pro Mini

I got an error "stk500_getsync() not in sync resp=0x00" when I tried to update an Arduino Pro Mini with an FTDI Basic Breakout 5V/3.3V - Micro USB. Maybe someone has instructions on how to resolve this issue. I use the last version of Arduino IDE.
All standard stuff like drivers, ports installed and configured.

I have communication with controller and I receive answers from it, but when I try to flash the firmware I get that error.

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.


message:
LED and Switch Compolation Error Arduino 101

I'm getting an error on line 9 for some reason, (digitalWrite(Sender, HIGH);), and I just cant figure out why. My goal is to have two sets of flashing patterns, one for each switch state. I don't know how important this is but I'm using an Arduino 101. This is also my first day programming so the answer could be staring me right in the nose, (in fact, I would prefer that haha). Thank you for your time!

    // Starting this by declairing intigers
    int Sender = 2; // Switch Out on pin two
    int LedG = 10; // LED Green out on pin ten
    int LedR = 11; // LED Red out on pin eleven
    int Reader = 12;  // Switch Input on pin twelve
    //configuring I/O
    pinMode(Sender = OUTPUT); // Setting pin two to output
    pinMode(Reader = INPUT); // Making pin 12 set to read switch data
    digitalWrite(Sender, HIGH); //Making pin two hot
    //main loop
    void loop() {
      if (digitalRead (Reader) == HIGH) { // if Switch input is reading on than do pattern A
        digitalWrite(LedG, HIGH); //turning on green led
        delay(50); //delay next instruction
        digitalWrite(LedG, LOW); //turn green led off
        digitalWrite(LedR, HIGH); //turn red led on
        delay(50); //delay next instruction
        digitalWrite(LedR, LOW); //turn red led off
      }
      else { //if switch input is readion off than play pattern b
        digitalWrite(LedR, HIGH); //turn red led on
        delay(1000); //delay next instruction
        digitalWrite(LedR, LOW); //turn red led off
        digitalWrite(LedG, HIGH); //turning on green led
        delay(1000); //delay next instruction
        digitalWrite(LedG, LOW); //turn green led off
      }
    }

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
    }


message:
SerialUSB on Arduino Due

I'm starting fiddling with a Due but I can't seem to be able to communicate over USB with it. Here is my code:

    int bauds = 9600;

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

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

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

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

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!


message:
Formula for current through shift register

[![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.

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


message:
Expected declaration before } token

Below is my code. The idea is it is supposed to wait for the ? character, print K, and turn on the LED. If it does not detect ? then it should keep waiting.

Below is my code:

    incomingByte = Serial.read();
    sendBack = K;
    int pollTime = 200;

    int ledPin = 9;

    bool running = true;

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

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

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


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

I need to power a light bulb or something like 110 V or 220 V at normal amperage for TV or something at that range like a fan...

My micro-controller is an Arduino with 5 V out and 12 V max out trough transistor switch.

To my understanding a stepper motor drive could be a viable option to enable the relays... I can even control current, right?

[Up to 8 channels][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

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!


message:
How do I clear sim800L buffer?

Let's say that I've tried sending an SMS directly from serial monitor or any kind of terminal. For whatever reason (syntax error, etc), my attempt fails. Now, I try sending it again, but this time by code (as seen on [this site][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/

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.


message:
Most memory efficient way to program

I currently know 3 ways to do a program. Which one of them is the most memory friendly. Note that the example code is simple (blinking a led) and the final code will be VERY VERY complex. Also, the way I code is not the best, so suggest any suggestions in the way to write things or where to put them please.

1- All in the loop. The most basic way of programming.

    const int led = 2;
    const int interval = 500;
    bool ledState = false;

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

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

2- Functions. Similar to the loop but a little neither. Can be splitted into many tabs.

    const int led = 2;
    const int interval = 500;
    bool ledState = false;

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

    void loop() {
      blinkLed();
    }

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

Then finnaly, objects. The most supreme of them all (and the one that I know the least). I like objects and classes because multitasking with it is much easier. It is more flexible too. Code taken from [here][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

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.