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

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

    Arduino: 1.8.5 (Windows 8.1), Board: "Arduino/Genuino Uno"

    C:\Users\julie_000\Documents\Arduino\BIO_199\BIO_199.ino: In function 'void loop()':

    BIO_199:19: error: too few arguments to function 'long int map(long int, long int, long int, long int, long int)'

       t1 = map(2, 0, 1023, 2);

                             ^

    In file included from sketch\BIO_199.ino.cpp:1:0:

    C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Arduino.h:253:6: note: declared here

     long map(long, long, long, long, long);

          ^

    exit status 1
    too few arguments to function 'long int map(long int, long int, long int, long int, long int)'

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

How do I fix this error?

title: Fixing Error function 'long int map

Answers: 1

body:
`map` takes 5 parameters, not 4.  You have the original lower and upper bounds, the desired lower and upper bounds, but you forgot the actual value you want to map:

    map(value, fromLow, fromHigh, toLow, toHigh)

So

    t1 = map(t2, 2, 0, 1023, 2);

(assuming those numbers are actually meaningful...)


body:
I'm trying to take the position data generated from this servo sweep, and send over serial to another Arduino. The position data is stored as `pos` in the code I included, what would be the best method for doing this?

    /* Sweep
     by BARRAGAN <http://barraganstudio.com>
     This example code is in the public domain.

     modified 8 Nov 2013
     by Scott Fitzgerald
     http://www.arduino.cc/en/Tutorial/Sweep
    */

    #include <Servo.h>

    Servo myservo;  // create servo object to control a servo
    // twelve servo objects can be created on most boards

    int pos = 0;    // variable to store the servo position

    void setup() {
      myservo.attach(9);  // attaches the servo on pin 9 to the servo object
    }

    void loop() {
      for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
        // in steps of 1 degree
        myservo.write(pos);              // tell servo to go to position in variable 'pos'
        delay(15);                       // waits 15ms for the servo to reach the position
      }
      for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
        myservo.write(pos);              // tell servo to go to position in variable 'pos'
        delay(15);                       // waits 15ms for the servo to reach the position
      }
    }

title: Sending servo position data from one Arduino to another

Answers: 1

body:
Yes, sending data over Serial is as simple as using `Serial.write()` or it's siblings. When sending data over Serial you have to consider, how you want to send it.

 1. **Raw binary data:** You can simply use the `Serial.write()` command, which will send the variable as binary data. If you whatch this on the serial monitor of your PC, you will not see readable numbers, because what is shown there is interpreted as ASCII-encoded data, where every byte value has a corresponding character (for example the value 97 is the letter 'a'). On the other Arduino you just use `Serial.read()` to write the byte data directly to a variable. This is practical, if you are sending always the same amount of data (like the value of one sensor). If the length of a message is variable, you have to use a delimiter, to mark the end of a message. Here the second way is more save.
 2. **ASCII encoded data:** You can send your data human readable as ASCII encoded data. The value 128 then would consist of 3 bytes, one for each character. Here you always have to use a delimiter, so that the receiver can tell the values apart. A common message delimiter is the newline character '\n'. On Windows you also often have newline and carriage return '\r' together. For decoding you can use one of the many functions, that convert a string/character array to a number with the wanted format (in your case integer), for example `atoi()`.

Refer to the Serial examples in the Arduino IDE to see the code in action.

Note: Since the value of `pos` only varies between 0 and 180, you can use one byte to save and transmit it, instead of the 2 bytes the integer uses.


body:
I'm trying to create a small laser "turret" with x-axis control. The arduino receives input through IR sensor. I'm having a problem where my servo will preform my up and reset function(moves and prints as intended), but When i preform the down function the servo does not move. I believe the function is executing (it outputs angle to LCD and text to serial monitor) but there is no movement.
Any help would be greatly appreciated!

    #include <IRremote.h>
    #include <LiquidCrystal_I2C.h>
    #include <Servo.h>

    int IRPIN = 3;
    int angle = 0;
    int test = 0;
    IRrecv irrecv(IRPIN);
    decode_results results;
    Servo spinnything;
    LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

    void setup()
    {
     irrecv.enableIRIn();
     lcd.begin(16, 2);
     lcd.backlight();
     spinnything.attach(5);
     spinnything.write(angle);
     lcd.setCursor(0, 0);
     lcd.print("WARNING");
     lcd.setCursor(2, 1);
     lcd.print("!!!LASER!!!");
     delay(1500);
     lcd.clear();
    }

    void loop()
    {
     if (irrecv.decode(&results)) {
      irrecv.resume();
     }
     if (results.value == 0xE172C837) {
      up();
      results.value = 0x00000000;
     }
     if (results.value == 0xE17228D7) {
      down();
      results.value = 0x00000000;
     }if (results.value == 0xE1724CB3) {
      reset();
      results.value = 0x00000000;
     }
     lcd.setCursor(0,0);
     delay(10);
    }

    void up() {
     if (angle < 180) {
      angle = angle + 18;
      spinnything.write(angle);
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("Current Angle");
      lcd.setCursor(3, 1);
      lcd.print("=");
      lcd.setCursor(5, 1);
      lcd.print(angle);
      Serial.print("up");
     }
    }
    void down() {
     if (angle > -180) {
      angle = angle - 18;
      spinnything.write(angle);
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("Current Angle");
      lcd.setCursor(3, 1);
      lcd.print("=");
      lcd.setCursor(5, 1);
      lcd.print(angle);
      Serial.print("down");
     }
    }
    int reset() {
     angle = 0;
     spinnything.write(angle);
     lcd.clear();
     lcd.setCursor(0, 0);
     lcd.print("Current Angle");
     lcd.setCursor(3, 1);
     lcd.print("=");
     lcd.setCursor(5, 1);
     lcd.print(angle);
     Serial.print("reset");

    }

title: Servo issue, won't go into negative range

Answers: 1

body:
First of all `Servo.write(int)` takes a value ranging from 0 to 180 degrees.
Then, servos themselves can only move from 0 to 180 usually. Some can do more, some can do less. But regardless of how much a servo actually moves, you should expect that doing `Servo.write(0)` the servo would rotate all the way to one side, doing `Servo.write(180)` it should go to the other side, doing `Servo.write(90)` it should stay in the middle.

Also, `lcd.setCursor(5, 1);` is basically useless as the lcd driver itself would advance the cursor as the previous characters are written. Just do `lcd.print("= ");` if you want an additional space between the equals symbol and the number


body: I have an ADXL345 accelerometer and I read it with an arduino through I2C. I want to get readings at a frequency higher than 500Hz. According to the documentation this should be easily achievable, however I've downloaded and used multiple libraries and none of them was able to achieve a sampling rate higher than 100Hz. They were all based on the arduino Wire library which doesn't seen very efficient. Could someone point me to a library or give me pieces of code that will allow me to sample data at 500+Hz? I send the data to matlab, not that it probably matters.

title: Fastest reading through i2c

Answers: 1

body:
If you want highest possible frequency, I'd use SPI instead.
With 16 MHz Arduino, SPI clock can be 4MHz.

The chip only supports I2C at 400 KHz clock, which is way slower.
<http://www.analog.com/media/en/technical-documentation/data-sheets/ADXL345.pdf>


body:
I have a joystick and am using the following code to show the output to the serial monitor:

    // Arduino pin numbers
    const int SW_pin = 2; // digital pin connected to switch output
    const int X_pin = 0; // analog pin connected to X output
    const int Y_pin = 1; // analog pin connected to Y output

    void setup() {
      pinMode(SW_pin, INPUT);
      digitalWrite(SW_pin, HIGH);
      Serial.begin(115200);
    }

    void loop() {
      Serial.print("Switch:  ");
      Serial.print(digitalRead(SW_pin));
      Serial.print("\n");
      Serial.print("X-axis: ");
      Serial.print(analogRead(X_pin));
      Serial.print("\n");
      Serial.print("Y-axis: ");
      Serial.println(analogRead(Y_pin));
      Serial.print("\n\n");
      delay(500);
    }`

Even when I am not moving the joystick, the X and Y axis outputs change continuously. Anywhere from around 50 to 600 (it seems.)

Every read has a new number.

What could be causing this?

I used the guide on [https://www.brainy-bits.com/arduino-joystick-tutorial/][1]

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

  [1]: https://www.brainy-bits.com/arduino-joystick-tutorial/
  [2]: https://i.stack.imgur.com/KOC02.png

title: Read from analog input "bounces" around

Answers: 0


body:
I am trying to use HC-05 (5V) with Arduino Pro Mini (3.3v) but I have had little success.

I am using a coin cell to power the pro mini which powers it on and is working fine.

But, my HC-05 doesn't power on. I am trying to power it externally using two 3.7v Lipo-batteries that gives a total of 7.4v but I have tried numerous changes and nothing seems to work.

Circuit Diagram attached below.
[![enter image description here][1]][1]

**Also, HC 05 has an onboard regulator for levelling it to 3.3v**
[![enter image description here][2]][2]

Please Help!!!

  [1]: https://i.stack.imgur.com/EWLjQ.jpg
  [2]: https://i.stack.imgur.com/MHqxz.jpg

title: Can't power HC-05(5v) with Arduino Pro mini (3.3v)?

Answers: 1

body:
It seems like 7.4V DC is greater than the 5V regulator input range on the HC-05.

For example, in the [Core Electronics tutorial][1] for the HC-05 (the tutorial PDF calls it a JY-MCU. I can't find any major differences), the pinout table says the voltage should be from 3.6V to 6V DC:

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

These same values are confirmed by a back-of-the-circuit-board photo from [arduino-info.wikispaces][3]:

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

[Components101][5] says the range is 4V to 6V.

Unfortunately your coin cell voltage is too low. That leaves you with the following options to drop your voltage (if you must use the 7.4V DC battery). Your choice will probably depend on the Wh capacity of your battery, and how efficient you need the voltage drop circuit to be.

 1. Zener diode (few components, inefficient use of power)
 2. Voltage divider with resistors (few components, inefficient use of power)
 3. Linear regulator (few (IC) or many (discrete) components, inefficient use of power)
 4. Switching regulator (many components, efficient use of power (because it does not use a resistor to drop the voltage)

Further details on each of these options are at [Lower Voltage Methods Other than Voltage Dividing][6].

  [1]: https://core-electronics.com.au/attachments/guides/Product-User-Guide-JY-MCU-Bluetooth-UART-R1-0.pdf
  [2]: https://i.stack.imgur.com/LHcly.png
  [3]: https://arduino-info.wikispaces.com/BlueTooth-HC05-HC06-Modules-How-To
  [4]: https://i.stack.imgur.com/Vkt8s.jpg
  [5]: https://components101.com/wireless/hc-05-bluetooth-module
  [6]: https://electronics.stackexchange.com/questions/154553/lower-voltage-methods-other-than-voltage-dividing


body:
I am learning Arduino and pardon me if this is nooby. I am trying to make an LED glow when the tilt switch is tilted. The LED should not glow if the tilt is in normal position. The circuit and the code are in the attached image.

Based on my understanding of the code, I thought that when the tilt switch pin 5 is passed with HIGH signal from 5V the IF condition gets satisfied and tje LED on pin 13 would glow.

But it does not happen. The LED just glows before I tilt the tilt switch. Could you please clarify/correct my mistake. Thank you.

[![Circuit][1]][1]

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

Attaching the code below as per suggestion

    int ledPin = 13;
    int switchPin = 5;

    void setup() {
      pinMode(ledPin,OUTPUT);
      pinMode(switchPin,INPUT);
    }

    void loop() {
      Serial.begin(9600);
      if (digitalRead(switchPin) == HIGH) {
        digitalWrite(ledPin,HIGH);
        Serial.print("we are here");
      }
      if (digitalRead(switchPin) == LOW) {
        digitalWrite(ledPin,LOW);
        Serial.print("there");
      }
    }

title: Understanding how a tilt switch works

Answers: 1

body:
Understanding how PULLUP works lead to the solution. Also learnt that switches are supposed to be connected to ground. Thank you all for your time. Especially chrisl.

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

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


body:
Can someone give me any idea what condition should i use in input 11 numbers only in the switch case? I only want to type and input 11 numbers only but The problem is it can type more than 11 numbers.

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

    LiquidCrystal_I2C lcd(0x3F,16,2);  // set the LCD address to 0x27 for a 16 chars and 2 line display

    const byte Rows= 4; //number of rows on the keypad i.e. 4
    const byte Cols= 3; //number of columns on the keypad i,e, 3

    //we will definne the key map as on the key pad:

    char keymap[Rows][Cols]=
    {
    {'1', '2', '3'},
    {'4', '5', '6'},
    {'7', '8', '9'},
    {'*', '0', '#'}
    };

    //  a char array is defined as it can be seen on the above

    //keypad connections to the arduino terminals is given as:

    byte rPins[Rows]= {1,2,3,4}; //Rows 0 to 3
    byte cPins[Cols]= {5,6,7}; //Columns 0 to 2

    // command for library forkeypad
    //initializes an instance of the Keypad class
    Keypad kpd= Keypad(makeKeymap(keymap), rPins, cPins, Rows, Cols);

    char entryStr[8];
    int i=0;
    long number1=0;
    long number2=0;

    void setup()
    {
       Wire.begin();
       lcd.init();
       lcd.backlight();
       Serial.begin(9600);
       delay(100);

    }

title: Keypad Type 11 numbers only?

Answers: 1

body:
Three simple approaches.

 1. You could get a string, and limit it to 11 characters in length. You then convert the string to `num`
 2. You could check that 9999999999<`num`<=99999999999
 3. You could count the number of valid 'kpd.getKey()' and when it gets to 11 exit the function (returning `num` as it stands)

The OP suggests only 11 digits. Of course, if less that 11 digits are acceptable, the returning value could be padded with `0`.

`lcd.print1 can natively takes a string, and the best approach is to treat `num` as a string instead of as a number. A number (in itself) is only useful if you want to do arithmetic. A lot of times a series of digits are used as an identifier - these are not really numbers but strings with a limited character set.

