body:
Can I use my Arduino Uno as a USB to serial converter to program my Raspberry pi 0 over serial communication?

My idea: Computer connects to Arduino via USB > Arduino connects with Raspberry pi 0 via GPIO pins.

How do I go about this?

title: Using Arduino Uno as USB to serial converter

Answers: 3

body:
If you load an empty program in your arduino, and make the folowing connections:

Pi  -->  Arduino

Pin 8 --> Pin 1

Pin 10 --> Pin 0

Gnd --> Gnd

than you should see your linux console in the arduino serial program is you set the baudrate to 115200.

This method will work for the raspberry pi models without wifi.
On the wifi models the pins on the pi will be different.

The Arduino uses FTDI usb-to serial converter. This converters uart side is connected to the AVR-chip via pin 0 and 1. If you load an empty program in your arduino, it wil not use these lines. Now you can connect directly to the FTDI chip thru this pins. The converter does not care if it is communicating with the arduino or the pi over these lines.

body: You may also put Arduino in a reset state then Rx & Tx lines of serial converter will be free.

body:
In the arduino ide, go to file > examples > arduino as isp.
Might be a good starting point.

Seems like a lot of work though. If I were in that situation then I'd either use an ethernet cable and SSH, or, use a mobile phone as a WiFi hot-spot.


