text:
How can I run the arduino IDE 1.8.9 on debian testing as regular user?
When I start the arduino IDE as regular user from my debian testing system, I get a crash right after the splash screen:
Temp/arduino-1.8.9/arduino                                                              :)
Picked up JAVA_TOOL_OPTIONS:
java.lang.NullPointerException
        at processing.app.BaseNoGui.onBoardOrPortChange(BaseNoGui.java:679)
        at processing.app.Base.onBoardOrPortChange(Base.java:1317)
        at processing.app.Base$12.actionPerformed(Base.java:1544)
        at processing.app.Base.rebuildBoardsMenu(Base.java:1494)
        at processing.app.Base.<init>(Base.java:275)
        at processing.app.Base.main(Base.java:151)
Temp/arduino-1.8.9/arduino  7,28s user 0,50s system 183% cpu 4,243 total

When I start it with sudo I can use everything regularly. There are quite a few bug reports mainly in the archlinux community about a similar issue, where they suggest to install a package arduino-avr-core to solve it. But I assume, the reason why it happens for me, is different, since it runs fine with root privileges, and we do not have such a package in debian. Debians arduino IDE from the repos is way to old to use it these days with modern boards.
My Groups: tty uucp dialout cdrom floppy sudo audio dip video plugdev systemd-journal netdev bluetooth lpadmin scanner docker
The file permissions are fine for the ide and the arduino data directory.
The permissions for the usb device are also correct, just in case:crw-rw----+ 1 root dialout 188, 0 Mai  4 11:42 /dev/ttyUSB0
My Java environment:
java --version                                                                          :)
openjdk 11.0.3 2019-04-16
OpenJDK Runtime Environment (build 11.0.3+1-Debian-1)
OpenJDK 64-Bit Server VM (build 11.0.3+1-Debian-1, mixed mode, sharing)

Maybe someone ran into the same problem as well?

If you ran with sudo then your Arduino data directory may be locked to your user. Try deleting it. sudo rm -rf .arduino15 when in your home directory.  I am just installing a VM of debian testing to check it out.

Looking at how it runs with sudo under debain - when run with sudo it uses root's .arduino15. When run as the user it uses the user's .arduino15. So it could just be that your .arduino15 directory is screwed and deleting it will fix it.

Wow... it turned out, that I was not aware of the existence of ~/.arduino15. I tried to delete the ~/Arduino and ~/.arduino direcory several times, but to no avail. Deleting ~/.arduino15 indeed fixed the issue.

IDE version 1.5.0 changed the data directory from .arduino to .arduino15 - I guess there were changes in the content formatting for that version, and they wanted to protect earlier versions.

It turned out, that the current Arduino IDE is using a directory ~/.arduino15 for data. I was not aware of the existence of it. The comments to my question made that clear. I tried to delete the ~/Arduino and ~/.arduino direcory several times, but to no avail. Deleting ~/.arduino15 indeed fixed the issue.


text:
DHT11 data in Arduino UNO to Firebase through ESP8266
Hello Good Day to Everyone.
I have a project where I need to send DHT11 sensor data to a Firebase database using both Arduino UNO and Esp8266 esp-01 wifi module. Both of them must work together to send the data.

Arduino Code:
#include <dht.h>

dht DHT;

#define DHT11_PIN 7

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

}

void loop() {
 // put your main code here, to run repeatedly:
int chk = DHT.read11(DHT11_PIN);
Serial.print("Temperature = ");
Serial.println(DHT.temperature);
Serial.print("Humidity = ");
Serial.println(DHT.humidity);
delay(1000);

}

My arduino code is working fine. Now comes the part where I need to program the ESP8266 which I am really confused how to pass the data to the wifi module and send it to firebase. I tried to code some and this is my
ESP8266 Code:
#include <ESP8266WiFi.h>
#include <FirebaseArduino.h>
#include <DHT.h>

#define FIREBASE_HOST "test.firebaseio.com"
#define FIREBASE_AUTH "authcode"

#define WIFI_SSID "mywifi"
#define WIFI_PASSWORD "12345"

#define DHTTYPE DHT11
#define DHTPIN  7

DHT dht(DHTPIN, DHTTYPE);
float temp_f;
unsigned long previousMillis = 0;
const long interval = 2300;

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

WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.print("connecting");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
 Serial.println();
 Serial.print("connected: ");
 Serial.println(WiFi.localIP());

Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);

 }

void loop() {
delay(2000);
float h = dht.readHumidity();
float t = dht.readTemperature();
delay(50);
Firebase.setFloat("temp",t);
Firebase.setFloat("hum",h);
delay(1000);
}

I don't want my esp8266 to go stand alone. I wanted the data to come from the arduino but somehow I don't know how to receive the data from the arduino in the esp8266.
I hope someone can enlighten me..
thank you

Have you solve the problem? Im also having this problem,can share it?

did you find a solution iam waiting for one also ?

Dump the Arduino Uno and just program the ESP8266.

First of all, FirebaseArduino.h library is for ESP8266 itself and not for Arduino UNO.
The code you have written will not work as you are giving instructions like Firebase.setFloat("temp",t); to UNO. It will not compile.
What you should do is set ESP8266-01 as your primary board and let the UNO transmit the data by software serial.
ESP8266-01 will capture that data and transmit it over the Internet.
YOU CAN'T USE FirebaseArduino.h FOR ARDUINO UNO! It is for the ESP8266.
All YouTube videos will show you how to code for NodeMCU esp8266-12E. Do that for ESP-01 and communicate with Arduino for data (converting data calculated to string will help to reduce problems). Get data in form of string from UNO and transmit it using ESP-01!
If you want I can share all video list that I found useful!

source: Stack Exchange

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

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

sort: votes


text:
Using multiple sensors on ESP8266 Wifi module
I have an ESP8266 ESP-01 WiFi module.
I have a project where I need to use the following and send their data to a firebase database.
2x Force Sensitive Resistors(Sensor)
1x GPS module
My question is what GPS module can I use to send GPS location thru the ESP8266 Wifi module. My ESP-01 has only 2 GPIO. What should I do so I can use 2 FSR and GPS module at the same time send all 3 data to firebase realtime database.
Thanks

I would go for an i2c A/D converter, example ADS1015 (4 analog input, 12 bit) and connect that to the ESP-01.
Ref.:
https://en.wikipedia.org/wiki/I%C2%B2C
https://www.youtube.com/watch?v=6IAkYpmA1DQ&t=32s

Hello thank you for response. I searched this device and does this work like a 'GPIO' extension? Since ESP-01 only have 2 if I use this it will have 4 inputs? What is the connection when I use it on ESP-01?
http://www.esp8266learning.com/wp-content/uploads/2016/09/wemos-ads1015_bb.png

It has 4 GPIO, https://acrobotic.com/media/wysiwyg/products/esp8266_esp01_horizontal-01.png . And yes ADS1015 uses a i2c communication, https://en.wikipedia.org/wiki/I%C2%B2C, an universal serial buss where you can connect several devices to.

If I will use a different esp version NodeMCU V3 ESP8266 ESP-12E will it give me more GPIO slots? I checked them and found out that the ADS1015 price is closer to a new esp. What do you think? I just need enough slots for 2 FRS and 1 GPS module. Thanks

The ESP8266 chip only have one ADC (Analog input). And yes it will give you more I/O pins. So its the demand for two FRS that causes the demand for an alternative.

The ADC analog input is for the FRS or the GPS? Sorry Im really lost right now. Im trying to use this https://imgur.com/Rk67hI1 Will this be enough to power 2 FRS and a gps module? Thank you for your patience...

ADC = Analog to Digital Converter = Analog input that can measure voltage. And I assume that the FRS is analog resistors? Oh and the NodeMCU is nice, I prefer WEMOS D1, but it's quite the same

I think the NodeMCU got 1ADC and WEMOS got 11 Digital I/O pins
1 Analog Input pin which I think not enough for 2 FRS which uses ADC pins what do you suggest?

If I'm going to help you, you have to work also, not just asking! And I can't see that you give credits. So google the words "ESP8266 ADS1015 arduino"

I apologize. I guess I got too dependent on your replies and haven't done my part but thank you for still replying even though im kinda annoying. I have decided to use an Arduino UNO r3 which have 5 ADC slots and gonna use the Esp8266 esp-01 to send the data to firebase. Thank you for helping.

@Snoopy You are welcome and if you need any help in the future you are welcome, and the choice you have made is a good one. And one thing that also drive one to answer is to get credit for it :-) its the arrows to the left of the discussion.

You really need something external to both provide the analog inputs for the force sensors and the serial communication for the GPS module.
The simplest "something" is another microcontroller.  Ideally one with two UART ports.
You can then:

Communicate between the microcontroller and the GPS with one UART
Sample the FSRs with the microcontroller
Format and send the data to the ESP-01 through the other UART

Using SoftwareSerial you chould just about do it with an Arduino Uno (though you'd have to disconnect whatever was on the hardware UART every time you wanted to program it), but ideally something with more UARTs would be better, such as a Mega2560.
A halfway house between the two would be a board based around the ATMega32U2 which uses a direct USB connection for programming leaving the hardware UART free to be used permanently. However you'd still need to use SoftwareSerial to emulate the second UART (maybe best for the GPS since it's then only used for receiving).

Why not just write the sensor-handling code on the ESP8266, using an external ADC to work around the single-ADC on the ESP8266? The ESP is quite capable.

@josecanuc The chip is capable, but the ESP-01 is seriously lacking in IO pins. It has the UART pins and two GPIOs that are used to select the boot mode, so you have to be very careful with them. Best to stick to UART only.

@Majenko Thanks for the response I am still new to embedded systems and somehow i cannot understand some of it but I have an USB to TTL UART and Arduino UNO to use. My code is currently programmed in the wifi module using the GPIO2 as the sensor #1. i do not know where to plug the sensor#2 and gps module. If I plug them at the arduino or UART how will they send data since the code is inside the wifi module. I am confused Sorry im beginner

@Majenko If I will use an NodeMCU V3 ESP8266 ESP-12E instead will it be enough to run all 2sensors and 1 gps module?

Unless it has an added external ADC chip you still only get 1 ADC channel. However it is possible to add an external ADC chip to it for more channels. The GPS should be able to attach directly.