Some examples (not tested):

**Example 1:** counting the digits entered. Simply added a counter `numcount` - you can see where I use it in the conditional loop, where I increment it, and where I clear it.

    long GetNumber()
    {

      long num = 0;
      long numcount = 0;
      char key = kpd.getKey();
      while(key != '#' && numcount <= 11)
      {
        switch (key)
        {
        case NO_KEY:
          break;
        case '0':
    [... skipped for brevity ...]
        case '9':
          lcd.print(key);
          num = num * 10 ;
          num= num+ (key-'0');
          numcount += 1;
          break;
      case '*':
        num = 0;
        numcount = 0;
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("Re-type number:");
        lcd.setCursor(0,1);
        break;
      }
      key = kpd.getKey();
    }
    return num;
    }

**Example 2:** Simple check on the value of `num`. In this case both the "#" and `num` reaching a certain value will exit the function in a controlled way. A better loop method would be to `loop ... until` - checking the condition at the end of the loop rather than at the beginning.

    long GetNumber()
    {
      long num = 0;
      char key = kpd.getKey();
      while(key != '#' && num <= 99999999999)
      {
        switch (key)
        {
        case NO_KEY:
          break;
        case '0':
        [... skipped for brevity ...]
        case '9':
          lcd.print(key);
          num = num * 10 ;
          num= num+ (key-'0');
          break;
        case '*':
          num = 0;
          lcd.clear();
          lcd.setCursor(0,0);
          lcd.print("Re-type number:");
          lcd.setCursor(0,1);
          break;
        }
        key = kpd.getKey();
          }
      return num;
    }

**Example 3:** using a string. Same comment about checking conditions at the end of the loop instead of the beginning apply. I haven't worked with strings in C for a few decades, so the routines I used (`strlen`, `strcat`) may need some work or tweaking.

    string GetNumber()
    {
      string num = "";
      char key = kpd.getKey();
      while(key != '#' && strlen(num) <= 11)
      {
        switch (key)
        {
        case NO_KEY:
          break;
        case '0':
        [... skipped for brevity ...]
        case '9':
          lcd.print(key);
          num = strcat(num,key)num * 10 ;
          break;
        case '*':
          num = "";
          lcd.clear();
          lcd.setCursor(0,0);
          lcd.print("Re-type number:");
          lcd.setCursor(0,1);
          break;
        }
        key = kpd.getKey();
        }
      return num;
    }


body:
I'm creating a binary calculator with my Arduino. This will take two different binary numbers and add them together. I am focusing right now on the Byte One Input screen. For this, I can use two buttons, the left to change to selected bit to either 0 or 1 when pressed, and the right button to move to the next bit, or when at the end, to move to the next screen. I am having difficulty with the debouncing of the buttons.

Right now, the debouncing is not working and the position changes from 1 to 8 or 16 instead of to the second bit when I hit the right button.

Any help would be great!

**Fixed Code: See accepted answer below.**

           #include <LiquidCrystal.h>
    /*(RS, E, D4, D5, D6, D7)*/
    LiquidCrystal lcd(12,11,5,4,3,2);
    #include <Button.h>

    int page = 0;
    int binary[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
    int con = 80;
    char btn_push;
    int pos = 0;

    const int button1Pin = 8;
    const int button2Pin = 9;
    int button1State = HIGH;
    int button2State = HIGH;
    int lastButton1State = HIGH;
    int lastButton2State = HIGH;

    unsigned long debounceDelay = 50;

    //****************************************************************setup*****************************************
    void setup() {
      pinMode(button1Pin, INPUT_PULLUP);
      pinMode(button2Pin, INPUT_PULLUP);

      Serial.begin(9600);
      analogWrite(6,con);
      mylcd.begin();
      lcd.print("Welcome");
    }

    //************************************************************loop************************************************

    void loop() {

      int reading1 = digitalRead(button1Pin);
      int reading2 = digitalRead(button2Pin);

      if (reading1 == lastButton1State &&
          reading2 == lastButton2State)
        return;  // do nothing if no change

      delay (debounceDelay);  // debounce

      // re-read so we can catch both buttons down at once
      reading1 = digitalRead(button1Pin);
      reading2 = digitalRead(button2Pin);

      // save for next time
      lastButton1State = reading1;
      lastButton2State = reading2;

      if (reading1 == LOW && reading2 == HIGH)     // first one down
        btn_push = 'D';
      else if (reading1 == HIGH && reading2 == LOW)  // second one down
        btn_push = 'U';
      else if (reading1 == LOW && reading2 == LOW)  // both
        btn_push = 'S';
      else
        return;  // nothing interesting

     Serial.print("btn_push = ");
     Serial.println(btn_push);

        // page select
        switch (page) {

        case 0:
          page0();
          break;
        case 1:
          page1();
          break;
        case 2:
          page2();
          break;
        case 3:
          page3();
          break;
        case 4:
          page4();
          break;
        }

    }

    // The rest is the same, excluding the functions that are no longer needed

title: Debouncing Multiple Buttons

Answers: 3

body: The button stays down long enough for you to cycle through more than once, first setting binary[i] to 1 then to 0, etc. you need to add some logic to say “this is the first time I’ve seen this button state”

body:
Your first problem is here:

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

    char ReadKeypad(){
      if(button1.isPressed() && !button2.isPressed()){
        return 'D';
      }
      else if(button2.isPressed() && !button1.isPressed()){
        return 'U';
      }
      else if (!button1.isPressed() && !button2.isPressed()){
        return 'N';
      }
      else if (button1.isPressed() && button2.isPressed()){
        return 'S';
      }
    }

The compiler gives a warning, which you should pay attention to:

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

    In function 'char ReadKeypad()':
    warning: control reaches end of non-void function [-Wreturn-type]
     }
     ^

The warning basically is that if no button is pressed you are returning an undefined value. It would be better to add to the end:

    return 0;  // no button pressed

---

Then later on in `page1` function:

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

      for (int i; i<16; i++){
        lcd.print(binary[i]);
      }

