text:
Unable to get Arduino Ethernet Shield IP address connected to Raspberry
My Arduino Uno with Ethernet Shield is connected to a Raspberry (rasp1) and the Ethernet Shield is connected to another Raspberry (rasp2) by Ethernet cable; rasp2 has a private IP address (192.168.10.0). I want to find out the Arduino IP address.
I used the example sketch  DHCPAddressPrinter but when running it the Serial Monitor remains empty (as Mac Address I used the address located underneath the shield).
Code Used:
#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = {
    0x90, 0xA2, 0xDA, 0x11, 0x32, 0x49
};

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;

void setup() {
    // Open serial communications and wait for port to open:
    Serial.begin(9600);
    // this check is only needed on the Leonardo:
    while (!Serial) {
        ; // wait for serial port to connect. Needed for Leonardo only
    }

    // start the Ethernet connection:
    if (Ethernet.begin(mac) == 0) {
        Serial.println("Failed to configure Ethernet using DHCP");
        // no point in carrying on, so do nothing forevermore:
        for (;;)
        ;
    }
    // print your local IP address:
    Serial.print("My IP address: ");
    for (byte thisByte = 0; thisByte < 4; thisByte++) {
        // print the value of each byte of the IP address:
        Serial.print(Ethernet.localIP()[thisByte], DEC);
        Serial.print(".");
    }
    Serial.println();
}