Thanks! May I know the difference between the ADC slot and GPIO slot? So I need 2 ADC slots for the FRS and the GPS will attach to the GPIO? This is the exact product im trying to buy https://imgur.com/Rk67hI1

FSRs are analog. You need to connect them to an analog (ADC) port. The GSM is UART. You need to connect it to a pair of UART pins or a pair of GPIO pins which you emulate UART on with SoftwareSerial.

I understand now thank you. Last question what ESP8266 can you suggest that has atleast 2 ADC pins for FSR and some GPIO for the GPS? There are so many too choose from and i dont know what to use best.

No ESP8266 has more than one ADC pin. You may find a board with an external ADC chip added but I don't know of one of hand. Wemos and NodeMCU are probably the boards to look at.

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


text:
Global variable won't update inside void loop arduino
I need to update my global variable once I get a 'overdtrue' response and light up my LED but only my LED is lighting up but my global variable is not updated.
Here is my code
int x = 0;

void loop() {
if (content.indexOf("ovrdtrue") > 0)
 {
  x++;
  digitalWrite(ledPin, HIGH);

 }
fsrReading = analogRead(fsrAnalogPin);
Serial.print("Analog reading = ");
Serial.println(fsrReading);
Serial.print("X: ");
Serial.println(x);
}

The x value should be 1 but only the LED has light up. Please help.

once I get a 'overdtrue' response - if (content.indexOf("ovrdtrue") > 0) - is it overdtrue or ovrdtrue?

Sorry for the confusion. it's "ovrdtrue"

My guess is that there is more to this code (which actually looks like parts from an HTTP server). Your snippet is leaving out the part that could explain this behavior. Either post a working snippet with the error or post more of the actually code.

It seems like I forgot to include an if else condition above the ovrdtrue.
if(content.indexOf("true") > 0)
{
  digitalWrite(ledPin, HIGH);

}

Arduino is reading this condition even though the data received "ovrdtrue" but this contains some word "true" so this is the one getting read and not the ovrdtrue condition. I just changed the condition variable not close to the word true and it worked fine. I'm sorry for this.

Here is my code

your code ran without setup()?
you are conditionally incrementing "x", and if your condition doesn't hold true, the increment doesn't take place.

You never set the LED pin to LOW, so it will stay lit up regardless of the global variable.

Yes I want it to stay lit at the same time change my global variable x value from 0 to 1 with the digitalWrite(ledPin, HIGH); command but somehow it's ignoring the x++; and just lights up the LED

You need to post more code. What pin is ledPin? Is ledPin ever set to output? Do you change x elsewhere? Do you change ledPin elsewhere? Is x declared elsewhere? Global variables definitely update inside loop so your problem is elsewhere.

Are you sure the LED is not lighted from the start?
It's unclear if in the Setup you set the light on or off (or it is default on or off).
Print a Serial print inside the if statement to be sure that the if block is entered, also print before the if the value of content to be sure if 'ovrdtrue' is found in the string.
Also, since you want the LED on in this situation, explicitly set it off in the setup.

the LED are not lighted from the start. I think it has found the "ovrdtrue" because it is lighting the LED with the HIGH during the if and that's ok but my problem is why is it ignoring the x++ and not updating my global variable inside the if.


text:
Shall an active piezo buzzer module draw as much as 10mA on its signal pin?
I have connected an active piezo buzzer to my arduino: KY-012 Active buzzer module.
I was a bit surprised that it drew like ~10mA on the signal pin from my nodemcu, which I find a bit weird, since the signal generator itself is powered separately. Even if 10mA is in spec of the GPIO pins I wonder if that much current is considered a normal amount to expect.
The module draws an additional ~10mA from the power supply line.
Has probably someone the possibility to provide comparable measurements?

For what it's worth: https://arduinomodules.info/ky-012-active-buzzer-module/   ... it has 3 pins, but the middle pin is not even connected and the max current is 30 mA (which is within absolute max current limits of an Arduino GPIO but not 'recommended'.

The middle pin must be connected somehow. It draws a current, when the S pin is connected to VCC. But it is correct, that even when unconnected, the module produces a sound.... weird.

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


text:
What do I do with the potentiometer on Adafruit RGB LCD
So I just got my Adafruit RGB backlight positive LCD 16x2 + extras - black on RGB In this picture it shows a potentiometer beside the LCD. Anyone know where this is supposed to go?

If it helps, I'm mounting the shields on an Adafruit I2C Controlled + Keypad Shield Kit for 16x2 LCD

It goes the same place as for any other LCD. Just because the backlight is an RGB LED doesn't change how the LCD functions.

It's the same pot (functionally) as the orange one in the shield kit.

The potentiometer is for setting the contrast level of the LCD. The Shield Kit shown also comes with a pot (the one with the orange face). Assembled it should look like this:

Notice the pot in the lower right corner to the right of the microcontroller ic and above the reset button.

The contrast is set by inputting an analog voltage into Pin 3 on the LCD header. The analog voltage is created using the potentiometer and is easily adjusted by the user when in operation.
The diagram below shows (only) the circuit needed to adjust the contrast on the LCD display.


text:
What is the meaning of [type]* for arrays?
I've seen * used with arrays in some programs but not in others. The page on arrays doesn't mention it at all, but I often see it near functions when values are being passed.
Where would I find more information on this?

There are several possible usages, each with its own meaning, so you are going to have to ask about a specific example.  One possibility is the fact that you can have an array of pointers, a pointer to an array, etc, but there is also the related fact that that arrays readily and gracefully degrade to pointers.

Ok! Looks like I was talking about pointers Time to learn today

You are asking about Pointers -
 https://www.tutorialspoint.com/cprogramming/c_pointers.htm.


text:
Disable Reset when Com Port Connected/Disconnected
I've noticed that when I open and close the com port my Arduino is connected to, the device resets. This makes the program run the setup profile again and it loses the previous variable states. Is there any way to prevent this?

If you review the Uno schematic, you can see the circuitry that enables an automatic reset when serial communication starts.  The circuitry is intended to allow easy program downloading.
There are two or three ways to prevent that reset:  add a 10 μF capacitor from ground to reset;  use a much-lower resistance for the pullup on reset; cut a trace from the serial-interface pin (eg CTS) that pulls reset.
The first method is relatively easy to implement, and easy to remove whenever you want to install a new program.
References:  Disabling AutoReset On SerialConnection and ArduinoISP on Uno requires 10uF cap -- WHY?, both at Arduino.cc.


text:
delay(time); vs if(millis()-previous>time); and drift
Going through an old project, I had code on two Arduino Due that looked like this
void loop()
{
  foo();
  delay(time);
}

taking to heart the majority of literature on using delay(); I recoded this as
void loop()
{
  static unsigned long PrevTime;
  if(millis()-PrevTime>time)
  {
    foo();
    PrevTime=millis();
  }
}

However, this seems to have created a situation where the two devices drift over a period of time when they didn't previously
My question is twofold:

Why would if(millis()-PrevTime>time) cause more drift than
    delay(time)?
Is there a way to prevent this drift without going back to delay(time)?

What is the order of magnitude of "period of time" over which you notice the drift? Are the two devices in the same location, thus at the same temperature? Are they run on a crystal oscillator or a ceramic resonator?

Personally I prefer Majenko's solution, and always use it (I put the incrementing before the other instructions, but this is just a preference). Note, however, that this timing is PRECISELY 100ms, while the other code (foo; delay;) has a period longer than 100ms (it is 100ms + time of foo). So you will experience drift (but it is the delay-implemented SW which is drifting). In any case, keep in mind that even perfectly equal implementations "drift", because clocks are not equal; if you need complete synchronization use a signal to, well, synchronize the two programs.

The two devices are next to each other, after running from Friday at 17:00 to Monday at 9:00 there was a 4 min drift.
I'm deciding that I'm going to use a digital pin to synchronize the inputs as per your suggestion

"The two devices are next to each other, ..." that doesn't mean the timing mechanism is not accurate you are talking about an error rate of ~800ppm, high for two crystal oscillators but reasonable for even one ceramic resonator. you have to compare it vs. a reasonably accurate timing standard to be sure: crystals are typically within 20ppm, and tcxo's can do sub 1ppm. that would be my way of doing it.

There's one important thing that you need to remember when working with time on an Arudino of any form:

Every operation takes time.

Your foo() function will take an amount of time. What that time is, we cannot say.
The most reliable way of dealing with time is to only rely on the time for triggering, not for working out when the next triggering should be.
For instance, take the following:
if (millis() - last > interval) {
    doSomething();
    last = millis();
}

The variable last will be the time the routine triggered *plus the time doSomething took to run. So say interval is 100, and doSomething takes 10ms to run, you will get triggerings at 101ms, 212ms, 323ms, etc. Not the 100ms you were expecting.
So one thing you can do is to always use the same time regardless by remembering it at once specific point (as Juraj suggests):
uint32_t time = millis();

if (time - last > interval) {
    doSomething();
    last = time;
}

Now the time that doSomething() takes will have no effect on anything. So you will get triggerings at 101ms, 202ms, 303ms, etc. Still not quite the 100ms you wanted - because you're looking for more that 100ms having passed - and that means 101ms or more.  Instead you should use >=:
uint32_t time = millis();

if (time - last >= interval) {
    doSomething();
    last = time;
}

Now, assuming that nothing else happens in your loop you get triggerings at 100ms, 200ms, 300ms, etc.  But note that bit: "as long as nothing else happens in your loop"...
What happens if an operation that takes 5ms happens to occur at 99ms...? Your next triggering will be delayed until 104ms. That's a drift. But it's easy to combat. Instead of saying "The recorded time is now" you say "The recorded time is 100ms later than it was". That means that no matter what delays you get in your code your triggering will always be at 100ms intervals, or drift within a 100ms tick.
if (millis() - last >= interval) {
    doSomething();
    last += interval;
}

Now you will get triggerings at 100ms, 200ms, 300ms, etc. Or if there are delays in other bits of code you may get 100ms, 204ms, 300ms, 408ms, 503ms, 600ms, etc.  It always tries to run it as close to the interval as possible regardless of delays.  And if you have delays that are greater than the interval it will automatically run your routine enough times to catch up with the current time.
Before you had drift. Now you have jitter.

Because you reset the timer after the operation.
static unsigned long PrevTime=millis();