Another compiler warning:

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

    In function 'void page1()':
    warning: 'i' may be used uninitialized in this function [-Wmaybe-uninitialized]
           for (int i; i<16; i++){

You haven't initialized `i` so it could have any value. That should read:

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

      for (int i = 0; i<16; i++){
        lcd.print(binary[i]);
      }

Ditto further down.

---

If I add some debugging here:

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

    void MainmenuBtn(){
      btn_push = ReadKeypad();
      Serial.print ("btn_push = ");
      Serial.println (btn_push);
     // WaitBtnRelease();
    }

And then press a button, I see:

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

    btn_push = D
    btn_push = D
    btn_push = D
    btn_push = D
    btn_push = D
    btn_push = D
    btn_push = D
    btn_push = D
    btn_push = D
    btn_push = D
    btn_push = D
    btn_push = D

So that is registering as **many** presses, not just one. You should test for "has the button state changed?". That is:

* Is the button closed now?
* Was it closed before?
* If the two are different, then the button has just been pressed.

---

Adding debugging prints is **very helpful** in general when things aren't going to plan.

If you had added those extra prints to your MainmenuBtn function you would immediately have seen that it looked like the button was pressed hundreds of times (until you let go) rather than once.

>  the position changes from 1 to 8 or 16 instead of to the second bit when I hit the right button

Exactly. Since it is treating a button press as a multiple press you would expect exactly that to happen. Effectively you have built in a very fast auto-repeat (unintentionally).

---

### Edited to add:

Your code is so confusing I've rewritten the state change stuff.

    #include <LiquidCrystal.h>
    /*(RS, E, D4, D5, D6, D7)*/
    LiquidCrystal lcd(12,11,5,4,3,2);
    #include <Button.h>

    int page = 0;
    int binary[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
    int con = 80;
    char btn_push;
    int pos = 0;

    const int button1Pin = 8;
    const int button2Pin = 9;
    int button1State = HIGH;
    int button2State = HIGH;
    int lastButton1State = HIGH;
    int lastButton2State = HIGH;

    unsigned long debounceDelay = 50;

    //****************************************************************setup*****************************************
    void setup() {
      pinMode(button1Pin, INPUT_PULLUP);
      pinMode(button2Pin, INPUT_PULLUP);

      Serial.begin(9600);
      analogWrite(6,con);
      mylcd.begin();
      lcd.print("Welcome");
    }

    //************************************************************loop************************************************

    void loop() {

      int reading1 = digitalRead(button1Pin);
      int reading2 = digitalRead(button2Pin);

      if (reading1 == lastButton1State &&
          reading2 == lastButton2State)
        return;  // do nothing if no change

      delay (debounceDelay);  // debounce

      // re-read so we can catch both buttons down at once
      reading1 = digitalRead(button1Pin);
      reading2 = digitalRead(button2Pin);

      // save for next time
      lastButton1State = reading1;
      lastButton2State = reading2;

      if (reading1 == LOW && reading2 == HIGH)     // first one down
        btn_push = 'D';
      else if (reading1 == HIGH && reading2 == LOW)  // second one down
        btn_push = 'U';
      else if (reading1 == LOW && reading2 == LOW)  // both
        btn_push = 'S';
      else
        return;  // nothing interesting

     Serial.print("btn_push = ");
     Serial.println(btn_push);

        // page select
        switch (page) {

        case 0:
          page0();
          break;
        case 1:
          page1();
          break;
        case 2:
          page2();
          break;
        case 3:
          page3();
          break;
        case 4:
          page4();
          break;
        }

    }

    // The rest is the same, excluding the functions that are no longer needed

I made the buttons INPUT_PULLUP so that they normally read HIGH if not pressed, thus LOW means pressed (therefore the switches should be wired from the digital pin on one side to Gnd on the other side).

It still isn't perfect but that should give you something to play with. Add some more debugging prints to see what is going on in the other functions.

body:
As an alternative to using two inputs, consider using a single analogue input with several momentary buttons - each with differing resistor values in series - this will let you avoid debouncing altogether. Just 5/3V3->resistor->btn->analogInput.

At worst, you will need to smoothe out jitter on analog reads. Have a look at https://www.codeproject.com/Tips/709109/ADKeyboard-Library-for-Arduino


body:
I wold like to make me a REST API with string values and more string Keys.

like: ~http://url.tld/foo/bar/xy to get "bar" and do more...

Can somebody tell me how to get the second word out of the URL? In this case "bar".

The tutorial show's how to use /arduino/digital/13/1 as to set pin 13 High.I would like to get a different syntax.
Something like this: arduino/device1/switch/on

By now i searched quite long and tested different things as you can see below, but i can't get more than one word caught to trigger from the client object.

is boils down to the question why my client object changes the payload.

this part:

    void process(BridgeClient client) {
      String url0 = client.readString();
      Console.print("process url0: ");      // --> is "bar/xy"
      Console.println(url0);
      String command = client.readStringUntil('/');
      String url1 = client.readString();
      Console.print("process url1: ");
      Console.println(url1);               // --> is "" aka:empty!

i made a MWE to show what i already did:

    // Libraries:
    #include <Bridge.h>
    #include <BridgeServer.h>
    #include <BridgeClient.h>
    #include <Console.h>

    // Constants:
    const bool on = HIGH;
    const bool off = LOW;

    // Objects:
    BridgeServer server;

    void setup() {
      pinMode(6, INPUT_PULLUP);
      Bridge.begin();
      server.begin();
      Console.begin();
      while (!Console);
      Console.println("setup done..");
    }

    void loop() {
      BridgeClient client = server.accept();
      if (client) {
        process(client);
        client.stop();
      }
    }

    void process(BridgeClient client) {
        String url0 = client.readString();
        Console.print("process url0: ");   // --> is "bar/xy"
        Console.println(url0);
        String command = client.readStringUntil('/');
        String url1 = client.readString();
        Console.print("process url1: ");
        Console.println(url1);             // --> is "" aka:empty!
      if (command == "device1") {
        device1(client);
      }
      if (command == "status") {
        Console.print("process: command == status  | command: ");
        Console.println(command);
        statusCommand(client);
      }
    }

    void device1(BridgeClient client) {
      String URL = client.readString();
      Console.println("URL:");
      Console.println(URL);                               // ---> is "on"
      String mode = client.readStringUntil('\r');
      Console.println("mode:");
      Console.println(mode);                            // ---> is ""
      String value = getStringPartByNr(URL, '/', 1);
      Console.println("value:");
      Console.println(value);                            // ---> is ""
      power(on);
      if ( URL == "on"){
        client.print(F("found /on"));
        power(on);
      }
      else if ( URL == "off"){
        client.print(F("found /off"));
        power(off);
      }
    }

    void power(bool on_off){
      bool checkpin = digitalRead(6);                          // machine state
      if (checkpin == LOW && on_off == HIGH) {        // means power is off and on is called
        digitalWrite(13, HIGH);
        Console.print(" checkpin == LOW && on_off == HIGH [1] ");
      }
      else if (checkpin == HIGH && on_off == LOW) { // means power is on and off is called
        digitalWrite(13, LOW);
        Console.print(" checkpin == HIGH && on_off == LOW [2] ");
      }
    }

    void statusCommand(BridgeClient client) {
    }

    // splitting a string and return the part nr index split by separator
    String getStringPartByNr(String data, char separator, int index) {
        int stringData = 0;        //variable to count data part nr
        String dataPart = "";      //variable to hold the return text
        for(int i = 0; i<data.length()-1; i++) { //Walk through the text one letter at a time
            if(data[i]==separator) { //Count the number of times separator character appears
                stringData++;
            } else if(stringData==index) { //get the text when separator is the rignt one
                dataPart.concat(data[i]);
            } else if(stringData>index) { //return text and stop if the next separator appears
                return dataPart;
                break; // - to save CPU-time
            }
        }
        return dataPart; //return text if this is the last part
    }

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

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

title: BridgeServer REST API with more string values

Answers: 1

body:
You misunderstand the [networking Client class][1] concept. It is a [stream][2] like the Serial object. Bytes are stored in the Client object's buffer only until you read them.

  [1]: https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/Client.h
  [2]: https://www.arduino.cc/reference/en/language/functions/communication/stream/


body:
I am using a HC-06 and i want to read a number ending with f as a delimiter, the first three numbers as my servo position, however converting the string into int is giving an endless series of 0s. I added the Serial.print(servopos) to see that its a never ending series of 0s, and nothing seems to fix this problem. What am I doing wrong? (I tried using long for servopos instead of int, it didn't fix the issue)

    #include <SoftwareSerial.h>
    #include <Servo.h>

    Servo myservo; // servo name

    int bluetoothTx = 10;
    int bluetoothRx = 11;
    int fwd = 12;
    int bwd = 13;

    SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);
    String content = "";
    char character;

    void setup()
    {
      myservo.attach(9); // attach servo signal wire to pin 9
      //Setup usb serial connection to computer
      Serial.begin(9600);

      //Setup Bluetooth serial connection to android
      bluetooth.begin(9600);

      pinMode(fwd, OUTPUT);
      pinMode(bwd, OUTPUT);

    }

    void loop()
      {
      if(bluetooth.available()> 0 ) // receive number from bluetooth

        character = bluetooth.read();

        if (character!='f'){
            content += (char) character;
            delay(10);
          }

        else{
          int servopos = content.substring(0,3).toInt();
          Serial.print(servopos);
         // myservo.write(servopos);

          String directMvt = content.substring(3);
          if (directMvt == "00"){
                digitalWrite(fwd, LOW);
                digitalWrite(bwd, LOW);
          }
          else if (directMvt == "10"){
                digitalWrite(fwd, HIGH);
                digitalWrite(bwd, LOW);
          }
          else if (directMvt == "01"){
                digitalWrite(fwd, LOW);
                digitalWrite(bwd, HIGH);
          }
          else if (directMvt == "11"){
                digitalWrite(fwd, LOW);
                digitalWrite(bwd, LOW);
          }
          content = "";
      }
    }

title: Unable to convert string read from bluetooth to int

Answers: 1

body:
I've found your problem: You have a missing pair of `{ }`, that should enclose the `if(bluetooth.available()>0)` statement. Without the parenthesis it only encloses the following statement, which is the serial reading.

Now follow the logic: Before you are sending something over serial, the global variable `character` should be zero. So then, since the NULL character is not equal to `f`, the NULL characters are added to the string. Then you send a string like `18000f` via bluetooth serial. The code is adding the characters to the string variable, until it find the `f` character. Now it goes directly in the `else`-statement, printing the value of `servopos` and then resetting the string variable. On the next loop iteration, there isn't something available at the SoftwareSerial, so it goes to the `if(character !='f')` statement. The `character` variable is global and it is still filled with the `f` value, that it got in the last loop iteration. So the `else` statement is executed forever very fast. But since you reseted the content of the string variable in the last iteration, there is nothing to convert to integer here. So this gives you a forever lasting series of zeros.

Enclosing the code in the first `if` statement solves your problem, since then, it only does something, when data is available at the serial interface. Also you should consider using a local variable for `character`, since you only need it there and your problem would have been obvious (through a compiler error), if you used a local variable here. Using global variables, when there is no need to, can make things more complex and error-prone.


body:
**EDIT**: I have created an issue about this here: https://github.com/esp8266/Arduino/issues/4593

---------------

**I have this server:** `185.205.210.197`
(Check that it works: http://185.205.210.197/)

**And I have this code in my ESP8266:**

    #include <ESP8266WiFi.h>

    #define HOST "185.205.210.197"
    #define PORT 80
    #define WIFI_SSID "SSID"
    #define WIFI_PSW "PASSWORD"

    const char* ssid = WIFI_SSID;
    const char* password = WIFI_PSW;

    void setup () {
      Serial.begin(115200);
      WiFi.begin(ssid, password);

      while (WiFi.status() != WL_CONNECTED) {
        delay(5000);
        Serial.println("Connecting to Wifi...");
      }

      while(!pingServer()) {
        delay(3000); //Send a request every 3 seconds
      }
    }

    void loop() {}

    bool pingServer() {
      WiFiClient client;

      if (!client.connect(HOST, PORT)) {
        Serial.println("connection failed");
        return false;
      }

      Serial.println("connection success!");
      return true;
    }

**The expected result:** Connection success, but got connection failed.

If I try connecting with my PC, it works, **only with ESP8266 it doesn't**.

Tapping with Wireshark I suspect that there is a problem with ESP8266 TCP packets, here I leave them for you to analyze:

**PC TCP connection request (which works):**

`000030006b081c001a48ea4c0000000010009e098004dba400000000800401009e090b221f000000c603000004000000880254009801a7ad45b7000af5f4e90c000af5f4e90c603c0000aaaa0300000008004500003c000040003706cb37b9cdd2c5c0a82b490050df312dfea1498c6ac92aa0120000079c00000204058c0402080a336f35554aeb0fe90103030700ead7d1`

**ESP8266 TCP connection request (which receives no response from server):**

`000019006f080000952a9f520000000012049e098004daa1000801a200000af5f4e90c2c3ae80f137f000af5f4e90c5000aaaa0300000008004500002c00030000ff06431dc0a82b70b9cdd2c5c00100500000196d000000006002086040f80000020402189ccdd933`

**What I've also checked:**

* The ESP connects fine to other servers.

* There is no firewall blocking the connection between ESP and the server.

* I've tried this in different networks and conditions, the error persists.

* Other computers can connect to the server, so ESP should be able as well.

* Tried with different ESP8266 boards to rule out hardware malfunctioning.

* I am using NODEMCU V0.9 board (original firmware) with Arduino IDE and [this ESP8266 library][1].

**How to replicate:**

0. Using the latest Arduino IDE and ESP8266 library.

1. Check that the test server works at http://185.205.210.197:80/ (just open this link basically and see that is running nginx).

2. Copy and upload the code above to your ESP8266 (NODEMCU or similar).

3. Open the Arduino IDE console/monitor and confirm that no connection is established to port 80.

4. Rage in admiration for such a strange bug.

**I've opened an Issue for this:** https://github.com/esp8266/Arduino/issues/4593

  [1]: https://github.com/esp8266/Arduino

title: ESP8266 cannot create TCP connections to this particular server

Answers: 1

body:
Not a cookie cutter answer, I did a quick test and my ESP8266 does connect to you nginx. Of course you do not accept the params from my fridge, but this is what I see in the log.

    7007 :
    7010 :

    For online documentation and support please refer to
    7012 : nginx.org.

    7015 : Commercial support is available at
    7018 : nginx.com.

    7020 :
    7022 :

    Thank you for using nginx.

    7024 :
    7026 :
    7028 : HTTP : closing connection

You should be able to see that on your side as well.

I am using letscontrolit/ESPEASY  https://github.com/letscontrolit/ESPEasy

And their code to connect looks like

      // Use WiFiClient class to create TCP connections
      WiFiClient client;
      if (!ControllerSettings.connectToHost(client))
      {
        connectionFailures++;
        addLog(LOG_LEVEL_ERROR, F("HTTP : connection failed"));
        return false;
    }

      boolean connectToHost(WiFiClient &client) {
        if (!checkHostReachable(true)) {
          return false; // Host not reachable
        }
        byte retry = 2;
        bool connected = false;
        while (retry > 0 && !connected) {
          --retry;
          connected = client.connect(getIP(), Port);
          if (connected) return true;
          if (!checkHostReachable(false))
            return false;
        }
        return false;
    }

I am using generic HTTP for my controller which here: https://github.com/letscontrolit/ESPEasy/blob/503fd3555e010b08b48fb2dc18290ef120005308/src/_C008.ino

You could try the connect to function to see if that works for you.


body:
This is, hopefully, a simple issue!

I'm trying to access my fully working libraries (fully compiles, and works with the hardware perfectly) from another library (Computer.h) to abstract it away from the Sketch.ino file.

LLRelay, and all my other libraries, work flawlessly when instanced/constructed/built/etc within the main Sketch.ino; however, when called within "Computer.h", there's issues.

I've been at this for most of the day trying different things, from instantiating the libraries in the header files, the *.cpp files, to within functions, to changing the scope and publicity/privacy of them - still no luck.  See the (2 * "HERE -") comments for the errors.

Any help is greatly appreciated!

This is what I have managed to reduce it down to for debugging:

Sketch.ino

    // Sketch.ino
    #include "Computer.h"

    Computer pc1;

    void setup(){};

    void loop(){
        pc1.update();
    };

Computer.h

    // "../customLibs/Computer.h"
    #ifndef Computer_lib
    #define Computer_lib
    #if(ARDUINO > 100)
        #include "Arduino.h"
    #else
        #include "WProgram.h"
    #endif

    class Computer {
     public:
      Computer();
      void update();
     private:
      void fans();
    };
    #endif

Computer.cpp

    // "../customLibs/Computer.cpp"
    #include "Computer.h"
    #include "src/relay/LLRelay.h" /* Potential culprit, I have tried many variations and locations for this to go, all with the same, or similar compilation errors */

    /* HERE - "undefined reference to `LLRelay::LLRelay(unsigned char)'" */
    LLRelay fan1(13); // fan1(uint8_t relayPin);

    Computer::Computer(){
     Serial.begin(9600);
    };

    void Computer::update(){
        fans();
    };

    void Computer::fans(){

     /* HERE - "undefined reference to `LLRelay::On()'" */
     fan1.On();

    };

LLRelay.h

    // "../customLibs/src/relay/LLRelay.h"
    #ifndef LLRelay_lib
    #define LLRelay_lib
    #if(ARDUINO > 100)
      #include "Arduino.h"
    #else
        #include "WProgram.h"
    #endif

    class LLRelay {
      public:
        LLRelay(uint8_t relayPin);
        void On();
        void Off();
      private:
        uint8_t _relayPin;
    };
    #endif

LLRelay.cpp

    // "../customLibs/src/relay/LLRelay.cpp"
    #include "LLRelay.h"

    LLRelay::LLRelay(uint8_t relayPin){
      _relayPin = relayPin;
      pinMode(_relayPin, OUTPUT);
      digitalWrite(_relayPin, LOW);
    };

    void LLRelay::On(){
      digitalWrite(_relayPin, HIGH);
    };

    void LLRelay::Off(){
      digitalWrite(_relayPin, LOW);
    };

title: Libraries/classes using other libraries/classes

Answers: 2

body: The Arduino build process does not consider libraries used from other libraries. You will need to include `src/relay/LLRelay.h` in the main project file in order to make it compile.

body:
The Arduino IDE must detect the library to include it in the build process. It is done by matching a library to a header file by searching the libraries in configured library locations. Only the root folder and the `src` subfolder of a library are searched.

If your library is in the sketch folder's `libraries` subfolder and it is called `customLibs`, then only the `customLibs` folder and the `customLibs/src` subfolder are searched and the include file `LLRelay.h` in `customLibs/src/relay` folder is not found.

reference: [Layout of library folders and files][1]

  [1]: https://github.com/arduino/arduino/wiki/arduino-ide-1.5:-library-specification#layout-of-folders-and-files


body:
I am using an Arduino Uno and HX711 amplifier to collect data from a load cell. I previously had the load cell calibrated and functioning, but now the load cell will not read any values; only 0's are outputted, even when I apply a small load to the sensor. I have re-soldered and replaced the connecting wires. Are there any suggesting for getting a readout from my sensor?

I have been testing with 2 different load cells: Sparkfun's TAL220 Straight Bar 10kg load cell and an LFS 210-300 from Cooper Instruments (the latter is the one I want to use long term). My load cell is connected like the HX711 Breakout Guide (with an Arduino Uno instead of a RedBoard and a USB connection):

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

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

I have been using the HX711 Breakout Guide Calibration sketch to test my load cell:

    #include <HX711.h>

    #define DOUT 3
    #define CLK 2

    HX711 scale(DOUT, CLK);

    float calibration_factor = 282650; //-7050 worked for my 440lb max scale setup

    void setup() {
      Serial.begin(9600);
      Serial.println("HX711 calibration sketch");
      Serial.println("Remove all weight from scale");
      Serial.println("After readings begin, place known weight on scale");
      Serial.println("Press + or a to increase calibration factor");
      Serial.println("Press - or z to decrease calibration factor");

      scale.set_scale();
      scale.tare(); //Reset the scale to 0

      long zero_factor = scale.read_average(); //Get a baseline reading
      Serial.print("Zero factor: "); //This can be used to remove the need to tare the scale. Useful in permanent scale projects.
      Serial.println(zero_factor);
    }

    void loop() {

      scale.set_scale(calibration_factor); //Adjust to this calibration factor

      Serial.print("Reading: ");
      Serial.print(scale.get_units(), 1);
      Serial.print(" kgs"); //Change this to kg and re-adjust the calibration factor if you follow SI units like a sane person
      Serial.print(" calibration_factor: ");
      Serial.print(calibration_factor);
      Serial.println();

      if(Serial.available())
      {
        char temp = Serial.read();
        if(temp == '+' || temp == 'a')
          calibration_factor += 10;
        else if(temp == '-' || temp == 'z')
          calibration_factor -= 10;
      }
    }

I am still new to Arduino and data acquisition in general, so any suggestions would be appreciated!

title: Load Cell and HX711 only outputting 0's

Answers: 1

body:
This line is where you are reading the data and printing it:

    Serial.print(scale.get_units(), 1);

The 1 on the end of the line defines how many digits you are displaying from your reading. I have a similar setup to yours and I have it set to 5 which shows up to +/-0.00001kg. (Obviously, the accuracy will be different depending on which load cell you have)


body:
I have this [SD-card module][1]. I have formatted the SD with [this tool][2]. My problem is that the **Arduino Uno** can't initialize the SD. I tried with this script:

    // include the SD library:
    #include <SPI.h>
    #include <SD.h>

    // set up variables using the SD utility library functions:
    Sd2Card card;
    SdVolume volume;
    SdFile root;

    const int chipSelect = 7;

    void setup() {
      // Open serial communications and wait for port to open:
      Serial.begin(9600);
    }

    void loop(void) {
      if (!card.init(SPI_HALF_SPEED, chipSelect)) {
        Serial.println("Doesn't work properly");
      } else{
        Serial.println("works properly");
      }
      delay(2000);
    }

And the result:

    Doesn't work properly
    Doesn't work properly
    Doesn't work properly
    Doesn't work properly
    Doesn't work properly
    Doesn't work properly
    Doesn't work properly
    Doesn't work properly
    Doesn't work properly
    Doesn't work properly
    works properly
    works properly
    works properly
    works properly
    works properly
    works properly
    Doesn't work properly
    Doesn't work properly
    Doesn't work properly
    works properly
    works properly
    works properly
    Doesn't work properly

The "works properly" happens, usually, when I move the module slightly. Is there a way to repair the module?

OS: Windows 10

  [1]: https://www.miniinthebox.com/it/p/sd-card-module_p407346.html?currency=EUR&litb_from=paid_adwords_shopping&country_code=it&utm_source=google_shopping&utm_medium=cpc&adword_mt=&adword_ct=202539328488&adword_kw=&adword_pos=1o3&adword_pl=&adword_net=g&adword_tar=&adw_src_id=50918876091_866086207_44403958060_pla-331029837337&gclid=Cj0KCQjw4_zVBRDVARIsAFNI9eB_Yz3q4c_ig1ezRy2QsX2l2pTvPGu9WDVuPkofQqx7XJpWJ0KTC54aAnSGEALw_wcB
  [2]: https://www.sdcard.org/downloads/formatter_4/

title: SD card doesn't work properly

Answers: 0


body:
I mada a  4wd car with ultrasonic sensors and servo. I use 4 AA 1.5 volt batteries for power. But the motor does not move. What is the problem?

![image](https://i.stack.imgur.com/pSJ3M.jpg)

![Schematic](https://i.stack.imgur.com/rTbik.jpg)

title: Motor does not move with 4 batteries

Answers: 2

body:
In the future, please detail your attempts at solving the problem so far so we can help you better.

Approach the issue as methodically as possible. I don't know how familiar you are with electronics, so please excuse me if you think some of these questions are basic:

 1. Ensure that the servo motor works first without any other motors or
    sensors connected to the Arduino Sensor Shield (have you used this servo motor before?)
 2. Ensure that your GVS wiring is in the correct order. Servos come with a 3 way socket that plug straight onto the Sensor Shield: G goes to the Brown or Black wire, V goes to the (middle) Red wire, S goes to the Orange wire. The good news is as the +5V is in the middle, things will not blow up if you put the 3-pin plug on the wrong way. The servo just will not work until you plug it in correctly.
 3. Is the Arduino Sensor shield working correctly. Does the LED pin work? Do other signals sent from the board work?
 3. Remember that servo motors work differently to normal DC motors. You need to use [Pulse Width Modulation][1] to set the position. If you have never done this before, you will find the [Arduino Servo Motors][2] page useful. Also, you will get some excellent understanding and code from this [Adafruit page][3]. It is for a different Arduino shield, but the principles are the same.

  [1]: https://en.wikipedia.org/wiki/Pulse-width_modulation
  [2]: https://www.arduino.cc/en/Reference/Servo
  [3]: https://learn.adafruit.com/adafruit-motor-shield-v2-for-arduino

body: Use a LiPo battery I.e 2S(7.4V)


body:
I've a SparkFun Pro Micro which is an Arduino Leonardo clone. Unfortunately my attempts to upload programs failed. I did some research in the internet and found you have to use SparkFun's configuration. There is a board manager's URL you have to use: https://raw.githubusercontent.com/sparkfun/Arduino_Boards/master/IDE_Board_Manager/package_sparkfun_index.json

So far so good. After trying to use this I attempted to do an upload and failed. I tried it with different settings but all failed. While earlier there was a serial port named `/dev/ttyACM0` there now is no such port any more. Further research gave me the information that you might get the device running if you a) reset to boot loader mode where you should have an 8 seconds window to upload and b) actually perform the upload.

I can verify: If I pull RESET to ground I can switch into this 8 seconds mode. Then the device `/dev/ttyACM0` appears after about 1 second for about 7 seconds. As instructed I immediately try to do an upload. This is strange: I immediately (!) get the following output:

* Line 1: `Sketch uses 4140 bytes (14%) of program storage space. Maximum is 28672 bytes.`
* Line 2: `Global variables use 149 bytes (5%) of dynamic memory, leaving 2411 bytes for local variables. Maximum is 2560 bytes.`
* Line 3: `avrdude: ser_open(): can't open device "/dev/ttyACM0": No such file or directory`
* Line 4: `Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.`

The TTY should be there as the 7 seconds have not been passed in that case. Furthermore my user account is in `dialout` which enables it to use the tty.

If I trust this error message that means the tty is gone as soon as `avrdude` tries to access it. Which shouldn't be that way, should it?

Has anyone encountered this situation before? How can I upload a program to the mikrocontroller? Has anyone has any experience with that situation here?

--

Additional information:

* ArdunoIDE 1.8.5
* Ubuntu (Mate) Linux 16.04

title: Problem uploading to ATMega using ArduinoIDE ("unbricking" "bricked" microcontroller?)

Answers: 1

body:
We use these a lot, and it's very easy to accidentally program the boards with the incorrect settings - particularly as the Sparkfun Pro Micro library defaults to the 3.3V/8 MHz variant instead of the more common 5V/16MHz.

I have recovered the boards with the bootloader reset method, but it is hard - you have to get the timing just right. What we do now is to simply reinstall the bootloader using an ISP programmer (instructions: https://learn.sparkfun.com/tutorials/installing-an-arduino-bootloader). It works first time, and ends up being much quicker than repeated tries to get the reset timing right. Just make sure that you have the right board selected when you burn the bootloader. We use a USBASP, and it only takes a couple of minutes to set up.


body:
I have a SIM800L module (green board). I used [this][1] to test my module.

In that page, it use a SIM800L red board with a 3.7v LiPo battery. But I directly connected 5v from the Uno to the module.

 *            GND      >>>   GND
 *        RX  10       >>>   TX
 *        TX  11       >>>   RX
 *            5v       >>>   Vin

I see "Message Sent Successfully!" message in COM window but nothing happened.

I can not find the problem.

The SIM800L module (green board) specification [is here][2].

The SIM800L module (red-green-blue boards) [is here][3].

  [1]: https://exploreembedded.com/wiki/GSM_SIM800L_Sheild_with_Arduino
  [2]: http://thecaferobot.com/store/sim800l-gprs-gsm-sms-microsim-module-5v
  [3]: http://thecaferobot.com/store/catalogsearch/result/?q=SIM800L

title: SIM800L can't send SMS

Answers: 1

body:
I used a [Power Supply][1] and tested the board and SIM800L with it.

At the beginning, the SIM800L only uses a max of 100mA (V = 5v) and after finding the network only 10mA. In this situation the message is sent. I tested it with 4.2v but no message was sent.

It seems it needs 5v to be applied. The 5v of the Uno will be reduced to reach the SIM800L and so no message is sent.

  [1]: https://en.wikipedia.org/wiki/Power_supply


body: I'm trying to control a stepper motor for my FYP with an Arduino Mega. I tried code form examples, stepper one revolution. It worked when I uploaded it but if i turn the power off during the half position of a revolution, then next time I turn on the supply it first moves that portion backwards then it works according to the program. I want that when I turn on the power supply it should move according to the code and forget the last movement. Can anybody help me on this issue?

title: Arduino with stepper motor

Answers: 1

body: A stepper motor doesn't have any mechanical "steps" as such. When powered off, a stepper is free-wheeling. When you power it up - energize a set of set of coils - the rotor will move to the nearest of several positions corresponding to whichever coils are energized. Thus, it doesn't retain its position across a power-down; your code has to "find it" each time. Usually that involves driving it until the attached mechanism trips an optical or mechanical switch, giving the software a reference-point. Your other option is to apply a holding current (less than the stepping current) to the presently energized coils and not completely power down the motor's power supply when the rest of the system powers down. The software would have to save the motor position before the power down in a non-volatile memory, such as EEPROM, where it can retrieve it again at the next power-up.


body:
I am using an MG946R Servo.

When I use the power directly from the Arduino (Uno) and do a sweep, it works as expected.

However, when I replace the Arduino power with external power, the Servo either doesn't move or it moves randomly.

I've tried this with both a multi voltage power adaptor, setting the power to both 4.5V and 6V, as well as with a 4 x AA battery pack.

When I use a multi meter set at 6V and check the pins going into the Servo (when it's moving randomly) the voltage keeps moving to anywhere between  5.20V and 5.70V.

It seems that the Servo doesn't move when using battery pack, even though the voltage on the pins reads 5.75V.

Is there something that I am missing here?

title: Using Servo with External Power

Answers: 0


body:
I'd like to add a method that replaces the entire image buffer into the [Adafruit_SSD1306][1] library. I haven't worked with dynamic memory handling for ages and I'm not sure how to just simply overwrite its pointer to point to a different memory address where my newBuffer is.

    static uint8_t buffer[SSD1306_LCDHEIGHT * SSD1306_LCDWIDTH / 8] = {}

    void Adafruit_SSD1306::setBuffer(uint8_t * newBuffer) {
      buffer = newBuffer; // not sure which operator to use
    }

Update: Passing by reference wouldn't work. The question is: how to overwrite by copying? Would it work well with `memcpy`?

    void Adafruit_SSD1306::setBuffer(uint8_t * newBuffer) {
      memcpy(newBuffer, buffer, (SSD1306_LCDWIDTH * SSD1306_LCDHEIGHT / 8));
    }

Update: The code above doesn't seem to making anything. This one neither:

    void Adafruit_SSD1306::setBuffer(uint8_t * newBuffer) {
      for(int16_t i = 0; i < SSD1306_LCDWIDTH * SSD1306_LCDHEIGHT / 8; i++) {
        buffer[i] = 255; // experimenting
      }
    }

Update: `setPixel` doesn't work either. - Needed `display.display();` :)

  [1]: https://github.com/adafruit/Adafruit_SSD1306/blob/master/Adafruit_SSD1306.cpp

title: Overwrite image buffer (inside Adafruit SSD1306)

Answers: 0


body:
I'm trying to upload my exported HEX file by avrdude using this command
```
/Users/user_acc/Downloads/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude -C/Users/user_acc/Downloads/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf -v -patmega32u4 -cavr109 -P/dev/cu.usbmodem1421 -b57600 -D -Uflash:w:/Users/user_acc/Documents/Arduino/at_command_A6/at_command_A6.ino.with_bootloader.leonardo.hex:i
```

But instead of loading the file it's stuck on connecting to programmer.

Output: https://scr.hu/rYNzzm
https://paste.ubuntu.com/p/74p37fGYPN/

The output from ArduinoIDE is exactly the same and it finds the programmer without the problem and loads the file.

```
/private/var/folders/5h/7rxp3rmn5351zh6r8cxhz1sr0000gn/T/AppTranslocation/5C2325EE-CF38-4140-8860-717C9DBAF376/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude -C/private/var/folders/5h/7rxp3rmn5351zh6r8cxhz1sr0000gn/T/AppTranslocation/5C2325EE-CF38-4140-8860-717C9DBAF376/d/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf -v -patmega32u4 -cavr109 -P/dev/cu.usbmodem124 -b57600 -D -Uflash:w:/var/folders/5h/7rxp3rmn5351zh6r8cxhz1sr0000gn/T/arduino_build_78519/at_command_A6.ino.hex:i
```

Output: https://scr.hu/M72NaV

Can somebody help me? :)

title: Avrdude can't connect to butterfly programmer

Answers: 1

body:
I found a post of somebody with a similar issue. His solution fixed my issue!

https://stackoverflow.com/questions/46813157/avrdude-command-line-cant-connect-to-programmer-for-leonardo


body:
I basically would like to ask this same question (in another context / more generically):

https://www.reddit.com/r/arduino/comments/25my2t/lgpl_and_arduino_in_commercial_products/

Stated differently:

What are the legal implications of LGPL licence in commercial products using Arduino boards (and or Arduino software/firmware)?

and about creating my own libraries for Arduino? (less or more permissive licenses cases for a derivative work)

and lastly, I'm also curious about this statically vs linked library conditions of LGPL (and how this would be applicable in this case)

thanks!

title: LGPL and Arduino in Commercial Products

Answers: 1

body:
IANAL, but my understanding is:

* Any LGPL code *you modify* you need to make available as source.
* Using LGPL code in your project doesn't constitute modification of that code unless you actually modify that code (See above).
* Any code *you* write that is not contained *within* LGPL code (see above) is yours to license as you wish. That means your libraries are *your* libraries. Your sketch is *your* sketch.

So in short, things that must be released as LGPL:

* Modifications to the core code.
* Modifications to other people's libraries

Things that are yours to license as you wish:

* Your libraries
* Your sketches

Things you should (if you're nice) provide attribution for:

* Arduino API
* Third party libraries

As far as hardware goes:

> These files are licensed under a Creative Commons Attribution Share-Alike license, which allows for both personal and commercial derivative works, as long as they credit Arduino and release their designs under the same license. The Arduino software is also open-source.

Which means if you *use their designs within your own design you should attribute it and make it open source under the CC-BY license.* Otherwise, if you just use their hardware verbatim there's nothing to attribute - you haven't used their designs, but a commercial product as a component.


body:
I will start by asking can the nodemcu and nrf24l01 be setup as a receiver.Im trying to read basic pir sensor data sent from arduino nano and  a nrf24l01 set as transmitter. I want to receive this data on nodemcu and a nrf24l01 set as a receiver. The problem is nodemcu serial monitor and tft display is showing nothing. The nrf's rec/transmitter work perfectly when connected to arduino nanos. My loop code will not cyle on the esp8266 and nrf24l01, which is verified by no data on the tft display and serial monitor showing no received data. If I disconnect either sck, mosi or miso the loop code will cycle but no data is received.

My connections

    Nodemcu       NRF24L01
    D8 -----------> CE
    D3 -----------> CSN
    D5 -----------> SCK
    D6 -----------> MISO
    D7 -----------> MOSI

My connections

     Nano           NRF24L01
    Pin  7 ---------> CE
    Pin  8 ---------> CSN
    Pin 13 ---------> SCK
    Pin 12 ---------> MISO
    Pin 11 ---------> MOSI

!!!!!!Nodemcu and NRF24 Code!!!!!

    #include <SPI.h>
    #include "RF24.h"

    #define CE D8
    #define CSN D3
    RF24 myRadio (CE, CSN);

     byte addresses[][6] = {"0","1"};

    struct package
    {
      int id=0;
      float VALUE = 0.0;
      char  text[100] ="empty";
    };
    typedef struct package Package;
    Package data;

    int led = D0;

    void setup()
    {
      pinMode(led, OUTPUT);
      Serial.begin(115200);

      myRadio.begin();
      myRadio.setChannel(115);
      myRadio.setPALevel(RF24_PA_MAX);
      myRadio.setDataRate( RF24_250KBPS ) ;
      myRadio.openReadingPipe(1, addresses[0]);
      myRadio.startListening();
      delay(1000);
    }

    void loop()
    {

      if ( myRadio.available())
      {
        while (myRadio.available())
        {
        myRadio.read(&data, sizeof(data));
        Serial.print("\nPackage:");             //Serial Monitor Text
        Serial.print(data.id);                  //id of data packag
        Serial.print("\n");                     //newline
        Serial.println(data.VALUE);       //text to receiver line 2
        Serial.println(data.text);  //text to receiver line 3

        digitalWrite(led, HIGH);
        delay(500);
        digitalWrite(led, LOW);
        delay(500);
       }

       }
    }

    !!!!!!Nano and NRF24 Code!!!!!

    #include "RF24.h"

    RF24 myRadio (7, 8);
    byte addresses[][6] = {"0", "1"};

    struct package
    {
      int id = 1;
      float VALUE ;
      char  text[100] = "Sensor <1> Transfer";   //text to receiver
    };
    typedef struct package Package;
    Package data;

    const int pinSensor = 4; // output signal pin of laser module/laser pointer
    int PirSensor = 3;

    int led = 2;
    void setup()
    {
      pinMode(pinSensor, INPUT); // set the laser pin to output mode
      pinMode(led, OUTPUT);
      digitalWrite(led, LOW);
      Serial.begin(115200);

      myRadio.begin();
      myRadio.setChannel(115);
      myRadio.setPALevel(RF24_PA_MAX);
      myRadio.setDataRate( RF24_250KBPS ) ;
      myRadio.setCRCLength(RF24_CRC_16); // Set CRC length to 16-bit to ensure quality of data
      myRadio.openWritingPipe( addresses[0]);
      myRadio.stopListening();
      delay(1000);
      }

    void loop()
    {
     PirSensor = digitalRead(pinSensor); // receiver/detector send either LOW or HIGH
      if (PirSensor == 1){
        data1.VALUE = 1.00;
        Serial.print("Motion ");
        Serial.println(data.VALUE); // send value to console

        myRadio.write(&data, sizeof(data));

      Serial.print("\nPackage:");
      Serial.print(data.id);
      Serial.print("\n");
      Serial.println(data.VALUE);
      Serial.println(data.text);

      digitalWrite(led, HIGH);
      delay(500);
      digitalWrite(led, LOW);
      delay(500);
      }
    else{
        data.VALUE = 0.00;
        Serial.print("No Motion");
        Serial.println(data.VALUE); // send value to console

        myRadio.write(&data, sizeof(data));

      Serial.print("\nPackage:");
      Serial.print(data.id);
      Serial.print("\n");
      Serial.println(data.VALUE);
      Serial.println(data.text);

      digitalWrite(led, HIGH);
      delay(500);
      digitalWrite(led, LOW);
      delay(500);
    }
    }

title: Nodemcu and NRF24L01

Answers: 0


body:
i am using 16x2 LCD with arduino nano for my project.

when i connect arduino nano with usb power supply from pc or any mobile changer adapter then all the character on LCD is visible properly. But when i connect it with 5V regulated power to arduino nano than character on LCD is not visible properly (characters are visible and project is running fine but pixel which needs to be hidden are also little darker so it characters aren’t visible properly)

i have connected Vee pin of LCD with ground for maximum brightness.

title: character on 16X2 LCD is not visible properly

Answers: 1

body: Disconnect Vee from GND and wire it up properly with a potentiometer. It doesn't set the brightness - it sets the bias point for displaying the different pixels in the matrix.


body:
I got this error in the following program:

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

    #include <SoftwareSerial.h>
    #include <dht.h>
    dht DHT;
    int a;
    String temp;
    String humid;
    SoftwareSerial esp(0, 1);
    #define SSID "abcd"
    #define PASS "99999999"

    void sendAT(String cmd) {
      Serial.print("SEND=");
      esp.println("cmd");
      Serial.println("cmd");
    }

    boolean connectwifi() {
      Serial.println("AT+CWMODE=1");
      delay(2000);
      Serial.println("AT+CWLAP");
      String cmd="AT+CWJAP="\"abcd"\",\"99999999"\";
      sendAT(cmd);
      delay(5000);
      if (Serial.find("ERROR")){
        Serial.println("Recieved:Error could not connect");
        return false;
      }
      else{
        Serial.println("Wifi connected \n");

      }
      cmd="AT+CIPMUX=0";
      sendAT(cmd);
      if(Serial.find("Error")){
        esp.print("RECIEVED ERROR");
        return false;
      }
    }

      void setup() {
      // put your setup code here, to run once:
      Serial.begin(115200);
      esp.begin(115200);
      send("AT");
      delay(5000);
      if(Serial.find("OK")){
        Serial.println("Recieved:OK\n ESP ready to send data\n");
        connectwifi();

      }

    }

      void loop() {
      // put your main code here, to run repeatedly:
      a=DHT.read11(5);
      temp=DHT.temperature;
      humid=DHT.humidity;
      Serial.println("temperature: ");
      Serial.println(temp);
      Serial.println("humidity: ");
      Serial.println(humid);
      Serial.print("\n");
      updateTS(temp,humid);
      delay(3000);

    }

    void updateTS(String T, String H){
      String cmd="AT+CIPSTATRT=\"TCP\",\"api.thingspeak.com\",80";
      sendAt(cmd);
      delay (2000);
      if (Serial.find("Error")){
        Serial.print("Recieved :Error\n EXIT1");
        return;
      }
      cmd="GET/update?key=CJWN3VJZCQVTJD2J&field1="+T+"&field2+"+H+"\r\n";
      Serial.println("AT+CIPSEND=");
      Serial.println(cmd length());
      if (Serial.find(">")){
        esp.print(">");
        esp.print(cmd);
        Serial.println(cmd);
        }
        else{
          sendAT("AT+CIPCLOSE");
        }
        if (Serial.find("Error")){
          Serial.println("Recieved: Error \n EXIT2");
        }
        Serial.println();
    }
        }
    }

The error message displayed is:

    arduinoo_sketch:21: error: stray '\' in program

       String cmd="AT+CWJAP="\"abcd"\",\"99999999"\";

       ^

    arduinoo_sketch:21: error: stray '\' in program

    arduinoo_sketch:21: error: stray '\' in program

    C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino:21:47: warning: missing terminating " character

       String cmd="AT+CWJAP="\"abcd"\",\"99999999"\";

                                                   ^

    arduinoo_sketch:21: error: missing terminating " character

       String cmd="AT+CWJAP="\"abcd"\",\"99999999"\";

       ^

    C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino: In function 'boolean connectwifi()':

    arduinoo_sketch:22: error: expected ',' or ';' before 'sendAT'

       sendAT(cmd);

       ^

    C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino:24:26: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

       if (Serial.find("ERROR")){

                              ^

    C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino:34:25: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

       if(Serial.find("Error")){

                             ^

    C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino: In function 'void setup()':

    arduinoo_sketch:44: error: 'send' was not declared in this scope

       send("AT");

                ^

    C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino:46:22: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

       if(Serial.find("OK")){

                          ^

    C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino: In function 'void loop()':

    arduinoo_sketch:64: error: 'updateTS' was not declared in this scope

       updateTS(temp,humid);

                          ^

    C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino: In function 'void updateTS(String, String)':

    arduinoo_sketch:75: error: 'sendAt' was not declared in this scope

       sendAt(cmd);

                 ^

    C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino:77:26: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

       if (Serial.find("Error")){

                              ^

    arduinoo_sketch:83: error: expected ')' before 'length'

       Serial.println(cmd length());

                          ^

    C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino:84:22: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

       if (Serial.find(">")){

                          ^

    C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino:92:28: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

         if (Serial.find("Error")){

                                ^

    C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino: At global scope:

    arduinoo_sketch:97: error: expected declaration before '}' token

         }

         ^

    exit status 1
    stray '\' in

title: Error : stray '\' in program

Answers: 2

body:
At least one example is here:

    String cmd="AT+CWJAP="\"abcd"\",\"99999999"\";

You probably meant

    String cmd="AT+CWJAP=\"abcd\",\"99999999\"";

This is a pretty trivial issue, you should be able to fix it simply by proofreading your sketch carefully.

body:
By properly formatting your code (ctrl-T in the IDE), you realize what is wrong with your code... In

      String cmd = "AT+CWJAP="\"abcd"\",\"99999999"\";
                   sendAT(cmd);

See how `sendAT(cmd);` is indented as if it was part of the previous line? It means you have some trouble with the quotes.


body:
I have a few MakerBot Mightyboards running off ATmega1280 chips that can no longer use their standard USB port to connect to a computer (to make a long story short, there's a little inductor that blew up between the USB port and the 8u2 chip and it is essentially impossible to replace). I have noticed, however, that they have headers for the RXD1 (PD2) and TXD1 (PD3) pins on the 1280 as seen in this picture:

[![PD0-PD3 pins on Mightyboard Rev H][1]][1]

Would it be possible to hook up an external 8u2 (or similar) chip programmed as a USB to serial converter ([something like this][2]) and use it as if it were the normal USB port (e.g. for uploading firmware)?

(I wanted to add atmega1280 as a tag, but it doesn't seem to exist)

  [1]: https://i.stack.imgur.com/jKOX1.jpg
  [2]: https://www.dfrobot.com/product-581.html

title: Using TXD1/RXD1 on ATmega1280 for USB communication

Answers: 1

body:
Not directly, no.

The USB interface connects to TX0 and RX0 - you have access to TX1 and RX1. The bootloader is set to look at TX0 and RX0.

You would have to compile and install a new version of the bootloader that is set to use TX1 and RX1.


body:
I wrote Arduino code to receive analog input from different voltage dividers connected to four pins (A0 to A4) and analog input from a temperature sensor (LM35) to A5. `analogRead` inside the for loop always returns zero whereas `analogRead` outside the for loop returns correct values.

What has to be changed to get correct values?

    int time=0,y=0;
    float volt;
    String str;
    int countParallel=0;
    float voltage[]={0,0,0,0};
    float temperature=0;
    int sensors_pin[]={A1,A2,A3,A4,A5};
    String x="";

    // the setup rouontine runs once when you press reset;
    void setup() {
      pinMode(2,OUTPUT);
      pinMode(3,OUTPUT);
      pinMode(4,OUTPUT);
      pinMode(5,OUTPUT);
      pinMode(6,OUTPUT);
      pinMode(7,OUTPUT);
      Serial.begin(9600);
      Serial.setTimeout(50);
    }

    // the loop routine runs over and over again forever;
    void loop() {
      Serial.println(analogRead(A5)*500/1023);
      delay(1000);
      while (Serial.available() > 0) {
        int inChar = Serial.read();
        if (isDigit(inChar)) {
          x += (char)inChar;
        }
      }
      // Parallel Disharging
      //  Serial.println(x);
      if(x.toInt()==1) {
        digitalWrite(13,HIGH);
        if(countParallel<1) {
          digitalWrite(6, HIGH);
          digitalWrite(7, HIGH);
          countParallel++;
        }
       for(int i=1,x=14;i<=5;i++,x++) {
        if(i<4) {
          Serial.println(analogRead(x)*(5/1023));
          delay(100);
        } else if(i==5) {
          Serial.println(analogRead(x) * p(500/1023));
          delay(100);
        }
        if(volt<2.8){
         digitalWrite(i+1,HIGH);
       } else if(temperature>40) {
         digitalWrite(2,HIGH);
         digitalWrite(3,HIGH);
         digitalWrite(4,HIGH);
         digitalWrite(5,HIGH);
        }
      }
    }

    // Series Discharge
    if(x.toInt()==2){
        for(int i=A0;i<=A4;i++){
          if(i<A4) {
            voltage[i] = analogRead(sensors_pin[i]) * (5/1023);
            Serial.println(10);
            delay(100);
          } else if(i==A4) {
            temperature = analogRead(sensors_pin[i])*(500/1023);
            Serial.println(9);
            delay(100);
          }
          if(volt<2.8) {
            digitalWrite(i, HIGH);
            delay(100);
          } else if(temperature>40) {
            digitalWrite(2,HIGH);
            digitalWrite(3,HIGH);
            digitalWrite(4,HIGH);
            digitalWrite(5,HIGH);
          }
         }
      }
    }

title: analogRead() inside a loop always returns 0

Answers: 1

body:
    voltage[i]=analogRead(sensors_pin[i])*(5/1023)

Is equivalent to

    voltage[i]= analogRead(sensors_pin[i])*0
              = 0;

You are using an integer division, not a floating point divsion. `5 / 1023` evaluates to `0`, `5.0f / 1023` evalues to `0.00488..`. You have repeated this error throughout your lower loop code, which is why you're only getting `0`.

In your outer loop you printed it as

    Serial.println(analogRead(A5)*500/1023);

Which will first multiply by 500, then divide by 1023, which works. But since you put the above expression in parenthesis, it was first evaluated.


body:
I am trying to run two stepper motor at same time with different RPM.
I decided to use two rotary encoder for change the RPM separately.

But,
I am in problem with driving stepper at same time due to the delay time of the step pulse.

How can I generate separate(different duty cycle) step pulses for stepper motors? It's the main problem that I faced.

I have used some Arduino libraries and all of that library has same system for step pulse generation. But, I couldn't understand those well.

    void AH_EasyDriver::setSpeedRPM(long RPM)
    {
       float DIV = RPM*this->MOTOR_RESOLUTION;
        this->STEP_DELAY =  60000000.0L/DIV;
     }

This function calculate the step time for given specific RPM

    void AH_EasyDriver::move(int NUMBER_OF_STEPS)
    {
       while(STEPS > 0) {
        if (micros() - this->LAST_STEP_TIME >= this->STEP_DELAY) {
          this->LAST_STEP_TIME = micros();
          STEPS--;
          stepMotor();
    }
    }

    }

This function rotate the motor the motor in STEP_DELAY using stepMotor() function.

    void AH_EasyDriver::stepMotor()
    {
      digitalWrite(this->STEP_pin, HIGH);
      delayMicroseconds(100);
      digitalWrite(this->STEP_pin, LOW);
      delayMicroseconds(100);
    }

This function makes **CONSTANT** step pulses.

I removed some lines in the function. [This][1] is the link for original .cpp file.
All of stepper controlling libraries has this functions.
I couldn't understand how this functions can change the RPM. Can someone explain this?

  [1]: https://github.com/ramonidea/Icing-Food-printer/blob/705f0ba2f09132a0ba9c169a89e9b2fd0e2478dc/AH_EasyDriver_20120512/AH_EasyDriver/AH_EasyDriver.cpp

title: Run two stepper at same time

Answers: 2

body:
When using a normal stepper driver, you say the driver to do one step, by sending him one pulse. The length of these pulses does not have a meaning. they are constructed, so that the driver can sense them. The driver does not make smaller steps than 1 full step, if you don't tell him on extra pins (The library you use can utilize those pins too). So the `stepMotor()` function is correct. You can drive the motors with different speeds by doing a step for each motor in different intervals (different number of steps per time).

Your `move()` function blocks the execution of other code, until the motion is completed. You are doing this with the `while( STEPS > 0 )` loop. You need to modify your code to be non-blocking. This is normally done in the way, that is shown by the `BlinkWithoutDelay` example of the Arduino IDE. You are using it too: You have to use the `millis()` or `micros()` function, to check if it is time to do a step.

Replace the `while` with an ´if´-statement:

    if( STEPS > 0 )

and make the `STEPS` variable a member variable of the class instance. Then make sure you execute the function often enough, so that it will not miss the time to do a step. Do the same with the second motor. For example something that looks like this:

    void setup(){
      ...
      stepper1.doSteps(100);
      stepper2.doSteps(200);
    }

    void loop(){
      stepper1.move();
      stepper2.move();
    }

Here in the `setup` function the steppers are told to move `100` and `200` steps. (You would have to write the function `doSteps(int number_of_steps)` yourself). The motion is then done by the `move()` functions, when it is time to do so. Since these two functions are looped very fast, they shouldn't miss the time for a step.

This is also the way the `AccelStepper` library works, which is also a common stepper library.

body:
The method to produce simultaneous pulses is simple, but requires a different approach similar to Direct Digital Synthesis (DDS).

1) Keep one counter variable per motor
2) Increment each counter variable by a set amount in a fixed time loop
3) When a counter variable reaches a threshold value, generate a very short step pulse
4) When a threshold is met, subtract the threshold value from the corresponding counter

The amount that each counter variable is incremented sets the generated pulse rate, reaching the threshold faster or slower, therefore setting the motor speed. A value of 0 stops the motor, a value equal to the threshold generates a step pulse for each iteration of the loop, reaching the highest speed. An arbitrary number of motors may be controlled simultaneously as long as the code can run within the fixed loop time. Since a step can only occur at fixed intervals, the rate of the timed loop should be several times the fastest step rate you intend to use to minimize timing jitter.

This style of control is often implemented using a timed interrupt service routine (ISR) which is a short function set to repeat at a several kHz frequency, interleaving with the rest of the program. This allows a slower loop to run a control algorithm simultaneous to the step generation.

If not using a timed interrupt function, the step generation loop must busy-wait until a set time has elapsed before repeating again. This means you cannot do much else than drive the motors until you stop and break out of the loop.


body:
Arduino: 1.8.3 (Windows 10), Board: "Arduino/Genuino Uno"

    C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -cstk500v1 -PCOM8 -b19200 -e -Ulock:w:0x3F:m -Uefuse:w:0xFD:m -Uhfuse:w:0xDE:m -Ulfuse:w:0xFF:m

    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:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

             Using Port                    : COM8
             Using Programmer              : stk500v1
             Overriding Baud Rate          : 19200
             AVR Part                      : ATmega328P
             Chip Erase delay              : 9000 us
             PAGEL                         : PD7
             BS2                           : PC2
             RESET disposition             : dedicated
             RETRY pulse                   : SCK
             serial program mode           : yes
             parallel program mode         : yes
             Timeout                       : 200
             StabDelay                     : 100
             CmdexeDelay                   : 25
             SyncLoops                     : 32
             ByteDelay                     : 0
             PollIndex                     : 3
             PollValue                     : 0x53
             Memory Detail                 :

                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
               flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
               lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
               hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
               efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
               lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
               calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
               signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

             Programmer Type : STK500
             Description     : Atmel STK500 Version 1.x firmware
             Hardware Version: 2
             Firmware Version: 1.18
             Topcard         : Unknown
             Vtarget         : 0.0 V
             Varef           : 0.0 V
             Oscillator      : Off
             SCK period      : 0.1 us

    avrdude: AVR device initialized and ready to accept instructions

    Reading | ################################################## | 100% 0.02s

    avrdude: Device signature = 0x000000 (retrying)

    Reading | ################################################## | 100% 0.02s

    avrdude: Device signature = 0x000000 (retrying)

    Reading | ################################################## | 100% 0.02s

    avrdude: Device signature = 0x000000
    avrdude: Yikes!  Invalid device signature.
             Double check connections and try again, or use -F to override
             this check.

    avrdude done.  Thank you.

    Error while burning bootloader.

title: Problem in bootloading 328p using Arduino as ISP. Please help me in figuring out the problem.I have uploaded the verbose below

Answers: 1

body:
there is great community called [avrfreaks.net][1] great with anything with AVR.

There is [thread][2] going with exactly same issue. follow it.

one quick thing try different 328p chip if it works mostly this one is bricked.
still want o experiment try changing crystal, fuse-bit , ISP , external clock generator.

  [1]: http://www.avrfreaks.net
  [2]: https://www.avrfreaks.net/forum/does-device-signature-0x000000-mean-atmega-bad


body:
Im not good in arduino, but I have project that control motor using limit switch.

The rule is:

1. When switch OFF, motor ON

2. When switch ON, motor OFF for 1 hour (i dont want use delay because cannot multitasking so it will be stopped another program which have to running in the same time)

3. After 1 hour, motor ON (although switch state still ON)

What type of timer I have to use? And how the code? Thanks. Sorry if i dont have any codes.

title: Timer for Control Motor using Limit Switch

Answers: 1

body:
There is no need to do a complex thing like using extra timers for this. You can use non-blocking code with the `millis()` function, like in the `BlinkWithoutDelay` example of the Arduino IDE (You should really try it and understand how it works). The `millis()` function returns the number of milliseconds since the Arduino has powered up and it will overflow after about 50 days (and with the code from the mentioned example this wouldn't be a problem either).

Basically you save a timestamp of the last event and check, if it is time to do something. For your case I would add a boolean, indicating, that the motor should be off and that the state of the switch doesn't matter anymore. Then (I assume that you want to disable the motor again by switching to OFF and ON again) you would have to reset this variable, when the switch goes to OFF state again. Something like this:

<!-- language: c -->

    boolean state=true; // on by default
    unsigned long timestamp=0;

    void loop(){
      if(switch_on() && state){
        state=false;
        // switch off the motor here
        timestamp = millis();
      }
      if(switch_off()){
        state=true;
      }
      if(!state && millis()-timestamp > INTERVAL){
        //switch on the motor here
      }
    }

Be sure to have a good code for checking the switch state, since most mechanical buttons need debounce code. In the above code I replaced this with simple functions to illustrate the timing functionality.


body:
So I need some tips on working with long strings with the arduino. I have a barcode scanner working. This barcode scanner reads a persons driver license. the result is a lengthy character string of varying length that's 300+. Using substring doesn't work when looking for a certain section of the string and indexOf results in a -1 in most spots. Is there anyway getting around this? Right now I have the data just stored in a string variable.

Thanks.

title: Working with long strings

Answers: 2

body:
Since the Arduino Uno only has a few KB, 300 bytes is a considerable amount.

My advice:

- Define a fixed char[300] array, where 300 is the max amount of characters you want to support.
- Use the C (string.h) library as Majenko already suggests.

The last thing you want is that the string will be copied somehow, using up double the amount of data, or triple. It's hard to see what's going on under water, by casting or even by implicit casting a copy can be made, so 600/900 bytes are used.

For the default library, searching should work for strings longer than 256 characters. You can even write them yourself, for example if you can make it more efficient if you know something about the characters (e.g. if you can skip some because you know some patterns exist or don't exist).

Update after your comment below.

What you can try:

- Try (if existing) an example sample for the barcode scanner to see if the hardware is ok. If not possible try to make a minimal sketch.
- Double check the wiring (although it seems easy).
- Try different wires (maybe a jumper wire is malfunctioning).
- Try another sketch using serial, but without the barcode scanner (to verify RX/TX is not broken on the Arduino).

body:
So when printing my string variable, I get the full, uninterrupted string displayed to me. I decided to index through my string with a for loop and come to find out, I had many null characters included in the string itself. I did a check to make sure that the character isn't a NULL character before appending it to my string upon creation, and that seemed to do the trick. indexOf is working now.

Reason I decided to index through my string is because I tried to string.toCharArray(buff, DL.length()); and despite the length, I would only get one character pushed into buff.

Thanks for all the tips guys!


body:
I'm making a game of snake on the adafruit Neopixel shield and have run in to a problem. How do you fill out an array (in this case a 5*8 array) with values once the class has been called.
This is my code so far

H file

    #include <Arduino.h>
    #include <Adafruit_NeoMatrix.h>
    #include <streaming.h>

    class Snake : public Adafruit_NeoMatrix
    {
     public:
        Snake();
        void drawSnake();

     private:
        int snakeBoard[5][8];
    };

CPP file

    #include "Snake.h"

    Snake::Snake() : Adafruit_NeoMatrix(8, 5, D6,
      NEO_MATRIX_TOP        + NEO_MATRIX_LEFT +
      NEO_MATRIX_ROWS       + NEO_MATRIX_PROGRESSIVE,
      NEO_GRB               + NEO_KHZ800)
    {
      begin(); // start the matrix
      show();

      int snakeBoard[5][8] = {{1,1,0,0,0,0,0,0},
                            {0,0,1,0,0,0,0,0},
                            {0,0,1,0,1,1,-1,0},
                            {0,0,1,1,1,0,0,0},
                            {0,0,0,0,0,0,0,0}};
    }

    void Snake::drawSnake()
    {
      for(int y = 0; y < 5; y ++)
      {
        for(int x = 0; x < 8; x ++)
        {
          Serial << "X: " << x << " Y: " << y << " Value" << snakeBoard[x][y] << endl;
          delay(100);
        }
      }
      drawPixel(5,5,Color(0,0,255));
      show();
    }

When I run the program random garbage is printed in the serial monitor.

title: Initializing an array within a class

Answers: 1

body:
As already mentioned by @chrisl, you are creating a new local variable which overshadows your class member.

An easy way to get what you want is to `memcpy` your initial values into the array:

    Snake::Snake() : Adafruit_NeoMatrix(8, 5, D6,
      NEO_MATRIX_TOP        + NEO_MATRIX_LEFT +
      NEO_MATRIX_ROWS       + NEO_MATRIX_PROGRESSIVE,
      NEO_GRB               + NEO_KHZ800)
    {
      begin(); // start the matrix
      show();

      int initialSnakeBoard[5][8] {{1,1,0,0,0,0,0,0},
                            {0,0,1,0,0,0,0,0},
                            {0,0,1,0,1,1,-1,0},
                            {0,0,1,1,1,0,0,0},
                            {0,0,0,0,0,0,0,0}};
      memcpy(snakeBoard, initialSnakeBoard, sizeof(initialSnakeBoard));
    }

You can achieve the same thing by utilizing C++11 constructor lists to initialize your members ([see here][1]):

    Snake::Snake() : Adafruit_NeoMatrix(8, 5, D6,
      NEO_MATRIX_TOP        + NEO_MATRIX_LEFT +
      NEO_MATRIX_ROWS       + NEO_MATRIX_PROGRESSIVE,
      NEO_GRB               + NEO_KHZ800),
      snakeBoard {{1,1,0,0,0,0,0,0},
                            {0,0,1,0,0,0,0,0},
                            {0,0,1,0,1,1,-1,0},
                            {0,0,1,1,1,0,0,0},
                            {0,0,0,0,0,0,0,0}}
    {
      begin(); // start the matrix
      show();
    }

You also have an error in your `drawSnake` routine: You confused the order of the indexes. With `snakeBoard[5][8]` you declare 2-dimensional integer array with 5 rows containing 8 elements each. Then, `snakeBoard[0]` will be a pointer to the first row (which has 8 elements). So the first index is `y` and must only range from `0` to `4` inclusive. The function must be:

    void Snake::drawSnake() {
     for(int y = 0; y < 5; y ++)
     {
      for(int x = 0; x < 8; x ++)
      {
       Serial.println("X: " + String(x) + " Y: " + String(y) + " Value " + String(snakeBoard[y][x]));
       delay(100);
      }
     }
    }

This then prints all the expected array elements to the the `Serial` port, as tested on my Arduino Nano.

  [1]: https://stackoverflow.com/a/22975356/5296568


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

Hello

My serial monitor keep showing these unreadable characters. Anyone know what is going on? Many thanks!

[![Schematic][2]][2]
[![Physical][3]][3]
[![Physical2][4]][4]

----------

  [1]: https://i.stack.imgur.com/6Ljd6.jpg
  [2]: https://i.stack.imgur.com/njNXd.jpg
  [3]: https://i.stack.imgur.com/hL2LB.jpg
  [4]: https://i.stack.imgur.com/y0NPK.jpg

title: Serial Monitor appears unreadable characters

Answers: 1

body:
It can have many reasons, but the most likely are:

- You set the baudrate wrong
- You set the stop/start bits wrong
- You send wrong data
- The cable is bad

It helps if you show your sketch(es), for sender/receiver and possibly your circuit.


body:
I have an Arduino Pro mini 3.3V, 8 mHz and I want to use the pulsein() function for a low-going pulse. My question: Does the timer start when the function senses a LOW on the input pin, or when the function senses a high-to-low transition, or either?

Code snippet:

    pinMode(3,INPUT); // Signal input to Arduino from pin 2 on LM339  - D3
    int pwindow = 6000; // Maximum timeout value for pulsewidth
    long pcounterA = 0; // Unfiltered Pulse Width of Channel 1
    pcounterA = pulseIn(3,LOW,pwindow);
    Serial.print(pcounterA);

Thanks for any help.
JT

title: When does the pulsein() function start counting?

Answers: 1

body:
According the official [Arduino Reference: PulseIn][1]

Fragment:

> Reads a pulse (either HIGH or LOW) on a pin. For example, if value is
> HIGH, pulseIn() waits for the pin to go HIGH, starts timing, then
> waits for the pin to go LOW and stops timing. Returns the length of
> the pulse in microseconds. Gives up and returns 0 if no pulse starts
> within a specified time out.

  [1]: https://www.arduino.cc/reference/en/language/functions/advanced-io/pulsein/


body:
I have defined a byte array as a constant in the Atmel's flash memory:

    const uint8_t eye [] PROGMEM = {
      0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
      0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff
    };

How can I (repeatedly) read the length of this constant in the program? All the available functions in avr/pgmspace.h do not deliver the proper length, no matter how I use them. I tried strlen(eye), strlen_P(eye), strLen_PF(eye) and also sizeof(eye). I'm new to C, so I'm not sure about the whole pointer stuff.

title: Arduino IDE: How to get PROGMEM const length?

Answers: 1

body:
Probably the best way would be to define below it

    const int eye_len = sizeof(eye)/sizeof(eye[0]);

If the linker does link time optimization, or if you only use it within the same file (and declare it static), it shouldn’t cost any memory, otherwise it will take up two bytes of ram.