void loop() {

how are you connecting two ethernet cables to the ethernet shield?

192.168.10.0 is not a valid IP address (unless it's on a /32 subnet which makes no sense on ethernet).
You need to allocate a proper IP address within a proper subnet, such as 192.168.10.1/24 (i.e., IP 192.168.10.1 and netmask 255.255.255.0), and either manually provide a similar IP address to the Arduino (such as 192.168.10.2/24 [IP 192.168.10.2 netmask 255.255.255.0]), or install and configure a DHCP server on the Raspberry to hand out IP addresses within that subnet range (e.g., 192.168.10.100/24 to 192.168.10.200/24) for the Arduino to then be able to use DHCP mode.
Most of that is outside the scope of an Arduino SE site, though.


text:
Non-blocking analogRead
In my recent project, I'm working with the motor. I have to drive the motor for the specific time like for 2 minutes, 3 minutes, 4 minutes and 5 minutes. I already created functions for that. And motor drive based on readings taken from the sensor.
My code is below:
#define PIN_OUTPUT 6

const int kPinIN1 = 4;
const int kPinIN2 = 5;

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

  pinMode(kPinIN1, OUTPUT);
  pinMode(kPinIN2, OUTPUT);
}

void loop()
{
  Serial.println(analogRead(A0));

  if(analogRead(A0) > 100 && analogRead(A0) < 200)
  {
    motorDriveFor2Min();
  }
  else if(analogRead(A0) > 200 && analogRead(A0) < 300)
  {
    motorDriveFor3Min();
  }
  else if(analogRead(A0) > 300 && analogRead(A0) < 400)
  {
    motorDriveFor4Min();
  }
  else if(analogRead(A0) > 400 && analogRead(A0) < 500)
  {
    motorDriveFor5Min();
  }
}

void motorDriveFor2Min()
{
  digitalWrite(kPinIN1, HIGH);
  digitalWrite(kPinIN2, LOW);

  analogWrite(PIN_OUTPUT, 255);

  verboseDelay(7000);

  digitalWrite(kPinIN1, LOW);
  digitalWrite(kPinIN2, HIGH);

  analogWrite(PIN_OUTPUT, 255);

  verboseDelay(7000);

  digitalWrite(kPinIN1, HIGH);
  digitalWrite(kPinIN2, LOW);

  analogWrite(PIN_OUTPUT, 255);

  verboseDelay(7000);

  digitalWrite(kPinIN1, LOW);
  digitalWrite(kPinIN2, HIGH);

  analogWrite(PIN_OUTPUT, 255);

  verboseDelay(7000);

  digitalWrite(kPinIN1, HIGH);
  digitalWrite(kPinIN2, LOW);

  analogWrite(PIN_OUTPUT, 255);

  verboseDelay(7000);

  digitalWrite(kPinIN1, LOW);
  digitalWrite(kPinIN2, HIGH);

  analogWrite(PIN_OUTPUT, 255);

  verboseDelay(7000);

  digitalWrite(kPinIN1, HIGH);
  digitalWrite(kPinIN2, LOW);

  analogWrite(PIN_OUTPUT, 255);

  verboseDelay(7000);

  digitalWrite(kPinIN1, LOW);
  digitalWrite(kPinIN2, HIGH);

  analogWrite(PIN_OUTPUT, 255);

  verboseDelay(7000);

  digitalWrite(kPinIN1, HIGH);
  digitalWrite(kPinIN2, LOW);

  analogWrite(PIN_OUTPUT, 255);

  verboseDelay(64000);
}

void motorDriveFor3Min()
{
  motorDriveFor2Min();

  digitalWrite(kPinIN1, HIGH);
  digitalWrite(kPinIN2, LOW);

  analogWrite(PIN_OUTPUT, 255);

  verboseDelay(7000);

  digitalWrite(kPinIN1, LOW);
  digitalWrite(kPinIN2, HIGH);

  analogWrite(PIN_OUTPUT, 255);

  verboseDelay(7000);

  digitalWrite(kPinIN1, HIGH);
  digitalWrite(kPinIN2, LOW);

  analogWrite(PIN_OUTPUT, 255);

  verboseDelay(7000);

  digitalWrite(kPinIN1, LOW);
  digitalWrite(kPinIN2, HIGH);

  analogWrite(PIN_OUTPUT, 255);

  verboseDelay(7000);

  digitalWrite(kPinIN1, HIGH);
  digitalWrite(kPinIN2, LOW);

  analogWrite(PIN_OUTPUT, 255);

  verboseDelay(32000);
}

void motorDriveFor4Min()
{
  motorDriveFor3Min();

  digitalWrite(kPinIN1, HIGH);
  digitalWrite(kPinIN2, LOW);

  analogWrite(PIN_OUTPUT, 255);

  verboseDelay(7000);

  digitalWrite(kPinIN1, LOW);
  digitalWrite(kPinIN2, HIGH);

  analogWrite(PIN_OUTPUT, 255);

  verboseDelay(7000);

  digitalWrite(kPinIN1, HIGH);
  digitalWrite(kPinIN2, LOW);

  analogWrite(PIN_OUTPUT, 255);

  verboseDelay(46000);
}

void motorDriveFor5Min()
{
  digitalWrite(kPinIN1, HIGH);
  digitalWrite(kPinIN2, LOW);

  analogWrite(PIN_OUTPUT, 255);

  verboseDelay(120000);

  digitalWrite(kPinIN1, HIGH);
  digitalWrite(kPinIN2, LOW);

  analogWrite(PIN_OUTPUT, 255);

  verboseDelay(7000);

  digitalWrite(kPinIN1, LOW);
  digitalWrite(kPinIN2, HIGH);

  analogWrite(PIN_OUTPUT, 255);

  verboseDelay(7000);

  digitalWrite(kPinIN1, HIGH);
  digitalWrite(kPinIN2, LOW);

  analogWrite(PIN_OUTPUT, 255);

  verboseDelay(7000);

  digitalWrite(kPinIN1, LOW);
  digitalWrite(kPinIN2, HIGH);

  analogWrite(PIN_OUTPUT, 255);

  verboseDelay(7000);

  digitalWrite(kPinIN1, HIGH);
  digitalWrite(kPinIN2, LOW);

  analogWrite(PIN_OUTPUT, 255);

  verboseDelay(7000);

  digitalWrite(kPinIN1, LOW);
  digitalWrite(kPinIN2, HIGH);

  analogWrite(PIN_OUTPUT, 255);

  verboseDelay(7000);

  digitalWrite(kPinIN1, HIGH);
  digitalWrite(kPinIN2, LOW);

  analogWrite(PIN_OUTPUT, 255);

  verboseDelay(7000);

  digitalWrite(kPinIN1, LOW);
  digitalWrite(kPinIN2, HIGH);

  analogWrite(PIN_OUTPUT, 255);

  verboseDelay(7000);

  digitalWrite(kPinIN1, LOW);
  digitalWrite(kPinIN2, HIGH);

  analogWrite(PIN_OUTPUT, 255);

  verboseDelay(120000);
}

void verboseDelay(unsigned long ms)
{
  unsigned long now = millis();
  unsigned long start = now;

  do
  {
    now = millis();
  }
  while (now - start < ms);
}

Here, I have four functions named motorDriveFor2Min(), motorDriveFor3Min(), motorDriveFor4Min() and motorDriveFor5Min() for my specific time means for 2 minutes, 3 minutes, 4 minutes and 5 minutes respectively.
So, suppose If I want to drive motor for 4 min then I have to call function motorDriveFor4Min() and for that, I have to set my reading between 300 & 400. But I can't able to do that because when my reading reaches at 100 then it starts executing another function means motorDriveFor2Min() and then continuously run that functionality. During that time I try to change the reading but nothing happens. After restating Arduino it run according to the reading.
So, I thought maybe delay() function block everything. So I replace inbuilt delay function with custom delay function. But that can't solve my problem. Then I google it out and I found out that analogRead may cause this problem. Any suggestion for this.

That is clearly a design fault. What does your analog reading represent? Are there discrete values for stopping the motor? Like <100 and >500? You could simply keep running until the reading reaches those.

In essence, all your program does is run the motor all the time. Because as soon as it has run to motor for X minutes, it immediately goes through your code again, and run for Y minutes. I think you benefit from adding a button. So that only when you press the button, the motor will run for X minutes, where X is dependent on the position of your potentiometer.

If you want to determine the length of time to drive the motor before the motor starts (as it sounds like you want to) what you probably need is a "go" button.  If you can alter your goal and instead keep reading the analog to make an ongoing decision if you want to keep driving it, that would probably be wiser - the time taken to do even a blocking analog read is short in motor terms.  Keep in mind that your system should have a non-software "emergency stop" and that you really shouldn't be using an Arduino to control anything where mis-operation would be hazardous.

In effect, right now, you have the reset button or power switch functioning as a "go" button that causes it to evaluate the (hopefully desired) analog input value you have set.

Also you should call analog read only once for your printout and decision tree and save the result in a variable.  Otherwise every check may see a different value and you could fall through satisfying none.  And change some of your comparisons to include the equals case, so that the boundary numbers like 200, 300 etc don't fall through satisfying nothing.

your code repeats unnecessarily .... you only need one motorDriveForXMin() function .... just pass the delay in an argument value ..... motorDriveForXMin(4)  ..... multiply the argument by the delay value of 1 minute inside the function ..... also your code does not check for values of 200, 300 and 400

@mystery I Here analogRead is sensor reading. Depend upon sensor reading motor run for specific time. Suppose if reading is about between 100 & 200 then a motor run for 2 minutes.

@Gerben yeah, I just added button. So that first I set my analogRead value then press button for start execution.

@ChrisStratton Yeah one button is needed for that. without that, I can't able to fulfill my purpose.

@jsotola No it's not unnecessarily. Every function's functionality is different from each other.

It's not analogRead. It's not (just) delay. It's the whole method of your program.
The way it's written you can do nothing else while driving a motor for X minutes.
You need to rethink your whole program so that it's not "run for X minutes" each time, but instead "Run the motor until the time is up" and constantly re-evaluate what the time should be.
That means:

No "run for X" functions.
No delay() functions (of any form - yours is as bad as the normal one).
A state machine to determine what should be happening when.
Constantly referencing both millis() and analogRead() to determine what state the state machine should be in or progress to and when.

Actually, that's not quite the problem.  They want to do nothing but drive the motor for several minutes.  The problem is that while they are adjusting the pot (or before they get a chance to) it takes off on an undesired reading.   It's possible the task could be re-organized to drive the motor for some period of time, and then read the analog input to decide if driving should continue - and that might be smarter, but it's not the goal that was stated.

@ChrisStratton For something like this there are many many ways of achieving the same thing. None are wrong. Either way, the underlying methodology of their existing program prevents any proper control and they need to re-think how to better do what they want.

@Majenko Thank you for clearing my misunderstanding about the delay() and analogRead(). I just find out a better way for my logic.

source: Stack Exchange

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

sort: votes


text:
Change format preferences for Arduino IDE in Linux
How can I change Arduino IDE preferences for formatting? I found the preferences file: <user>/.arduino15/preferences.txt, but there are no lines that control IDE formatting. In Windows there is a special file for formatting: <ArduinoIDE_folder>/lib/formatter.conf.

same place <ArduinoIDE_folder>/lib/formatter.conf

@Juraj , as <ArduinoIDE_folder> do u mean <user>/.arduino15?

no, .arduino15 is on Windows C:\Users\User\AppData\Local\Arduino15. I installed Arduino IDE on linux into /home/user/arduino-1.8.5

I have my custom formatter.conf in /home//.arduino15

It happened, that my formatter.conf was in /usr/share/arduino/lib/. So I copied it to /home/<user>/.arduino15/ folder and made changes that I needed. And also:

Copy it in the same folder of file "preferences.txt" and modify the copy. This way, you won't lose your custom formatter settings when upgrading the IDE.

That is correct.  However, when upgrading, I often the remove the .arduino15 folder as well to make a fresh start. Recently I had to remove the .arduino15 folder without upgrading to a new version. The arduino ide was sometimes slow and had troubles when installing new libraries.

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


text:
Can't assign String to Array of String
I have to input 5 words and organize.
In order to organize words, I have to get them into Array of String to compare.
I succeed to get char[buffer] into String in_str but somehow in_str doesn't
get into str[5].
is String str[i]=in_str;  Wrong?? How can I put in_str to Array of String str??
void setup() {
  Serial.begin(9600); }

void loop() {
  int state = 1, len = 0 ,i=0, k=1;
  char buffer[128];
  String str[5];
  while (true) {
    if (state == 1) {
      Serial.print("Enter the ");
      Serial.print(k);
      Serial.print("th Word --> ");
      state = 2;
    }
    while (Serial.available()) {
      char data = Serial.read();
      if (data == '\n') {
        buffer[len] = '\0';
        String in_str = buffer;
        String str[i]=in_str;
        Serial.println(in_str);

        i=i+1;
        k=k+1;
        len = 0;
        if(i>4){state = 3; }
        else {state = 1;}
        break;
      }
      buffer[len++] = data;
    }
  if(state==3){
    Serial.println("After Sorting");
   for (int i = 0; i < 4; i++) {
    for (int j = i + 1; j < 5; j++) {
      int compare = str[i].compareTo(str[j]);
      if (compare > 0) {         String temp = str[i];
        str[i] = str[j];
        str[j] = temp;
      }
    }
  }

   for (int i = 0; i < 5; i++) {
    Serial.println(String(i) + " : " + str[i]);
  }

    break;
  }

  }
}

When you write String str[i]=in_str; that is wrong. You only write the type when you are declaring the variable, once.
When assigning, you need only write the variable name, not the type: str[i]=in_str;

I thought like hours to solve this problem but this was a simple mistake.. thanks for your help


text:
Fixing Error function 'long int map

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?

Use formatting! And don't post pictures of code!

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


text:
Sending servo position data from one Arduino to another
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
  }
}