unsigned long t = millis();

if (t - PrevTime > time) {
    foo();
    PrevTime = t;
}

no. notice that PrevTime is static.

@dannyf, yes, and?

if you knew what "static" means, you would know why your answer isn't correct.

I know what static does with local variable.. I do not understand why you think my answer has something to do with the static. I just moved the current millis reading before foo() is invoked.

For what you are trying to do, delay() is the appropriate way to implement the code. The reason you would want to use the if(millis()) is if you want to allow the main loop to continue to loop so your code or some other code outside of that loop can do other processing.
For example:
long next_trigger_time = 0L;
long interval = DESIRED_INTERVAL;

void loop() {
   do_something(); // check a sensor or value set by an interrupt
   long m = millis();
   if (m >= next_trigger_time) {
       next_trigger_time = m + interval;
       foo();
   }
}

This would run foo() on the specified interval while allowing the loop to continue to run in between. I put the calculation of next_trigger_time before the call to foo() to help minimize the drift, but it is inevitable. If drift is a significant concern, use an interrupt timer or some sort of clock/timer synchronization. Also remember that millis() will wrap around after some period of time and I didn't account for that to keep the code example simple.

I already mentioned the rollover issue at the end of my answer.

My standard consulting fee $100/hr if you want me to write code for you. I think what I have written is a sufficiently relevant.

Then vote for his answer if you like it better.

I fail to see the point in posting a deficient solution when a good one has already been accepted. Majenko's solution doesn't suffer from the rollover problem, and it shows that the drift is not “inevitable”, but rather very easy to avoid. This answer provides no added value.

@EdgarBonet, Majenko's solution doesn't discuss why you might choose to not use delay() even if it does cause drift. My code example was meant to highlight that, not provide a "complete" solution. So my answer does add value to the discussion, but I guess you didn't actually read my answer either.


text:
Unreliable serial communication from Arduino Mega
I'm using an Arduino Mega to send serial commands to a device that supports RS485 or RS422 half-duplex. To do this, I'm using the following code:
bool foo(int A, int B)
//...
//Const global int to byte 1&2
//Math on int A and int B to make bytes 3-8
//...
  unsigned char cmd[8]={[byte1],[byte2],[byte3],[byte4],[byte5],[byte6],[byte7],[byte8]};
  while(rep)
  {
    for (int i=0; i< 8; i++)
    {
      Serial2.write(cmd[i]);   // Send C string
    }
    if(Serial2.available())
    {
      //device echoed == command recieved
      rep=false;
    }
  }

The odd thing is that sometimes the loop gets it right on the first try, other times it takes 50+ tries to receive a command. This makes me think that there is something in my code that is making the data transmission unreliable. I believe it could be one of the following three things.

I still need an RS485 module

In a previous version of my software, I was using the software serial library and used an RS485 module similar to the one shown here:

As I'm no longer using the software serial library and instead using the Mega's Serial2 port, I thought I could get rid of the module. Is this incorrect? If so, why would the commands work after N attempts as opposed to never working at all?

Looping the Serial2.write()

Previously, while using the above module, I had to have two lines of code that would shift the DE and RE pins high or low depending on if I was sending or receiving data. I realized that these needed to be outside the for (int i=0; i< 8; i++) loop as otherwise, the device would not be able to read/understand the data being passed. Do I need to reimplement some version of this with the Arduino Mega's native serial? If so, how would I do this?

I'm Not supporting a tri-state the transmit buffer

I was rereading the device's manual and found this line:

The converter must have the hardware and software support to tri-state the transmit buffer following the message transmission.

Honestly, I have no idea what this means. Does Arduino do this? If not, how can I make this happen?

Additional things of note:

I'd much rather use something like Majenko's pointer way to send data to my device so that I could make the code not rely on the fact that there are always 8 bytes transmitted. However, sometimes a byte will be \0 (or any other termchar) which would stop the loop prematurely. Is there a way to avoid this?
I'm still pretty new here, Is there some way that I can do this better than the way I'm currently doing it?

As I'm no longer using the software serial library and instead using the Mega's Serial2 port, I thought I could get rid of the module. Is this incorrect? If so, why would the commands work after N attempts as opposed to never working at all?

You still need the module. RS-485 and RS-422 are electrically incompatible with CMOS.

Previously, while using the above module, I had to have two lines of code that would shift the DE and RE pins high or low depending on if I was sending or receiving data. I realized that these needed to be outside the for (int i=0; i< 8; i++) loop as otherwise, the device would not be able to read/understand the data being passed. Do I need to reimplement some version of this with the Arduino Mega's native serial? If so, how would I do this?

Absolutely. Also you need to flush the serial after transmitting and switching back to receiving:
digitalWrite(DE_PIN, HIGH);
Serial2.write(cmd, 8);
Serial2.flush();
digitalWrite(DE_PIN, LOW);

Flushing the serial pauses your program until the entire command has been transmitted. That means not only sent from the TX buffer to the TX FIFO in the UART hardware, but also the last byte from the FIFO has been shifted out onto the wire. If you don't do that your command will get truncated by the transceiver module as you switch back to receive mode prematurely.
Note: I forget which is which for the DE pin - HIGH/LOW or LOW/HIGH. Change it appropriately. Also note that you don't need to manually loop - the Serial code already has that facility for you.

The converter must have the hardware and software support to tri-state the transmit buffer following the message transmission.

That is what the DE/RE pins do - switch the module between active drive (transmit) and high-impedance (receive).

I'd much rather use something like Majenko's pointer way to send data to my device so that I could make the code not rely on the fact that there are always 8 bytes transmitted. However, sometimes a byte will be \0 (or any other termchar) which would stop the loop prematurely. Is there a way to avoid this?

That is only applicable with strings. With binary data you always have to know the length (though that doesn't have to be hard coded). All you need is a maximum length for any buffers you have.

I'm still pretty new here, Is there some way that I can do this better than the way I'm currently doing it?

Besides my notes above, this method:
while(rep)
{
  for (int i=0; i< 8; i++)
  {
    Serial2.write(cmd[i]);   // Send C string
  }
  if(Serial2.available())
  {
    //device echoed == command recieved
    rep=false;
  }
}

is completely wrong. You are sending a command and then immediately looking for a response. You haven't given that response time to either be generated by the remote end or be received by the Mega.
Instead it should be:

Send the command.
Look for some response data
If some data has arrived then add it to the response buffer
If the whole response has not yet arrived go back to 2

You can also add 2.5: if it's been checking too long then abort with a "timeout".

Ok, I'll add the module back in. If they're electrically incompatible, any idea why it works sometimes? Is this the CS equlivlant to a stopped clock being right twice per day?

@ATE-ENGE Pretty much ;) Without the module you're connecting a differential pair to a single-ended TX / RX pair. The module is needed to convert single ended into differential and back again.


text:
Passing a NeoPixel object reference to a custom library
I'm new to Arduino programming and haven't programmed in C++ in the past. I'm trying to create a custom library to cycle a rainbow on my NeoPixel LED strip. I want to pass a reference or pointer or whatever into the library class so I can keep the code in my project file as simple as possible.
Here is my current project code:
#include <YaNeoPixelCycle.h>
#include <Adafruit_NeoPixel.h>

#define CONTROL_PIN 3
#define LED_COUNT 8
Adafruit_NeoPixel neoPixel(LED_COUNT, CONTROL_PIN, NEO_RGBW + NEO_KHZ800);
YaNeoPixelCycle cycle = YaNeoPixelCycle(neoPixel,255,100,200);

void setup() {
}

void loop() {
  cycle.tryStep();
}

And here is the library I tried to create:
/*
    Youkai's Artificery NeoPixel cycle library.
    A super basic RGB LED cycle.
*/

#ifndef YaNeoPixelCycle_h
#define YaNeoPixelCycle_h

#include "Arduino.h"
#include <Adafruit_NeoPixel.h>

class YaNeoPixelCycle{
    public:
        YaNeoPixelCycle(Adafruit_NeoPixel& neoPixel, int saturation, int brightness, int hueStep);
        void tryStep();
    private:
        Adafruit_NeoPixel& _neoPixel;
        unsigned int _ledHue = 0;
        int _saturation;
        int _brightness;
        int _hueStep;
};

#endif

/*
    Youkai's Artificery timer library.
    Some basic non-blocking timer functions.
*/

#include "Arduino.h"
#include "YaNeoPixelCycle.h"

YaNeoPixelCycle::YaNeoPixelCycle(Adafruit_NeoPixel& neoPixel, int saturation, int brightness, int hueStep){
    _neoPixel = neoPixel;
    _saturation = saturation;
    _brightness = brightness;
    _hueStep = hueStep;
    _neoPixel.begin();
    _neoPixel.show();
}

void YaNeoPixelCycle::tryStep(){
    _ledHue += _hueStep;
    _neoPixel.fill(_neoPixel.ColorHSV(_ledHue, _saturation, _brightness));
    _neoPixel.show();
}

The first step would be getting this to function at all. Uploading this to my Sparkfun ProMicro bricks it and I have to reset it to upload code again.
After that it would be awesome if it was possible to declare the NeoPixel in the project file but not actually initialize it until the library file. I'd love to pass CONTROL_PIN and LED_COUNT as variables to the library with YaNeoPixelCycle(..., int controlPin, int ledCount) so I don't have to set up a bunch of duplicate variables in my main file if I'm running more than one NeoPixel strip.
This is my own custom library so I'm not too worried about it being obscure. If it's possible/easier I would be fine just moving all of the NeoPixel code entirely into the library and never creating it at all in the main file. Just passing the control pin and LED count as parameters and having to "know" that those refer to a NeoPixel would be fine too.

If you want to initialize it in the library, why do you need an instance of NeoPixel, that is external to the library? You could simply put the complete declaration of it into the library. I currently don't see your problem

I wasn't thinking originally of declaring it in the library. But if that works it would be fine too.

Yes, it works. You can simply have it only there

You call _neoPixel.begin() and _neoPixel.show() in the constructor of your class. This constructor runs before the Arduino is initialized. This is why   begin() functions are used. Add a begin() function to your class and call cycle.begin() in setup().
void YaNeoPixelCycle::begin() {
  _neoPixel.begin();
  _neoPixel.show();
}

Of course remove the _neoPixel.begin() and _neoPixel.show() from the constructor.