body:
I'm rather new to Arduino programming. I have a problem compiling the following bit of code:

    const int relay1 = 10;  //Power Relay 1
    const int relay2 = 11;  //Power Relay 2
    const int relay3 = 12;  //Toggle Relay
    const int button1 = 3;
    const int button2 = 4;
    const int button3 = 5;

    //---Button States---\\
    int button1State;   //Current state of Button 1
    int button2State;   //Current state of Button 2
    int button3State;   //Current state of Button 3
    int button1State_prev = LOW;  //Previous state of Button 1
    int button2State_prev = LOW;  //Previous state of Button 2
    int button3State_prev = LOW;  //Previous state of Button 3

    //---General Variables---\\
    int userSelection = 0;
    int interlockState = 0;
    int platformState = 0;

    //---Interval-Tracking Variables---\\
    unsigned long lastTime_Debounce1 = 0;   //Button 1 debounce time
    unsigned long lastTime_Debounce2 = 0;   //Button 2 debounce time

    //---Activity Delays---\\
    const unsigned int relayDelay = 10;           //Delay between relay actions (ms)
    const unsigned int debounceDelay = 60;        //Delay for button de-bouncing (ms)

    void setup() {
      //Configure Pins
      pinMode(relay1, OUTPUT);
      pinMode(relay2, OUTPUT);
      pinMode(relay3, OUTPUT);
      pinMode(button1, INPUT);
      pinMode(button2, INPUT);
      pinMode(button3, INPUT);

      digitalWrite(relay1, LOW);
      digitalWrite(relay2, LOW);
      digitalWrite(relay3, LOW);
    }

    void loop() {
      //Read value of each input pin
      int button1Reading = digitalRead(button1);  //Current reading of Button 1
      int button2Reading = digitalRead(button2);  //Current reading of Button 2
      int button3Reading = digitalRead(button3);  //Current reading of Button 3

      //Debounce Button1
      if (button1Reading != button1State_prev) {
        lastTime_Debounce1 = millis();
      }
      button1State_prev = button1Reading;
      if ((millis() - lastTime_Debounce1) > debounceDelay) {
        if (button1Reading != button1State) {
          button1State = button1Reading;
        }
      }

      //Debounce Button2
      if (button2Reading != button2State_prev) {
        lastTime_Debounce2 = millis();
      }
      button2State_prev = button2Reading;
      if ((millis() - lastTime_Debounce2) > debounceDelay) {
        if (button2Reading != button2State) {
          button2State = button2Reading;
        }
      }

For some reason, the compiler is convinced that the variable `lastTime_Debounce1` in the second IF-statement, on Line 54, has not been declared in-scope. I don't understand how this is possible, since the variable in question is a defined and initialized global.

If I comment-out the first trio of IF-statements (handling Button 1), the second trio (handling button 2) has no problem compiling, even though it does exactly the same thing in exactly the same way.

I checked all the usual suspects: spelling, braces, semicolons, even commented-out blocks of code one at a time, but I can't find the source of the problem. I'm using the Arduino 1.8.2 IDE.

Can someone please point out the mistake I'm missing?

title: Why can't my IF statement see a global?

Answers: 1

body:
The backslash in your comments are the problem. As per C++ language definitions, a `\` at the end of the line is interpreted as a "line continuation". Thus, your comment gets continued in the next line and your variable declaration and initialization is commented out.

This is apparent when opening your code with a good syntax highlighting program, like Notepad++.

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

Removing all `\\` from the end of the comment line solves your problem.

Side note: For more info, look at https://stackoverflow.com/a/30290133/5296568. Backslashes at the end of a line are actually useful when used in multi-line macro definitions.

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


body:
I am trying to upload the Blink sketch to my ATmega chip which is now on a breadboard connected via an FTDI chip.

My clock is running, power is OK. I connected the reset pin via a 100 kohm to the vcc and have a 0.1 uF capacitor between the reset pin and the DTR pin of my FTDI chip.

[![a picture][1]][1]
[![a close up][2]][2]

Connections to the PCB with the FTDI chip:
[![Connections to the PCB with the FTDI chip][3]][3]

Does anybody know what I am doing incorrectly?

On a side note, I am running Ubuntu 16.04

All this seems correct to me, yet when I try to program the controller I get this exact:

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

    /home/yalishanda/Downloads/arduino-1.8.5/arduino-builder -dump-prefs -logger=machine -hardware /home/yalishanda        /Downloads/arduino-1.8.5/hardware -tools /home/yalishanda/Downloads/arduino-1.8.5/tools-builder -tools /home/yalishanda    /Downloads/arduino-1.8.5/hardware/tools/avr -built-in-libraries /home/yalishanda/Downloads/arduino-1.8.5/libraries -libraries     /root/Arduino/libraries -fqbn=arduino:avr:uno -ide-version=10805 -build-path /tmp/arduino_build_476404 -warnings=none -build-        cache /tmp/arduino_cache_889393 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.arduinoOTA.path=/home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr -prefs=runtime.tools.avrdude.path=/home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr -prefs=runtime.tools.avr-gcc.path=/home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr -verbose /home/yalishanda/Downloads/arduino-1.8.5/examples/01.Basics/Blink/Blink.ino
    /home/yalishanda/Downloads/arduino-1.8.5/arduino-builder -compile -logger=machine -hardware /home/yalishanda/Downloads/arduino-1.8.5/hardware -tools /home/yalishanda/Downloads/arduino-1.8.5/tools-builder -tools /home/yalishanda    /Downloads/arduino-1.8.5/hardware/tools/avr -built-in-libraries /home/yalishanda/Downloads/arduino-1.8.5/libraries -libraries /root/Arduino/libraries -fqbn=arduino:avr:uno -ide-version=10805 -build-path /tmp/arduino_build_476404 -warnings=none -build-cache /tmp/arduino_cache_889393 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.arduinoOTA.path=/home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr -prefs=runtime.tools.avrdude.path=/home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr -prefs=runtime.tools.avr-gcc.path=/home/yalishanda/Downloads/arduino-1.8.5/hardware    /tools/avr -verbose /home/yalishanda/Downloads/arduino-1.8.5/examples/01.Basics/Blink/Blink.ino
    Using board 'uno' from platform in folder: /home/yalishanda/Downloads/arduino-1.8.5/hardware/arduino/avr
    Using core 'arduino' from platform in folder: /home/yalishanda/Downloads/arduino-1.8.5/hardware/arduino/avr
    Detecting libraries used...
    "/home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10805 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-I/home/yalishanda/Downloads/arduino-1.8.5/hardware/arduino/avr/cores/arduino" "-I/home/yalishanda/Downloads/arduino-1.8.5/hardware/arduino/avr/variants/standard" "/tmp/arduino_build_476404/sketch/Blink.ino.cpp" -o "/dev/null"
    Generating function prototypes...
    "/home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10805 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-I/home/yalishanda/Downloads/arduino-1.8.5/hardware/arduino/avr/cores/arduino" "-I/home/yalishanda/Downloads/arduino-1.8.5/hardware/arduino/avr/variants/standard" "/tmp/arduino_build_476404/sketch/Blink.ino.cpp" -o "/tmp/arduino_build_476404/preproc/ctags_target_for_gcc_minus_e.cpp"
    "/home/yalishanda/Downloads/arduino-1.8.5/tools-builder/ctags/5.8-arduino11/ctags" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives "/tmp/arduino_build_476404/preproc/ctags_target_for_gcc_minus_e.cpp"
    Compiling sketch...
    "/home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10805 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-I/home/yalishanda/Downloads/arduino-1.8.5/hardware/arduino/avr/cores/arduino" "-I/home/yalishanda/Downloads/arduino-1.8.5/hardware/arduino/avr/variants/standard" "/tmp/arduino_build_476404/sketch/Blink.ino.cpp" -o "/tmp/arduino_build_476404/sketch/Blink.ino.cpp.o"
    Compiling libraries...
    Compiling core...
    Using previously compiled file: /tmp/arduino_build_476404/core/wiring_pulse.S.o
    Using previously compiled file: /tmp/arduino_build_476404/core/WInterrupts.c.o
    Using previously compiled file: /tmp/arduino_build_476404/core/hooks.c.o
    Using previously compiled file: /tmp/arduino_build_476404/core/wiring.c.o
    Using previously compiled file: /tmp/arduino_build_476404/core/wiring_analog.c.o
    Using previously compiled file: /tmp/arduino_build_476404/core/wiring_digital.c.o
    Using previously compiled file: /tmp/arduino_build_476404/core/wiring_pulse.c.o
    Using previously compiled file: /tmp/arduino_build_476404/core/wiring_shift.c.o
    Using previously compiled file: /tmp/arduino_build_476404/core/CDC.cpp.o
    Using previously compiled file: /tmp/arduino_build_476404/core/HardwareSerial.cpp.o
    Using previously compiled file: /tmp/arduino_build_476404/core/HardwareSerial0.cpp.o
    Using previously compiled file: /tmp/arduino_build_476404/core/HardwareSerial1.cpp.o
    Using previously compiled file: /tmp/arduino_build_476404/core/HardwareSerial2.cpp.o
    Using previously compiled file: /tmp/arduino_build_476404/core/HardwareSerial3.cpp.o
    Using previously compiled file: /tmp/arduino_build_476404/core/IPAddress.cpp.o
    Using previously compiled file: /tmp/arduino_build_476404/core/PluggableUSB.cpp.o
    Using previously compiled file: /tmp/arduino_build_476404/core/Print.cpp.o
    Using previously compiled file: /tmp/arduino_build_476404/core/Stream.cpp.o
    Using previously compiled file: /tmp/arduino_build_476404/core/Tone.cpp.o
    Using previously compiled file: /tmp/arduino_build_476404/core/USBCore.cpp.o
    Using previously compiled file: /tmp/arduino_build_476404/core/WMath.cpp.o
    Using previously compiled file: /tmp/arduino_build_476404/core/WString.cpp.o
    Using previously compiled file: /tmp/arduino_build_476404/core/abi.cpp.o
    Using previously compiled file: /tmp/arduino_build_476404/core/main.cpp.o
    Using previously compiled file: /tmp/arduino_build_476404/core/new.cpp.o
    Using previously compiled file: /tmp/arduino_build_476404/core/core.a
    Archiving built core (caching) in: /tmp/arduino_cache_889393    /core/core_arduino_avr_uno_fbfa3aa7d5698fed1dc5326dc32eae8f.a
    Linking everything together...
    "/home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr/bin/avr-gcc" -w -Os -g -flto -fuse-linker-plugin -Wl,--gc-sections -mmcu=atmega328p  -o "/tmp/arduino_build_476404/Blink.ino.elf" "/tmp/arduino_build_476404/sketch/Blink.ino.cpp.o"     "/tmp/arduino_build_476404/core/core.a" "-L/tmp/arduino_build_476404" -lm
    "/home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr/bin/avr-objcopy" -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0  "/tmp/arduino_build_476404/Blink.ino.elf"     "/tmp/arduino_build_476404/Blink.ino.eep"
    "/home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr/bin/avr-objcopy" -O ihex -R .eeprom      "/tmp/arduino_build_476404/Blink.ino.elf" "/tmp/arduino_build_476404/Blink.ino.hex"
    Sketch uses 928 bytes (2%) of program storage space. Maximum is 32256 bytes.
    Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.

    /home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr/bin/avrdude -C/home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr/etc/avrdude.conf -v -patmega328p -cstk500v1 -P/dev/ttyUSB0 -Uflash:w:/tmp/arduino_build_476404/Blink.ino.hex:i

    avrdude: Version 6.3, compiled on Jan 17 2017 at 11:00:16
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "/home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr/etc/avrdude.conf"
         User configuration file is "/home/yalishanda/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyUSB0
         Using Programmer              : stk500v1
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
    ...

  [1]: https://i.stack.imgur.com/2TfCP.jpg
  [2]: https://i.stack.imgur.com/a92Lg.jpg
  [3]: https://i.stack.imgur.com/yLVTG.jpg

title: Issue programming breadboarded Arduino via FTDI chip

Answers: 2

body: Right now you don't have a bootloader on your chip that's the reason why it wouldn't be programmed via UART so to flash the bootloader you need an ISCP programmer and an arduino bootloader.hex file.

body:
10K reset pullup.
Check your crystal caps, they should be 22pF.

The response does look like the chip does not have a bootloader tho.
Or Rx & Tx lines are swapped.


body:
I connect an HC-05 module to an Arduino nano with CH341 serial chip (voltage divider on RX pin). I am trying to make a bridge for a test, i.e. serial in, echo local and echo to Bluetooth and vice versa. I modified the echo code from [here](http://spacetinkerer.blogspot.com).

    int incomingByte = 0;    // for incoming serial data

    #include <SoftwareSerial.h>

    SoftwareSerial BTSerial(10, 11); // RX | TX

    void setup() {
        BTSerial.begin(38400);    // opens serial port, sets data rate to 9600 bps
        Serial.begin(9600);    // opens serial port, sets data rate to 9600 bps
    }

    void loop() {
      // send data only when you receive data:
      if (Serial.available() > 0) {

        // read the incoming byte:
        incomingByte = Serial.read();

        // say what you got:
        Serial.print((char)incomingByte);
        BTSerial.print((char)incomingByte);
      }

      if (BTSerial.available() > 0) {

        // read the incoming byte:
        incomingByte = Serial.read();

        // say what you got:
        Serial.print((char)incomingByte);
        BTSerial.print((char)incomingByte);
      }

under OSX I open two terminals. In the first terminal using `screen /dev/cu.wchusbserial1410 9600` I see local echo as desired. But on the second terminal using `screen /dev/cu.HC-05-SPPDev 38400` I see nothing after pairing. The only effect is that by typing the latter command, the module stops blinking rapidly and blinks only two times with long pause in between. Exiting the `screen` environment, then again blinks rapidly.

Appreciate any hints what I am doing wrong...

=====

intermediate success but not quite there yet:

I simplified the code and corrected the wrong connection. Local echo on serial works as usual, even between the two, characters are being transferred, but they are black question marks instead of why I typed.

    /*
     * echo script
     */

    byte incomingByte;

    #include <SoftwareSerial.h>

    SoftwareSerial BTSerial(3, 2); // RX | TX

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

    void loop() {
      if (Serial.available()) {
        incomingByte = Serial.read();
        Serial.print((char)incomingByte);
        BTSerial.print((char)incomingByte);
      }

      if (BTSerial.available()) {
        incomingByte = BTSerial.read();
        Serial.print((char)incomingByte);
        BTSerial.print((char)incomingByte);
      }
    }

Any ideas?

========

Edited the Buadrate to 9600. Now everything works.

title: HC-05 bridge using Arduino Nano and GNU Screen

Answers: 1

body:
Based on the above comments I provide here the full answer in the hope it will be useful in the future.

HC-05 has two modes. The **Communication Mode** and **AT Command Mode**. In the latter mode, HC-05 responds in kind of "config" way and many default settings of the communication mode can be change here. While the baud rate of the communication mode, and many other settings can be changed, the baud rate of the AT command mode is always fixed 38400 to avoid any confusions and mistakes. On the other hand, the **default** factory baud rate of the communication mode, i.e. before any change, is set to 9600. So the solution to my problem was to set the baud-rate to 9600 on my newly purchased HC-05 and I was able to make an echo bridge between HC-05 Bluetooth and serial. Here is the code:

    /*
     * echo script
     */

    byte incomingByte;

    #include <SoftwareSerial.h>

    SoftwareSerial BTSerial(3, 2); // RX | TX

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

    void loop() {
      if (Serial.available()) {
        incomingByte = Serial.read();
        BTSerial.print((char)incomingByte);
      }

      if (BTSerial.available()) {
        incomingByte = BTSerial.read();
        Serial.print((char)incomingByte);
      }
    }

After pairing HC-05 with OSX, I was able to open two OSX Terminals with one of these commands in the first terminal:

    screen /dev/cu.wchusbserial1410 9600

and in the other:

    screen /dev/cu.HC-05-SPPDev 9600

Everything worked properly, i.e. typing in one terminal produced characters in the other and vice versa. For changing the default baud-rate in the communication mode, I found a very good tutorial which can be found [here](http://www.martyncurrey.com/arduino-with-hc-05-bluetooth-module-at-mode/).


body:
I am trying to build a sketch that reads a single number from the Serial Monitor and uses it to light a 7 segment display with this number.

I need to compare the input with the known values, stored in a char array, to know which character was typed in and associate the matching binary combination to light the 7 segment display.

I have made a sample code extracted from the sketch, just to test if I am able to pass a char and get the correct result back:

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

    char nums[] = "0123456789."; // The characters we will check against

    /* Tried also these, same results
          char nums[12] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.', '\0'};
          char nums[] = "456789.0123";
    */

    void setup() {
      Serial.begin(9600);
      Serial.println("Write a single character"); Serial.println(" ");
    }

    void loop() {
      if (Serial.available() > 0) {
        char text = Serial.read(); // Read a single char from serial
        Serial.print("Character provided is: "); Serial.println(text);
        char c = parseChar(text); // Evaluate the char
        Serial.print("Character returned is: "); Serial.println (c);
        if (strcmp(c, text) == 0) { // Check if the returned char is the same
          Serial.print("      CORRECT character returned");
        } else {
          Serial.print("      WRONG character returned");
        }
        Serial.println(" ");
      }
    }

    char parseChar(char c) {
      int comp = 0;
      Serial.println("----- parseChar() START-----");
      Serial.print("  Parameter 'c' is: "); Serial.println(c);
      for (int i = 0; i < sizeof(nums) ; i++) { // Check the values of the array one by one
        comp = strcmp(c, nums[i]); // Compare the chars
        Serial.print("  Compare to nums["); Serial.print(i); Serial.print("] = "); Serial.print(nums[i]); Serial.print(" --> Result: "); Serial.println(comp);

        /* If the check matches, return the character at that index.
           For simplicity, it just returns the matching char of the array,
           that should be the same as the one sent in to the function.
        */
        if (comp == 0) {
          Serial.println("----- parseChar() END (found) -----");
          return nums[i];
        }
      }
      Serial.println("----- parseChar() END (not found)-----");
      return 0;
    }

The function works well for all numbers from 0 to 6. However, for any number over 6, or any other character, the strcmp() function returns always 0, so the returned character is the index 0 of the array, regardless of the character typed.

This is the Serial Monitor output for different characters:

    Write a single character

    Character provided is: 3
    ----- parseChar() START-----
      Parameter 'c' is: 3
      Compare to nums[0] = 0 --> Result: 1
      Compare to nums[1] = 1 --> Result: 1
      Compare to nums[2] = 2 --> Result: 1
      Compare to nums[3] = 3 --> Result: 0
    ----- parseChar() END (found) -----
    Character returned is: 3
          CORRECT character returned

    Character provided is: 6
    ----- parseChar() START-----
      Parameter 'c' is: 6
      Compare to nums[0] = 0 --> Result: -6
      Compare to nums[1] = 1 --> Result: 1
      Compare to nums[2] = 2 --> Result: 1
      Compare to nums[3] = 3 --> Result: 1
      Compare to nums[4] = 4 --> Result: 1
      Compare to nums[5] = 5 --> Result: 1
      Compare to nums[6] = 6 --> Result: 0
    ----- parseChar() END (found) -----
    Character returned is: 6
          CORRECT character returned

    Character provided is: 7
    ----- parseChar() START-----
      Parameter 'c' is: 7
      Compare to nums[0] = 0 --> Result: 0
    ----- parseChar() END (found) -----
    Character returned is: 0
          WRONG character returned

    Character provided is: g
    ----- parseChar() START-----
      Parameter 'c' is: g
      Compare to nums[0] = 0 --> Result: 0
    ----- parseChar() END (found) -----
    Character returned is: 0
          WRONG character returned

As you can see, the parseChar() function never returns a "not found" result, even for chars that are not in the array. In fact, it never loops through the array, as the first comparison returns 0 always.

I can't figure out why the strcmp() function returns 0 when the chars are different. Am I missing something?

title: strcmp() returns 0 when chars are different

Answers: 1

body:
`strcmp` is not for comparing a single character like your `c` parameter. It is for comparing a null-terminated string. I'm a little surprised you didn't get a compiler error, but there it is.

If you want to compare individual characters, just compare them with `==`.


body:
I would like to create a compile error so sketch does not upload in certain cases.

I have written a library with a function that adds pins being used to an array. If the same pin is used twice I want to fail the compilation (preferably with an error that explains why). Is this possible?

    void CheckPinNum(int newPinNum){
      for (int i=0; i <= PinArrayLength; i++){
        if (newPinNum == PinArray[i])
          failCompilation("You entered same pin twice!");
      }
    }

title: Purposely create compile error to fail the upload

Answers: 2

body:
To answer the question asked in the title:

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

    #if some_condition
    # error Some error message
    #endif

But note that this technique only works at _compile time_, which
probably makes it useless for you.

body:
It's impossible to check dynamic behavior compile time.

However, the best 'alternative' I can think of, is during the setup set all pin numbers (if that is possible).

And if something is wrong, let the 'user' or client know something is wrong. In extreme cases, just by putting the Arduino in an endless loop, in best cases, send a serial line, blink a light or whatever feedback.

You can do the same later on (when CheckPinNumber needs to be called in the loop, so not at setup), but the sooner you can do these checks, the better.


body:
Is it a problem to use multiple softwares to read the data that came from the same USB port simultaneously?

I have a board connected to a PC by USB, which is read by an application developed in C#. I display the data from the board in a table form.

Now I have to plot the data. The problem is that both the board and the software are deployed and can't be modified. So I have to create another program to do that, but the user should be able to run both softwares simultaneously.

Thank you!

title: Running multiple programs with one Arduino

Answers: 1

body:
The question is not so much about Arduino, but about PC serial ports. There are programs/drivers out there that allow a user to "split" a serial port into two or more virtual serial ports, each of which can be opened by separate Windows applications, such as your C# programs.

Some of these programs or drivers are commercial and not free, and some are free.

https://www.fabulatech.com/serial-port-splitter-help/serial-port-splitting.html

http://www.eterlogic.com/help/vspe/UsageSplitPage.html

http://www.aggsoft.com/tcp-com/tcp-com-com-splitting.htm


body: Does anybody know of a sketch that can turn a single servo 180 degrees clockwise/counterclockwise with the x axis of a joystick, light a bar graph LED with the Y axis, and sound a buzzer when the joystick button is depressed.

title: Joysitck with servo, LED array and buzzer

Answers: 1

body:
You have a distinct set of requirements that you could turn into a sketch yourself.  I'm guessing you have never written a program before, in which case the problem really is you don't know how to do what you want to.

So, break the problem down into small chunks.  The less complex a problem the more likely you are to find a generic solution on the web that you can 'borrow'.

 1. How do you turn a servo?
 2. How do you read the position of a joystick?
 3. How do you light a LED bar graph?
 4. How do you sound a buzzer?

I'm pretty certain that you can find pages that tells you how to do each of those in separate sketches.  Once you have each of those working you need to merge the setup functions, making sure they don't over write each other and then tackle the loop functions (which will be more difficult).  BUT I know there are posts on here about how to merge two sketches into one.

I'm 99% certain you will not find a sketch that does what you want.  I'm 99% certain you will be able to coble together a solution that will do what you want if you break it down.

If you get stuck, post the code you have and explain your problem and people will help.

Good luck.


body:
Me and my girlfriend are working on a small automatic plant watering system. Our first goal is to make an electrical 12V pump suck water out of a bottle.

As we were reading tutorials online we noticed that many people hook up a driver such as the l293 to their arduino in order to control the pump (essentially a brushed DC motor).

http://www.ti.com/lit/ds/symlink/l293.pdf

Our pump is 12V 4.2 W.

My question is do we really need a driver like that for just activating / deactivating the pump ?

In my understanding the driver offers an H-bridge setup allowing to control up to two motors in both directions.

Are there any other reasons to prefer this driver instead of a simple MOSFET / Transistor setup with such a simple use case like ours ?

Thank you for your help.

Best regards

title: Drive a 12V pump do I need a l293 driver

Answers: 1

body: Unless you wish to reverse the direction of the pump without reconnecting the wires in the opposite way, there is no need for a L293. A MOSFET that operates as a switch should be sufficient in your case. You can also try to PWM it and reduce/control the water flow.


body:
I'm working inside the Arduino IDE environment and have made a class that builds on the [Adafruit RDG LCD with interrupts][1] While looking at how to combine the `Attach Interrupt()` into my class I came across [this post about using namespaces][2]

> Why make a class then? What about a namespace?
>
> A class with one instance is like a group with one person in it.
>
> -nickgammon

Understanding that Mr.Gammon is kind of a big deal around these parts, I'd like to understand how to insert/alter my current class into a namespace format. Currently, the most in-depth tutorial [I've found is here][3], but I don't see how I would mix in the `Attach Interrupt()` function

Right now, my code looks like

    /**** Pre-Setup *****/
    #define Menu_PIN 3
    voltile bool flag;

    //Init Class
    class LcdMenu : public Adafruit_RGBLCDShield
    {
      public:
      MenuFoo()
    }
    LcdMenu LcdM;

    //run Setup
    void setup()   /****** SETUP: RUNS ONCE ******/
    {
      pinMode(Menu_PIN, INPUT_PULLUP);
      attachInterrupt(digitalPinToInterrupt(Menu_PIN), ProcMenu, FALLING);
    }

    void loop()
    {
      if(flag){
        LcdM.MenuFoo();
        flag=false;
      }
    }

    //Handles Inturrupts for Class
    void ProcMenu()
    {
      flag=true;
    }

    //define MenuFoo
    void LcdMenu::MenuFoo(){[code]}

As I understand it, Implementing a namespace would eliminate the need for the `ProcMenu()` function making my code easier to read/maintain.

  [1]: https://forums.adafruit.com/viewtopic.php?f=47&t=31107
  [2]: https://forum.arduino.cc/index.php?topic=160101.0
  [3]: https://luckyresistor.me/2014/10/31/how-and-why-to-use-namespaces/

title: Arduino Interrupts Classes and Namespace

Answers: 2

body:
I don't it will change your design.

The main reason to use namespaces is to have an extra 'layer' of hierarchy.

Like a book that can be divided in chapters (classes).
But if you want to combine multiple books (projects) than you use name classes (e.g. to prevent name clashes of equally named class names).

body:
In this particular instance, and since you are inheriting from a class
of a known library, making your own class makes sense. You just have to
be aware that, although you can in principle have multiple instances of
a class, you can only have _one single handler_ for a particular
interrupt. Thus the handler cannot be a regular method of the class (a
method that knows it has been called for `this` instance), but it can be
a `static` method. Such a method is much like a regular function which
uses (abuses?) the class as a sort of namespace.

I would try something along these lines:

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

    class LcdMenu : public Adafruit_RGBLCDShield
    {
    public:
      LcdMenu();
      void begin([params]) {
        Adafruit_RGBLCDShield::begin([params]);
        attachInterrupt(digitalPinToInterrupt(Menu_PIN), handleInterrupt, FALLING);
      }
      void MenuFoo();
      void update() {
        if (flag) {
          MenuFoo();
          flag=false;
        }
      }
    private:
      static volatile bool flag;
      static void handleInterrupt() { flag = true; }
    }

    volatile bool LcdMenu::flag;

Then you just have to call `LcdM.update()` in `loop()`.


body:
I would like to run a Nano 3.0 from both the VIN (mains power supply 7V) and USB power (backup). I understand it selects the highest voltage and switches to VIN at 6.6V. However I am unsure of the following:

1. How is it possible to detect which power source is being used?
2. How is it possible to detect if the source has been switched?
3. How is it possible to detect if the power source NOT in use has been disconnected.

title: Nano v3 dual power source use & detection

Answers: 1

body:
To check, if VIN is connected, you can connect VIN through a voltage divider to a digital pin (as suggested in the comment of Code Gorilla). For checking the USB connection you would have to connect VUSB to another digital pin. Since VUSB is not exposed on a pin, this could be difficult to do, but it is possible.

But note, that this would also show a disconnect, when the voltage drops (e.g. empty battery). When you want to detect real mechanical disconnects, you need a power jack with an extra switch integrated.

Let's take a look at the schematics: [Arduino Nano 3.0 Schematics][1]
[![Schematics of Arduino Nano v3.0 voltage supply][2]][2]
The selection of voltage supply is done by the diode D1. If the voltage resultung from the VIN regulator is higher than VUSB - diode_voltage_drop, the diode is closing and the power comes from VIN. If the voltage resulting from VIN is lesser, the current can flow from VUSB. How much power is really drawn from USB depends on the voltage difference.

So - to detect which source is actually used - you can measure the voltage on the diode with an analog measurement with the ADC or through connecting for example a comparator and using a digital pin.

Note that the voltage on the diode can be positive or negative, depending on which source is used.

  [1]: https://www.arduino.cc/en/uploads/Main/ArduinoNano30Schematic.pdf
  [2]: https://i.stack.imgur.com/DPGm2.png


body:
I bought an arduino nano (knockoff from Elegoo) and according to the Amazon description it comes with a bootloader.

From what I've read, this means that programming can occur over the usb connection rather than having to rely on a dedicated serial programmer.

I installed the necessary drivers, plugged in the Nano, and ran this command (not to program, just to see if the board would be recognized):

`avrdude -p m328p -b 57600 -P /dev/wcbhserial1460 -c arduino`

It recognized the board and said it was ready to be programmed. If I then actually go ahead and ask it to flash a hex file onto the board, will the `-c arduino` argument tell avrdude to use the bootloader or does it just overwrite everything? Can I reprogram multiple times using this command?

I'm using Atmel Studio 7 and am configuring it to call the appropriate avrdude command.

**EDIT:** According to [this answer](https://arduino.stackexchange.com/a/18865), the `-D` flag will program the chip _without_ clearing the flash, allowing the bootloader to preserved. Unfortunately, since the ATmega devices don't support partial flash memory clearing, this will only work once. So essentially I need to reupload the bootloader each time, which kinda defeats the purpose of it right?

It looks like though he is talking about using an AVRISP, so does all that not apply if you're just programming using the bootloader and the usb connection in the first place?

title: Will avrdude overwrite the bootloader on my Nano?

Answers: 0


body:
I want to create an integer whose total value cannot go beyond a range of numbers when added to and subtracted from. For example, if the "total_value" started at 0 (of a total possible range between -5 and 5), and then, using a button that added 1 to the total value, I got to 5, if I was to press it again it would not go to six but either reset to 5 or block another input of +1.

How would I go about achieving something to this effect?

Liam

title: How do I create boundaries for the possible values of an integer?

Answers: 3

body:
You can not create a number with arbitrary upper and lower limits.  It is common in the C language to create an integer comprised of 16 bits.  Such an integer has a minimum of:

    -(2^15) = -32768

...and maximum of:

    (2^15) - 1 = +32767

Instead, after pressing the positive button, consider testing if "total_value" is 5 and skipping adding 1 to "total_value" if TRUE.  Conversely, after pressing the negative button, consider testing if "total_value" is -5 and skipping subtracting 1 from "total_value" if TRUE.

body:
For adding:

    total_value = total_value + 1;
    if (total_value > 5)
      total_value = 5;

And for subtracting:

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

    total_value = total_value - 1;
    if (total_value < -5)
      total_value = -5;

You may find a C or C++ tutorial very helpful.

---

Another method for adding:

    if (total_value < 5)
      total_value++;

And for subtracting:

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

    if (total_value > -5)
      total_value--;

body:
You are probably looking for the [constrain()](https://www.arduino.cc/reference/en/language/functions/math/constrain/) macro (an existing implantation of clamp logic, credit goes to @Edgar Bonet)

    value = constrain(value + input, -5, 5);

----------

If you get tired of writing `constrain()` you can even wrap it in a new type (which might be over-engeneering), producing something like following(code not tested)

    template<typename T>
    struct BoundValue {
     T value;
     const T vmin, vmax;
     //similar for other operators +,/,-=,...
     decltype(*this)& operator+=(T operand) { value = constrain(value + operand, vmin, vmax); return *this; }
     operator T() const { return value; }
     BoundValue(const T& vmin, const T& vmax) : vmin(vmin), vmax(vmax) {}
     BoundValue& operator=(const T& other) { value = constrain(other, vmin, vmax); return *this; }
    };

and use like variable of its argument type

 BoundValue<int> val(-5, 5);
 val += 6;//val = 5


body:
I tried connecting RX of GPS to Pin 18 and TX of GPS to Pin 19 but I get an error that No GPS is detected,check wiring.VCC of GPS to 5V.

I have set baudrate to 115200.I am trying DeviceExample code of TinyGPS++ library.

title: How do I connect my Ublox neo 6M GPS Module with arduino mega 2560?

Answers: 1

body:
The default baud rate for ublox NEO-6M GPS devices is 9600, **not** 115200.

And try [NeoGPS](https://github.com/SlashDevin/NeoGPS).  It's smaller, faster, more accurate, more reliable and it comes pre-configured to use `Serial1` on a Mega.  Be sure to read the Installation instructions.  If it doesn't work, follow the Troubleshooting pages and try NMEAdiagnostic.ino.

NeoGPS has an example sketch (ubloxRate.ino) that can configure the NEO-6M to other baud rates, once you get the basic programs working at 9600.


body:
When i press a button to subtract 1 from 5 it skips to 3, it's the same when I add 1 to -5 it skips displaying - 4 and goes straight to -3.

This is the code that i am using:

    //Testing the use of addition and subtraction with the menu options.

    #include <LiquidCrystal.h>

    LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

    int lcd_key     = 0;
    int adc_key_in  = 0;
    int calc_total;

    #define btnRIGHT  0
    #define btnUP     1
    #define btnDOWN   2
    #define btnLEFT   3
    #define btnSELECT 4
    #define btnNONE   5

    int read_LCD_buttons(){
        adc_key_in = analogRead(0);

        if (adc_key_in > 1000) return btnNONE;

        if (adc_key_in < 50)   return btnRIGHT;
        if (adc_key_in < 150)  return btnUP;
        if (adc_key_in < 300)  return btnDOWN;
        if (adc_key_in < 450)  return btnLEFT;
        if (adc_key_in < 700)  return btnSELECT;

        return btnNONE;

    }

    void setup(){
       lcd.begin(16, 2);
       lcd.setCursor(0,0);
       lcd.print (calc_total);

    }

    void loop(){

       lcd_key = read_LCD_buttons();
       calc_total = constrain(calc_total, -4, 4);

       switch (lcd_key){

           case btnRIGHT:{
                lcd.clear();
                calc_total = calc_total - 1;
                lcd.print (calc_total);
                delay(700);
                lcd.setCursor(0,0);
                break;
           }
           case btnLEFT:{
                lcd.clear();
                calc_total = calc_total + 1;
                lcd.print (calc_total);
                delay(700);
                lcd.setCursor(0,0);
                break;
           }
         }
    }

Answers: 2

body:
The whole point of `constrain` function is to keep the values between `-4` and `4` (including). In your code you can go to the -5 and show it, but right after that it's adjusted to `-4` (and you are not displaying this value).

If you increment this value, you can get only result and this is  `-4 + 1 = -3`.

body:
Your main problem is that you aren't looking for a *change* in buttons. You're only doing your adding or subtracting *while* a button is pressed.

That means, all the time you're holding `btnLEFT` in your total is incrementing until it hits your limit.

You need to remember the button state from the previous iteration of `loop()` and compare it to the current state - and only if they differ do you need to do anything.

Also you should perform your constrain immediately after your addition or subtraction. As it is, you add or subtract, display the new value (I assume you do - I don't see the code for that), and only afterwards do you then chop the value back down to +/-4 (assuming it's outside the range). So your 5 becomes 4, and your next subtraction takes you to 3.


body:
I want to change *timer0* frequency because I need to use 4 PWM pins at a frequency lower than 500Hz and the SPI on an ATmega328. So I changed *timer2* to *Fast PWM* with 64 divisor, enabled the overflow interrupt for timer2 and disabled the overflow interrupt for timer0:

      TCCR2A = _BV(WGM21) | _BV(WGM20);
      TCCR2B = _BV(CS22);
      TIMSK2 |= (1 << TOIE2); // enable overflow interrupt for timer2
      TIMSK0 &= ~(1 << TOIE0); // disable overflow interrupt for timer0

and changed the ISR vector in *wiring.c* from `ISR(TIMER0_OVF_vect)` to `ISR(TIMER2_OVF_vect)`.

But `delay` doesn't work. What can be the problem?

title: Using timer2's ISR instead of timer1's in Arduino wiring.c breaks Serial object

Answers: 1

body:
> Now everything works except for delay()

`delay()` uses `micros()` and `micros()` reads the hardware registers, like this:

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

    unsigned long micros() {
     unsigned long m;
     uint8_t oldSREG = SREG, t;

     cli();
     m = timer0_overflow_count;
    #if defined(TCNT0)
     t = TCNT0;
    #elif defined(TCNT0L)
     t = TCNT0L;
    #else
     #error TIMER 0 not defined
    #endif

    #ifdef TIFR0
     if ((TIFR0 & _BV(TOV0)) && (t < 255))
      m++;
    #else
     if ((TIFR & _BV(TOV0)) && (t < 255))
      m++;
    #endif

     SREG = oldSREG;

     return ((m << 8) + t) * (64 / clockCyclesPerMicrosecond());
    }

You would need to change all those references (TCNT0, TIFR0, TOV0 etc.) to use the Timer 2 equivalents.


body:
I need to assign a string to an array value:

`char mystr[3] = "Hello";`

But when I run this code on arduino simulator: tinkercad.com, I get this error:

`1:17: error: initializer-string for array of chars is too long [-fpermissive]`

Why I'm getting this error?

title: Assign string to an array value

Answers: 1

body: You have asked the compiler to allocate 3 `char` of memory, and then you ask it to fill that memory with 6 `bytes` of data (5 characters, plus null-char for termination.)


body: Im building a bedside alarm clock/home assistant. I have a few buttons that input, an LCD display and some RGB LEDs. The LCD and RGBs are only on when commanded to be on. I was wondering if I could leave the mega plugged in and constantly running or if that would burn it out. Im a bit new to this so sorry if this is dumb. If it would burn out, how long is its lifetime?

title: Do Arduino Megas Burn Out?

Answers: 1

body:
As long as you operate the electronics within specification they will run for years and years. The first thing to probably fail will be the electrolytic capacitors that will dry out after maybe 10 years.

When reading datasheets and specifications the metric you are interested in is the **MTBF** - the [Mean Time Between Failures](https://en.wikipedia.org/wiki/Mean_time_between_failures).


body:
Hello Stack Exchangers!

I am currently working on a project which requires me to use PSOC4 - 049's to scan a series of inputs, and feed this data back to an arduino over I2C.

The arduino, or in this case a teensy 3.5, is the main unit which hosts a UI and retains key system variables. I wish to have the teensy send a few unsigned bytes to the arduino, and when user input is detected have the PSOC act as the master and send relevant information back to the arduino.

Unfortunately I've been trying for about a week now to no avail.

Currently I have 2 Teensy 3.5s sitting on my I2C bus and 1 PSOC4.
I send the first teensy a 'H' or 'L' character from a terminal over USB and it turns an LED high or low respectively,

This teensy then relays this character over the I2C Bus to the other teensy at address 0x10, which also toggles an LED.

The idea is that the first teensy then also forwards a value to the PSOC at address 0x11 but this simply isn't working for me!

I can't seem to get a single byte over to the PSOC let alone set up the full MMMS system I need!

Does anyone see what I'm doing wrong or have a good simple example of a PSOC project using Multi Master Multi Slave?

=-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-=
ARDUINO MASTER CODE     (Might be doing something wrong)
=-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-=
(Note that this function is part of a much larger project and is just being called from main at this time, much of the project is removed here but should not effect this code in any way)

    #include <Wire.h>
    void setup()
    {
         Wire.begin();
         Serial.begin(9600);
    }

    void loop()
    {checkCommand();}

    byte I2CTargetAddr[8] = {0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17}; //       Declares the addresses of the PSOCs

    void checkCommand() // Reads Serial Commands H or L, sets an LED, then     relays the instruction (hopefully) to the PSOC to do the same thing.
    {
      static int CCFR = 1;

      if (CCFR == 1)
      {
        pinMode(36, OUTPUT);  // Debug LED
        digitalWrite(36,HIGH);
        CCFR = 0;
      }

      char c;
      static char previousC = 'L';

      static byte low = 0;
      static byte high = 255;

      Wire.setClock(100000); // Set to 100kHz

      while(Serial.available())
      {
        c = Serial.read();

        if(c == 'H')
        {
          Wire.beginTransmission(I2CTargetAddr[0]);
          Wire.write('H');
          Wire.endTransmission();
          digitalWrite(36, HIGH);
        }

        else if(c == 'L')
        {
          Wire.beginTransmission(I2CTargetAddr[0]);
          Wire.write('L');
          Wire.endTransmission();
          digitalWrite(36, LOW);
        }
      }

    if(c == 'H')
    {
      Wire.beginTransmission(I2CTargetAddr[1]);
      Wire.write(high);
      Wire.endTransmission();
      //digitalWrite(high, HIGH);
    }

    else if(c == 'L')
    {
      Wire.beginTransmission(I2CTargetAddr[1]);
      Wire.write(low);
      Wire.endTransmission();
      //digitalWrite(low, LOW);
    }

      previousC = c;
    }

=-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=--=-=
ARDUINO TEST SLAVE CODE  (Seems to be totally fine)
=-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=--=-=

    #include <Wire.h>
    #define LED_1 23  // PWM Capable LED Pin

    void setup()
    {
      Wire.begin(0x10);
      Wire.onReceive(receiveEvent); // Calls the receiveEvent function when     something happens to the I2C bus
      pinMode(LED_1,OUTPUT);
      digitalWrite(LED_1, HIGH);
    }

    void loop()
    {
    }

    void receiveEvent(int howMany)
    {
      while(Wire.available())
      {
        char c = Wire.read();

        if (c == 'H'){digitalWrite(LED_1, HIGH);}
        if (c == 'L'){digitalWrite(LED_1, LOW) ;}
      }
    }

=-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-=-=-=-==-=-=-=-=-=-=-=-=-=
PSOC 4 Code
=-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-=-=-=-==-=--==-=-=-=-=-=-=

The topdesign includes a bootloadable component, a pin for LED Extern and LED Local, and an i2c block set as multi slave/ multi master at 100kb/s

-------------------------------MAIN.C---------------------------------

    #include <project.h>
    #include <main.h>

    extern uint8 I2CSlaveIn[BUFFER_SIZE];
    extern uint8 I2CSlaveOut[BUFFER_SIZE];
    extern uint8 I2CMasterIn[BUFFER_SIZE];
    extern uint8 I2CMasterOut[BUFFER_SIZE];

    /* Fast BootLoad ISR */
    CY_ISR_PROTO(bootloadISR_Handler);

    CY_ISR(bootloadISR_Handler)
    {
        Bootloadable_1_Load();   // Forces a restart of the bootloader,     triggered by the onboard button.
    }

    int main(void)
    {
        BootLoadSys_Start(); // Initialise easy bootloader tool
        bootloadISR_ClearPending();
        bootloadISR_StartEx(bootloadISR_Handler);

        initI2C(); // Initialised i2c

        CyGlobalIntEnable; /* Enable global interrupts. */

        uint8 transferredIn[BUFFER_SIZE];
        uint8 byteCount;
        uint8 lastVal = 0;

        LED_Local_Write(0);
        int i;

        for(;;)
        {
            if (0u != (MYI2C_I2CSlaveStatus() & MYI2C_I2C_SSTAT_WR_CMPLT)) //     Wait for master to complete Write
            {
                byteCount = MYI2C_I2CSlaveGetWriteBufSize();
                MYI2C_I2CSlaveClearWriteStatus();             // Take a wild guess

                for (i =0; i<byteCount; i++)
                {transferredIn[i] = I2CSlaveIn[i];} // Copy data from the buffer

                MYI2C_I2CSlaveClearWriteBuf();
            }

            if (transferredIn[0] != lastVal)
            {
                if (transferredIn[0] == 255u){LED_Local_Write(1);}
                if (transferredIn[0] == 0u  ){LED_Local_Write(0);}
            }

            lastVal = transferredIn[0];

        }
    }

----------------------------------I2C.C------------------------------------

    #include "project.h"
    #include "i2c.h"
    #include "main.h"

    uint8 I2CSlaveIn[BUFFER_SIZE];
    uint8 I2CSlaveOut[BUFFER_SIZE];
    uint8 I2CMasterIn[BUFFER_SIZE];
    uint8 I2CMasterOut[BUFFER_SIZE];

    void initI2C()
    {
        MYI2C_I2CSlaveSetAddress(MY_SLAVE_ADDR);

        MYI2C_I2CSlaveInitReadBuf( (uint8 *)I2CSlaveOut  , BUFFER_SIZE);
        MYI2C_I2CSlaveInitWriteBuf((uint8 *)I2CSlaveIn  , BUFFER_SIZE);

        MYI2C_Start();  // Calle after buffer setup
    }

----------------------------------I2C.h----------------------------------

    #define BUFFER_SIZE 1u // Sets Buffers size
    #define MY_SLAVE_ADDR 0x11u

    void initI2C();

title: Trouble with Arduino -> PSOC4 communications over I2C! (Multi master/ slave config)

Answers: 1

body:
So it turns out I'm an idiot.
At some point in the last day or so I must have accidentally changed the pins that the I2C component is assigned to.

This code (or at least code very similar to this, after a couple of minor changes) works perfectly for the slave side.

Feel free to make use of it if you need it!


body:
I have a small L298N module which I would like to use to run a couple of dc motors. The module I have is smaller than most of the ones you see on eBay, it looks like this...
[![enter image description here][1]][1]
I am trying to use the following library :
https://github.com/AndreaLombardo/L298N

I have managed to get the motor going forwards and backwards, but the problem is, this module doesn't have a pin for enable ( EN for PWM from the Arduino) and the library seems to require this; therefore I can't control the speed of the motors.

Does anyone have any experience with these modules? Is there a different technique I should be using? Is there another library that works with these kind of modules?

All help appreciated.

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

title: running a dc motor with a small L298N module and an arduino and the L298N library

Answers: 2

body:
PWM is used to control the duty cycle and not the voltage directly so your PWM will work directly on the input pins of motor driver and you will be able to control the speed.
just use analogWrite on the input pin which was held HIGH and HOLD the other pin to LOW. If you desire to change the direction while simultaneously controlling the speed. just analogWrite both the pins. Just keep in mind that the duty cycle of both the pins should not be tweaked simultaneously. while the speed is being controlled in one direction the other pin should be at analogWrite(other,0).

body:
 you can use this snippet in your code if you want

    void Loop()
    {
       //this is basically to demostrate how you can control the speed
       // and direction simultaneously
       for(i=0;i<256;i+=51)
       {
          analogWrite(motorForwardPin,i);
          analogWrite(motorBackwardPin,0);
          delay(2000);
       }
       for(i=0;i<256;i+=51)
       {
          analogWrite(motorForwardPin,0);
          analogWrite(motorBackwardPin,i);
          delay(2000);
       }
    }


body:
I am trying to control the LED on pin13 using the below code but it's not working.
With this code I am able to print to the Serial Monitor but the code has no effect on the any of the digital pins. I am unable to control the LED and so I have gotten stuck and can't advance further. I can't understand why it is happening even if I have excluded the new line from the Bluetooth app that I am using to send the strings and same on the Serial Monitor.

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

    #include<SoftwareSerial.h>          // import the serial library

    SoftwareSerial bluetooth(6, 7);     // RX, TX

    void setup(){
      Serial.begin(9600);               //set baud rate
      bluetooth.begin(9600);
      pinMode(13, OUTPUT);
      digitalWrite(13, LOW);
    }

    void loop(){
      while (bluetooth.available()){
        char ch = bluetooth.read();
        message += ch;
      }

      if(!bluetooth.available()){
        if(message != ""){
          if(message.equalsIgnoreCase("on")){
            digitalWrite(13, HIGH);
          }else{
            digitalWrite(13, LOW);
          }
          Serial.println(message);
          message = "";
        }
      }
    }

title: Not able to control digital pins using commands sent via HC-05 module

Answers: 1

body:
Your logic is a complete mess.  You have:

1. If a character is available, read it and add it to `message`.
2. If another character is available, compare what you have already stored with `on`.
  * If it's equal ('o' is not equal to 'on') turn on, otherwise turn off.
  * Print what you have stored.
3. Forget what you stored
4. Go to 1 (a character is still available since you never read it in stage 2).

Instead you need something more like:

1. If a character is available, read it into a variable.
2. If the character you read is a line ending character:
  * Compare your `message` with 'on' and take appropriate action
3. If the character you read is *not* a line ending character:
  * Add the character to `message`.
4. Go to 1.

Note how you only check once if there is a character available, and all your testing is done within that one `if` block.


body:
I have connected two arduinos using pins: RX and TX and managed to send a string as an array of values:

    //sender

    char mystr[6] = "hello";

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

    void loop() {
      Serial.write(mystr);
      delay(1000);
    }

And receive it:

    //receiver

    char mystr[6];

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

    void loop() {
      Serial.readBytes(mystr,5);

      if(mystr[0] == 'h' && mystr[1] == 'e' && mystr[2] == 'l'){

        for(int i = 0;i < sizeof(mystr);i++){

          Serial.print(mystr[i]);

          if(i == sizeof(mystr) - 1){
           Serial.print("\r\n");
          }
        }
      }
      delay(1000);
    }

That worked fine! But I need to send and receive something like this:

    int a[3][4] = {
       {0, 1, 2, 3} ,
       {4, 5, 6, 7} ,
       {8, 9, 10, 11}
    };

How can I do that?

title: Send an multidimensional array of values from one arduino to another through serial port

Answers: 1

body:
Use two for loops to send the multidimensional array, and two for loops to receive the multidimensional array.

Sending:

    int a[3][4] = {
       {0, 1, 2, 3} ,
       {4, 5, 6, 7} ,
       {8, 9, 10, 11}
    };

    for (int x = 0; x < 3; x++)
    {
       for (int y = 0; y < 4; y++)
       {
          Serial.print(a[x][y]);
       }
    }

Receiving

    for (int x = 0; x < 3; x++)
    {
       for (int y = 0; y < 4; y++)
       {
          a[x][y] = Serial.read(); // Not sure about the exact prototype
       }
    }

If the sizes are fixed (like in your case 3 and 4), than you don't have to send the dimensions, just sent the values in order: 0, 1, 2, 3, 4, ... like above.

And when receiving them you know the first four values belong to row 0, next four values to row 1 etc.

If you need dynamic sizes, first send the number of rows and columns and than the values.

In that case instead of 3 and 4 define two constants and use them:

    #define NR_ROWS 3
    #define NR_COLUMNS 4

    int a[NR_ROWS][NR_COLUMNS] = {
       {0, 1, 2, 3} ,
       {4, 5, 6, 7} ,
       {8, 9, 10, 11}
    };

    for (int x = 0; x < NR_ROWS; x++)
    {
       for (int y = 0; y < NR_COLUMNS; y++)
       {
          Serial.print(a[x][y]);
       }
    }


body:
I'm trying to make [this][1] project.

But i have a problem running this code. It appears to be `val = digitalRead(inPin);` breaks entire program. just because i call this from the `callback` function which attached as an interrupt function `Timer1.attachInterrupt(callback);`

Here is the more simplified problem simulation program,

    #include "TimerOne.h"

    int inPin = 7;   // sensing digital pin 7

    int val;

    void setup() {
      pinMode(inPin, INPUT);      // sets the digital pin 7 as input to sense receiver input signal

      Serial.begin(9600);
      Timer1.initialize(8);  // initialize timer1, and set the frequency; this drives both the LC tank as well as the pulse timing clock
      // note: modify this as needed to achieve resonance and good match with the desired tags
      // the argument value is in microseconds per RF cycle, so 8us will yield RF of 125kHz, 7us --> 143kHz, etc.

      Timer1.pwm(9, 512);

      Timer1.attachInterrupt(callback);
    }

    void callback()
    {
      val = digitalRead(inPin);//once you comment this line, it works fine
    }

    void loop() {
      Serial.print("Program running \n");

    }

Any help is much appreciated.

  [1]: https://playground.arduino.cc/Main/DIYRFIDReader

title: Arduino TimerOne breaks the program when calling "digitalRead"

Answers: 1

body:
The time between 2 interrupt triggers is only 8us. Also `digitalRead()` is a quite big function, that needs some time to execute (I don't know how much). That way it is to short for the Serial print command to execute in the leftover time. Make the following change and you will see, that it works.

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

    void loop(){
      noInterrupts();
      Serial.print("Program running \n");
      interrupts();
      delay(1000);
    }
Now the interrupts are disabled during the execution of the `Serial.print()`, so that it can finish. After this the interrupts are enabled again and we wait for 1 second to give the interrupts some time before we are disabling them again.

The speed of the Arduino is limited, so you cannot do much, when constantly triggering interrupts in the pace of 8us. If you only want to check this digital input you can get the value directly with using the PINB registers (refer to [this side][1]), which works much faster.

Also you should consider making the variable `val` volatile, since it will can change everytime through your interrupt service routine.

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


body:
I want to make my Attiny85 and my Arduino UNO communicate together with I2C protocol. Since Attiny do not support Wire library, I use TinyWire by lucullusTheOnly and Wire on the Uno.

The Attiny is sending data as the master to the Uno, the slave.

Here is my code:

Master

    #include <TinyWire.h>

    byte slave_address = 10;

    void setup() {
     // config TinyWire library for I2C master functionality
     TinyWire.begin();
    }

    void loop() {
     TinyWire.beginTransmission(slave_address);
     TinyWire.send('c');
     // endTransmission sends the bytes in the buffer to the slave and returns 0 if there was no error
        TinyWire.endTransmission();
     delay(500);
    }

Slave

    #include <Wire.h>

    void setup() {
      Wire.begin(10);                // join i2c bus with address #10
      Wire.onReceive(receiveEvent); // register event
      Serial.begin(9600);           // start serial for output
    }

    void loop() {
      delay(100);
    }

    // function that executes whenever data is received from master
    // this function is registered as an event, see setup()
    void receiveEvent(int howMany) {
      while (1 < Wire.available()) { // loop through all but the last
        char c = Wire.read(); // receive byte as a character
        Serial.print(c);         // print the character
      }
      int x = Wire.read();    // receive byte as an integer
      Serial.println(x);         // print the integer
    }

I connect the pin like this :

    Arduino --> Attiny
    SCL ---- PIN 7
    SDA ---- PIN 5

I try to pull-up the clock and data line with 2.2k resistors but nothing happened, I receive nothing on the Uno from the Attiny.
Any idea ? Thanks !

title: I2C communication between Attiny85 as master and arduino UNO as slave

Answers: 2

body:
The pure master functionality of the TinyWire library is currently buggy. As a work around you can initiate the library on the ATTiny also as a slave with an address. When the `endTransmission()` function is called, the library switches temporarily to master mode for sending the bytes. I've tested this with your code in my own setup and it works. (Be sure, that the frequency in the ATTiny is set right. I tested the library only for 8MHz. For my own ATTiny's I had to do an extra step and set the correct fuses with avrdude)

I think the pure master part is blocking itself after the first transmission. I will add an issue in the github project. Maybe I can fix this in some time.

Chrisl aka lucullusTheOnly

EDIT: I had to think about this and looked into the library. The problem was found easily. In `twi.cpp` there is a `NOISE_TESTING` define block in the master send/receive function, which is constantly triggering error #6 (unexpected stop condition). In slave mode this doesn't happen, because directly before sending as a master it calls the master init function, which clears all USI flags, including the stop condition flag, that is polled in the send/receive function.

I have deactivated the `NOISE_TESTING` in the github project. If you don't want to download the current version, you can just open twi.h and comment the definition of `NOISE_TESTING`.

body:
I have the same issue even though I have the latest Github version with the NOISE_TESTING define block disabled.

I believe it has something to do with the line 359 in TWI.cpp where the stop condition isn't issued if a NACK happens:

          if( temp_result.result & (1<<TWI_NACK_BIT) )
      {
        if ( USI_TWI_state.addressMode )
          USI_TWI_state.errorState = USI_TWI_NO_ACK_ON_ADDRESS;
        else
          USI_TWI_state.errorState = USI_TWI_NO_ACK_ON_DATA;
        return (FALSE);
      }

I think it should be :

          if( temp_result.result & (1<<TWI_NACK_BIT) )
      {
        if ( USI_TWI_state.addressMode )
          USI_TWI_state.errorState = USI_TWI_NO_ACK_ON_ADDRESS;
        else
          USI_TWI_state.errorState = USI_TWI_NO_ACK_ON_DATA;
        USI_TWI_Master_Stop();
        return (FALSE);
      }

I tried it on ISIS in pure master only and it worked. I don't know if this is a viable solution or if it will cause any conflict with how the rest of the lib works.


body:
I have little to no experience in programming and i'm very slowly and gradually getting the hang of it. My next project is that i'm making a clock, and wanted to use multiple functions for the hour:minute:seconds instead of just using one for everything. But after reading some i came to the conclusion that the arduino can only run one function at a time. So my question is how can i make the illusion of multiple functions running simultaneously on a LCD screen.

My code:

    #include <LiquidCrystal.h>

    LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

    int lcd_key     = 0;
    int adc_key_in  = 0;
    #define btnRIGHT  0
    #define btnUP     144
    #define btnDOWN   329
    #define btnLEFT   504
    #define btnSELECT 741
    #define btnNONE   5

    int read_LCD_buttons()
    {
     adc_key_in = analogRead(0);

     if (adc_key_in > 1000) return btnNONE;
     if (adc_key_in < 50)   return btnRIGHT;
     if (adc_key_in < 195)  return btnUP;
     if (adc_key_in < 380)  return btnDOWN;
     if (adc_key_in < 555)  return btnLEFT;
     if (adc_key_in < 790)  return btnSELECT;
     return btnNONE;

    }
    unsigned long minInterval = 60000UL; // Interval for minutes in milliseconds
    unsigned long secInterval = 1000UL;  // Interval for seconds in milliseconds
    unsigned long prevMinMillis = 0UL;   // Holds the timestamp of the last time Minute() was called
    unsigned long prevSecMillis = 0UL;   // Holds the timestamp of the last time Second() was called

    void setup()
    {
     lcd.begin(16, 2);
    }

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

      if (currentMillis - prevMinMillis > minInterval)
      {
        prevMinMillis = currentMillis;
        Minute();
      }

      if (currentMillis - prevSecMillis > secInterval)
      {
        prevSecMillis = currentMillis;
        Second();
      }

    }

    void Second(){
      int First_Digit = 0;
      int Second_Digit = 0;

      for(Second_Digit; Second_Digit<10; Second_Digit++){
        if(Second_Digit==10){
          First_Digit = First_Digit + 1;
          }

        lcd.setCursor(0, 0);
        lcd.print(First_Digit);
        lcd.setCursor(1, 0);
        lcd.print(Second_Digit);
        lcd.clear();

        if(First_Digit==5 && Second_Digit==9){
          First_Digit = First_Digit - 5;
          Second_Digit = Second_Digit -10;

          }
        if(Second_Digit==9){
          First_Digit = First_Digit + 1;
          Second_Digit = Second_Digit - 10;
          }

      }
    }
    void Minute(){
      int First_Digit = 0;
      int Second_Digit = 0;
      for(Second_Digit; Second_Digit<10; Second_Digit++){
        if(Second_Digit==10){
          First_Digit = First_Digit + 1;
          lcd.print(First_Digit);
          }

        lcd.setCursor(3, 0);
        lcd.print(First_Digit);
        lcd.setCursor(4, 0);
        lcd.print(Second_Digit);
        lcd.clear();

        if(First_Digit==5 && Second_Digit==9){
          First_Digit = First_Digit - 5;
          Second_Digit = Second_Digit -10;
          lcd.print(First_Digit);

          }
        if(Second_Digit==9){
          First_Digit = First_Digit + 1;
          lcd.print(First_Digit);
          Second_Digit = Second_Digit - 10;
          }

      }
    }

title: How do i run multiple functions simultaneously on a LCD screen?

Answers: 1

body:
Use the state machine model shown in [BlinkWithoutDelay][1]

    unsigned long minInterval = 60000UL; // Interval for minutes in milliseconds
    unsigned long secInterval = 1000UL;  // Interval for seconds in milliseconds
    unsigned long prevMinMillis = 0UL;   // Holds the timestamp of the last time Minute() was called
    unsigned long prevSecMillis = 0UL;   // Holds the timestamp of the last time Second() was called

    void setup()
    {
     lcd.begin(16, 2);
    }

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

      if (currentMillis - prevMinMillis > minInterval)
      {
        prevMinMillis = currentMillis;
        Minute();
      }

      if (currentMillis - prevSecMillis > secInterval)
      {
        prevSecMillis = currentMillis;
        Second();
      }

    }

With this example, `Second()` is called only when the difference between "now" and the last time it was called is greater than `secInterval`. Likewise for `Minute()`.

[Note, the code above will not run as-is, but I assume you have initialized the LiquidCrystal library and assigned the pins as per your schematic.]

**EDIT BASED ON UPDATED CODE SAMPLE**

Issue 1:

In both your `Minute()` and `Second()` functions you have a sequence like:

    lcd.setCursor(0, 0);
    lcd.print(First_Digit);
    lcd.setCursor(1, 0);
    lcd.print(Second_Digit);
    lcd.clear();

After writing the characters, you immediately clear the LCD screen. Don't do this, it erases all the output on your LCD.

Issue 2:

At the start of the `Minute()` function, you have the following:

  int First_Digit = 0;
  int Second_Digit = 0;

This means the variables `First_Digit` and `Second_Digit` are initalized to zero every time the function is called. This means you won't get an increment of the value, it will start at zero every time you try to update the LCD. You can declare those variables as `static` so that the value remains the same between calls of the function. Static variables are automatically initialized to zero. Thus:

    static int First_Digit;
    static int Second_Digit;

and similarly in the `Second()` function.

You're correct that `digitalWrite()` is not needed in your function as it is described. `digitalWrite()` is for changing a physical pin on the Arduino to a `LOW` or `HIGH` value (that is, a 0V or 5V voltage.) In the Blink without Delay example, `ledPin` and `ledState` are just variables to hold the pin identifier for the blinking LED, and the current state (`LOW` or `HIGH`) of that pin. Again, not necessary for your code, as you have described it.

**SECOND UPDATE**

Having tackled the issue of how to run multiple functions "simultaneously", now move on to fixing the overly complicated code for writing the minute and second values to the LCD... I'm not sure why you put the `for` loop in the `Minute()` and `Second()` functions, but it's unnecessary.

You also are treating each digit way too complicated. If your value for the seconds counter is 0 to 59, why not keep track of it that way, and then display each digit as necessary:

    void Second() {
      static int second;

      second++;
      if (second>59) {
        second = 0;
      }
      lcd.setCursor(0, 0);
      lcd.print(second/10);   // Prints the 10s digit
                              // Note, lcd.print automatically moves to the next column
      lcd.print(second % 10); // Prints the remainder after dividing by 10
    }

    void Minute() {
      static int minute;

      minute++;
      if (minute>59) {
        minute = 0;
        // Probably want to increment an Hour counter here?
      }
      lcd.setCursor(3, 0);
      lcd.print(minute/10);   // Prints the 10s digit
                              // Note, lcd.print automatically moves to the next column
      lcd.print(minute % 10); // Prints the remainder after dividing by 10
    }

  [1]: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay


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

    /*aim of the program is to generate 2 different varying frequency from the
    same output which is controlled by 2 triggers*/
    void setup()
    {
     pinMode(2,INPUT); //setting the trigger pins 2,3
     pinMode(3,INPUT);
     pinMode(6,OUTPUT); //output pin
    }

    void loop()
    {
     if(digitalRead(2)==HIGH && digitalRead(3)==LOW) { //trigger conditions
            infra();
        }
     else if(digitalRead(2)==LOW && digitalRead(3)==HIGH) {
            red();
        }
     else if((digitalRead(2)==HIGH && digitalRead(3)==HIGH) || (digitalRead(2)==LOW && digitalRead(3)==LOW)) {
      Serial.println('help');
     }
    }

    void infra() //function varies sinosoidaly (working)
    {
     float f;

     for(f=16000; f<=20525; f+=4.525) {
      tone(6,f);
     }

     for(f=20525; f>=16000; f=f-4.525) {
      tone(6,f);
     }
    }

    void red() //function varies sinosoidaly (working)
    {
     float p;

     for(p=25000; p<=32071; p+=7.071) {
      tone(6,p);
     }

     for(p=32071; p>=25000; p=p-7.071) {
      tone(6,p);
     }
    }

title: The code fails to generate the values I want, when both trigger pins 2, 3 are high or low. Why?

Answers: 1

body:
To send anything to serial you need to initialize it first with:

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

    void setup()
    {
        Serial.begin(115200);
        //other code
    }

And you are using wrong quotes for the string.
They should be double quotes `"` not single ones `'`.

Also you could simplify your code, if you removed the third `if`, since it's just checking the already known state at that point.

You should also read the button state only once, save them into a variable and then just compare those variables.

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

    bool button1_state = digitalRead(2);
    bool button2_state = digitalRead(3);
    if (button1_state && !button2_state) {
        infra();
    }
    else if (!button1_state && button2_state) {
        red();
    }
    else {
        Serial.println("help");
    }


body:
I have just started getting into Arduino and c++ programming!

For all the talk on the internet about c++ being incompatible with 8-bit and even 16-bit microcontrollers, how is it that Arduino Microcontrollers can safely handle c++ code, in terms of the ram usage? Is it that Arduino's library does not contain or utilize features such as constructors or objects (of C++) that (I believe) are very ram-usage-intensive?

Cheers!

title: How can Arduino's 8 bit Microcontrollers handle C++

Answers: 4

body:
It's a misconception that using constructors or C++ in general requires lots of RAM. Plus, to be clear, the AVR processors like the Micro and Uno have separate RAM and PROGMEM (program memory). So, code for functions does not, in itself, use RAM.

As an example, this small program for the Micro:

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

    int main ()
      {
      }

That uses only 206 bytes of PROGMEM and 0 bytes of RAM (according to the IDE).

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

    Sketch uses 206 bytes (0%) of program storage space. Maximum is 28,672 bytes.
    Global variables use 0 bytes (0%) of dynamic memory, leaving 2,560 bytes for local variables. Maximum is 2,560 bytes.

---

Adding in a class, with a constructor, and using that class, increases the memory a bit:

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

    class foo
      {
      public:
      int bar;  // some class variable

      foo ()  // constructor
        {
        bar = 1;
        }
      };  // end of foo

    foo nick;  // a global variable
    int main ()
      {
      PORTD = nick.bar;
      }

That uses 2 bytes of RAM, and 278 bytes of PROGMEM. Hardly a lot.

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

    Sketch uses 278 bytes (0%) of program storage space. Maximum is 28,672 bytes.
    Global variables use 2 bytes (0%) of dynamic memory, leaving 2,558 bytes for local variables. Maximum is 2,560 bytes.

---

Of course, the more things you do, the more RAM and PROGMEM it takes, however the compiler generates quite efficient code, and the linker strips out things that are not needed by your code.

---

> Is it that Arduino's library does not contain or utilize features such as constructors or objects (of C++) ...

A lot of libraries use classes and constructors (for example the Serial library, the Print class, and a lot of others). There is nothing inherently RAM-intensive about a constructor. It's just a function that does something, with an implied **this** pointer to the current instance of the class.

---

> do lambdas work? (from a comment)

Yes you can use lambdas:

    // array of function pointers
    void (*doActionsArray []) () =
     {
     [] { Serial.println (0); } ,
     [] { Serial.println (1); } ,
     [] { Serial.println (2); } ,
     [] { Serial.println (3); } ,
     [] { Serial.println (4); } ,
     };

    void setup ()
      {
      Serial.begin (115200);
      Serial.println ();

      doActionsArray [3] ();
      }  // end of setup

    void loop () { }

---

>  as long as you don't (extensively) use: the standard library, exceptions, templates ... (from a comment)

Templates can certainly simplify doing things like writing to, or reading from EEPROM and similar. For example:

    #include <Arduino.h>  // for type definitions
    #include <EEPROM.h>

    template <typename T> unsigned int EEPROM_writeAnything (int ee, const T& value)
    {
        const byte* p = (const byte*)&value;
        unsigned int i;
        for (i = 0; i < sizeof(value); i++)
         EEPROM.write(ee++, *p++);
        return i;
    }

    template <typename T> unsigned int EEPROM_readAnything (int ee, T& value)
    {
        byte* p = (byte*)&value;
        unsigned int i;
        for (i = 0; i < sizeof(value); i++)
         *p++ = EEPROM.read(ee++);
        return i;
    }

---

The standard library? There are implementations for the Arduino. We have to bear in mind that RAM is limited, however if you are going to do something *anyway* that involves linked lists, etc. then the Standard Template Library will probably do what you want as efficiently as you could if you coded it "by hand".

---

The bottom line is you need to be aware of what you are coding on. I have seen examples like this:

    float foo [1000];  // hold my readings

That blows the available RAM on a Uno straight away. Nothing to do with C++ per se.

---

The other thing to be aware of is some tricks you can usefully employ. One common one is to replace:

    Serial.println ("Program starting.");

With:

    Serial.println (F("Program starting."));

The first example causes the compiler to copy the string "Program starting." from PROGMEM into RAM, using some of your valuable RAM. The second example doesn't.

body:
The talk about C++ being incompatible with small MCUs implies that developers would use features it provides. In a *good* C++ project you're expected to use vectors and iterators instead of C arrays, throw exceptions instead of returning error codes, use lambda-functions, templates etc.

As long as you don't use those features, C++ memory consumption is manageable. The reason for this is simple: such limited C++ is just a syntactic sugar around C structures and function pointers.

The problems usually start when you write a class which is complex enough that its constructor can fail. Then you have a tough choice to make: start using exceptions and drastically increase memory consumption, or write classes which *pretend* they never fail to construct (which often results in a program which *pretends* to work).

body:
To write effective code with limited resources (RAM, program space, processing), you need to know enough about the processor to avoid features which it can't do.  In this case you're limited on all three counts, so you want to get away from anything complex and slow.

A good start is to avoid any features later than C++98, or at least C++03.  These features generally come at a cost.

Beyond that, particular issues are:-

 - Polymorphism.  All classes using virtual members have a [virtual method table][2], meaning every function call from that class needs to look up against a table.  On a small processor, this does slow down your function calls.  By all means use this where it's required, but if you have performance issues then you want your polymorphic classes to live at a higher level where the function calls happen less often.  Don't do this for low-level functions which get called thousands of times in a loop.
 - Exceptions.  Already covered by other answers.
 - Inline.  This is a *good* thing.  Where you can use this, it can claw back some processing cycles: not just from the function call itself; but also from further optimisation in the calling functions.

And of course general issues for embedded firmware on low-end micros:-

 - Dynamic memory allocation (new and delete, or most STL containers).  This is ***always*** an [anti-pattern][1] in embedded development.  It requires a chunk of RAM to be set aside for heap, and you always need to consider the possibility of allocation failing.  If you really need some kind of dynamic storage, consider whether a FIFO buffer or something better bounded would be appropriate.
 - Longer integers.
 - Integer multiply and divide.
 - Anything floating-point.
 - Anything using a lot of stack, whether this is lots of local variables, lots of function parameters, or over-enthusiastic function partitioning.

  [1]: https://en.wikipedia.org/wiki/Anti-pattern
  [2]: https://en.wikipedia.org/wiki/Virtual_method_table

body:
C++ is fine with Arduinos or other AVR based Systems.
I've been use it for quite a while in a home automation project.

The avr runtime does not support exceptions nor dynamic memory allocation, as has been stated. [you can provide an implementation  though][1].

There is much of C++ left to make use of. here are some examples

**Templates**

They are very useful because, e.g. they allow to move work from runtime to compiletime. I use template for a [replacement of the Arduino HAL functions DigitalWrite and others, without the runtime and code bloat][2].

compare this

    int main(void)
    {
            DDRB |= (1<<7);
            while(  (  ( PINB & (1<<6) ) !=(1<<6) ) )
                    ;
            while(1)
            {
                    _delay_ms(100);
                    PORTB |= (1<<7);
                    _delay_ms(100);
                    PORTB &= ~(1<<7);
            }
    }

to this

    int main(void)
    {
            IOPin<13> ledpin;
            IOPin<12> testpin;
            ledpin.SetDir(out);

            while(0 == testpin.State())
                    ;
            while(1)
            {
                    _delay_ms(100);
                    ledpin.SetHigh();
                    _delay_ms(100);
                    ledpin.SetLow();
            }
    }

The template based version is much more readable, and generates exactly the same assembler code. In the abovementioned linked article i explain the template and why this works.

**more on templates**

The following code uses the "curiously recurring template pattern" CRTP.
It is used to create a job class, which i use for a primitive scheduling

This template builds a chain of registrable items.

    template<class registered>
    struct Registered {
     static registered *registry;
     registered *chain;
     Registered() : chain(registry) {registry=static_cast<registered*>(this);}
    };

The job class applies the CRTP pattern. The constructor takes the actual callback where the work is done, and how often the job is done.

    class Job : public Registered<Job>
    {
     voidFuncPtr m_p;
     uint16_t m_periodic;
     uint32_t m_lastrun;
     uint16_t m_initialdelay;
     public:
     Job(voidFuncPtr p,uint16_t periode=0,uint16_t initialdelay=0):m_p(p),m_periodic(periode),m_lastrun(0),m_initialdelay(initialdelay)
     {

     }
     void run(uint32_t t_ms)
     {
      // tbd handle wraparound !!
      if(t_ms >= m_lastrun + m_periodic + m_initialdelay)
      {
       m_p();
       m_lastrun=t_ms;
       m_initialdelay=0;
      }
     }
    };

to use the job class i just create the instances for the jobs and pass lambdas or regular function pointers

    Job jserial([](){mqttrouteradapter.handleSerialMQTT();},10);
    Job jupdate(updatemc,1);
    Job jprint(printstate,500);

initialize the beginning of the chain of jobs

    template<> Job *Registered< Job >::registry = 0;

and inside main, run an infinite loop which calls the jobs.

    while (1)
     {
      for ( auto p = Job::registry; p; p=p->chain )
      p->run(millis());
     }

**Lambdas**

Nice to avoid a callback function

instead of

    void handleserial(void)
    {
     mqttrouteradapter.handleSerialMQTT();
    }
    Job jserial(handleserial,10);

i can write something like

    Job jserial([](){mqttrouteradapter.handleSerialMQTT();},10);

**the new meaning of auto**

Allows to deduce the type automagically. This function iterates over "something" passed the second parameter. It compiles, if the passed type provides the operations/attributes used in the function.
[And yes, **this** works only since c++17][3]

 void runRx(const char* data, auto msg_registry) {
  for (auto p = msg_registry; p; p = p->chain) {
   p->rx(data);
  }
 }

**using a recent compiler**

If you want to use a recent compiler (The Arduino IDE uses gcc4.9) you can [build your own gcc avr toolchain rather easily][4]. Then you have gcc 7.2 with c++17 support !
An other very good reason to use gcc 7.2 is, that they have improved the error messages by a great deal.

My conclusion is, there is no excuse using c, except you havn't yet learned c++. And use a new compiler !

  [1]: http://www.avrfreaks.net/forum/c-new-delete-operator-confusion
  [2]: https://haarer.github.io/c++/avr/templates/i/o/2018/01/21/c++-template-based-hardware-access-vs-classic-approach.html
  [3]: http://en.cppreference.com/w/cpp/language/auto
  [4]: https://github.com/haarer/toolchain68k


body:
I installed Arduino IDE version 2.1 on Ubuntu via apt-get. Then I typed the following command in terminal to see if the Arduino IDE compiles my sketch.

     arduino --verify xx.ino

However, this command launches the GUI IDE. Is the CLI not supported anymore, or is the cause in apt-get the package?

title: arduino --verify / --upload not working (command line)

Answers: 1

body:
It's quite possible that this "version 2.1" doesn't support command line processes. I've never heard of an Arduino IDE version 2.1. My understanding is the version you get from `apt-get install arduino` is something like 2:1.0.5+dfsg2 so maybe you interpreted that as 2.1. That version is based on Arduino IDE 1.0.5, though apparently it has some non-standard modifications. Command line operation was [first added](https://github.com/arduino/Arduino/blob/master/build/shared/manpage.adoc#history) in Arduino IDE 1.5.2, though some additional functionalities were added in newer versions.

You should always install the official Arduino IDE downloaded from:
https://www.arduino.cc/en/Main/Software


body:
After months of good use, both my boards Mega 2560 and Uno became unavailable for uploading sketch or burning bootloader.

    Sketch uses 444 bytes (1%) of program storage space. Maximum is 32256 bytes.
    Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
    C:\[...]bin/avrdude -CC:[...]avrdude\6.3.0-arduino9/etc/avrdude.conf -v -patmega328p -cstk500v1 -PCOM5 -Uflash:w:C:\Users\GREGOR~1\AppData\Local\Temp\arduino_build_242793/BareMinimum.ino.hex:i

    avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2014 Joerg Wunsch

             System wide configuration file is "C:[...]\arduino\tools\avrdude\6.3.0-arduino9/etc/avrdude.conf"

             Using Port                    : COM5
             Using Programmer              : stk500v1
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x03
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x03

**Facts :**

 - v1.6.20 of the boards
 - v1.8.5 of the IDE
 - Windows 8.1 64bits
 - Programmer: "AVR ISP"
 - Drivers are fine (the boards are well recognized)
 - Serial monitor works
 - I'm trying to upload the "Bare minimum" exemple sketch
 - Nothing in pin 0 and 1, nothing at all is plugged actually
 - Get Board info:
 - Uno : VID 2A03
 - Mega2560 : VID 2A03
 - From instructions [here][1], every instruction is "echoed back"

**What i tried :**

 - https://forum.arduino.cc/index.php?topic=385160.0
 - https://arduino.stackexchange.com/questions/22191/avrdude-stk500-recv-programmer-is-not-responding
 - https://zestedesavoir.com/forums/sujet/5676/probleme-televersement-arduino
 - All other programmers
 - A few old versions of boards
 - Resetting the boards a few times, during upload, before, after...

Nothing works. If you have any idea.....

Thank you all !

  [1]: https://arduino.stackexchange.com/questions/13292/have-i-bricked-my-arduino-uno-problems-with-uploading-to-board

title: avrdude: stk500_recv(): programmer is not responding after all tries

Answers: 1

body:
It eventually worked by using **upload** / ctrl+U (what I *didn't try*... smh) instead of  **upload using programmer** / ctrl+shift+U.

So i know now where it comes from, though I don't know what's wrong with AVR ISP.


body:
Is it possible to burn arduino code programmatically?

I was thinking of one way and that is to download hex file from my online server. Store contents of the hex file in a string, and write that string to arduino flash, restart arduino and it should run new code in flash.

Can this be done? If not than please suggest me any other way to burn the code using C++ instructions.

title: Arduino Burn the code programmatically

Answers: 1

body:
First, the Arduino Uno has 32 KB of flash, but only 1 KB of RAM. So, to be able to store the new program in a string means your new program can only be, at most, 1kb.

Secondly, only the bootloader can write to flash. So you could write a new bootloader that downloads the new program (in parts) and writes it to the flash. You would however need quite a big bootloader, leaving less space for actual code. Also the main program still needs to access the server to see if it needs to "reboot" so the bootloader can run the update process.

An example of an OTA bootloader can be found at https://www.rotwang.co.uk/projects/bootloader.html which might be a good starting point. Similar idea https://ncrmnt.org/2014/02/27/rf24boot-a-universal-over-the-air-bootloader-for-all-those-ucs/

Another option is to write the new firmware to an external EEPROM. Then your modified bootloader only has to read the new firmware from EEPROM, making it a lot simpler and smaller. There is some useful info in the question https://arduino.stackexchange.com/questions/11694/ota-updates-for-arduino-using-nrf24l01

MySensors.org already made such a bootloader: https://www.mysensors.org/about/bootloader

I know there exists another bootloader that does just that, but I can't seem to find it.


body:
So i've chosen to purchase a Wemos D1 R2 board in order that my old Arduino Uno R3 projects can get some new IoT features. However, even if my code is working in Uno perfectly, i want to test it using D1 before adding features. My problem is that, even if i have found tables showing differences between the 2 boards' pinouts, i cannot understand the correspondence between the pinouts.

So i am giving you the table below. Let's say i want to define echo and trigger pins for a sensor in my code. For example:

    #define TRIGGER_PIN 4
    #define ECHO_PIN 3

That would be pins D3 and D4 at my Uno. But i cannot understand which those pins would be in Wemos D1 R2. Also, my two boards can be seen below for comparison

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

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

  [1]: https://i.stack.imgur.com/ELW7g.jpg
  [2]: https://i.stack.imgur.com/9Gwbj.jpg

title: Arduino Uno R3 to Wemos D1 R2 project migration - Pinout problems

Answers: 1

body:
The tricky thing with the WeMos boards is the pin notation is different from other Arduino boards.

Sometimes you will see the digital pins on Arduino boards referenced with the D*n* notation. For example: "Connect the HC-SR04's Trig pin to D4 on the Uno". In fact some boards such as the Nano even use the D*n* pin notation on their silkscreen. This is just a way of further differentiating the pins from the A*n* pins. You will only refer to that pin by the number 4 in your code.

The WeMos boards are different. You actually need to use `D3` and `D4` in your code to control the pins marked D3 and D4 on the silkscreen:

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

    #define TRIGGER_PIN D4
    #define ECHO_PIN D3

We can take a peek at the source code of the [ESP8266 core for Arduino](https://github.com/esp8266/Arduino/) to see why:
https://github.com/esp8266/Arduino/blob/2.4.0/variants/d1_mini/pins_arduino.h#L40-L50

    static const uint8_t D0   = 16;
    static const uint8_t D1   = 5;
    static const uint8_t D2   = 4;
    static const uint8_t D3   = 0;
    static const uint8_t D4   = 2;
    static const uint8_t D5   = 14;
    static const uint8_t D6   = 12;
    static const uint8_t D7   = 13;
    static const uint8_t D8   = 15;
    static const uint8_t RX   = 3;
    static const uint8_t TX = 1;

Now you can see that if you use your original code:

    #define TRIGGER_PIN 4
    #define ECHO_PIN 3

That would actually be referring to the pins marked D2 and RX on the WeMos D1 R2!