How about to just send it over serial? You seem to already have decided, that you want to use serial, so why don't you just do it? Is there a specific problem?

would it just be a basic serial.read() and serial.write command?

Yes that's all you would need. You'd be sending two bytes over, so the receive side would  have to deal with that.

you posted code that has nothing to do with your question ... your question is about sending data from one arduino to another arduino ... you posted code that positions a servo

When using bytes for location (0-180 degrees), you can simply use: myservo.write(pos);myserial.write(pos); and on the receiving side myservo.write(receivedValue); (check some tutorials on how to receive a value.

@jstolat - no, as the question clearly states, they want to add communication to the provided code.  It is very much relevant, as it is the starting point.

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.

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

Actually, that simple binary method is limited not to fixed-length messages, but rather to single-word messages.  If you want to send longer messages, regardless if they are fixed length or variable, you need a mechanism to achieve at least initial synchronization to indicate the start of a word.  Time gap is the weakest such method, reserved or escaped codes etc are more robust but complex.  ASCII encoding with a delimiter (especially a newline) does indeed become attractive, and is readily observed in a terminal as well.


text:
Servo issue, won't go into negative range
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");

}

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

Thanks so much Valerio! My project is now working thanks to you. Time to go fire up the 3d printer for a base. :)


text:
Fastest reading through i2c
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.

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