This helped. I also needed to apparently use a "member initializer list" instead of doing the assignment in the constructor. I guess my NeoPixel object wasn't getting set properly the way I was doing it above.

Thanks for this!  I also had my members being set in the ctor which didn't work.  I was going crazy trying to figure out why it didn't work.  Switched to member initializer list and it's working fine now.


text:
What is wrong with my code? RGB potentiometer
Arduino programming has been a huge learning curve for me and I am trying to create a project with an rgb that's color is determined by a potentiometer. To where the further I turn it, the further across the rainbow spectrum it goes. I can't figure out how to do all values in between because I am not educated enough but I came up with this basic code...
int redpin = 6;
int greenpin = 3;
int bluepin = 5;
int potPin = 0;

void setup() {
  // put your setup code here, to run once:
  pinMode(redpin, OUTPUT);
  pinMode(bluepin, OUTPUT);
  pinMode(greenpin, OUTPUT);
  pinMode(potPin, INPUT);
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  int wavecolor = analogRead(potPin);
  Serial.print(wavecolor);
  {
    if (wavecolor = 0) {
      setColor(255, 0, 0);  // red
    }
    if (wavecolor > 0 or wavecolor < 333) {
      setColor(0, 255, 0);  // green
    }
    if (wavecolor > 333 or wavecolor < 667) {
      setColor(0, 0, 255);  // blue
    }
    if (wavecolor > 667 or wavecolor < 1022) {
      setColor(255, 255, 0);  // yellow
    }
    if (wavecolor = 1023) {
      setColor(80, 0, 80);  // purple
    }
  }
}

void setColor(int red, int green, int blue)
{
#ifdef COMMON_ANODE
  red = 255 - red;
  green = 255 - green;
  blue = 255 - blue;
#endif
  analogWrite(redpin, red);
  analogWrite(greenpin, green);
  analogWrite(bluepin, blue);
}

And for some reason, where the light should change colors once the potentiometer goes past a certain number, the light just flickers and only changes colors to white when it is all the way up or down. Also, it has a weird flickery yellow color.
Since I am new to this, can one of you better educated people be willing to assist me?

think about this .... what will happen if you set the potentiometer to 333?