If you set the SPI2X: Double SPI Speed Bit, you can run at 8MHz, but the ADXL345 only support upto 5Mhz.

Yes, 16MHz Arduino can run SPI clock at 1 MHz, 2 MHz, 4 MHz (default speed), 8 MHz (and 4 additional slower speeds - but not 5 MHz). I use 8 MHz for a lot of shift register projects.

Thanks. Wouldn't SPI require to convert between 5 to 3.3V for the arduino? In any case,  400KHz would be far more than I need but I fail to reach that sampling rate with the Wire library.

5V down to 3.3V, and 3.3V up to 5V is easily down with a couple of chips. 74HC4050, sN74HC125


text:
Read from analog input "bounces" around
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/

Can you observe the voltage at X and Y via a multimeter or an oscilloscope? Your code looks right but the hardware might have a problem. Relaxed position should read 512 (~2.5V)

const int X_pin = 0; should technically be const int X_pin = A0;, but if I recall shouldn't matter.

This is a fairly simple project.  I suspect bad parts and suggest you swap out the joystick then, if that doesn't work, the Arduino.  If that is not an option: consider if only 1 of the 2 analog input has noise on it that wiring for that input from the joystick is wrong or broken.  If both analog inputs have noise on them inspect both the ground and 5 volt wires.  However I doubt that is the problem as if either worked then all the analog readings would always be zero (only ground is connected) or its maximum (only 5 volts is connected) which I believe is 255.


text:
Can't power HC-05(5v) with Arduino Pro mini (3.3v)?
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.

Also, HC 05 has an onboard regulator for levelling it to 3.3v

Please Help!!!

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

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

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

Zener diode (few components, inefficient use of power)
Voltage divider with resistors (few components, inefficient use of power)
Linear regulator (few (IC) or many (discrete) components, inefficient use of power)
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.

My module is 5~7v version unfortunately which is the cause of all of my problem. I have added the module image to the original question.

Also note that 3.7 Volt is the nominal values. It's more like 4.2 when fully charged. So you'd end up with 8.4 Volt when both batteries are full.

@HardikSharma did you choose a technique to reduce your voltage, or are you just going to use a 5V power supply? Also, please upvote my answer if useful or vote it as the answer if it answered your question (https://stackoverflow.com/help/privileges/vote-up)

My GND was loose and using a single battery worked after fixing that. So thanks for the information anyway.


text:
Understanding how a tilt switch works
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.

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

Don't paste an image of the code. Code is text -- just paste the text right into the question, select it and type CTRL-K to format it as code.

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

Edit your question -- don't put the code as a comment.

Check your tilt switch with the continuity setting on a multimeter to find out at what orientations it's considered "ON" and which are "OFF"

Did that Sir. Just figured it out :)

Thanks for the response, Even when I flick it ON/OFF the LED keeps glowing, I think I maybe making mistake on the pinmodes or something :S
If the orientation was the issue, then the other IF condition would have satisfied when I tilt the switch

The code is functional, besides the fact that you're probably filling up the serial port output buffer. Note that your loop() runs at probably close to half a million times  a second, and you are trying to write a string of text every time through the loop. Try commenting out the Serial.print() statements and see if that clears anything up.

How about using a pullup/pulldown resistor? When there is no connection from the input pin to any potential it will be floating

Thanks chrisl, Its what you said. The PULLUP.
Looks like I did not read the theory right. Switches are supposed to be connected to the ground, with PULLUP specified. I connected them to 5V.

Learning arduino with a tinkercad simulation? Do you have a real arduino board?

Yes I do have it. But I am a noobie and little paranoid that I might short it. So I learn using tinkercad and if it works then I try them out on Arduino

Is this a simple mercury switch?  You call it a tilt switch but I am not sure what you mean.

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.

Switches aren't "supposed" to be connected to ground. It's just that if they are you can make use of the internal pullup instead of having to attach an external pulldown.

Don't post code as an image.


text:
Keypad Type 11 numbers only?
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);

}

I tried that code but the problem is. Its still input more than 11 numbers

I did upload a photo in Displaying LCD it can input almost 15 numbers. I want only to input 11 numbers

Am I missing something? You count the number of digits entered, and stop when you have 11 of them. I suggest doing some C tutorials.

did you ask this same question on March 27th? .... are you Shin Doe? ... if you are, why are you asking again?

Please don't post the same question twice.

Three simple approaches.