Equality comparison in C and C++ is expressed by == operator. ==, not =. This
if (wavecolor = 0) {

actually assigns zero to your wavecolor variable, thus destroying the value you just read.
The common sense says that you actually need and in your conditions, not or
if (wavecolor > 0 and wavecolor < 333) {

The or conditions that you curently use are simply always true, which makes them nonsensical.
This is valid syntax
wavecolor > 0 or wavecolor < 333
wavecolor > 0 and wavecolor < 333

but you might want to try using more "canonical" forms
wavecolor > 0 || wavecolor < 333
wavecolor > 0 && wavecolor < 333

or and and are "alternative" forms of || and && operators, introduced a long time ago for reasons that are all but obsolete today.
Assuming that you meant and instead of or, in your conditions you managed to "exclude" such values as 333, 667 and 1022 - they wouldn't match any of and conditions. Changing some strict comparisons to non-strict ones might be in order.
As a side note, in a single-file program all file-scope variables should be either const or static. In your case
const int redpin = 6;
const int greenpin = 3;
const int bluepin = 5;
const int potPin = 0;

"should be either const or static", saves a few bytes of SRAM too, can come in handy in big programs with lots of variable data.

Stylistic point: I prefer to write my conditions to look like ranges (in languages that don't have ranges built in), so 0 < wavecolor and wavecolor < 333 rather than wavecolor > 0 and wavecolor < 333

@Alexander: It makes perfect formal sense. But in practice it doesn't always work as well as one might expect. It clashes with another natural principle: express comparisons as "variable vs. limit" in that specific order, since that is how we usually express them in natural language. Which approach will win in the end is a matter of personal preference.

@AnT Yeah, it's certainly contentious, but I have 3 reasons I prefer it: 1) It "looks" like a range, 2) The operands are ordered from least on the left to greatest on the right (which is usually how things are ordered, e.g. the x axis on a graph)

Try this code below. This will give you the desired output!
int redpin = 6;
int greenpin = 3;
int bluepin = 5;
int potPin = 0;

void setup() {
  // put your setup code here, to run once:
  pinMode(redpin, OUTPUT);
  pinMode(bluepin, OUTPUT);
  pinMode(greenpin, OUTPUT);
  pinMode(potPin, INPUT);
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  int wavecolor = analogRead(potPin);
  Serial.print(wavecolor);
  {
    if (wavecolor == 0) {
      setColor(255, 0, 0);  // red
    }
    else if (wavecolor > 0 && wavecolor < 333) {
      setColor(0, 255, 0);  // green
    }
    else if (wavecolor >= 333 && wavecolor < 667) {
      setColor(0, 0, 255);  // blue
    }
    else if (wavecolor >= 667 && wavecolor < 1022) {
      setColor(255, 255, 0);  // yellow
    }
    else if (wavecolor >= 1022) {
      setColor(80, 0, 80);  // purple
    }
  }
}

void setColor(int red, int green, int blue)
{
#ifdef COMMON_ANODE
  red = 255 - red;
  green = 255 - green;
  blue = 255 - blue;
#endif
  analogWrite(redpin, red);
  analogWrite(greenpin, green);
  analogWrite(bluepin, blue);
}

Read up on logical and relational operators in Arduino (||, &&, >, <, ==, >=, <=) etc.
 I will leave the logic development to you as it is what develops your coding ability and trust me logic is the most important and fun part of writing a code!


text:
UDP Packet not receiving
I started a project where I wanted to send sensor data from one arduino to another and let this 2nd Arduino send the data to a tablet to visualize sensordata like speed, temperature etc.
I wanted to send this in intervalls so UDP would be my way to go. I used the sketches which were provided from the Arduino software which worked well for a while. But after relocating to a new place it doesn't seem to work and I do not know why - I readjusted IP's, Ports and resetted my router.
This is my UDPWrite
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.h>
#include "dht.h"
#define dht_apin A0 // Analog Pin sensor is connected to
dht DHT;
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192, 168, 1, 178);
IPAddress IP_Remote(192, 168, 1, 177);
IPAddress Port_Remote(8887);

unsigned int localPort = 8887;      // local port to listen on

// An EthernetUDP instance to let us send and receive packets over UDP

EthernetUDP Udp;

void setup() {

  // start the Ethernet and UDP:
  Serial.begin(9600);
  Ethernet.begin(mac,ip);

  Udp.begin(localPort);

  Serial.println(Ethernet.localIP());

}

void loop() {

  DHT.read11(dht_apin);

  Udp.beginPacket(IP_Remote, Port_Remote);
    Udp.write("hello");
    Udp.write("Current humidity");
    Udp.endPacket();

         Serial.println("Test");

    delay(2000);//Wait 2 seconds before accessing sensor again.

}

This is my UDPRead
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.h>

// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192, 168, 1, 177);

unsigned int localPort = 8887;      // local port to listen on

// An EthernetUDP instance to let us send and receive packets over UDP
EthernetUDP Udp;

char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; //buffer to hold incoming packet,

void setup() {
  // start the Ethernet and UDP:

  Serial.begin(9600);
  Ethernet.begin(mac,ip);
  Udp.begin(localPort);
  Serial.print(Ethernet.localIP());
}

void loop() {

  int packetSize = Udp.parsePacket();
  if(packetSize)
  {
      Serial.println("Test");
Serial.print("Received packet of size ");
    Serial.println(packetSize);
    Serial.print("From ");
    IPAddress remote = Udp.remoteIP();
    for (int i =0; i < 4; i++)
    {
      Serial.print(remote[i], DEC);
      if (i < 3)
      {
        Serial.print("Test");
      }
    }
    Serial.print(", port ");
    Serial.println(Udp.remotePort());

    // read the packet into packetBufffer
    Udp.read(packetBuffer,UDP_TX_PACKET_MAX_SIZE);
    Serial.println("Contents:");
    Serial.println(packetBuffer);
}
}

This is what Wirehsark shows:

eceived.
The Arduinos are connected to my Switch Port5 and Port6 which are mirrored to Port8 to which I am connected via Notebook.
After a few tests, I do not seem to get into my
int packetSize = Udp.parsePacket();

if(packetSize) {

statement for a reason I cannot yet grasp. Udp.parsePacket should receive the UDP package from 192.168.1.178
I can Ping the .178 but not the .177.
I changed cables, ports, IPs, Switch and even the Arduinos. So I would think that the problem is code based.
Thank you very much for your help.

not the cause, but: 1) you can print the IPAddress with Serial.print(ip). 2) why do you have Udp.begin() on reader. it starts listening

if you can't ping the board, the shield is not connected to the network. run some of the example sketches of the Ethernet 2.00 library. for example the WebClient example

Change local port to 8080, other ports are not generally available for local network communication.

@Vaibhav - Well I'll be damned, it works now. I assure you, it has worked before with the ports I have assigned and I even switched ports. But 8080 works. Thank you very much

what could block the port? the router? between two local devices? I don't believe it

@Juraj - No, I do not either. But it works after changing the port. I changed it back for testing reasons and it didn't work anymore.


text:
Arduino Sensor Values to Raspberry Pi using NRF24
Im trying to send temperature sensor data through NRF24L01 to Raspberry Pi and read it in Raspberry Pi using python. But the temperature sensor data comes to the Raspberry Pi as letters, which I found out is in Ascii values. Im not sure how to display the actual readings from the Arduino to the Raspberry Pi
Here is the Arduino code:
#include <DallasTemperature.h>
#include <OneWire.h>
#include <SPI.h>
#include <RF24.h>
#include "printf.h"
#define ONE_WIRE_BUS 2

OneWire oneWire (ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

RF24 radio(9, 10);

void setup(void) {

  Serial.begin(9600);
  sensors.begin();
  radio.begin() ;
  radio.setPALevel(RF24_PA_MAX) ;
  radio.setChannel(0x76) ;
  radio.openWritingPipe(0xF0F0F0F0E1LL) ;
  radio.enableDynamicPayloads() ;
  radio.powerUp() ;
}

void loop(void) {
  sensors.requestTemperatures();
  float temperature = sensors.getTempFByIndex(0);
  radio.write(&temperature, sizeof(float));
  delay(1000);
  Serial.print(sensors.getTempFByIndex(0));
}

Here is the code for Raspberry Pi in Python
from lib_nrf24 import NRF24
import time
import spidev

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
pipes = [[0xE8, 0xE8, 0xF0, 0xF0, 0xE1], [0xF0, 0xF0, 0xF0, 0xF0, 0xE1]]

radio = NRF24(GPIO, spidev.SpiDev())
radio.begin(0, 17)

radio.setPayloadSize(32)
radio.setChannel(0x76)
radio.setDataRate(NRF24.BR_1MBPS)
radio.setPALevel(NRF24.PA_MIN)

radio.setAutoAck(True)
radio.enableDynamicPayloads()
radio.enableAckPayload()

radio.openReadingPipe(1, pipes[1])
radio.printDetails()
radio.startListening()

while True:

    while not radio.available(0):
        time.sleep(1/100)

    receivedMessage = []
    radio.read(receivedMessage, radio.getDynamicPayloadSize())
    print("Received: {}".format(receivedMessage))

    print("Translating...")
    string = ""

    for n in receivedMessage:
        if (n >= 32 and n <= 126):
            string += chr(n)
    print("Our received message decodes to: {}".format(string))

I want to get the temperature value in numbers instead of letters. Instead of like this:
Translating ... Our received message decodes to: N

why are you asking a python question at an arduino site? ... arduino does not run python

Im trying to see if there is a way to modify the Arduino's code to get the sensor values as a string so that it can be read by rpi


text:
Connect MPU6050 in pins other than A4 & A5
I need to use a MPU6050 gyro and a Ultrasonic sensor for my project. My Arduino Uno did not come with separate SDA and SCL pins, so I have to use the A4 and A5 pins for that purpose, and I have connected the Ultrasonic sensor with them.
\With no SDA and SCL pins available, and A4 and A5 already occupied, is there any way to use other pins like A0 and A1 for SDA and SCL connections?

Have you seen the software I2C library here?

Why not move the ultrasonic to other pins? BTW: SCL/SDA and A4/A5 are physically the same pins - you can't use both at once.

Your Uno did not come with seperate SDA and SCL pins, because on the microcontroller, that is used on the Uno (Atmega328p) these pins are shared too. That is a common practice, because not everyone needs I2C, but may want more analog pins.
You have basically 2 ways to go here:

You can leave the ultrasonic sensor, where it is connected now, and try it with a software I2C library like this one, that can be used on nearly any other pin pair. Note, that in this case the I2C protocol will be completely handled in software, which puts a bigger workload on the microcontroller and may need other resources, that you want to use later (for example it might use timer hardware).
You can put the ultrasonic sensor to other pins, because it is not limited anyway. You can use any digital pin pair. The MPU can then be connected to A4 and A5, as they are the pins of the hardware I2C interface. IMO this is the cleaner solution, since the core of the I2C protocol will be handled in hardware without the code doing anything for it. The code just puts the data into a buffer, not more. Also it will not use any other hardware inside of the microcontroller.

Which of these options is the best here is up to you. Maybe you have a good reason to not move the ultrasonic sensor to other pins.

Uh oops: The LCD with I2C is connected to the A4 and A5, not the ultrasonic sensor. So I guess I'll have to go with the first one?

You can connect multiple devices to the same I2C bus. It is a bus and every device has an address.

A4/A5 are the I2C Bus. You will connect multiple I2C devices in parallel to the pins. I would suggest wiring them Uno to device to device, with pullup resistors 3.3K or 4.7K pullup resistors to Vcc on the last device.


text:
How to use I2C library
My A4 and A5 pins are already hooked up to a LCD and I want to connect a MPU6050 as well. In a separate thread, someone told me to use SoftI2CMaster library to use other pins as SDA ans SCL. But I don't quite know how to do that. I want to use A2 and A3 for I2C, and a code snippet would be very helpful.

Are there no examples in the SoftI2CMaster library?

I tried following them, but got a lot of errors, a lot of them

in previous question it was ultrasonic sensor on A4 and A5. now it is LCD. has the LCD I2C interface? I2C is a bus. you can wire more I2C devices to the I2C pins

Yeah the LCD's got I2C. Tried wiring them like that, didn't work.

Oh and yeah, my bad. Wrote ultrasonic sensor by mistake : /

got a lot of errors, a lot of them ... are we supposed to guess what they were?

You really should use the hardware I2C bus on A4 and A5 for both devices. Describe exactly, how it didn't work when you tried. Provide a schematic or wiring diagram and show us your code. Then we will look, if we can spot the problem.

please post your code

Ya, I will jump on the bandwagon and say again that I2C is a bus, it is designed to handle multiple devices.  Work on getting it to work correctly rather then hoping that bitbanging it with software is going to work.

If you are not using PULL UP in your SCL SDA lines please use them as I2C lines are open drain by default.

Use both devices on I2C, with different addresses.  Hook it up like this

And call each transmission with a different address
void setup() {
  Wire.begin();                           //begin the wire comunication
  Wire.beginTransmission(0x68);

Image and snippet from electronoob's very complete tutorial


text:
Update custom library
I've recently made a custom library. Then, I've imported the library into the IDE via the add .zip library. Once I tried to compile the code, I've realised that I made a small typo. Once I changed the error and then retried to compile the code, the error still appeirs and I'm quite sure that I've changed it.
So my guess is that the library is not updating. I've tried to go to manage library and then seeing if there is an other version of the library. There wasn't any.
So is there an easy fix to this solution that doesn't involve updating or downgrading the IDE?

I've never used that option but normally you just need to delete the compiled files in the library.  So assuming they aren't in the zip file, are they somewhere in you profile's temp directory?

I actually found this answer on Stack Overflow.

In the Arduino GUI on windows, if I click on Sketch --> Import Library, at the bottom of the menu there is a section called "Contributed".
Unfortunately, I had misclicked and added a library I did not want to that list.
How can I remove it from that list?
The help page only mentions that "If a sketch no longer needs a library, simply delete its #include statements from the top of your code" but it does not mention how to remove the library from the list of contributed libraries.

By : @merlin2011 from Stack Overflow.

Text from here says this:

In Arduino v16 and earlier, libraries were stored in the
  ArduinoInstallDirectory/hardware/libraries folder, which also
  contained all the built-in libraries (like Wire and Serial).
In v17 and up, the user libraries are now stored in the
  ArduinoSketchDirectory/libraries folder.

Check your version of the Arduino SDK and then look in the appropriate directory for your library source code.  Then change it there.
The Arduino SDK is fairly simple and often compiles everything to avoid problems like this.  The installing from a zip file feature (unless it has changed) is more for convenience when downloading a single zip file.  I have often developed & edited custom library source code where the SDK expects to find it.

Thanks, but I'm using the IDE from Arduino.cc and not the one from Arduino.org.

If you could elaborate what difference that would make I would appreciate it.  I would learn something and possibly make the answer better.

Also, you might check the time stamp on your source files to make sure they are newer than the compiled files.

I there is no real difference except that the .org version is all orange compared to the more user friendly .cc. No real diferrences. 1.7 is the latest of .org. I believe and it hasn't changed much. .cc` on the other hand has regular IDE updates. Heck, one just got released around 2 weeks ago. Its IDE version 1.6.13.


text:
MPU-6050 - angle drift
Setup

Windows 7 Entreprise
MPU-6050 : GY-521 breakout
Arduino Nano (chinese) with CH340 FTDI driver
Arduino IDE 1.6.12
Library for the gyro

Problem
When I run my code, the MPU will detect the angles at a good enough accuracy, but when I leave it on the table, the MPU starts drifting. Its not anything major, yet, but on something like a rocket guidance system, these values can srew up many things.

Actual questions

Is this a common problem?
Why is this happening?
What is the best way to solve it?

Note
I'll include the code if you guys really need it, but I doubt its the problem because multiple codes have had the same problem.
Please do not recommend any other gyros.

Related question: What is the difference between Accelerometer, Gyro, and Magnetometer Sensor?

Drift/rotation around the z-axis?

@Gerben, all axes actually, thats wty its a huge problem :(

You can use the accelerometer to compensate. As on earth there is always a 1g acceleration straight down (i.e. gravity). I found the data you get from the MPU to be quite stable. Only the rotation in the Z axis can drift a bit.

@Gerben, on a rocket, you can only afford a minimum amount of mistakes..... Don't want the rocket to go where it ain't suppose to go.

I was using MPU6050 Arduino library implemented by tockn and having big drifting problems. I realized these were caused by a delay I had inserted in the loop. I suppose the implementation use some sort of integration to have the values and delay causes misfunctionality.

Is this a common problem?

Yes it is. The drift is a common problem.

Why is this happening?

The drift results, in general, from the fact that to calculate the angles it is made an integration. The errors and noises present in the inicial variable before integration (in this case angular velocity) will be "summed" over time.
For simplicity, let's say your gyro is perfect with noise free but it has a small offset , and lets considere only rotation in one axis, meaning:
Ang_Velocity(x) = Real_Ang_Velocity(x) + offset_x

if this was the case, the sensor standing still should output only:
Ang_Velocity(x) = 0 + offset_x

now using the integral over time results in an output of:
Angle(x) = int[Ang_velocity(x)] = offset_x * t

For example note that using a simple 0.01 offset over axis x, causes the sensor to output 1rad angle after 100 seconds and in fact the sensor didn't move at all.
Taking this as example the sources of errors I'm aware of are:

offset: already talked
scale factor:  is the relation between input and output
scale factor linearity: sometimes the scale factor at slow speeds are not the same as speed increases.
temperature: (not 100% sure!) this changes the sensitivities of axis. Majority of digital sensores already come with an integrated temperature sensor. If not auto compensated, there will be probably information on the datasheet to guide you how to compensate for this. If your application will not take high temperature variations, it is common sense to let the sensor achieve thermal internal stability and then do a simple calibration.
Random Walk: This is probably the hardest to process. In general is assumed that the noise is a normal distribution with mean of zero and a certain variance (white noise). If that was true, the integral over time, as time increases would go to zero (because the mean is zero). However, the noise is usually not evenly distributed in the spectrum, causing the integral to not tend to zero (Brownian noise).

way to solve it?

The first two are simple using calibration. You must do a series of tests at diferent rotation speeds to determining the non-linearities, offsets (at zero speed) and scales factors for each axis.
Then your sensor equation of the module should take acount for this facts. Usually the sensor datasheets describes the equation to be used.
Take a look at IMU_Zero in the repository you gave.
As for the other two, it depends on the application. Typically the temperature will be considered stable after a few working minutes. If temperature is important datasheet will probably be your best friend.
As for random walk. The most common use to take into account corrections of this is to use an accelerometer (and in some cases magnetometer) and apply a sensor fusion algorithm generally denoted as AHRS.
Some examples go as:

Sebastian Magdwick - Open source IMU and AHRS algorithms
Extended Kalman Filter
Direction Cosine Matrix filters
Complementary filters

If you really want to model the noise of the sensor to improve the result, you probably should search for Allan variance but you will need a lot of basis in stochastic processes and statistical theory
Some devices like yours already have an Motion processor built-in, that makes a similar application of (probably) one of these filters. See examples MPU6050_DMP6.ino
If you just want an implementation, just google for AHRS arduino. Github as a lot of examples used by other sensors that are easy to adapt. For instance and this
More information on IMU errors

The change in yaw (rotation of the x-y plane around the z-axis) is not drift or an error that needs to be nullified.
I set my MPU-6050 on the kitchen table and collected the axis outputs over a six and one half hour period.  The pitch and roll values were rock solid over the entire period.
  The Yaw values, however, constantly change at an extremely linear rate of 0.25 degrees per minute.  That's 15 degrees per hour. The planet you are on is rotating at that rate. This is not a coincidence.

Flip it over and repeat the experiment.  If you are correct, you should see the same change in the other direction.  You should also measure the other gyro axis - since your experiment is not at one of the earth's poles, you should  see rotation in the other axis as well.  Don't confuse this with pitch and role determined from the accelerometers and thus referenced to gravity.


text:
Most memory efficient way to program
I currently know 3 ways to do a program. Which one of them is the most memory friendly. Note that the example code is simple (blinking a led) and the final code will be VERY VERY complex. Also, the way I code is not the best, so suggest any suggestions in the way to write things or where to put them please.
1- All in the loop. The most basic way of programming.
const int led = 2;
const int interval = 500;
bool ledState = false;

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

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

2- Functions. Similar to the loop but a little neither. Can be splitted into many tabs.
const int led = 2;
const int interval = 500;
bool ledState = false;

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

void loop() {
  blinkLed();
}

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

Then finnaly, objects. The most supreme of them all (and the one that I know the least). I like objects and classes because multitasking with it is much easier. It is more flexible too. Code taken from here.
class Flasher
{
  // Class Member Variables
  // These are initialized at startup
  int ledPin;      // the number of the LED pin
  long OnTime;     // milliseconds of on-time
  long OffTime;    // milliseconds of off-time

  // These maintain the current state
  int ledState;                 // ledState used to set the LED
  unsigned long previousMillis;   // will store last time LED was updated

  // Constructor - creates a Flasher
  // and initializes the member variables and state
  public:
  Flasher(int pin, long on, long off)
  {
  ledPin = pin;
  pinMode(ledPin, OUTPUT);

  OnTime = on;
  OffTime = off;

  ledState = LOW;
  previousMillis = 0;
  }

  void Update()
  {
    // check to see if it's time to change the state of the LED
    unsigned long currentMillis = millis();

    if((ledState == HIGH) && (currentMillis - previousMillis >= OnTime))
    {
      ledState = LOW;  // Turn it off
      previousMillis = currentMillis;  // Remember the time
      digitalWrite(ledPin, ledState);  // Update the actual LED
    }
    else if ((ledState == LOW) && (currentMillis - previousMillis >= OffTime))
    {
      ledState = HIGH;  // turn it on
      previousMillis = currentMillis;   // Remember the time
      digitalWrite(ledPin, ledState);   // Update the actual LED
    }
  }
};

Flasher led(2, 500, 500);

void setup()
{
}

void loop()
{
  led.Update();
}

So, which is the best out of those 3.

Which board are you targeting?Which version of the hardware core for that board are you using?

Arduino Pro Mini by Sparkfun (Atmega328P_smd)

Which version of Arduino AVR Boards? You can check at Tools > Board > Boards Manager...

its version 1.6.14

Compile each variant and present the memory foot-print together with basic code analysis (LOC, complexity). And please define what you think is better. For instance, the OOP Flasher variant can be reduced in footprint and still keep the abstraction by rewriting to a template class.

You could tell the compiler to inline the function using inline void blinkLed(). That way the actual machine code will be identical in the first two cases.

That is an incredibly hard question to give a definitive answer to.
In general using OO consumes more memory, but that is the price you pay for greater flexibility and ease of use. The difference is usually minor though. Variables within an object take the same amount of space as variables outside an object. It's just the overhead of instantiating the object itself that adds to the memory usage, and that can be quite small, depending of course on what the object does.
Calling functions increases memory use on the stack. Every time you call a function the return address and a number of the internal CPU registers, along with some of the parameters, get placed on the stack. The deeper your function calls go the bigger the stack gets. But that is all temporary - as you leave the functions the stack shrinks again.
However, this is where it gets more complex:
The compiler performs optimizations. One of them is to consider functions for inlining. This replaces the function call with the content of the function that is being called. It makes for a slightly larger program, but it's a program that runs faster and uses less stack.
In your first two examples, because there is only one call to the blinkLed() function, the compiler will see that as a good candidate for using inline. So your first and second programs may well both end up exactly the same.
There are times, as well, where variables that you declare don't actually ever exist. For instance, if you use a couple of temporary variables to do a few calculations in a function and then return the result the compiler may instead just use CPU registers to store the temporary values instead of allocating variable space in memory.
So it is very hard to say "this is better" or "that is better". Instead you should pay more attention to how and where you declare and use your variables.
In general there are two rules:

Keep your variables the smallest size possible for the contents (use 8 bit variables instead of int for storing smaller numbers).
Keep the scope of variables as small as possible.

The latter is often overlooked. The scope of a variable is the block (delimited by { and } for example) where the variable is declared. Anything inside that block, including sub-blocks, can see the variable. By keeping the variable in as small a scope as possible you increase the chances that the compiler will choose to use CPU registers instead of allocating memory.  For example:
int i;

for (i = 0; i < 1000; i++) {
    .... do something ....
}

.... other things ....

for (i = 30; i < 2000; i++) {
    .... do something else ....
}

That is pretty much guaranteed to allocate memory for i.  However:
for (int i = 0; i < 1000; i++) {
    .... do something ....
}

.... other things ....

for (int i = 30; i < 2000; i++) {
    .... do something else ....
}

With that method the variable i will only exist within the first loop, after which it disappears. It is then recreated as an entirely new variable for the second loop. It doesn't need to stay in memory in between. The compiler may just place it in internal registers, or it may reuse the same block of memory, etc.
Also by keeping scope as small as possible you increase the ability of the compiler to re-use the same bits of memory for different purposes. 10 integers in different scopes doesn't mean 20 bytes of memory - it may mean just 2 bytes for all 10 integers.
So as you can see managing memory effectively can be a bit of a black art at times.

One other note not directly related to the code in the question which may be relevant to your final project - keep an eye on your use of the standard libraries. e.g. std::string will take more memory than using a c style char* for a string, lists/vectors will take up more memory than an array etc...

Optimizing your first example into the second is one of the basic optimizations automatically done by the compiler... provided the two loops belong to the same function.

@EdgarBonet You're making assumptions about the compiler. Yes, avr-gcc 4.9.2 might do that. Other versions might not. Other compilers for other chips might not. It is highly likely that it might, but it's not something you should rely 100% on happening if you can give the compiler a helping hand with just simple things like keeping the scope to the absolute minimum.

If yours doesn't do this basic stuff, you should probably get a better one.

@EdgarBonet Unless a better one isn't available. Not all compilers are GCC. Some are incredibly basic. Some are little more than a direct conversion to equivalent assembly.

There are very good observations about coding with limited resources in this book:
https://www.amazon.com/Programming-Arduino-Next-Steps-Sketches/dp/0071830251
It covers the items you ask about and more besides, including some brought up in the comments.
As others indicate- there are some 'best' practices to consider but often the most efficient method is context-dependent.


text:
Arduino Uno Wifi R2 Mesh Network
I currently have a project that uses a few Xbee S1 modules to report temperature measurements to a computer. I'm thinking about reworking the project to use the newer Arduino Uno WiFi R2 boards.
Is there an existing library that will allow me to create a mesh network for a number of Wifi R2's (about 20+)? I know there's a Mesh Library for the ESP8266 I'd be curious if I could either use this library or if one exits for the native board

why do you want to use Uno WiFi for this? two MCU? IMU? crypto chip? not compatible sensor libraries?

I was thinking about using the Uno WiFi for the simplicity of having most functionality on one board. I also want some level of security (like that provided by the crypto chip)

ok. don't buy 20. try one first

Fair point, I'll get 2-3 to verify 1st. I want to make sure the solution is able to do 20+ish

first test if it works with your sensors. it is ATMega4809. it has a different  architecture then the classic Uno 328p

It will, the sensors are run through an I2C ADC.

the crypto-chip and IMU are already on I2C. the Nina esp32 is wired to I2C too (not used yet). and there is no mesh support yet in WiFiNina firmware and library. why not use esp8266?


text:
Getting maximum value from HX711 and use it in the code further
i am using HX711 module to get value from load cell.my projects is a tensile strength testing machine,which will increase the load gradually and break at its maximum capacity.therefore i need the maximum value at which the specimen breaks.and use that value in the code to calcuate the tensile strengh of the specimen using the formula(tensile strength=load/cross section area of specimen).
Please help me with this and if possible ,i will be very gratefull if anyone can help me with the code too.
Thank you

Please show us the code, that you already have. What is your problem with reaching the goal? Everytime, that the load increases, you measure with the load cell and save the result in a variable, but only, if it's greater, that the previous value. Sense the breaking of the specimen by checking for a large load decrease in your load cell. The saved value at this time is the absolute maximum, that was reached.

Thank you, i do not have any code for the project, i am new to arduino programming.i just know the basics.can you please help me with the code.?

Thank you, The code should take the maximinum value from the load cell at which the specimen broke and use that value to calculate the tensile strengh using the formula given above i.e (maximum load÷cross section area) where cross section area is calculated by formula-((pi÷4)*(r^2)) and 'r' is entered by user which is the radius of the specimen.

We won't write the code for you, since we are not a free coding service, but I will try to give you some hints, how you can do it.

Timing of measurements: The measurements themselves can be done with one of the HX711 libraries, that are available on the web, but you may want to time them to get more regular measurements. This can be done in a non-blocking coding style like in the BlinkWithoutDelay example, that comes with the Arduino IDE. It involves the millis() function to measure the time since the last measurement and act accordingly. This is explained many times troughout the web and on this site.
Saving the data and finding the maximum: This depends on what else you want to do with the data.

Saving all data for later processing: You might want to save all data (the load curve) for later use. In this case you have to define an array of appropriate length (the length depends on the duration and frequency of the measurement). Also define a position variable or pointer, that marks the current position in this array. Everytime when you do a measurement, you save the result to the array element at the saved position and increment the position variable after that. After the end of the measurement, you declare a value variable with the value of the first array element. Then you loop through all the following elements (for(int i=1;i<array_length;i++)). Inside the loop you calculate and save the maximum of 2 numbers: The value of the current array element and the saved variable. This can be done with saved_value = max(saved_value, array[i]);. When the loop is finished, you will have the maximum value in the saved_value variable.
No saving of data: You can also calculate a flying maximum without saving all data. Declare a variable (max_value), that will hold the maximum value, and set it to zero. Then, everytime when you do a measurement, you execute max_value = max(current_value, max_value); which calculates the maximum of the two numbers (current measurement and the previously calculated maximum). At the end of the measurement you will have the absolute maximum in the max_value variable.

Sensing the end of measurement: You need to sense the end of the measurement (when the specimen breaks) (though this can be done manually if you like). For this I would suggest to calculate the speed in which the load changes. During the measurement the load will increase slowly. In the moment of breaking the load will decrease very fast. The speed between two load measurments is calculated by (value(x) - value(x-1))/measurement_interval. You can define a threshold of negative speed, so that every speed below it (faster negative decrease of load) will be sensed as breaking of specimen. You can check this on every measurement with a simple if statement, or you can calculate the speed over more than 2 consecutive measurements. That depends on the actual speed of load change and the frequency of load measurements.
Calculating the tensile strength: This is just writing your formula into the code using the variable names, that you used in the previous code. Be sure to use the correct variable type for your needs. Most likely you would want to use float.
Getting input from user: This depends largely on your planned means of interaction with the user. Is the Arduino connected to a PC and you use a serial terminal program? Then you can use this for user input (You might want to look at the SerialEvent example of the Arduino IDE, which shows how to work with messages and delimiter characters). Do you want to add a keypad and a LCD display? There are library available for these too, so it should not be very difficult to learn how to use then to get user input.

Thank you so much for the help.


text:
Problems with Serial.read()
void loop()
{
  if (sensor.begin() == true)
  {
    Serial.print("Current Conversion Mode: ");
    Serial.println(sensor.getConversionMode());
    Serial.println("Enter your mode of Conversion (number 0 - 3): ");
    while (Serial.available() == 0); // Waits for the user input
    mode = Serial.read(); // Reads the input string from serial port
    Serial.print("Number recieved: ");
    Serial.println(mode);
    delay(500);
    if (mode == '0' | mode == '1' | mode == '2' | mode == '3')
    {
      sensor.setConversionMode(mode);
      Serial.println();
      delay(500);
    }
    else
    {
      Serial.println("Conversion mode unsuccessfully set - Please enter a number 0 - 3");
    }
    delay(1000);
  }
  else // Runs when the device was unable to setup properly
  {
    Serial.println("Device failed to setup");
  }
}

I'm currently using the SparkFun red board to run this code on. I have been trying to get this to read from the serial monitor to take an input to send to the library I wrote to change the value of the conversion mode register of a temperature sensor. When I run the code, I can only have it run once correctly, then it jumps directly to the else statement for the inputs, saying that 0-3 was not an input. I tried the other methods that people have suggested  from this website and the Arduino forums but none of them have worked for me yet. I'm not sure if adding more delays would help - that was one of the most common suggestion I found for this specific issue and it wasn't that consistent. Please help! Thanks.

What does your "Number received:" tell you when it fails?

When it fails it has a 0 value, but before sometimes I was getting -1.

What data type is mode?

Mode has the data type of char. I have it declared as a global variable above the loop

Tested it with a dummy implementation of sensor. Works as expected. The problem must be in a part of the code you are not showing.

@EdgarBonet I really wonder how this code can run as expected. | is not the operand for OR. Also, mode is byte but he compares with a char. I guess there is a chance to find the error in the provided code.

@SimSon: You are right that | should be ||, but they turn out to be equivalent as long as their operands are both either 0 or 1. And mode is char according to the OP's comment.

@SimSon thank you for the catch on that- I will change that now

Using a slightly modified version of your sketch, I receive the following output in the serial monitor when I enter the number 2.

Current Conversion Mode: Enter your mode of Conversion (number 0 - 3):
  Number recieved: 2
Current Conversion Mode: Enter your mode of Conversion (number 0 - 3):
  Number recieved:
Conversion mode unsuccessfully set - Please enter a number 0 - 3
  Current Conversion Mode: Enter your mode of Conversion (number 0 - 3):
  Number recieved:
Conversion mode unsuccessfully set - Please enter a number 0 - 3
  Current Conversion Mode: Enter your mode of Conversion (number 0 - 3):

If you change mode to an int then retest, you'll see the second and third "Number recieved" are 10 and 13. That would be the New Line and Carriage Return characters. When you send data via the serial monitor, do you have "No Line Ending" selected or something else?
Here is a test sketch:
char mode;

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

void loop()
{
  if (true)
  {
    Serial.print("Current Conversion Mode: ");
    //Serial.println(sensor.getConversionMode());
    Serial.println("Enter your mode of Conversion (number 0 - 3): ");
    while (Serial.available() == 0); // Waits for the user input
    mode = Serial.read(); // Reads the input string from serial port
    Serial.print("Number recieved: ");
    Serial.println(mode);
    delay(500);
    if (mode == '0' | mode == '1' | mode == '2' | mode == '3')
    {
      //sensor.setConversionMode(mode);
      Serial.println();
      delay(500);
    }
    else
    {
      Serial.println("Conversion mode unsuccessfully set - Please enter a number 0 - 3");
    }
    delay(1000);
  }
  else // Runs when the device was unable to setup properly
  {
    Serial.println("Device failed to setup");
  }
}

Thank you for the suggestion, it worked! I just changed the the value to an int and then changed the serial monitor to "No Line Ending" and it worked. I never changed that setting before or really realized it was there. Thanks again!


text:
My webswerver works fine when there is only 1 servo used/defined in my code
I am trying to make a webserver which controls my 3 servos for a robotic arm. When I define and use 1 servo it is nice and quick, but whereas if I use more than 1 the webserver is very slow and barely loads. Someone please help.
I will post the code below. With this code the webserver is very slow:
#include <Ethernet.h>
#include <SPI.h>
#include <Servo.h>
String readString;
Servo robotservo1;
Servo robotservo2;

byte mac[] = { 0x2C, 0xF7, 0xF1, 0x08, 0x29, 0xAF };
byte ip []={10,1,1,121};// check back of your shield
   // when the shield connected the serioal monitor will display the ip address
EthernetServer server(80);

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
 Ethernet.begin(mac, ip);
server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());// prints my IP address, so you can copy paste in browsr

robotservo1.attach(9);
robotservo2.attach(10);

robotservo1.write(45);
robotservo2.write(45);

}

void loop() {
  // put your main code here, to run repeatedly:
EthernetClient client = server.available();
if (client) {
if (client.connected()){
  if (client.available()) {
  char c = client.read();
  if (readString.length() < 100) {
          readString += c;
        }
  if (c == '\n') {
          Serial.println(readString);
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println();
          client.println("<hmtl>");
          client.println("");
client.println("<title>Ethernet shield, hopefully works</title>");
client.println("");
client.println("<title>");
client.println("Control the robotic arm using the buttons below");
client.println("</title>");
client.println("");
client.println("");
client.println("<meta http-equiv=\"refresh\" content=\"4\">");
client.println("");
client.println("Control the robotic arm by pressing the buttons below!!!");
client.println("");
client.println("");
client.println("
");
client.println("Servo 1 or Base");
client.println("
");
client.println("<FORM>");
client.println("<INPUT type=button value=Servo-0 onClick=window.location='/?baseserv0\'>");
client.println("<INPUT type=button value=Servo-45 onClick=window.location='/?baseserv45\'>");
client.println("<INPUT type=button value=Servo-90 onClick=window.location='/?baseserv90\'>");
client.println("</FORM>");
client.println("
");

client.println("
");
client.println("Servo 2 or Elbow");
client.println("
");
client.println("<FORM>");
client.println("<INPUT type=button value=Servo-0 onClick=window.location='/?elbowserv0\'>");
client.println("<INPUT type=button value=Servo-45 onClick=window.location='/?elbowserv45\'>");
client.println("<INPUT type=button value=Servo-90 onClick=window.location='/?elbowserv90\'>");
client.println("</FORM>");
client.println("
");

client.println("
");
client.println("Servo 3 or Shoulder");
client.println("
");
client.println("<FORM>");
client.println("<INPUT type=button value=Servo-0 onClick=window.location='/?shoulderserv0\'>");
client.println("<INPUT type=button value=Servo-45 onClick=window.location='/?shoulderserv45\'>");
client.println("<INPUT type=button value=Servo-90 onClick=window.location='/?shoulderserv90\'>");
client.println("</FORM>");
client.println("
");

client.println("");
client.println("");
client.println("");

 delay(1);

  if(readString.indexOf("?baseserv0") >0)
            {
              robotservo1.write(0);
            }

          else{
            if(readString.indexOf("?baseserv45") >0)
            {
              robotservo1.write(45);
            }

          else{
            if(readString.indexOf("?baseserv90") >0)
            {
              robotservo1.write(90);
            }

  }

}

  if(readString.indexOf("?baseserv0") >0)
            {
              robotservo2.write(0);
            }

          else{
            if(readString.indexOf("?elbowserv45") >0)
            {
              robotservo2.write(45);
            }

          else{
            if(readString.indexOf("?elbowserv90") >0)
            {
              robotservo2.write(90);
            }

  }

}

  readString="";
          client.stop();
  }}}}}

you code is hard to read because it is formatted badly ... please correct the indentation ... for instance, all of the if statements should be indented to the same level ... also, the client.println() should all be equally indented

stop the client before handling motors. and some reading https://github.com/jandrassy/StreamLib/blob/master/README.md

I have no Ethernet board so I couldn't test the timings, but when I compiled your code for an Uno, I got a low free-memory warning; that 83% of memory was used and stability problems could occur. That's the compiler telling you that your code might not run right. It may very well be the reason your server was slow. The largest user of data-memory (SRAM) is the text in your client.print() statements.
I put that text into program-memory (Flash, of which there is over 10x as much!) which got the SRAM use down to 29%! Try running that and see if it won't behave a little bit better:
#include <Ethernet.h>
#include <SPI.h>
#include <Servo.h>
String readString;
Servo robotservo1;
Servo robotservo2;

byte mac[] = { 0x2C, 0xF7, 0xF1, 0x08, 0x29, 0xAF };
byte ip [] = {10, 1, 1, 121}; // check back of your shield
// when the shield connected the serioal monitor will display the ip address
EthernetServer server(80);

void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
   Ethernet.begin(mac, ip);
   server.begin();
   Serial.print("server is at ");
   Serial.println(Ethernet.localIP());// prints my IP address, so you can copy paste in browsr

   robotservo1.attach(9);
   robotservo2.attach(10);

   robotservo1.write(45);
   robotservo2.write(45);

}

void loop() {
   // put your main code here, to run repeatedly:
   EthernetClient client = server.available();
   if (client) {
      if (client.connected()) {
         if (client.available()) {
            char c = client.read();
            if (readString.length() < 100) {
               readString += c;
            }
            if (c == '\n') {
               Serial.println(readString);
               client.println(F("HTTP/1.1 200 OK"));
               client.println(F("Content-Type: text/html"));
               client.println();
               client.println(F("<hmtl>"));
               client.println(F(""));
               client.println(F("<title>Ethernet shield, hopefully works</title>"));
               client.println(F(""));
               client.println(F("<title>"));
               client.println(F("Control the robotic arm using the buttons below"));
               client.println(F("</title>"));
               client.println(F(""));
               client.println(F(""));
               client.println(F("<meta http-equiv=\")refresh\" content=\"4\">"));
               client.println(F(""));
               client.println(F("Control the robotic arm by pressing the buttons below!!!"));
               client.println(F(""));
               client.println(F(""));
               client.println(F("
"));
               client.println(F("Servo 1 or Base"));
               client.println(F("
"));
               client.println(F("<FORM>"));
               client.println(F("<INPUT type=button value=Servo-0 onClick=window.location='/?baseserv0\'>"));
               client.println(F("<INPUT type=button value=Servo-45 onClick=window.location='/?baseserv45\'>"));
               client.println(F("<INPUT type=button value=Servo-90 onClick=window.location='/?baseserv90\'>"));
               client.println(F("</FORM>"));
               client.println(F("
"));

               client.println(F("
"));
               client.println(F("Servo 2 or Elbow"));
               client.println(F("
"));
               client.println(F("<FORM>"));
               client.println(F("<INPUT type=button value=Servo-0 onClick=window.location='/?elbowserv0\'>"));
               client.println(F("<INPUT type=button value=Servo-45 onClick=window.location='/?elbowserv45\'>"));
               client.println(F("<INPUT type=button value=Servo-90 onClick=window.location='/?elbowserv90\'>"));
               client.println(F("</FORM>"));
               client.println(F("
"));

               client.println(F("
"));
               client.println(F("Servo 3 or Shoulder"));
               client.println(F("
"));
               client.println(F("<FORM>"));
               client.println(F("<INPUT type=button value=Servo-0 onClick=window.location='/?shoulderserv0\'>"));
               client.println(F("<INPUT type=button value=Servo-45 onClick=window.location='/?shoulderserv45\'>"));
               client.println(F("<INPUT type=button value=Servo-90 onClick=window.location='/?shoulderserv90\'>"));
               client.println(F("</FORM>"));
               client.println(F("
"));

               client.println(F(""));
               client.println(F(""));
               client.println(F(""));

               delay(1);

               if (readString.indexOf("?baseserv0") > 0)
               {
                  robotservo1.write(0);
               }

               else {
                  if (readString.indexOf("?baseserv45") > 0)
                  {
                     robotservo1.write(45);
                  }

                  else {
                     if (readString.indexOf("?baseserv90") > 0)
                     {
                        robotservo1.write(90);
                     }

                  }

               }

               if (readString.indexOf("?baseserv0") > 0)
               {
                  robotservo2.write(0);
               }

               else {
                  if (readString.indexOf("?elbowserv45") > 0)
                  {
                     robotservo2.write(45);
                  }

                  else {
                     if (readString.indexOf("?elbowserv90") > 0)
                     {
                        robotservo2.write(90);
                     }

                  }

               }

               readString = "";
               client.stop();
            }
         }
      }
   }
}


text:
Arduino USB host + RS232
I'd like to get a word of advice regarding the subject. Basically there's a COM port based device which I need to connect to an Android tablet via USB. The tablet will be exchanging data packages with the COM device, but a) Arduino may need to do same transformation of the packages b) the tablet should not leverage OTG feature and shouldn't be a master itself.
So, my questions are
1) Which Arduino board is the best fit?
2) Is it an option to use Chinese boards for the sake of cost optimization?
3) Do I need separate RS232 and USB shield or it's ok to leverage built in USB and data pins?
Apology for this quite a noob question but that's exactly who I am for Arduino platform. Appreciate any answers.

No Arduino implements a USB host. That would require a more or less complete OS to work. And it's not quite clear how are parts of your project connected together.

@DmitryGrigoryev I believe Arduino Duo must support USB Host mode, at least I saw that in various blogs and forums on the Internet : https://forum.arduino.cc/index.php?topic=548469.0 So, can you explain what do you mean, please?

True. Yet you have accepted an answer suggesting a 32U4, which doesn't have the host mode, so I still fail to understand what you're trying to do. Did you decide to use OTG, or use a Duo to connect your COM device and Android device together? Or is Arduino itself the COM based device you're talking about?

@DmitryGrigoryev sorry for being not clear. Given is a) COM device, b) Android tablet. To be solved is how to connect them allowing the tablet to send/receive data to/from the COM device, but keeping the tablet charged (so OTG is not an option as it would make it into master, thus giving it's charge away). Also, some additional transformation may be required to apply to data flowing between the devices.

1) Which Arduino board is the best fit? 2) Is it an option to use Chinese boards for the sake of cost optimization? 3) Do I need separate RS232 and USB shield or it's ok to leverage built in USB and data pins?

When communicating with Android you need to make sure that there is software available for doing the communication. That's really down to the application more than the operating system, and because of that it can be quite restricted what boards will work and what won't.
Personally I would go for either an ATMega32U4 based board which provides a standard CDC/ACM interface. This also has the advantage that the (often single) UART on the board is not used by the USB communication.
Then you need to convert the UART into RS232 using (for example) a MAX232 board.

yeah I've got full control over Android app and basically marrying it together with a bord won't be a problem.

I'm a bit puzzled now. Cuz ATMega32U4 is used in Arduino Micro and Leonardo which I believed are not able to be host devices. By reading docs I was leaning to Arduino Due, cuz the documentation for USBHost class specifically says the class is compatible with Due model only.

@Ivan You want the Android device to be the host.

Not exactly, I'd like it to be slave and a bord act as a host.

@Ivan Then you've got a long job in front of you. There's no (AFAIK) API for that kind of thing in Android. You can do file transfers, network sharing, etc, but not serial communication.  For that you need the Android device to be the host.

@Ivan Have you considered connecting to Android through Bluetooth instead?

Hmm, so basically you saying that I won't be able to use UsbDevice, UsbInterface, UsbEndpoint classes from Android SDK in case if the tablet is connected as slave and won't be possible to respond to Arduino bord when that requests a data?

Unfortunately, Bluetooth is not an option at all.

@Ivan The only resources you are likely to find are for using Android as the host. It's the normal option, it's the sensible option, and the only other mention I can find of someone wanting to do this mentions modifying the Android installation and compiling your own kernel. So.... no.

Cool, thanks a lot for helping. Will try to think something.

Sorry for bothering you, didn't do a deep dive into the subject but seems Android allows to connect USB accessories https://source.android.com/devices/accessories/custom#connecting-over-usb and I found an example (which I'm not sure is functional) - https://github.com/Geotab/android-external-device-example/blob/master/app/src/main/java/com/geotab/AOA/AccessoryControl.java So, will try to play with it.

Backing to the original question :) Do you think Arduino Due is the best board to experiment with this?

@Ivan That is with the Android being the master. An accessory is a device.

And no, I'd go for a Pro Micro or a Leonardo.

Hmm, that doc says "Due to the low power output of Android devices, AOA requires the accessory to act as a USB host, meaning the connecting accessory must power the bus.".

@Ivan AOA is a strange beast. It's not normal USB communication. "Host" mode is only from a power perspective in that system - the android device still has to connect to the accessory rather than the accessory connect to the phone. Also there is no AOA support in Arduino

right I see and seems it's exactly what I need. Basically the main goal is not to exhaust the tablet's battery. If AOA allows do software side of things on tablet but power still supplied externally, I'm okay with that. Will try to play with the boards you mentioned and maybe Arduino Due too. Thanks a lot for the help!

Damn, just noticed the last phrase "Also there is no AOA support in Arduino" :(

There's always the possibility that someone somewhere has written an AOA library plugin for the Arduino USB stack, but I doubt it. You may be working in Atmel Studio...

AOA is supported in Arduino (or was) but it is called ADK. https://www.arduino.cc/en/Guide/ArduinoADK. The last time anyone was excited about this was 2012. The USB Host Shield Library 2.0 has references to ADK as does the Due USB host library https://github.com/arduino-libraries/USBHost/tree/master/examples/ADKTerminalTest. Whether Arduino ADK still works, I do not know. BLE or WiFi are better options to communicate with an Android device.