You could get a string, and limit it to 11 characters in length. You then convert the string to num
You could check that 9999999999<num<=99999999999
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 treatnum` 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;
}

Thank you . Can you give me idea how to do it in my code?Im really a newbie. thanks a lot.

Thank you so much! I already tried your code and its working now. Thank you very much! :) :D


text:
Debouncing Multiple Buttons
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

Are you sure those last two if's are interpreted by the compiler the way you mean? I would use some more ()'s ! And instead of foo() == false you can use ! foo(), which makes things more readable. (at least to me)

@WoutervanOoijen You are right about readability, I will change it to !foo(). But regarding if the computer is reading the last two if's correctly, that's what I'm trying to figure out. I don't think it is, but I don't know how else I could code it so it works correctly.

@WoutervanOoijen == takes precedence over && - but I too consider it bad practice to rely on C++ operator precedence.

Note that == has a higher precedence than the logical and (&&), so in the first test only the button.2() statement is evaluated. http://en.cppreference.com/w/c/language/operator_precedence

@PeterSmith To make sure all arguments are read, should I use nested for loops? or is that going to be too messy?

@PeterSmith that is not true - it takes precedence, so it will evaluate if the second button is not pressed and do a logical AND with first button pressed. So it's if first button is pressed and second button is not pressed.

I don't get why you use a for loop - won't it run through that loop so fast that you cannot push the buttons fast enough anyways? I'd much more vote for an event based approach to a problem like this. Have a look at state machines and use button presses as input into the state machine.

@Arsenal I had only heard of switch case before, not state machines, but after looking into them, I might go that route it seems a lot more organized than my code is turning out to be. Thank you.

It's a good approach to learn for many problems, that skill will certainly not go to waste in the future - glad I could help you, even if I didn't provide an answer to your question.

note: you can reduce your code like if (button1.isPressed() && button2.isPressed() == false){ by using the ! not operator, as in  if (button1.isPressed() && !button2.isPressed()){

also simplify if(binary[i] == 0) { binary[i]=1;} to binary[i]=!binary[i];

There is no debouncing in the code.  Debouncing is a matter of time.  A simple method, is that after acting on any input you ignore all the buttons for a fraction of a second.  If you don't need to do much else, that can be a blocking delay.  If you do need to do other things, you'll need to check elapsed time.

@ChrisStratton I have just implemented some debouncing based on time, but I'm struggling with getting any valid input as it is still looping through fairly quickly.

It seems like your code will trigger on both press and release.

@ChrisStratton hmmmmm any suggestions of where I'm going wrong?

Your first problem is here:
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:
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:
  for (int i; i<16; i++){
    lcd.print(binary[i]);
  }

Another compiler warning:
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:
  for (int i = 0; i<16; i++){
    lcd.print(binary[i]);
  }

Ditto further down.

If I add some debugging here:
void MainmenuBtn(){
  btn_push = ReadKeypad();
  Serial.print ("btn_push = ");
  Serial.println (btn_push);
 // WaitBtnRelease();
}

And then press a button, I see:
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.

Wow! Thank you for catching all of my errors, I guess I've just been looking at the code too long. I agree I should have used debugging prints. I am working right now to figure out debouncing for the buttons to see if the state has changed. Just a question about that first problem you found, are you saying I should return 0 at the end of the function or instead of returning 'N' if neither button is pressed?

I've updated my code in an attempt to implement debouncing and detect a state change, but it seems I've only made the loop worse. Any ideas on what I'm doing wrong?

If 'N' means neither button, then sure.

You still aren't looking at the warnings. Your new function ButtonOne does not return anything when it "falls out" the bottom.

See amended answer with some suggested code changes.

Thank you! I was getting very confused trying different methods and it all just turned into a mess.

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”

Yes, I've modified to use debouncing, but have run into issues with this.

@Katie there is not in fact any debouncing in your code.  Debouncing is fundamentally a matter of time.

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


text:
BridgeServer REST API with more string values
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
}

maybe you should not create a copy of the Cllient object when passing it into a function. use reference parameter BridgeClient &client

i added it as screenshoot. its not clear visible because the console is white as well but underneeth the console output you see that im calling [myarduino].local/device1/on in a browser and the output of url0 [String url0 = client.readString();] is the full string but then after one time calling client.readStringUntil('/') the client seams to be manipulated and url1 [String url1 = client.readString(); ]  is empty.

same for 'BridgeClient &client'.

so you read all the input into ur10 with readString() and the expect to read what from it with readStringUntil()?

i expect url1 to be same as url0 because im reading the same object. why is it not the same?

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

ok, so how can i pass it thorugh a function without to loose the information about the "xy" string (of http://myarduino/foo/bar/xy)?

https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/ or http://forum.arduino.cc/index.php?topic=396450.0

or read it to / and then to / etc.

Do you mean to read to device1/foo/bar/ and then to device1/foo/ ?
thats not possible because readStringUntil('/'); finds the first and cuts away the rest of the string...

not cuts away, stores into output

I can’t follow...

the rest is still waiting in buffer to be read with the next readStringUntil

true. I cold swear i tested that with a negative result. now it works.

ah, i found a underlaying issue. somehow the string of the device1 gets recognzed by an if(command == "device1"){ switch(client)}; but not the switch afterwords wich takes the second readStringUntil("/") part... like void switch(client){ String command = client.readStringUntil('/'); if(command == "on"){ turn(client);}
the on does not get recogized. but im able to print command "on" to console.

but after the on, there is no /. the readStringUntil reads the rest of input and then waits a second and returns. I bet you have "on\r\n" in the String. and that is not equal to "on".

your my hero. that works. can you explain me what \r\n means and why it is that i have to expect (guess) that?

it is a 'new line' code. in this case at the end of the HTTP GET request's first line. on next lines are the HTTP headers


text:
Unable to convert string read from bluetooth to int
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 = "";
  }
}

Have you tried examining the contents of directMvt yet?

Don't post code as picture. Use copy paste

Instead of printing the converted number, try printing the substring, that you try to convert in the line above. Most likely the substring doesn't contain only numbers

Don't put delays in serial receiving code!

I printed the directMvt and the substring, they give the right answer, the problem seems to be in the toInt() function @IgnacioVazquez-Abrams

I printed the content of the substring before converting, it contains only the number i entered, for example if I enter 18000f, the first substring contains 180 and the second 00, I posted the code instead of the pic @chrisl

I had to put delays because I had the issue that the same characters arrives many times, because the sender sends slower than the loop, I had things like 1118888000000 for 18000f @ChrisStratton

That can only happen with a logic bug.  Fix the logic bug.  Do not use a delay, it a proof of misunderstanding.

the thing I believe the loop in the arduino code is faster than rate at which the cellphone sends the data thats why it happens and stops with delay, but I'll try to remove it again and see if I had a logical problem with my previous code @ChrisStratton

Of course the loop is faster; but that's not a problem with a proper program.

Do you think the android code is causing the issue with the delay ? The arduino code doesnt have any bug no? @ChrisStratton

Do you have any idea about the toInt() issue ? @ChrisStratton

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.


text:
ESP8266 cannot create TCP connections to this particular server
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.

How to replicate:

Using the latest Arduino IDE and ESP8266 library.
Check that the test server works at http://185.205.210.197:80/ (just open this link basically and see that is running nginx).
Copy and upload the code above to your ESP8266 (NODEMCU or similar).
Open the Arduino IDE console/monitor and confirm that no connection is established to port 80.
Rage in admiration for such a strange bug.

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

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.

Thank's for helping. I am going to try that. Meanwhile this might be a library problem indeed, I opened an issue in the official esp8266 lib repo: https://github.com/esp8266/Arduino/issues/4593


text:
Libraries/classes using other libraries/classes
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);
};

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

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.


text:
Load Cell and HX711 only outputting 0's
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):

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!

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)

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


text:
SD card doesn't work properly
I have this SD-card module. I have formatted the SD with this tool. 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

It sounds like maybe you have unreliable wiring connections.  Your module won't directly plug into an Arduino Uno, so how have you physically made the electrical connections?

I use: MISO -> Pin 12,
MOSI -> Pin 11,
SCK -> Pin 13,
SDCS ->Pin 10,
5V -> 5V,
GND -> GND

Yes, but how are these connections physically made?

With Jumper Wires like this: https://www.exploringarduino.com/parts/jumper-wires/

Show us a photopgraph of your actual setup.

https://imageshack.com/a/img923/318/ptdhHE.jpg

Manufacturing flaws in such jumper wires are not unknown, and the connections there or in the Arduino can wear.  Also long wire runs are not encouraged for things like this, either signals or power/ground.

Your stated wiring doesn't appear to match your code or picture.  To which signal is the green wire connected?

I connect the SDCS (green) to Pin 7 as in the code above; in the previous comment I make a typo. Could be a problem with the module?

I have formatted the SD with this tool. .... this does not describe what you actually did

I formatted the sd with the tool that is linked.


text:
Motor does not move with 4 batteries
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?

Schematic where?

I just added the above

you have to run a program

The L298 is a horrible chip, if you want to use that you'll probably have to add two cells to the battery pack just to account for its losses.  Note that you seem to be following a guide that recommends 6 cells, while you have only used 4.

When you say "the motor does not move", are you referring to the four DC motors, or the servo motor?

Thank you everyone. I have replaced the battery with 18650 (3.7 v). And it worked

If Aamir's answer helped you please vote it up and/or accept it, so people know that was the issue.

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:

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?)
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.
Is the Arduino Sensor shield working correctly. Does the LED pin work? Do other signals sent from the board work?
Remember that servo motors work differently to normal DC motors. You need to use Pulse Width Modulation to set the position. If you have never done this before, you will find the Arduino Servo Motors page useful. Also, you will get some excellent understanding and code from this Adafruit page. It is for a different Arduino shield, but the principles are the same.

The question seems more likely to be about the drive motors than the servo.

Ah. I hope my effort isn't wasted then. I guess it happens sometime. I've asked the author to clarify. Thanks for your detailed, helpful contributions to StackExchange Arduino. I just read some of your posts, and they are very helpful.

Thank you everyone. I have replaced the battery with 18650 (3.7 v). And it worked

@Riski, if you found any of the answers helpful, feel free to show your appreciation by selecting the answer and upvoting helpful answers. This is how the StackExchange system works: https://stackoverflow.com/help/privileges/vote-up

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


text:
Problem uploading to ATMega using ArduinoIDE ("unbricking" "bricked" microcontroller?)
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

version of IDE?

ArdunoIDE 1.8.5

Did uploading work with an other board, for example the arduino uno, or is this your first board? Are you in the dialout group? Is the modemmanager installed? You have to remove it. The purpose of the modemmanager is to cause troubles with an arduino pro micro (and other boards). If you don't like the extras by sparkfun, then you can burn the bootloader of the official arduino micro on it, but you have to take care that it has less pins. Do you have anything related to arduino installed from the repositories? can you try to remove java? Be sure to remove the librxtx-java.

I first used a completely different µC which worked perfectly. This was not an ATMega but a ESP8266. I then switched to the other board, tried to change settings for that board.

Yes, the modemmanager is installed. I read about that. But I can't uninstall the modem manager: It would uninstall the complete Mate UI because of dependencies. I do not know if the modemmanager interfers: I have used this board before and uploaded programs a few times to test it. Now I wanted to really make use of it ...

Why should I remove Java? What would that help? Please provide more information: I can't see how that would interfere with this avrdude (whatever that is ...)

I read a tutorial provided by SparkFun stating that you should switch the µC in this 8-seconds-Bootloader mode. It then should accept any upload (which it doesn't ...)

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.

I think I got the timing right. I was way within the 8 seconds. Nevertheless I'll have a look to the details you provided, thank you! I'll be on a business this week but will return to this topic next week. Please have a bit of patience! Thanks!


text:
SIM800L can't send SMS
I have a SIM800L module (green board). I used this 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.
The SIM800L module (red-green-blue boards) is here.

I am using A7 board - also have the same problem.. It might be the UNO boards. Voice call works 50% time, GPS location 100%

What library are you using? check with adafruit fonaLibray

https://github.com/cristiansteib/Sim800l

I used a Power Supply 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.


text:
Arduino with stepper motor
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?

Please post your code so that others can see how it's written and provide help/advice.

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.


text:
Using Servo with External Power
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?

Did you connect the grounds of both power supplies? This has to be done, when using more than one

@chrisl, I'm only using one of the power supplies (adapter or batteries) at one time.

Can you show us your circuit? Where have you checked the voltage with the multimeter? At the supply voltage or at the PWM pin?

@chrisl, sorry to waste your time. I figured it out. I needed to run connect the negative from the external power to the GND on the Arduino. (Which I hadn't done.)

What?! you have to connect BOTH grounds together? If the power supply to the arduino is a wall wart to its dc input and the power supply to the servo is another wall wart and both wall warts are plugged in to the same wall socket, arent the neutrals ALREADY connected?

@aquagremlin, yep, it seems that you do have to. I'm no expert so I'm not sure why.


text:
Overwrite image buffer (inside Adafruit SSD1306)
I'd like to add a method that replaces the entire image buffer into the Adafruit_SSD1306 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(); :)

Do you want to copy the contents of newBuffer in buffer or rewrite buffer to be uint8_t* which you can change?

(I'm feeding the newBuffer from network and) I wan't a solution that replaces the image buffer the fastest. I don't mind making some changes in the library as long as it's easy. :)

Does copying have big overhead compared to passing the value by reference?

I've just realised that passing by reference might not work as the buffer is in a specific location in the memory, can't be elsewhere.

Even when done properly, changing the code to point to a new buffer location won't free the old buffer.  Arduinos tend to have limited RAM, so you probably want to copy the contents into the existing static allocation, not abandon a big chunk of memory.

How would copying look like?

Something like memcpy() or similar most likely.

Can you check the update please?

void * memcpy ( void * destination, const void * source, size_t num );. You exchanged the argument order in your memcpy call.. Destination must be buffer. You must of course also guarantee that newBuffer has the required length.


text:
Avrdude can't connect to butterfly programmer
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? :)

please update the second picture  so that it shows the command line (roll the screen down a bit)

@jsotola I added the whole output from Arduino in the paste.ubuntu.com link

@jsotola Thats the output from Arduino. What command line do you want to see?

go to "preferences" in the Arduino IDE .... check "show verbose output during" upload .... do an upload ..... the actual avrdude command line gets diplayed .... post that command line

@jsotola it was all the time in the output that I provided. Its in the question now as well. Dont mind the cu.usbmodem124. I changed the port during my attempts.

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


text:
LGPL and Arduino in Commercial Products
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!

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.

thanks a lot for your prompt answer! =]
"IANAL" always, but this helps a lot.
as it seems you're more used to this, would you think something like this wold be a "nice" (in that sense) and correct way to mention and clarify dependencies along a project?
https://github.com/marcosassis/gamepaduino/wiki/modules#gamepad_joystick_adapter-module

Yup, looks good to me.

This looks like a pretty good summary. I've added additional details in my answer on this other question here, and have tried to cover its various facets. I'm not sure if the question I posted my answer on is the best candidate, but it was good enough I suppose.

Actually when using LGPL libraries (which is unavoidable with Arduino) you must share at least the object code of your entire application to let users relink your application code to a different version of the libraries. This is regardless of whether you made any modifications to those libraries or not. See LGPL section 4, especially 4(d)(0).


text:
Nodemcu and NRF24L01
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);
}
}

You should probably start by validating the SPI and control connections.  Perhaps you can write a simple sketch to read an nRF24 register and print that via serial.  Do you have a scope or logic analyzer you can probe with?   At the least double check that your ESP8266 pin assignments are correct for an SPI peripheral.

you might want to look into ESPNOW, it kinda obsoletes the nrf chip...


text:
character on 16X2 LCD is not visible properly
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.

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.

then how it is working fine when i connect USB as power supply.

Different voltages.