text:
Is the code correct? Nrf24l01
I'm am a beginner, so I'm sorry I have written this wrong.
Is this piece of code correct? If not where?
Transmitter:
#include <SPI.h>
#include "RF24.h"

int* Msg, mSg, msG;

RF24 radio(9, 10);
const uint8_t pipe = 1;

void setup() {
  // put your setup code here, to run once:
  radio.begin();
  radio.setPALevel(RF24_PA_LOW);
  radio.openWritingPipe(pipe);
}

void loop() {
  // put your main code here, to run repeatedly:
  Msg = analogRead(A1);
  radio.write(Msg, sizeof(Msg));
  mSg = analogRead(A2);
  radio.write(mSg, sizeof(mSg));
  msG = analogRead(A3);
  radio.write(msG, sizeof(msG));
  delay(100);
}

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

#define in1 2
#define in2 3
#define in3 4
#define in4 5

#define in5 A2
#define in6 A3
#define in7 A4
#define in8 A5

const int maxMsgLength = 64;
char Msg[maxMsgLength];
const int maxmSgLength = 64;
char mSg[maxmSgLength];
const int maxmsGLength = 64;
char msG[maxmsGLength];

RF24 radio(9, 10);
const uint8_t pipe = 1;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  radio.begin();
  radio.setPALevel(RF24_PA_LOW);
  radio.openReadingPipe(1, pipe);
  radio.startListening();
}

void loop() {
  // put your main code here, to run repeatedly:
  if (radio.available()) {
    radio.read(Msg, maxMsgLength - 1);
    radio.read(mSg, maxmSgLength - 1);
    radio.read(msG, maxmsGLength - 1);
  }

  int xAxis = Msg;
  int yAxis = mSg;
  int YAxis = msG;

  if (xAxis < 450) {
    // Forward
    digitalWrite(in1, 1);
    digitalWrite(in2, 0);
    digitalWrite(in3, 1);
    digitalWrite(in4, 0);
    Serial.println("Forward");
  }
  else if (xAxis > 550) {
    // Backward
    digitalWrite(in1, 0);
    digitalWrite(in2, 1);
    digitalWrite(in3, 0);
    digitalWrite(in4, 1);
    Serial.println("Backward");
  }
  else {
    // Stop
    digitalWrite(in1, 0);
    digitalWrite(in2, 0);
    digitalWrite(in3, 0);
    digitalWrite(in4, 0);
    Serial.println("Stop");
  }

  if (yAxis < 450) {
    // Left
    digitalWrite(in5, 1);
    digitalWrite(in6, 0);
    Serial.println("Left");
  }
  else if (yAxis > 550) {
    // Right
    digitalWrite(in5, 0);
    digitalWrite(in6, 1);
    Serial.println("Right");
  }
  else {
    // Stop
    digitalWrite(in5, 0);
    digitalWrite(in6, 0);
    Serial.println("Stop");
  }

  if (yAxis < 450) {
    // Flipper Up
    digitalWrite(in7, 1);
    digitalWrite(in8, 0);
    Serial.println("Up");
  }
  else if (yAxis > 550) {
    // Flipper Down
    digitalWrite(in7, 0);
    digitalWrite(in8, 1);
    Serial.println("Down");
  }
  else {
    // Stop
    digitalWrite(in7, 0);
    digitalWrite(in8, 0);
    Serial.println("Mid");
  }
  delay(250);
}

Edit:
Transmitter:
#include <SPI.h>
#include "RF24.h"

int x, y, f;

RF24 radio(9, 10);
const uint8_t pipe = 1;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  radio.begin();
  radio.setPALevel(RF24_PA_LOW);
  radio.openWritingPipe(pipe);
}

void loop() {
  // put your main code here, to run repeatedly:
  x = analogRead(A1);
  radio.write(x, sizeof(x));
  y = analogRead(A2);
  radio.write(y, sizeof(y));
  f = analogRead(A3);
  radio.write(f, sizeof(f));
  delay(100);
}

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

#define in1 2
#define in2 3
#define in3 4
#define in4 5

#define in5 A2
#define in6 A3
#define in7 A4
#define in8 A5

int x;
int y;
int f;

RF24 radio(9, 10);
const uint8_t pipe = 1;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  radio.begin();
  radio.setPALevel(RF24_PA_LOW);
  radio.openReadingPipe(1, pipe);
  radio.startListening();
}

void loop() {
  // put your main code here, to run repeatedly:
  if (radio.available()) {
    radio.read(&x, sizeof(x));
    radio.read(&y, sizeof(y));
    radio.read(&f, sizeof(f));
  }

  if (x < 450) {
    // Forward
    digitalWrite(in1, 1);
    digitalWrite(in2, 0);
    digitalWrite(in3, 1);
    digitalWrite(in4, 0);
    Serial.println("Forward");
  }
  else if (x > 550) {
    // Backward
    digitalWrite(in1, 0);
    digitalWrite(in2, 1);
    digitalWrite(in3, 0);
    digitalWrite(in4, 1);
    Serial.println("Backward");
  }
  else {
    // Stop
    digitalWrite(in1, 0);
    digitalWrite(in2, 0);
    digitalWrite(in3, 0);
    digitalWrite(in4, 0);
    Serial.println("Stop");
  }
  if(x > 1023)x = 1023;
  if(x < 0)x = 0;

  if (y < 450) {
    // Left
    digitalWrite(in5, 1);
    digitalWrite(in6, 0);
    Serial.println("Left");
  }
  else if (y > 550) {
    // Right
    digitalWrite(in5, 0);
    digitalWrite(in6, 1);
    Serial.println("Right");
  }
  else {
    // Stop
    digitalWrite(in5, 0);
    digitalWrite(in6, 0);
    Serial.println("Stop");
  }
  if(y > 1023)y = 1023;
  if(y < 0)y = 0;

  if (f < 450) {
    // Flipper Up
    digitalWrite(in7, 1);
    digitalWrite(in8, 0);
    Serial.println("Up");
  }
  else if (f > 550) {
    // Flipper Down
    digitalWrite(in7, 0);
    digitalWrite(in8, 1);
    Serial.println("Down");
  }
  else {
    // Stop
    digitalWrite(in7, 0);
    digitalWrite(in8, 0);
    Serial.println("Mid");
  }
  if(f > 1023)f = 1023;
  if(f < 0)f = 0;

  Serial.println(x);
  Serial.println(y);
  Serial.println(f);
  delay(250);
}

Thank you for your time.

Does it behave not the way you want? Because we don't know that. And if it does not behave like you want, describe exactly what you expect, and what you notice.

So, I want it to take the values from the joysticks and send it to the receiver side. There the joystick values must be taken and l298n must behave accordingly. If the joystick is pulled upward then the motors should go forward and vice versa. Same with the x-axis, if the joystick is pulled on the left side the motor must rotate to the left-hand side.

Ok ... and does your program behave like that? If yes, why ask the question? If not, describe what you see and what you expect.

So the program does not behave like that.

The joystick values do not get transmitted and on the receiver, the values are displayed as 0.

Did you try a default RF24 example?

Yes, the default example is working fine.

Try removing the pointer () in int Msg, mSg, msG;. In general, use print to print out all variables to pinpoint problems

Do you mean * <- this symbol.

Yes: remove that *

Still doesn't work

Then try print statements.

According to the code, the Serial monitor of the receiver shows Stop, Left, and Up.

Can you please explain the transmission of integers with the rf24.

The error came that print is not member of the RF24 library.

I created an answer (doesn't mean all is ok, but should give you some advice and solution)

I see (at least one ) problem.
First remove the * from:
int* Msg, mSg, msG;

Because it should store integers (numbers), not pointers to numbers.
Also, make the variables better. These almost identical names are quite confusing (name them x, y or z or a better name).
What you are doing is sending the 3 integers as integers (meaning that each integer is 2 bytes), so you send 6 bytes.
But in the receiver, you read characters, you have to replace this by:

Changing char  to int  for the 3 variables in the receiver side
Also here, change the names
Remove the constants for the length (64)
Instead read the code as you write it:
int xAxis;
radio.read(&xAxis, sizeof(int));

& means: address, the read function stores the value in xAxis (so you don't have to copy it afterwards).
Also print out the value after the read so you can check it.

Thank you this program does work. But even if the joysticks are in the middle the value shown in the serial monitor is Forward, Left, and Up(the first if statements in each argument). then too, the transmission glitches.

That depends on the values you get (did you check the values of x, y and zAxis?)

The values are coming insanely different

When the joystick is pulled upward the values go like 129, 0, 0 then 0, 129, 0 and then 0, 0, 129. But when it is pulled backward then the values are 16382, 0, -13872 and so.

Added if (x/y/f < 0)x/y/f = 0; and if (x/y/f > 1023)x/y/f = 1023;

Ok, also I think even then the radio communication is ok including parsing the data to variables ... So the only thing left (if not already solved) is the input from the joystick.

I tested the joystick inputs in another program just for printing the values of the joysticks. The default value of the joystick is 500 and the maximum is 1023 and the minimum is 0.

The values of the joystick are alright on the transmitter side. But I'm not sure of the receiver.

Thank you Michel. Now the code works just fine but it does glitch rarely. I forgot to add &x, &y, and &f in the transmitter.


text:
#define above static const int?
I see a lot of people, but also libraries, defining constants (like pin numbers, length of items etc) as #define:
#define LENGTH 5

While it is recommended to use in this case static const int:
static const int LENGTH = 5;

I did a test and for memory it does not make a difference.
Is there some specific Arduino reason why #define is (mis)used so often?

Old habits from plain C?

@EdgarBonet I was already a bit 'afraid' of such remark.

People copying examples from people that have bad habits, or learned from people with bad habits.

I would use a byte for values that are <=255, save on memory.

@CrossRoads You are right ... although I use mostly int's when I just want to test something, for a program where I expect (even in future) that memory is an issue (which is very fast for an Arduino) I use smaller types. In this case it doesn't matter, it doesn't use any SRAM memory.

For numbers, certainly, const <type> is preferred.  This is chiefly because it imposes a type (which would only be optional for a #define), which can have a knock-on effect for mathematics.
That's not to say that you should always use const <type> instead of #define.  #define has its place.
One of the benefits of #define over const <type> is that it is a direct literal text replacement. The replacement is done before the compilation, so anything that is valid in your code can be put in a #define, whereas only things which evaluate to the correct type at runtime can be placed in a const <type>.
Take strings for example.  Yes, you can use:
const char *foo = "This is text";

And you can use that wherever a const char * is expected.  However, if you use:
#define FOO "This is text"

you can use it anywhere a string literal is expected.  That makes for useful things such as C's way of concatenating string literals at compile time:
Serial.println("I say: " FOO);

The two string literals "I say: " and FOO (which expands to "This is text") are concatenated into a singe string literal at compile time into:
Serial.println("I say: This is text");

You can't do that with const char *.
Another big difference with const <type> compared with #define is when expressions are evaluated.  Take for example:
const float sinpi = sinf(3.141592653);

That will calculate the sine of PI once at startup. However:
#define SINPI sinf(3.141592653);

will calculate the sine of PI every time it is used.
So in this instance const float not only gives you an imposed type of float for all calculations, it also reduces calculation overhead by only running the calculation once and saving the result.
So as you can see there are pros and cons to each.  But in general, for numbers:

const <type> is preferred for storing internal numerical data that doesn't change, and
#define is most often used for user-configurable data, since it doesn't impose the ; at the end of the line which often gets forgotten by (newer) users.

Thanks for the insight ... the last remark is 'interesting' (forgotten by newer users).

even though it is not directly related to the subject of the question, perhaps you could mention the use of #define for conditional compiling

source: Stack Exchange

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

sort: votes


text:
Arduino resets itself
If I connect more power consuming components to Arduino, it gets reset. What is the cause of this observation?

Look up "brownout".  For example https://forum.arduino.cc/index.php?topic=246359.0

What is the solution for this?

When powered through USB there is a resettable polymeric ("poly") fuse. If you draw more than about 500mA this fuse will cut out and isolate the power.  When you remove the load the fuse will reset and allow power back to the board.
"Poly" fuses are in fact "Positive Temperature Coefficient" (PTC) thermistors. As they get hot their resistance increases (as opposed to the NTC thermistors you use for temperature sensing where the resistance decreases as they get hotter).  The current flowing through the PTC causes it to warm up. Too much current and it gets too hot, and the resistance gets too high (it's non-linear, so the resistance suddenly increases a lot).

Very good information!

Branded Arduino boards have overload protection on their voltage regulators. If the voltage regulator overheats it shuts down, and then attempts to restart when the temperature returns to normal. I believe there is also short-circuit protection, although I'm not positive.
When power returns the processor will do a power-on reset.

It depends on what is shorted. As stated by Duncan C, shorting the 5V pin to ground will probably not harm the arduino due to the mentioned protection mechanisms.
On the other hand an output port should not be shorted, chances are that the port gets destroyed.
In case of a short circuit the arduino "resets" itself because the voltage drops below the mcu's operating conditions, because the voltage regulator either shuts down completely or is not able to provide enough current.

Consider this: An Arduino was not designed as a power supply. Connect your loads to an external power supply things will get a lot better.

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


text:
Multiple WiFi client/server connections
I'm implementing a WiFi HTML web server using the WiFiNINA library, an Adafruit Airlift ESP32 coprocessor, and a Teensy 3.5. It's starting to work, but I have a couple of questions. This simplified code will illustrate the first.
#include <WiFiNINA.h>
#include "Wifi_names.h"

WiFiServer server(80);

void error (const char *msg) {
   Serial.println(msg);
   while (1) ; }

void setup(void) {
   Serial.begin(115200);
   while (!Serial) ;
   WiFi.setPins(19, 20, 21, -1, &SPI);
   if (WiFi.status() == WL_NO_SHIELD) error("no Wifi shield");
   Serial.print("ESP32 firmware version: "); Serial.println(WiFi.firmwareVersion());
   WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
   while (WiFi.status() != WL_CONNECTED) ;
   Serial.print("connected, IP address is ");
   server.begin();
   Serial.println(WiFi.localIP()); }

void show_client(const char *msg, WiFiClient *pclient) {
   Serial.print(msg); Serial.print(":");
   if (*pclient) {
      Serial.print(" IP "); Serial.print(pclient->remoteIP());
      Serial.print(" port "); Serial.print(pclient->remotePort()); }
   else Serial.print("none");
   Serial.println(); }

void check_for_another_client(const char *msg) {
   WiFiClient newClient;
   newClient = server.available();
   show_client(msg, &newClient); }

void loop(void) {
   WiFiClient client;
   while (!(client = server.available())) ;
   Serial.print("\n time: "); Serial.println((float)millis()/1000);
   show_client("client 1", &client);
   check_for_another_client("client 2");
   while (client.available() == 0) ;  // wait for data
   check_for_another_client("client 3");
   Serial.print("client 1 data read: "); Serial.println(client.read(), HEX); // read the data
   check_for_another_client("client 4");
   while (client.available()) client.read(); // flush the rest of the input
   delay(1000);
   client.stop(); // abort the connection
}

The output is:
ESP32 firmware version: 1.2.2
connected, IP address is 192.168.86.35

 time: 43.22
client 1: IP 192.168.86.32 port 62346
client 2: IP 192.168.86.32 port 62346
client 3:none
client 1 data read: 47
client 4:none

The question is: why does server.available() continue to say that I have new connections until there is some data available on the connection it already gave me? What if a second connection arrives after the 3-way TCP connection establishment handshake (SYN, ACK/SYN, ACK) but before any data arrives? How do I get that second connection?
The second question, which is related, is illustrated by the Sniffer trace of that transaction:
179 *REF*     192.168.86.32  192.168.86.35  TCP  66  62346 → 80 [SYN] Seq=0 Win=64240 Len=0 MSS=1460 WS=256 SACK_PERM=1
180 0.000239  192.168.86.32  192.168.86.35  TCP  66  62347 → 80 [SYN] Seq=0 Win=64240 Len=0 MSS=1460 WS=256 SACK_PERM=1
183 0.039352  192.168.86.35  192.168.86.32  TCP  58  80 → 62346 [SYN, ACK] Seq=0 Ack=1 Win=5744 Len=0 MSS=1436
184 0.039431  192.168.86.32  192.168.86.35  TCP  54  62346 → 80 [ACK] Seq=1 Ack=1 Win=64240 Len=0
185 0.039602  192.168.86.32  192.168.86.35  HTTP 488 GET / HTTP/1.1
195 0.278592  192.168.86.35  192.168.86.32  TCP  54  80 → 62346 [ACK] Seq=1 Ack=435 Win=5310 Len=0
197 1.053036  192.168.86.35  192.168.86.32  TCP  54  80 → 62346 [FIN, ACK] Seq=1 Ack=435 Win=5310 Len=0
198 1.053146  192.168.86.32  192.168.86.35  TCP  54  62346 → 80 [ACK] Seq=435 Ack=2 Win=64240 Len=0
199 1.053600  192.168.86.32  192.168.86.35  TCP  54  62346 → 80 [FIN, ACK] Seq=435 Ack=2 Win=64240 Len=0
200 1.060248  192.168.86.35  192.168.86.32  TCP  54  80 → 62346 [ACK] Seq=2 Ack=436 Win=5309 Len=0

The request is from the Chrome browser. As you can see, it tries to establish two simultaneous TCP connections from two different source ports, 62346 and 62347, because it will use the second one for embedded images. But WiFiMINA never accepts that connection with the 3-way handshake, and never gives it to me. Chrome will resend the second SYN packet three seconds later, but as long as the first connection is still active, WiFiMINA continues to ignore it.
How can you accept two simultaneous TCP connections on different source ports from the same client? That's required for Chrome.

The server.available() in Arduino networking libraries returns always the first connected client. This is in contrary with ESP8266 and ESP32 WiFi libraries for Arduino. They flag the returned connection as claimed and don't return it again. If the WiFiClient on ESP goes out of scope it is closed. In Arduino libraries you must stop() the Client to close the connection and free the 'socket'.
The Arduino Ethernet library has a new function not adopted yet by the WiFi libraries. It is server.accept(). It marks the connection as accepted and the next call doesn't return the same client. The sketch is still responsible to call stop(). The use of accept() is demonstrated in AdvancedChatServer example of the Ethernet library 2.00.
What you can do? Get the connection (WiFiClient), handle the request, send the response and stop() the connection. Then handle the next Client. Set Expires header to let browser cache the static files.

"The server.available() in Arduino networking libraries returns always the first connected client."  That doesn't seem to be the case for WiFiMINA. It's true the first time I call it in my example after connection ("Client 2"), but then as soon as data is available on the connection, server.available() returns zero.

Your suggestion to "...handle the request, send the response and stop()" won't work for Chrome, because by that time the library has already ignored the SYN packet establishing the second connection. Besides, Chrome expects both connections to be open at the same time. That's a totally legitimate use of the TCP/IP protocol.

but the TCP listening socket is on the ESP32. it should handle the TCP part of establishing the TCP connection. and then the connection should wait until the sketch gets to it

I agree, it should. But it doesn't seem to. Notice that it never responds to packet 180, which is trying to establish a connection from port 62347. Is there anything I could be doing wrong that causes it not to?


text:
Nothing gets sent to Arduino from Processing
I have a problem where I kwow that my bluetooth module (HC-05) is connected to a processing sketch, but nothing ever gets sent from the processing sketch,why?
No error messages but the info never gets sent over because I never see it in Arduino, where it would be printed to the Serial Monitor.
Full Processing Code:
import processing.serial.*;
import controlP5.*;

Serial myPort;
ControlP5 cp5;

int slider1 = 0;
int slider2 = 0;
int slider3 = 0;

void setup() {

  size(800, 800);
  cp5 = new ControlP5(this);
  PFont roboto = createFont("Roboto-Bold.ttf", 1, true);
  ControlFont font = new ControlFont(roboto, 28);
  Controller Aslider1 = cp5.addSlider("slider1")
    .setPosition(85, 100)
    .setCaptionLabel("Red")
    .setRange(0, 255)
    .setWidth(191)
    .setHeight(50);
  cp5.getController("slider1").getValueLabel().setFont(font).align(ControlP5.LEFT, ControlP5.BOTTOM_OUTSIDE).setPaddingX(0);
  cp5.getController("slider1").getCaptionLabel().setFont(font).align(ControlP5.RIGHT, ControlP5.BOTTOM_OUTSIDE).setPaddingX(0);

  Controller Aslider2 = cp5.addSlider("slider2")
    .setPosition(301, 100)
    .setCaptionLabel("Green")
    .setRange(0, 255)
    .setWidth(191)
    .setHeight(50);
  cp5.getController("slider2").getValueLabel().setFont(font).align(ControlP5.LEFT, ControlP5.BOTTOM_OUTSIDE).setPaddingX(0);
  cp5.getController("slider2").getCaptionLabel().setFont(font).align(ControlP5.RIGHT, ControlP5.BOTTOM_OUTSIDE).setPaddingX(0);

  Controller Aslider3 = cp5.addSlider("slider3")
    .setPosition(517, 100)
    .setCaptionLabel("Blue")
    .setRange(0, 255)
    .setWidth(191)
    .setHeight(50);
  cp5.getController("slider3").getValueLabel().setFont(font).align(ControlP5.LEFT, ControlP5.BOTTOM_OUTSIDE).setPaddingX(0);
  cp5.getController("slider3").getCaptionLabel().setFont(font).align(ControlP5.RIGHT, ControlP5.BOTTOM_OUTSIDE).setPaddingX(0);

  myPort = new Serial(this, "COM5", 9600);
}

void draw() {
  background(255, 100, 100);

  fill(255);
  stroke(1);
  rectMode(CENTER);
  rect(width/2, 350, 200, 75);

  fill(0);
  textSize(32);
  text("Send", width/2 - textWidth("Send") / 2, 350 + 10);

  if (mouseX > width/2 - 100 && mouseX < width/2 + 100 && mouseY > 350 - 75/2 && mouseY < 350 + 75/2) {
    if (mousePressed) {
      fill(100);
      stroke(1);
      rectMode(CENTER);
      rect(width/2, 350, 200, 75);

      fill(0);
      textSize(32);
      text("Send", width/2 - textWidth("Send") / 2, 350 + 10);
    } else {
      fill(170);
      stroke(1);
      rectMode(CENTER);
      rect(width/2, 350, 200, 75);

      fill(0);
      textSize(32);
      text("Send", width/2 - textWidth("Send") / 2, 350 + 10);
    }
  }
}

void mouseReleased() {
  if (mouseX > width/2 - 100 && mouseX < width/2 + 100 && mouseY > 350 - 75/2 && mouseY < 350 + 75/2) {
    fill(100);
    stroke(1);
    rectMode(CENTER);
    rect(width/2, 350, 200, 75);

    fill(0);
    textSize(32);
    text("Send", width/2 - textWidth("Send") / 2, 350 + 10);

    println(hex(color(int(slider1), int(slider2), int(slider3))).toString().substring(2));
    myPort.write(hex(color(int(slider1), int(slider2), int(slider3))).toString().substring(2));
    myPort.clear();
  }
}

Full Arduino Code:
#include <SoftwareSerial.h>
#include <Adafruit_NeoPixel.h>

const int PIN = 6;
const int NUMPIXELS = 30;

const byte rxPin = 2;
const byte txPin = 3;
SoftwareSerial mySerial (rxPin, txPin);

Adafruit_NeoPixel pixels(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);

unsigned long currentMillis;
unsigned long loopMillis;
unsigned long waitMillis;
int interval = 100;
int waitInterval = 0;
int redBrightness = 0;
int greenBrightness = 0;
int blueBrightness = 0;
bool wait = false;
bool goToRed = true;
bool goToOrange = false;
bool goToYellow = false;
bool goToGreen = false;
bool goToAqua = false;
bool goToPurple = false;

String hexValue;

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

void loop() {

  if (mySerial.available() > 0) {
    hexValue = mySerial.read();
    Serial.println(hexValue);
    if (hexValue != "shiftN" || hexValue != "shiftY") {
      shiftMode = false;
      // value is a hex
      redBrightness = hexValue.substring(0, 2).toInt();
      greenBrightness = hexValue.substring(2, 4).toInt();
      greenBrightness = hexValue.substring(4, 6).toInt();
    } else {
      if (hexValue = "shiftY") {
        shiftMode = true;
      } else {
        shiftMode = false;
      }
    }
  }

  pixels.show();

  setColor(redBrightness, greenBrightness, blueBrightness);

}

void setColor(int red, int green, int blue) {
  for (int i = 0; i < NUMPIXELS; i++) {
    pixels.setPixelColor(i, red, green, blue);
  }
}

Thanks for the help, cheers!
https://discourse.processing.org/t/nothing-gets-sent-to-arduino-from-processing/13654
https://stackoverflow.com/posts/57679763/edit

how do you know that the module is connected to Processing?

@jsotal it blinks twice and then repeats


text:
Micro is not recognised as HID device
Being a completely noob with Arduino (but not with coding though) I'm trying to create a simple buttonbox with a Micro unit.
For now, I can not figure out what should I do to make my Windows 10 recognize the Arduino as a HID device (joystick actually). What did I miss?

How should we be able to tell you, what you missed? You didn't give us any information at all. Provide the code, that you use. Also: Have you tried the examples from the Arduino IDE? For me they worked pretty well

@chrisl, Sorry, I thought it lays beyond arduino coding. I use a pretty simple matrix solution with Keyboard.h library. It works ok: all buttons are being recognized correctly (I use println for debug). Next thing I need is to make Win see the arduino as game controller. But no new devices are found in device list, no any devices available to add and so on. Should I make some extra steps to achieve that? As I know Micro board has a sort of HID controller in it's chip (sorry for missnaming if any) so it should be recognized in Windows by default. Should I use some extra library or something?

I don't quite understand, what you are trying to achieve. With the Keyboard library, the Micro will behave like a keyboard, which is by definition a HID device. I don't understand, where you mean it should appear in Windows and why? Gamecontrollers and keyboards are both HID devices, but they are not the same

this box should be a gamecontroller at the end. I sow a bunch of guides about how to make it and there no any steps described how to make Windows work with arduino as a game controller. So I have a gamepad now, what should I do to make Windows work with it when connected in USB?

As I wrote, Windows already works with it, treating it like a keyboard (as you told the Micro to behave like one). Generally Windows doesn't do much here. I guess you want, that it identifies itself as game controller. Then you cannot use the Keyboard library. Have you tried the Joystick library?

My bad. I mean I use Keypad.h not Keyboard.h Anyway, If I need Windows to see it as a game controller I have to use Joystick library https://github.com/MHeironimus/ArduinoJoystickLibrary, correct?

I think yes, though I haven't used it yet.

Joystick (github.com/MHeironimus/ArduinoJoystickLibrary) lib did the job. @chrisl, thx for the patience.


text:
Why voltage drop cause changes in analog reading of hall-effect sensor?
The sensor is a hall-effect UGN3503 sensor and I'm using a TL431 shunt regulator as voltage reference for analog readings.
I'm using analogRead() with setting the analog reference to external analogReference(EXTERNAL);.
schematic:

simulate this circuit – Schematic created using CircuitLab
The problem is changes in analog reading of hall-effect sensor. without connecting anything to Arduino but the sensor and TL431 reading is around ~1020, but for example connecting a single LED to any pins of Arduino causes the reading drop by ~2-3 or connecting the an I2C LCD causes the reading to drop to ~1010 etc...
How can i prevent analog read changes to happen when voltage drops?

You should show the Arduino in your circuit diagram, including how you connect the external voltage reference to the Arduino's AREF pin. (or is the AREF indicated in your diagram the connection to the Arduino's AREF pin). You should probably also show the relevant portions of your sketch's code.

@DuncanC the AREF in the diagram connected to the AREF pin of arduino and data pin of hall sensor to the a analog pin, and in the code there's really nothing except analogRead() and analogReference(EXTERNAL); and of course Serial.println()...

It sounds like your +5v supply is only barely adequate and sags as you draw even marginally more current. But even given that, your AREF is the TL431's voltage which 1) won't match the supply voltage (slightly redrawn schematic shows why), and 2) the sensor voltage could possibly exceed the AREF which is out of spec for the Arduino's A/D.
A more stable power supply - able to maintain its voltage despite the expected variation in current draw - would help a lot, but your best solution is to use the supply voltage as your AREF, unless you require the TL431 reference to be your AREF for some reason.

The power supply currently is a USB (Arduino UNO board), before TL431 i had a 3.3V regulator connected to the AREF. i thought changing it to TL431 can solve the problem but it didn't...

You said "A more stable (i.e., capable) would help a lot". Do you mean A more stable (i.e., capable) POWER SUPPLY would help a lot"? As in a higher current regulated power supply?

Yes - thanks for the catch. Fixed.

I suspect the USB 5v supply is rather noisy and sags slightly with load. A hall effect sensor measures TINY signals, so it's probably quite sensitive to changes in supply voltage.
You might try adding a capacitor to the line, but you'd be better off either feeding 7.5-9-VDC into the barrel connector and using the on-board voltage regulator on the Arduino to generate your 5V and 3.3V, or feeding a regulated 5V supply into a cut USB cable (that way you get the power source switching and fuse protection on Arduino boards, but still can use an externally regulated 5V supply.)


text:
Error: " stray '##' in program in
I am trying to use #define in Arduino IDE as I used to do in Atmel Studio like:
#define PROGRAM(N) void PROG_##N(void)

However I am getting a stray error because of the hashes, is there a way to implement this better?
Aim: PROGRAM(5){} becomes void PROG_5(void){} and so on.

It compiler in my Arduino IDE. Code:  (using \n as newlines):
#define PROGRAM(N) void PROG_##N(void) \n
PROGRAM(5){}\n
void setup(){}\n
void loop(){}

What version of the IDE are you using? You're not a Linux user that used apt-get to install it are you?

It is working now, the mistake was actually in a different file but Arduino IDE 1.8.8 kept saying it is here which was confusing. Thanks.


text:
Why is Serial Print causing different behaviour based on where its located
Im trying to test out these two motors I have where I need to call a function from the loop. I only want to call this function once so I made a quick little if statement to have the program only run once. However, it seems that when I run this file, the Variable I have set doesn't continue getting incremented. The code will tell more.
int i = 0;

void loop()
{
    // Serial.print("=====");Serial.print(i);Serial.println("=====");
    if(i == 1)
    {
        Serial.print("+++");Serial.print(i);Serial.print("+++");
        DeclinationMotor(DEC_freq, NULL, HIGH);
    }
    i++;
}

The behavior is really odd in that if i just run that code above, the variable i will not get incremented and become stuck at 1. However if I were to un-comment the other serial print line above the if statement, i would be incremented properly and that function will be executed only once.
For reference, the function DeclinationMotor is
float DeclinationMotor(float freqspeed, float angularDistance, byte direction)
{
    Serial.print(freqspeed); Serial.print("DEfS "); Serial.print(angularDistance); Serial.print("DEaD "); Serial.println(direction);

    int finalLocation = 0;
    if(freqspeed == NULL && angularDistance != NULL)
        freqspeed = DEC_freq;
    if(angularDistance != NULL)
    {
        if(direction == HIGH)
            finalLocation = DEC_degrees_from_home + angularDistance;
        else
            finalLocation = DEC_degrees_from_home - angularDistance;
    }

    SetPinFrequency(DEC_STEP, freqspeed);
    pwmWrite(DEC_STEP, 128);
    digitalWrite(DEC_DIR, direction);
    digitalWrite(DEC_running, HIGH);

    return finalLocation;
}

Full Code Here
//-----------------------------------------------------------------------------
#include <PWM.h>
void analogJoyStick();
void serialEvent();
void meridianFlipT();
float RightAscensionMotor(float freqspeed, float angularDistance, byte direction);
float DeclinationMotor(float freqspeed, float angularDistance, byte direction);
void StopRAMotor();
void StopDECMotor();

// --------------Todo--------------
// Turn the Variables into motor actions for serial event
// Write program that helps figure out the encoders degrees for its
// angle crap. You might just need to count exactly how many
// times the revolution goes around manually
// set up isrs for optical sensors and joystick
// create stop motors function
//

#define RA_sensor 2
#define DEC_sensor 3

// Sensor limit LEDs
#define RA_limit 27
#define DEC_limit 29

// Telescope Position Status LEDs
#define home_pos 35
#define tracking 37

// Joystick
#define xPin A0      // X axis
#define yPin A1      // Y axis
#define JS_button 26 // Button

// Motor 1
#define RA_STEP 10                // Step for Right Ascension
#define RA_DIR 12                 // Direction for Right Ascension
#define RA_EN 32                  // Enable motor disconnection
#define RA_OUT 36                 // Motor fault output
int RA_freq = 800;                // Frequency for normal movement
int RA_freq_tracking = 400;       // Frequency for tracking objects
int RA_freq_slow = 600;           // Frequency for when close to desired position
volatile byte RA_track_DIR = LOW; // Used to store last direction of RA motor

// Encoder 1
#define RA_A 18
#define RA_B 19
#define RA_I 22
long int RA_Encoder_Count = 0;      // Positive value means net position is in B direction
int RA_Complete_Rotations = 0; // Positive value means net complete rotation is in B direction
int RA_degrees_from_home = 0;  // Used to keep track of how far from home position

// Motor 2
#define DEC_STEP 11                 // Step for Declination
#define DEC_DIR 13                  // Direction for Declination
#define DEC_EN 34                   // Enable motor disconnection
#define DEC_OUT 38                  // Motor fault output
int DEC_freq = 800;                 // Frequency for normal movement
int DEC_freq_slow = 600;            // Frequency when close to desired position
volatile byte DEC_track_DIR = LOW;  // Used to store last direction of DEC motor

// Encoder 2
#define DEC_A 20
#define DEC_B 21
#define DEC_I 24
long int DEC_Encoder_Count = 0;      // Positive value means net position is in B direction
int DEC_Complete_Rotations = 0; // Positive value means net complete rotation is in B direction
int DEC_degrees_from_home = 0;  // Used to keep track of how far from home position

// Communication with ATmega328
#define COMM 39
#define RA_running 23
#define DEC_running 25

int i = 0;

void setup()
{
    // Sensor Inputs
    pinMode(RA_sensor, INPUT);
    pinMode(DEC_sensor, INPUT);

    // Sensor Fault LEDs
    pinMode(RA_limit, OUTPUT);
    pinMode(DEC_limit, OUTPUT);

    // Telescope Position Status LEDs
    pinMode(home_pos, OUTPUT);
    pinMode(tracking, OUTPUT);

    // Interrupts for Sensors
    // attachInterrupt(digitalPinToInterrupt(RA_sensor), RA_sensor_trip, CHANGE);
    // attachInterrupt(digitalPinToInterrupt(DEC_sensor), DEC_sensor_trip, CHANGE);

    // Right Ascension Motor Inputs and Outputs
    pinMode(RA_STEP, OUTPUT);
    pinMode(RA_DIR, OUTPUT);
    pinMode(RA_OUT, INPUT);
    // attachInterrupt(digitalPinToInterrupt(RA_OUT), RA_motor_fault, CHANGE);

    // Right Ascension Encoder Inputs
    pinMode(RA_A, INPUT);
    // attachInterrupt(digitalPinToInterrupt(RA_A), RA_Enc, RISING);
    pinMode(RA_B, INPUT);
    pinMode(RA_I, INPUT);

    // Declination Motor Inputs and Outputs
    pinMode(DEC_STEP, OUTPUT);
    pinMode(DEC_DIR, OUTPUT);
    pinMode(DEC_OUT, INPUT);
    // attachInterrupt(digitalPinToInterrupt(DEC_OUT), DEC_motor_fault, CHANGE);

    // Declination Encoder Inputs
    pinMode(DEC_A, INPUT);
    // attachInterrupt(digitalPinToInterrupt(DEC_A), DEC_Enc, RISING);
    pinMode(DEC_B, INPUT);
    pinMode(DEC_I, INPUT);

    // Joystick inputs
    pinMode(xPin, INPUT);
    pinMode(yPin, INPUT);
    pinMode(JS_button, INPUT);

    // Communication with ATmega328
    pinMode(COMM, OUTPUT);
    pinMode(RA_running, OUTPUT);
    pinMode(DEC_running, OUTPUT);

    // Constant signal to ATmega328 to confirm ATmega2560 is operational
    digitalWrite(COMM, HIGH);

    Serial.begin(9600);
    InitTimersSafe();

}

void loop()
{
    // Serial.print("=====");Serial.print(i);Serial.println("=====");
    if(i == 1)
    {
        Serial.print("+++");Serial.print(i);Serial.print("+++");
        DeclinationMotor(RA_freq, NULL, HIGH);
    }
    i++;
}

void analogJoyStick()
{
    int NumbX, NumbY;

    while(digitalRead(JS_button) == LOW)
    {
        NumbX = analogRead(xPin);
        NumbY = analogRead(yPin);

        // Here we go to to move the motor and the numbers have been created with
        // small numerical buffers to allow deadzones. It was made to be linear response
        // to the users input.

        if(NumbX > 530)
            RightAscensionMotor((RA_freq * (NumbX - 512)/512), NULL, HIGH);
        else if(NumbX < 500)
            RightAscensionMotor((RA_freq * (NumbX - 512)/512), NULL, LOW);
        else
            StopRAMotor();

        if(NumbY > 530)
            DeclinationMotor(800, NULL, HIGH);
        else if(NumbY < 500)
            DeclinationMotor(800, NULL, LOW);
        else
            StopDECMotor();
        delay(50);
    }
    // Track();
}

// this thing seems to be appended onto the end of the loop() so the immediate intersection must be
void serialEvent()
{
    char ident = Serial.read();     // first character will be the identifying character

    if(ident == 'R')
    {
        int number1 = Serial.parseInt();        // these variables should become global afterwards
        Serial.read();
        int number2 = Serial.parseInt();

        // you don't know what origin is yet so..
    }
    else if(ident == 'M')
    {
        int raAngle = Serial.parseInt();
        Serial.read();                              // These serial reads are for the separaters in the transmitted string
        int raDirection = Serial.parseInt();
        Serial.read();
        int dAngle = Serial.parseInt();
        Serial.read();
        int dDirection = Serial.parseInt();

        RightAscensionMotor(RA_freq, raAngle, raDirection);
        DeclinationMotor(DEC_freq, dAngle, dDirection);
    }

    // Serial.readbytes()
    Serial.read();      // this is to read the newline character out of the buffer.
}

// This needs to be called if
// if(Osensor1 || Osensor2)
    // meridianFlip();
void meridianFlipT()
{
    float finalLocationRA, finalLocationD;
    byte RACheck = LOW; byte DCheck = LOW;
    Serial.println("F1");    // newline is already incorporated

    // Right so, RA is normal yea whatever, but Declination is made this way to allow the counter weight
    // to always be pointed away from the tripod. For the latitude is 0 at the pole.
    finalLocationRA = RightAscensionMotor(RA_freq, 180, !RA_track_DIR);
    finalLocationD = DeclinationMotor(DEC_freq, ((180 - DEC_degrees_from_home) * 2), !DEC_track_DIR);

    // This is going to check to see if both the motors have turned to their respective locations theres
    // a little buffer period that is inputted to just to see if the motor gets there. We can replaced this later on
    while(RACheck == LOW || DCheck == LOW)
    {
        if(RACheck == LOW && (finalLocationRA + 2 > RA_degrees_from_home && finalLocationRA - 2 < RA_degrees_from_home))
        {
            digitalWrite(RA_running, LOW);
            RACheck = HIGH;
        }
        if(DCheck == LOW && (finalLocationD + 2 > DEC_degrees_from_home && finalLocationD - 2 < DEC_degrees_from_home))
        {
            digitalWrite(DEC_running, LOW);
            DCheck = HIGH;
        }
        delay(10);
    }

    //Track();            // Resume Tracking
    Serial.println("F0");
}

// These two are just functions to move the motors with. Might have a
// return to tell that its finished or something
float RightAscensionMotor(float freqspeed, float angularDistance, byte direction)
{
    Serial.print(freqspeed); Serial.print("RAfS "); Serial.print(angularDistance); Serial.print("RAaD "); Serial.println(direction);

    int finalLocation = 0;
    if(freqspeed == NULL && angularDistance != NULL)
        freqspeed = RA_freq;
    if(angularDistance != NULL)
    {
        if(direction == HIGH)
            finalLocation = RA_degrees_from_home + angularDistance;
        else
            finalLocation = RA_degrees_from_home - angularDistance;
    }

    SetPinFrequency(RA_STEP, freqspeed);                 // Look at SetPinFrequencySafe()
    pwmWrite(RA_STEP, 128);
    digitalWrite(RA_DIR, direction);
    digitalWrite(RA_running, HIGH);                 // I think this just turns it on?

    return finalLocation;
}

float DeclinationMotor(float freqspeed, float angularDistance, byte direction)
{
    Serial.print(freqspeed); Serial.print("DEfS "); Serial.print(angularDistance); Serial.print("DEaD "); Serial.println(direction);

    int finalLocation = 0;
    if(freqspeed == NULL && angularDistance != NULL)
        freqspeed = DEC_freq;
    if(angularDistance != NULL)
    {
        if(direction == HIGH)
            finalLocation = DEC_degrees_from_home + angularDistance;
        else
            finalLocation = DEC_degrees_from_home - angularDistance;
    }

    SetPinFrequency(DEC_STEP, freqspeed);
    pwmWrite(DEC_STEP, 128);
    digitalWrite(DEC_DIR, direction);
    digitalWrite(DEC_running, HIGH);

    return finalLocation;
}

void StopRAMotor()
{
    Serial.println("-RAMotor Stopped-");
    digitalWrite(RA_STEP, LOW);
    digitalWrite(RA_running, LOW);
}
void StopDECMotor()
{
    Serial.println("-DECMotor Stopped-");
    digitalWrite(DEC_STEP, LOW);
    digitalWrite(DEC_running, LOW);
}

have you tried putting the code into setup() instead. It is made for things, that only should run once

I totally could but that doesn't help me understand why this wouldn't work. (Btw i just did and it worked completely fine) @chrisl

Ahh sorry the F(freqspeed) was me just messing around with storing the data in the flash memory instead of the SRAM as i saw on some other threads.. I didn't have that during actual testing so i should've deleted it from this post. Thanks for the catch @juraj
Edit:
Its deleted now.

Yes that, AND the serial line inside of the if() inside of the loop function has a print out of the variable i, which constantly repeats it being 1. @Juraj

Here is my guess what happens:
Once the code in the if statement have run, the loop() only contains the incrementation of i. This will run very fast. After a rather short time (maybe someone here can make the calculation to get the time, that is needed) i will overflow, going from it's most positive value to it's most negative value, then incrementing further and finally reaching again 1. As this happens rather fast, you think, that i does not increment, but it is just flowing over again and again. i is of type int, which means, that it needs 65535 loop() iterations, to get to 1 again.
About the version with the extra Serial.print() calls: You didn't show us your setup(), but you probably have chosen a rather slow baudrate (maybe 9600, as it is used by many examples). At the first iterations the calls are just placing the data in the buffer and returning fast. But after a few iterations the Serial buffer is full. In this case the Serial.print()/Serial.write() functions (and their siblings) are blocking the code execution, until enough space in the buffer is free. So this would considerably slow down the executing of the loop(), thus considerably increasing the time between i overflows - to a point, where you don't wait long enough to actually see it overflow (but it will happen at some point).

To execute a code part only once you can either use the setup() function (if the call should happen at the start of the program), or you can use a simple flag. Imagine, that you don't increment i in the loop(), but that you are setting it's value to zero inside of the if statement. That would prevent the code in the if statement to execute again, until you yourself set i to 1 again.
byte flag = 0;

void setup(){
    flag = 1; // Set flag to 1 somewhere in your sketch as you like, to execute the if statement
}

void loop(){
    if(flag){
        //execute the wanted code here
        flag = 0; // deactivate this code by setting the flag to 0
    }
}

Notice, that I changed some things here:

I changed the name of the variable to flag, because that's what it is: A simple flag with only 2 states - zero and non-zero
I changed the type of the variable to byte, as you don't need a whole int (16 bits) for a simple flag. So I used the smallest variable type, a byte. (you could also use boolean here, but basically that's the same)
The if statement now only checks for the value of flag directly. It will evaluate as true, if flag is not zero, as false, if it is zero. (So you could set flag to any other value than zero to activate the code, but true is also defined as 1, so I stayed in line with this).
I set the flag back to zero inside the if statement, so that it will not be executed another time. It will only execute again, if you yourself set flag again to a non-zero value somewhere in your code.

Hmm thats interesing, but i don't get why then it wouldn't just skip some numbers at some point and be iterating slowly. However you gave me an idea for something that might be happening. So in other words, the buffer fills up with 8 prints and continues the loop. Once the loop reaches 1 again then it prints out the same 8 prints again which happen to be at i equals 1. This explains it printing out again every half a second. If this is the case, then making the variable i a double or something large should slow down the repeated print outs.

Im going to be putting a screenshot of the print out in the post

Also i just realized, then why is it that when I un-comment the Serial print line above the if() statement then the variable i gets properly incremented and outputed.

Can confirm, I did the opposite of that and made the variable i a byte, and now it prints out everything again a lot faster then before. Increasing it to a float makes it print out only one, but i did not wait nearly long enough to make up the for the numerical difference between an int and a float

The print in the if statement can only output i as 1, since it only executes, if i is one. So here you don't see if i increments. The increments happens outside of the if statement, so you can only see the incrementation, if you output i outside of the if statement. But just because you don't see it increment doesn't mean that it does not increment.

You should use long instead of float. Avr based Arduinos don't have native float calculation, so it is a waste of computation time to use float instead of long

Second one first, yea i ended up using long instead of float.
Yea thats what im saying aswell. The loop function keeps iterating through an int until i hits 1, adding the 8 print lines to the buffer. Since it does that super fast, it just prints those statements again and again at a decent speed, each time i overflows and hits 1. Changing the range that i can loop at, I.E. making it a byte or a long will change the speed at which the prints are printed. Having an outside serial.print just fills up the buffer with all those other numbers of i being made, making it look real time

I can test this later, but i assume if i leave it this way the buffer of the arduino will eventually really fill up and it will start skipping numbers. (when i have the out of if() statement un-commented. Or at least this is what i gleaned from playing around with it and reading everyones comments.

Yes, exactly. It also slows down the loop function

No, it will not skip numbers. The print calls will wait, until enough data from the buffer was send. It slows the sketch down, but it will not loose the serial data

Ah true lol yea i just realized that as you were typing it lol


text:
Can I use only Ruby or Crystal Lang with an Arduino?
I am new to Arduino. I have used other SBCs before and ran some ruby script to automate many tasks.
I know Ruby and Crystal programming languages.
Can I use Ruby or Crystal solely on Arduino for creating basic robot?

Short answer: No

Long answer: Noooooooooooooo.

You could bridging via Firmata: https://playground.arduino.cc/Interfacing/Ruby/
Another resource is https://code.tutsplus.com/articles/using-ruby-to-program-arduino--cms-21893
You will need to Flash your Arduino with Firmata and then program in Ruby.
I'm not sure if that would work with Crystal.

No. You cannot. It is not possible. And some more filler to make the answer long enough.

This is for Ruby:
https://playground.arduino.cc/Interfacing/Ruby/
Here are generic info about interfacing:
https://playground.arduino.cc/Main/Interfacing/


text:
Editing a particular position in a file stored in SD card
I am trying to store some variables in a text file which is saved in a SD card, using the SD library. Every time my program runs, it load the values of those variables from the file. After a few minutes, my program will attempt to change the value of some variables (not all).
This is what I would in a C program. I would locate the position (using position()) where the values to be edited is present, and then using the seek() function I would write at the given position thus overwriting the file.
Each variable is stored in a separate row. But for some reason the program only writes at the end of the file, even if I have moved the file pointer elsewhere. How can I do the above task?
A simple example of the code is as follows:
#include <SD.h> //Load SD library

int chipSelect = 53;
File file;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(chipSelect, OUTPUT); // chip select pin must be set to OUTPUT mode

  Serial.print("Welcome!");
  Serial.println();

  bool initialization_state = SD.begin(chipSelect);
  delay(400); // SD card needs sometime to intialize

  if (!initialization_state) { // Initialize SD card
    Serial.println("Could not initialize SD card."); // if return value is false, something went wrong
  } else {  // if return value is true
    Serial.println("SD card initialized");
  }

  SD.remove("misc.txt");
  file = SD.open("misc.txt",FILE_WRITE);
  file.print("Once you know the central idea and a rough plan for your paragraphs, you need to arrange them in a certain manner to get your story across.");
  file.println();
  file.print("Following are some possible ways of organizing your paragraphs.");
  file.println();
  file.print("Narration: Tell a story. Go chronologically, from start to finish. Description: Provide specific details about what something looks, smells, tastes, sounds, or feels like.");
  file.println();
  file.print("Organize spatially, in order of appearance, or by topic. Process: Explain how something works, step by step. Perhaps follow a sequence—first, second, third.");
  file.close();
  read_file();
  Serial.print("Read?");
  Serial.println();

  update_file();
  read_file();
}

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

void read_file() {
  Serial.println("--- Reading file ---");
  file = SD.open("misc.txt", FILE_READ);

  char character;
  while( (character = file.read()) != -1) {
    Serial.print(character);
  }
  Serial.println();
  file.close();
}

void update_file() {
  file = SD.open("misc.txt", FILE_READ);
  char character;
  while( (character = file.read()) != '\n') {}
  byte pos = file.position();
  file.close();

  file = SD.open("misc.txt", FILE_WRITE);
  file.seek(pos);
  file.print(" Love, love, love.");
  file.close();
}

In this program I am attempting to overwrite the second line. The while loop breaks at the first newline character. I store the location of the first character in the second line in a variable pos. Then I open the file object for writing, I seek the position where I want to write (using file.seek(pos) ) and then I print into the file. But when I read the file, the text "Love, love, love." is written at the end.
I am using the linux Arduino IDE 1.8.9.

Personally I would read the file line by line, writing each line to a temporary file. You then change the lines that need changing on the fly. Afterwards you delete the old file and rename the temporary file to the old name. That way you can more easily handle changes in the length of data.

@Majenko Ok. But I was wondering if my approach could be performed on an arduino? Does the SD library not support it?

No reason why it shouldn't. However: how do you know that you are not seeking to the end of the file?

Because once I had located and stored pos. I closed the file object. Then opened another file object in FILE_READ, used file.seek(pos) to go to the location and printed the remaining file on the serial monitor. It had worked.

The problem is that you are opening the file with FILE_WRITE.  That is a combined macro that is made up of:
#define FILE_WRITE (O_READ | O_WRITE | O_CREAT | O_APPEND)

The key one there is O_APPEND.  In the source code (SdFile.cpp) t says:

O_APPEND - If set, the file offset shall be set to the end of the file prior to each write.

So the seek does nothing if O_APPEND is set, since it is overridden.
So instead you need to open the file without O_APPEND.  In fact you don't need to close and open the file at all, since if opened correctly you can hop around at will reading and writing.  The flag O_RDWR is a combination of O_READ and O_WRITE.
For example:
void update_file() {
  file = SD.open("misc.txt", O_RDWR);
  char character;
  while( (character = file.read()) != '\n') {}
  file.print(" Love, love, love.");
  file.close();
}

The O_CREAT flag that is part of FILE_WRITE will create a new file if you try and open one that doesn't exist. By omitting that SD.open will fail if the file you are trying to modify doesn't exist.

Isn't file.seek(file.position()); a no-op?

@EdgarBonet Probably, yes.


text:
Arduino Mega failing to connect to XAMPP database/php server to send HTTP requests
I have developed an application with a SunFounder Mega2560 with a W5100 Ethernet shield that acts as a server and successfully parses TCP message packets from a client sending in updates. I am now trying to add HTTP GETs into the mix by sending off my data to update an XAMPP server, which I am treating as a client in my code.
For some reason, I can't seem to connect to the XAMPP's Apache service on my machine for it to receive the HTTP message to update the MariaDB table through a PHP script I created. The Apache service seems to be listening on port 80, which I am attempting to initiate the connection on.
You can mostly just pay attention to the postData() command below, but I'm including everything for completeness.
#include <stdlib.h>
#include <string.h>
#include <SPI.h>
#include <Ethernet.h>

#define MAX_CLIENTS 1
#define MAX_LINE_LEN 100
char inputs[MAX_CLIENTS][MAX_LINE_LEN] = {0}; // Instantiate 2D array of client/received data
int msg_array[] = {0,0,0,0};

EthernetServer server(1174);                  // Create server object on port of server, which will be used to respond to commands
EthernetClient *client = NULL;                // Create client objects limited to size of MAX_CLIENTS
EthernetClient db;                            // Create a client object just for posting HTTP commands to the database

byte mac[] = {0x24,0x0A,0xC4,0xAC,0xC1,0x78}; // Arduino's physical MAC
byte ip[] = {192,168,1,23};                   // IP of this controller
byte gateway[] = {192,168,1,77};              // Router address (internet)
byte myDns[] = {192,168,1,77};                // Router dns
byte subnet[] = {255,255,0,0};                // Subnet mask
byte dbserver[] = {192,168,1,77};             // IP address of SQL server

unsigned long wd_Dside, wd_Cside;             // Gather current Arduino pgm ms timestamp
unsigned long wd_Delap, wd_Celap = 0;         // Create an elapsed time counter
int dside_prev, cside_prev = 0;       // Create a previous state for each AV to determine code execution
char rId[3] = {0};
int avSide = 0;

// --------------------------------------------------------------------------------------------------------

void setup(){

// initialize the ethernet device
//  Ethernet.begin(mac, ip, myDns, gateway, subnet);
  Ethernet.begin(mac, ip);

  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
  ; // wait for serial port to connect. Needed for native USB port only
  }

  // Check for Ethernet hardware present
  if (Ethernet.hardwareStatus() == EthernetNoHardware) {
    Serial.println("Ethernet shield was not found.  Sorry, can't run without hardware.");
    while (true) {
      delay(1); // do nothing, no point running without Ethernet hardware
        }
  }

  if (Ethernet.linkStatus() == LinkOFF) {
    Serial.println("Ethernet cable is not connected.");
  }

  pinMode(22, OUTPUT);                          // pin selected to control AV D SIDE
  pinMode(23, OUTPUT);                          // pin selected to control AV C SIDE

  // wait 5 seconds for connection:

  delay(5000);
  server.begin();                                // Start server
  Serial.print("Server started on ");
  Serial.println(Ethernet.localIP());
  delay(1000);

  wd_Dside, wd_Cside = millis();

}

// --------------------------------------------------------------------------------------------------------

void loop() {

  delay(100);
  int i=0;

  EthernetClient newClient = server.available();
  if (newClient) {
    if (client==NULL){
    client = new EthernetClient(newClient);
  }
  }

  if (client != NULL && client->available()){                     // If the data isn't garbage and the data is available..
    Serial.print("Client's IP address: ");
    Serial.println(client->remoteIP());
    Serial.print("Client sent: ");
    char newChar = client->read();                                // Read the data
    Serial.println(newChar);

    if (newChar == '\0') {                                        // Check for a termination character for separation
      Serial.println("Client terminated message.");
      char delimiters[] = ",";                                    // Use a string parser in order to get command parameterization
      char* valIndex;
      valIndex = strtok(inputs[i], delimiters);
      for (int j=0; j<4; j++){                                    // Expand later to largest anticipated character count
        msg_array[j] = atoi(valIndex);
        //Serial.print(msg_array[j]);
        valIndex = strtok(NULL, delimiters);
      }

      switch(msg_array[0]) {                                      // Determine type of message received via Ethernet (Character 0 parsed as Message Type)

        case 3:                                                   // Examine string for instructions to turn AVs on or off.

        char cstr[16];
        strcat(rId, itoa(msg_array[2],cstr,10));              // Build rId string prior to any potential HTTP post (which refs rId)
        strcat(rId, itoa(msg_array[3],cstr,10));
        Serial.print("R ID: ");
        Serial.println(rId);

        if(msg_array[1] == 1)                                     // Msg type 3, Instruction 1: Turn D side AV ON
          {
            avSide = 0;
            if (dside_prev != msg_array[1]){
              Serial.println("Dside AV is OPEN.");
              digitalWrite(22, HIGH);                             // Set pin 4 low
              postData();                                         // Call the HTTP POST function
            }

            dside_prev = msg_array[1];
            wd_Delap = 0;                                         // Reset elapsed time watchdog time value for D side.
            wd_Dside = millis();                                  // Last good heartbeat received from client device on D side.
          }
        if(msg_array[1] == 2)                                     // Msg type 3, Instruction 2: Turn Dside AV OFF
          {
            avSide = 0;
            if (dside_prev != msg_array[1]){
              Serial.println("Dside AV is CLOSED.");
              digitalWrite(22, LOW);                              // Set pin 4 low
              //postData();                                         // Call the HTTP POST function
            }

            dside_prev = msg_array[1];
            wd_Delap = 0;                                         // Reset elapsed time watchdog time value for D side.
            wd_Dside = millis();                                  // Last good heartbeat received from client device on D side.
          }
        if(msg_array[1] == 3)                                     // Msg type 3, Instruction 3: Turn Cside AV ON
          {
            avSide = 1;
            if (cside_prev != msg_array[1]){
              Serial.println("Cside AV is OPEN.");
              digitalWrite(23, HIGH);                             // Set pin 5 high
              //postData();                                         // Call the HTTP POST function
            }

            cside_prev = msg_array[1];
            wd_Celap = 0;                                         // Reset elapsed time watchdog time value for C side.
            wd_Cside = millis();                                  // Last good heartbeat received from client device on C side.
          }
        if(msg_array[1] == 4)                                     // Msg type 3, Instruction 4: Turn Cside AV OFF
          {
            avSide = 1;
            if (cside_prev != msg_array[1]){
              Serial.println("Cside AV is CLOSED.");
              digitalWrite(23, LOW);                              // Set pin 5 high
              //postData();                                         // Call the HTTP POST function
            }

            cside_prev = msg_array[1];
            wd_Celap = 0;                                         // Reset elapsed time watchdog time value for C side.
            wd_Cside = millis();                                  // Last good heartbeat received from client device on C side.
          }

        rId[0]='\0';                                          // Clear the array
        break;

        case 6:
                                                                  // Examine string for EA status messages
        break;

        default:
          Serial.println("Default break encountered. Received gibberish.");
        break;

      }

    inputs[0][0] = '\0';                                      // Clear out this array element for the next message
    //client->stop();                                         // By default, kill the client session and just wait for a new TCP open
    //delete client;                                          // Remove client element's data
    //client = NULL;                                          // Reset to NULL
    Serial.println(inputs[0]);

    }

    else {

       if (strlen(inputs[i]) > MAX_LINE_LEN) {                     // Append it to the message content string, but first check for size compliance
        Serial.println("Max line length exceeded from client.");
        inputs[0][0] = '\0';                                       // Clear out this array element for the next message
       }
       else {
        size_t l = strlen(inputs[0]);
        inputs[0][l] = newChar;
        inputs[0][l + 1] = 0;
        // strcat(inputs[i], newChar);                             // Add character to the received string
       }

      Serial.print("inputs[0]: ");
      Serial.println(inputs[0]);

    }
  }

/* Update watchdog timers

wd_Delap = (millis()-wd_Dside);
wd_Celap = (millis()-wd_Cside);

if (wd_Delap>=60000)
      {
        Serial.print("Elapsed time on watchdog, D side: ");
        Serial.println(wd_Delap);
        Serial.print("Last message recieved: ");
        Serial.println(wd_Dside);
        digitalWrite(4, LOW);    // set pin 4 low
        Serial.println("Dside AV didn't hear from anyone in 60s; defaulting to OFF.");
      }

if (wd_Celap>=60000)
      {
        Serial.print("Elapsed time on watchdog, C side: ");
        Serial.println(wd_Celap);
        Serial.print("Last message recieved: ");
        Serial.println(wd_Cside);
        digitalWrite(5, LOW);    // set pin 5 low
        Serial.println("Cside AV didn't hear from anyone in 60s; defaulting to OFF.");
      }
  */
}

// Section to update database via HTTP
void postData() {
  Serial.println("Hit postData");
  client->stop();

  delay(250);
  Serial.println("Stopping and reconnecting.");

  if (db.connect(dbserver, 80)) {
    Serial.println("Connected to DB host machine.");
    db.print("GET /write_data.php?");

    db.print("RID=");
    db.print(rId);
    db.print("&");

    db.print("side=");
    db.print(avSide);
    db.print("&");

    db.print("state=");
    db.print("1");

    db.println(" HTTP/1.1");
    db.println("Host: localhost");
    db.println("User-Agent: Arduino/1.0");
    db.println("Connection: close");
    db.println();
    db.println();
    db.stop();

  }
  else {
  Serial.println("Connection failed to DB host machine.");
  }

  delay(5000);
}

This is the output:
Client's IP address: 192.168.1.77
Client sent: ,
inputs[0]: ,
Client's IP address: 192.168.1.77
Client sent: 3
inputs[0]: ,3
Client's IP address: 192.168.1.77
Client sent: ,
inputs[0]: ,3,
Client's IP address: 192.168.1.77
Client sent: 1
inputs[0]: ,3,1
Client's IP address: 192.168.1.77
Client sent: ,
inputs[0]: ,3,1,
Client's IP address: 192.168.1.77
Client sent: 3
inputs[0]: ,3,1,3
Client's IP address: 192.168.1.77
Client sent: ,
inputs[0]: ,3,1,3,
Client's IP address: 192.168.1.77
Client sent: 7
inputs[0]: ,3,1,3,7
Client's IP address: 192.168.1.77
Client sent:
Client terminated message.
R ID: 37
Dside AV is OPEN.
Hit postData
Connecting...
Connection failed to DB host machine.

Am I maybe initializing something incorrectly, or am I becoming a victim to one of the commonly references issues with the Ethernet library not being able to handle multiple connections on the Arduino?
Thanks!
EDIT:
Well with some troubleshooting of the HTTP methods and formats to address the URI, I didn't turn up much; But I did by chance notice that changing my semicolons to ampersands for the value fields are what did the trick! I have achieved communication to my MariaDB! The issue I'm having now is that the client disconnects after dumping the information to the database, and does not re-enter the normal loop to wait on another message.
My postData() routine above has been edited to show what I am doing. The main loop is looping, but does not show that the server() receives anything like it would previously.

Ethernet.begin(mac, ip); for IP 192.168.1.77 assumes gateway and DNS at 192.168.1.1. use "Host: 192.168.1.77". Is the port 80 open on firewall of the PC?

Can you reach port 80/send a POST from another machine on your network?

db.print("R ID="); there is a space inside your url. Urls shouldn't contain spaces.

@Juraj Are you referring to a specific function that the Ethernet() library implements? I don't see a Host parameter.

@MarkusDeibel you and Juraj's suggestions are good ones, as I couldn't access the web page without adding a rule for all port 80, 443 and 3306 traffic; however, the code is now stepping in and attempting to connect but locks up and restarts everything.

Host header in the request

Got the DB working! See edit above. My issue now is that the original server connection I have running to check for messages will no longer pick anything up after postData() is called!


text:
Issues controlling servo motors with serial monitor while using 16 channel servo Shield
I am making a 6-axis robotic arm that uses multiple servo motors.The goal is to create a program that accepts degree values from the serial monitor to control multiple servo motors.
I have just started programming with the Arduino, so I need help debugging a program that I have piece together from guides throughout the internet. The program will compile and upload, but when I input values into the serial monitor the servo will not move like I would like it to. At the moment, the servo motor will move 50 degrees. I have calibrated my servo but it still won't work properly. Furthermore, I kept the program for one servo just for testing I know that I will have to create an int motorA=0; motorB=1; etc. Any help will be appreciated
reference links:
https://forum.arduino.cc/index.php?topic=242458.0
https://www.youtube.com/watch?v=y8X9X10Tn1k
Hardware:
Arduino Uno
16 channel Arduino Servo shield
5v external power supply
MG995 Servo
Notes:
No connectivity issues
Motor is connected properly
No hardware issues
Program:
enter code here
String readString;
#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>

#define SERVOMIN  650
#define SERVOMAX  2350
#define FREQUENCY 60

Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();

int motorA = 0;
int motorB = 1;

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

void moveMotor(int ang, int motorOut)
{

 int angle = map(ang,0, 180, SERVOMIN,SERVOMAX);
 for ( uint16_t pulse_width = 0; pulse_width < angle; pulse_width++)
 {
   pwm.setPWM(motorOut, 0, pulse_width);

 }
}

void loop()
{
 //expect single strings like 30c, or 90a, or 180d,
//or combined like 30c,180b,70a,120d,

if (Serial.available())
{
  char c = Serial.read();  //gets one byte from serial buffer
  if (c == ',')
  {
    if (readString.length() >1)
    {
     Serial.println(readString); //prints string to serial port out

     int angle = readString.toInt();  //convert readString into a number

     Serial.print("writing Angle: ");
     Serial.println(angle);
     if (readString.indexOf('a') >0) moveMotor(angle, motorA);

     readString=""; //clears variable for new input
   }
 }
else {
  readString += c; //makes the string readString
  }
 }
}

What are you sending over serial to control the motor?

Degree values like 110a, or 120a, . The a just means motorA  and the number means the degree value

I don't see an obvious error. You can do some things, to further narrow down the problem: 1. Remove the for loop from moveMotor(), since it is too fast for the motor anyway, or make it slower by putting in a delay. 2. Check, if a PWM signal is actually outputted from the shield. If you don't have an oscilloscope, you can connect an LED to the channel and driving the channel slowly from 0% to 100% duty cycle (be sure to include a delay there). If the LED is fading in, the PWM signal is correctly outputed. 3. Recheck the pulse width, that your motors is reacting to and be sure to use it.

That clears up a lot thank you. I will use your advice. If I remove the for loop the motor will not move at all


text:
Write an array to SD
I'm new to the Arduino and I asked some questions around here and they were really helpful so I'm hoping I will get help once more
#define maxLen 800

volatile  unsigned int irBuffer[maxLen]; //stores timings - volatile because changed by ISR
volatile unsigned int x = 0; //Pointer thru irBuffer - volatile because changed by ISR

void setup() {
  Serial.begin(9600); //change BAUD rate as required
  attachInterrupt(0, rxIR_Interrupt_Handler, CHANGE);//set up ISR for receiving IR signal
}

void loop() {

  Serial.println(F("Press the button on the remote now - once only"));
  delay(5000); // pause 5 secs
  if (x) { //if a signal is captured
    Serial.println();
    Serial.print(F("Raw: (")); //dump raw header format - for library
    Serial.print((x - 1));
    Serial.print(F(") "));
    detachInterrupt(0);//stop interrupts & capture until finshed here
    for (int i = 1; i < x; i++) { //now dump the times
      if (!(i & 0x1)) Serial.print(F(" "));
      Serial.print(irBuffer[i] - irBuffer[i - 1]);
      Serial.print(F(", "));
    }
    x = 0;
    Serial.println();
    Serial.println();
    attachInterrupt(0, rxIR_Interrupt_Handler, CHANGE);//re-enable ISR for receiving IR signal
  }

}

void rxIR_Interrupt_Handler() {
  if (x > maxLen) return; //ignore if irBuffer is already full
  irBuffer[x++] = micros(); //just continually record the time-stamp of signal transitions

}

I would like to modify the code above to write to an SD file instead of printing it on the serial port. I've tried to use myFile.write or myFile.print but it won't work. Maybe I am just not that aware of how the SD functions work. Any tips?
This is a function to capture IR signals. I require them for a Arduino remote.
The modified code:
//you may increase this value on Arduinos with greater than 2k SRAM
#define maxLen 800

#include <SPI.h>
#include <SD.h>

File myFile;

volatile  unsigned int irBuffer[maxLen]; //stores timings - volatile because changed by ISR
volatile unsigned int x = 0; //Pointer thru irBuffer - volatile because changed by ISR

void setup() {
  Serial.begin(9600); //change BAUD rate as required
  attachInterrupt(0, rxIR_Interrupt_Handler, CHANGE);//set up ISR for receiving IR signal
}

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

  Serial.print("Initializing SD card...");

  if (!SD.begin(53)) {
    while (1);
  }
  Serial.println("initialization done.");

  // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
  myFile = SD.open("test.txt", FILE_WRITE);

  Serial.println(F("Press the button on the remote now - once only"));
  delay(5000); // pause 5 secs
  if (x) { //if a signal is captured
    Serial.println();
    myFile.print(F("Raw: (")); //dump raw header format - for library
    myFile.print((x - 1));
    myFile.print(F(") "));
    detachInterrupt(0);//stop interrupts & capture until finshed here
    for (int i = 1; i < x; i++) { //now dump the times
      if (!(i & 0x1)) myFile.write(F(" "));
      myFile.print(irBuffer[i] - irBuffer[i - 1]);
      myFile.print(F(", "));
    }
    x = 0;
    Serial.println();
    Serial.println();
    attachInterrupt(0, rxIR_Interrupt_Handler, CHANGE);//re-enable ISR for receiving IR signal
  }

}

void rxIR_Interrupt_Handler() {
  if (x > maxLen) return; //ignore if irBuffer is already full
  irBuffer[x++] = micros(); //just continually record the time-stamp of signal transitions

}

How is it not working? What is actually happening? And why don't you include the actual code in question (the SD card code), so that we can search for errors?

The code is in the question. The code is working, it prints to the serial monitor. I just want to modifiy it to 'print' to a file in an SD card.

You wrote, that you already tried to use the SD library to do so. But I cannot see this in your code. We need to see this, so that we can find possible errors in there. We will not simply write the code for you, as we are not a free code writing service. Explain what exactly the problem was, when trying to use the SD library. Otherwise your question is too broad.

file.print() should work exactly the same as Serial.print(). But you have to open the file first. Did you read the documentation of the SD library? The examples? Anything you didn't understand in these docs?

I just used file.print file instead that's why I dind't upload the code. I just need help to see where the problem is, not for someone to write my code. I will add it to the question right away.

You are still missing a description about what is actually happening? Doesn't the file exists after the program ran? Does it contain garbage or wrong values? If yes, what exactly does it contain?

That's the thing, it doesn't contain anything. That's why I wanted to make sure that the file.print() does the same thing. I'll just try to sketch the code in a different way, thanks !

If you never do a myFile.close() the buffered data will never get written to the SD card.

@Majenko that is true! It seem to work now

You are never closing the file.  The SD library (owing to how SD cards work) operates around a 512 byte buffer. Only when that buffer is full, or the library is manually instructed, will that buffer ever get written to the SD card.
The two ways of forcing the buffer to be written to the card are:

Close the file with myFile.close() or
Flush the file with myFile.flush()

Unless you do one of those after storing your data, since you are writing less than 512 bytes, the data will be lost when you power off (or reset) or remove the SD card.


text:
Send Arduino data to PHP inorder to upload in MySQL database
I'm trying to send arduino data to my online web server using a Arduino Uno and a Ethernet shield. I used POST method for sending data and tried sending data to my sever (add.php) using a online POST request generating  site (https://www.codepunker.com/tools/http-requests) . That works perfect and it updated my database with sent data. But my database doesn't get any data when I try to send data with Arduino and Ethernet shield. Any suggestions to make this work? What changes should I do to my arduino code?
Database

Serial Out
Initialize Ethernet with DHCP:
DHCP assigned IP 192.168.1.102
connected to 145.14.145.94
still working here
temp1=10&hum1=24
Successfull
Client Stopped

Arduino Code
  #include <SPI.h>
  #include <Ethernet.h>

  byte mac[] = { 0x00, 0xAB, 0xBA, 0xBC, 0xDD, 0x02 };
  EthernetClient client;
  String data;
  int t;
  int h;
  IPAddress ip(192, 168, 1, 177);
  IPAddress myDns(192, 168, 1, 1);
  char server[] = "lattalottaroom2.000webhostapp.com";

  void setup() {
    Serial.begin(9600);
    Serial.println("Initialize Ethernet with DHCP:");
    if (Ethernet.begin(mac) == 0) {
      Serial.println("Failed to configure Ethernet using DHCP");
      // Check for Ethernet hardware present
      if (Ethernet.hardwareStatus() == EthernetNoHardware) {
        Serial.println("Ethernet shield was not found.  Sorry, can't run without hardware. :(");
        while (true) {
          delay(1); // do nothing, no point running without Ethernet hardware
        }
      }
      if (Ethernet.linkStatus() == LinkOFF) {
        Serial.println("Ethernet cable is not connected.");
      }
      // try to congifure using IP address instead of DHCP:
      Ethernet.begin(mac, ip, myDns);
    } else {
      Serial.print("  DHCP assigned IP ");
      Serial.println(Ethernet.localIP());
    }

    // if you get a connection, report back via serial:
    if (client.connect(server, 80)) {
      Serial.print("connected to ");
      Serial.println(client.remoteIP());
    } else {
      // if you didn't get a connection to the server:
      Serial.println("connection failed");
    }

    Serial.println("still working here");

  }

  void loop() {
  t = 10;
  h = 24;

  data = "temp1=";

  data.concat(t);

  data.concat("&hum1=");

  data.concat(h);

    if (client.connect("lattalottaroom2.000webhostapp.com",80)) {
      Serial.println(data);
      client.print("POST /add.php HTTP/1.1");
      client.print("Host: lattalottaroom2.000webhostapp.com");
      client.print("Connection: close");
      client.print("Content-Type: application/x-www-form-urlencoded");
      client.print("Content-Length: ");
      client.println(data.length());
      client.println();
      client.print(data);
      Serial.println("Successfull");

    }

    if (client.connected()) {
      client.stop();
      Serial.println("Client Stopped");

    }

    delay(20000);
  }

connect.php
<?php

        function Connection(){
            $server="localhost";
            $user="id10666900_arduinodata";
            $pass="thunder";
            $db="id10666900_arduinodata";

            $connection = mysqli_connect($server,$user,$pass,$db);

            if (!$connection) {
                die('MySQL ERROR: ' . mysqli_connect_error());
            }

            return $connection;
        }
    ?>

add.php
<?php
      include("connect.php");

      $link=Connection();

      $query = "INSERT INTO `tempLog` (temp, hum) VALUES ('".$_POST["temp1"]."','"$_POST["hum1"]."')";

              if (mysqli_query($link, $query)) {
                 echo "New record created successfully";
              } else {
                 echo "Error: " . $query . "" . mysqli_error($link);
              }

              $link->close();

      header("Location: index.php");
  ?>

All your headers are on one long line. You need to split them. Use println instead of print when your header is a complete string.

Thanks for your quick response  Majenko . I changed those to println and still doesn't get any data to database.

What do you see when you echo the $query variable?

If I directly feed the data using the url like https://lattalottaroom2.000webhostapp.com/add.php?temp1=40&hum1=50 it echo INSERT INTO tempLog (temp, hum) VALUES ('40', '50') and updates the DB. However after I changed the arduino code as follows, I was able to upload data to local database with add.php using my arduino and ethernet shield. client.print("GET /arduino/add.php?");           client.print("temp1=");           client.print(t);           client.print("&hum1=");           client.println(h);

I have the same problem as you and I would like to know if you already know the answer? If you do, can you please share your knowledge. It would be very helpful. Thank you.


text:
Trouble in sensor data reading sequence
I am reading from two MPU6050 sensors using Arduino Uno but it give trouble in squence. The code is perfect and also sensors reading is done.
See image of serial monitor.

You can see the above image in which the output data of serial monitor is not lining up. It breaks the lines after some time interval. I want to expect the serial data in lining. Here is the code:
// I2Cdev and MPU6050 must be installed as libraries, or else the .cpp/.h files
// for both classes must be in the include path of your project
#include "I2Cdev.h"

#include "MPU6050_6Axis_MotionApps20.h"
//#include "MPU6050.h" // not necessary if using MotionApps include file

// Arduino Wire library is req1uired if I2Cdev I2CDEV_ARDUINO_WIRE implementation
// is used in I2Cdev.h
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
#include "Wire.h"
#endif

// class default I2C address is 0x68
// specific I2C addresses may be passed as a parameter here
// AD0 low = 0x68 (default for SparkFun breakout and InvenSense evaluation board)
// AD0 high = 0x69
//MPU6050 mpu;
MPU6050 mpu1(0x68);
MPU6050 mpu2(0x69); // <-- use for AD0 high

// uncomment "OUTPUT_READABLE_YAWPITCHROLL" if you want to see the yaw/
// pitch/roll angles (in degrees) calculated from the q1uaternions coming
// from the FIFO. Note this also req1uires gravity1 vector calculations.
// Also note that yaw/pitch/roll angles suffer from gimbal lock (for
// more info, see: http://en.wikipedia.org/wiki/Gimbal_lock)
#define OUTPUT_READABLE_YAWPITCHROLL

int pre_count = 0;

#define LED_PIN 13 // (Arduino is 13, Teensy is 11, Teensy++ is 6)
bool blinkState = false;

// MPU control/status vars
bool dmpReady1 = false;  // set true if DMP init was successful
uint8_t mpuIntStatus1;   // holds actual interrupt status byte from MPU
uint8_t devStatus1;      // return status after each device operation (0 = success, !0 = error)
uint16_t packetSize1;    // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount1;     // count of all bytes currently in FIFO
uint8_t fifoBuffer1[64]; // FIFO storage buffer

// MPU control/status vars
bool dmpReady2 = false;  // set true if DMP init was successful
uint8_t mpuIntStatus2;   // holds actual interrupt status byte from MPU
uint8_t devStatus2;      // return status after each device operation (0 = success, !0 = error)
uint16_t packetSize2;    // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount2;     // count of all bytes currently in FIFO
uint8_t fifoBuffer2[64]; // FIFO storage buffer

// orientation/motion vars
Quaternion q1;           // [w, x, y, z]         q1uaternion container
VectorInt16 aa1;         // [x, y, z]            accel sensor measurements
VectorInt16 aa1Real1;     // [x, y, z]            gravity1-free accel sensor measurements
VectorInt16 aa1World1;    // [x, y, z]            world-frame accel sensor measurements
VectorFloat gravity1;    // [x, y, z]            gravity1 vector
float euler1[3];         // [psi, theta, phi]    euler1 angle container
float ypr1[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity1 vector

// packet structure for InvenSense teapot demo
uint8_t teapotPacket1[14] = { '$', 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0x00, 0x00, '\r', '\n' };

Quaternion q2;           // [w, x, y, z]         q1uaternion container
VectorInt16 aa2;         // [x, y, z]            accel sensor measurements
VectorInt16 aa1Real2;     // [x, y, z]            gravity1-free accel sensor measurements
VectorInt16 aa1World2;    // [x, y, z]            world-frame accel sensor measurements
VectorFloat gravity2;    // [x, y, z]            gravity1 vector
float euler2[3];         // [psi, theta, phi]    euler1 angle container
float ypr2[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity1 vector

// packet structure for InvenSense teapot demo
uint8_t teapotPacket2[14] = { '$', 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0x00, 0x00, '\r', '\n' };

// ================================================================
// ===               INTERRUPT DETECTION ROUTINE                ===
// ================================================================

volatile bool mpuInterrupt1 = false;     // indicates whether MPU interrupt pin has gone high
void dmpDataReady1() {
  mpuInterrupt1 = true;
//  Serial.println("Mpu interrupt true");
}

volatile bool mpuInterrupt2 = false;     // indicates whether MPU interrupt pin has gone high
void dmpDataReady2() {
  mpuInterrupt2 = true;
}

// ================================================================
// ===                      INITIAL SETUP                       ===
// ================================================================

void setup() {
  // join I2C bus (I2Cdev library doesn't do this automatically)
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
  Wire.begin();
  TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
  Fastwire::setup(400, true);
#endif

  // initialize serial communication
  // (115200 chosen because it is req1uired for Teapot Demo output, but it's
  // really up to you depending on your project)
  Serial.begin(115200);
  while (!Serial); // wait for Leonardo enumeration, others continue immediately

  // NOTE: 8MHz or slower host processors, like the Teensy @ 3.3v or Ardunio
  // Pro Mini running at 3.3v, cannot handle this baud rate reliably due to
  // the baud timing being too misaligned with processor ticks. You must use
  // 38400 or slower in these cases, or use some kind of external separate
  // crystal solution for the UART timer.

  // initialize device
  Serial.println(F("Initializing I2C devices 1..."));
  mpu1.initialize();

   // initialize device
  Serial.println(F("Initializing I2C devices 2..."));
  mpu2.initialize();

  // verify connection
  Serial.println(F("Testing device 1 connections..."));
  Serial.println(mpu1.testConnection() ? F("MPU6050 1 connection successful") : F("MPU6050 1 connection failed"));

  // verify connection
  Serial.println(F("Testing device 2 connections..."));
  Serial.println(mpu2.testConnection() ? F("MPU6050 2 connection successful") : F("MPU6050 2 connection failed"));

  // wait for ready
  Serial.println(F("\nSend any character to begin DMP programming and demo: "));
  while (Serial.available() && Serial.read()); // empty buffer
  while (!Serial.available());                 // wait for data
  while (Serial.available() && Serial.read()); // empty buffer again

  // load and configure the DMP
  Serial.println(F("Initializing DMP 1..."));
  devStatus1 = mpu1.dmpInitialize();

  // load and configure the DMP
  Serial.println(F("Initializing DMP 2..."));
  devStatus2 = mpu2.dmpInitialize();

  // supply your own gyro offsets here, scaled for min sensitivity
  mpu1.setXGyroOffset(220);
  mpu1.setYGyroOffset(76);
  mpu1.setZGyroOffset(-85);
  mpu1.setZAccelOffset(1788); // 1688 factory default for my test chip

  // supply your own gyro offsets here, scaled for min sensitivity
  mpu2.setXGyroOffset(74);
  mpu2.setYGyroOffset(14);
  mpu2.setZGyroOffset(-19);
  mpu2.setZAccelOffset(253); // 1688 factory default for my test chip

  // make sure it worked (returns 0 if so)
  if (devStatus1 == 0) {
    // turn on the DMP, now that it's ready
    Serial.println(F("Enabling DMP 1..."));
    mpu1.setDMPEnabled(true);

    // enable Arduino interrupt detection
    Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
    attachInterrupt(0, dmpDataReady1, RISING);
    mpuIntStatus1 = mpu1.getIntStatus();

    // set our DMP Ready flag so the main loop() function knows it's okay to use it
    Serial.println(F("DMP 1 ready! Waiting for first interrupt..."));
    dmpReady1 = true;

    // get expected DMP packet size for later comparison
    packetSize1 = mpu1.dmpGetFIFOPacketSize();
  } else {
    // ERROR!
    // 1 = initial memory load failed
    // 2 = DMP configuration updates failed
    // (if it's going to break, usually the code will be 1)
    Serial.print(F("DMP 1 Initialization failed (code "));
    Serial.print(devStatus1);
    Serial.println(F(")"));
  }

  // make sure it worked (returns 0 if so)
  if (devStatus2 == 0) {
    // turn on the DMP, now that it's ready
    Serial.println(F("Enabling DMP 2..."));
    mpu2.setDMPEnabled(true);

    // enable Arduino interrupt detection
    Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
    attachInterrupt(0, dmpDataReady2, RISING);
    mpuIntStatus2 = mpu2.getIntStatus();

    // set our DMP Ready flag so the main loop() function knows it's okay to use it
    Serial.println(F("DMP 2 ready! Waiting for first interrupt..."));
    dmpReady2 = true;

    // get expected DMP packet size for later comparison
    packetSize2 = mpu2.dmpGetFIFOPacketSize();
  } else {
    // ERROR!
    // 1 = initial memory load failed
    // 2 = DMP configuration updates failed
    // (if it's going to break, usually the code will be 1)
    Serial.print(F("DMP 2 Initialization failed (code "));
    Serial.print(devStatus2);
    Serial.println(F(")"));
  }

  // configure LED for output
  pinMode(LED_PIN, OUTPUT);
}

// ================================================================
// ===                    MAIN PROGRAM LOOP                     ===
// ================================================================

void loop() {

  // if programming failed, don't try to do anything
  if (!dmpReady1) return;

  // if programming failed, don't try to do anything
  if (!dmpReady2) return;

// Serial.println("code access here 1");
  // wait for MPU interrupt or extra packet(s) available
  while (!mpuInterrupt1 && fifoCount1 < packetSize1) {
    // other program behavior stuff here
    // .
    // .
    // .
    // if you are really paranoid you can freq1uently test in between other
    // stuff to see if mpuInterrupt1 is true, and if so, "break;" from the
    // while() loop to immediately process the MPU data
    // .
    // .
    // .
     break;

//    Serial.println("code access here 2");
  }

  // wait for MPU interrupt or extra packet(s) available
  while (!mpuInterrupt2 && fifoCount2 < packetSize2) {
    // other program behavior stuff here
    // .
    // .
    // .
    // if you are really paranoid you can freq1uently test in between other
    // stuff to see if mpuInterrupt1 is true, and if so, "break;" from the
    // while() loop to immediately process the MPU data
    // .
    // .
    // .
    break;
  }

  // reset interrupt flag and get INT_STATUS byte
  mpuInterrupt1 = false;
  mpuIntStatus1 = mpu1.getIntStatus();

  // reset interrupt flag and get INT_STATUS byte
  mpuInterrupt2 = false;
  mpuIntStatus2 = mpu2.getIntStatus();

  // get current FIFO count
  fifoCount1 = mpu1.getFIFOCount();

  // get current FIFO count
  fifoCount2 = mpu2.getFIFOCount();

  // check for overflow (this should never happen unless our code is too inefficient)
  if ((mpuIntStatus1 & 0x10) || fifoCount1 == 1024) {
    // reset so we can continue cleanly
    mpu1.resetFIFO();
    Serial.println(F("FIFO overflow!"));

    // otherwise, check for DMP data ready interrupt (this should happen freq1uently)
  } else if (mpuIntStatus1 & 0x02) {
    // wait for correct available data length, should be a VERY short wait
    while (fifoCount1 < packetSize1) fifoCount1 = mpu1.getFIFOCount();

    // read a packet from FIFO
    mpu1.getFIFOBytes(fifoBuffer1, packetSize1);

    // track FIFO count here in case there is > 1 packet available
    // (this lets us immediately read more without waiting for an interrupt)
    fifoCount1 -= packetSize1;

#ifdef OUTPUT_READABLE_YAWPITCHROLL
    // display euler1 angles in degrees
    mpu1.dmpGetQuaternion(&q1, fifoBuffer1);
    mpu1.dmpGetGravity(&gravity1, &q1);
    mpu1.dmpGetYawPitchRoll(ypr1, &q1, &gravity1);
    int count = 0;
    count++;
    pre_count += count;
    Serial.print(pre_count);
    Serial.print("\t");
    Serial.print(ypr1[0] * 180 / M_PI);
    Serial.print("\t");
    Serial.print(ypr1[1] * 180 / M_PI);
    Serial.print("\t");
    Serial.print(ypr1[2] * 180 / M_PI);
    Serial.print("\t");
#endif

//    // blink LED to indicate activity
//    blinkState = !blinkState;
//    digitalWrite(LED_PIN, blinkState);
  }

   // check for overflow (this should never happen unless our code is too inefficient)
  if ((mpuIntStatus2 & 0x10) || fifoCount2 == 1024) {
    // reset so we can continue cleanly
    mpu2.resetFIFO();
    Serial.println(F("FIFO 2 overflow!"));

    // otherwise, check for DMP data ready interrupt (this should happen freq1uently)
  } else if (mpuIntStatus2 & 0x02) {
    // wait for correct available data length, should be a VERY short wait
    while (fifoCount2 < packetSize2) fifoCount2 = mpu2.getFIFOCount();

    // read a packet from FIFO
    mpu2.getFIFOBytes(fifoBuffer2, packetSize2);

    // track FIFO count here in case there is > 1 packet available
    // (this lets us immediately read more without waiting for an interrupt)
    fifoCount2 -= packetSize2;

#ifdef OUTPUT_READABLE_YAWPITCHROLL
    // display euler1 angles in degrees
    mpu2.dmpGetQuaternion(&q2, fifoBuffer2);
    mpu2.dmpGetGravity(&gravity2, &q2);
    mpu2.dmpGetYawPitchRoll(ypr2, &q2, &gravity2);
    Serial.print("\t");
    Serial.print(ypr2[0] * 180 / M_PI);
    Serial.print("\t");
    Serial.print(ypr2[1] * 180 / M_PI);
    Serial.print("\t");
    Serial.println(ypr2[2] * 180 / M_PI);
#endif

//    // blink LED to indicate activity
//    blinkState = !blinkState;
//    digitalWrite(LED_PIN, blinkState);
  }

   // blink LED to indicate activity
    blinkState = !blinkState;
    digitalWrite(LED_PIN, blinkState);
}

What is the problem?
Thanks in advance!

I totally don't understand what you mean by "trouble in sequence". Please explain more. What are you expecting and what is actually happening?

@chrisl you can see the above image in which the output data of serial monitor is not lining up. It breaks the lines after some time interval. I want to expect the serial data in lining.

Both printing codes are inside of different if statements, which involve testing mpuIntStatus1 and mpuIntStatus2. This works good, as long as in one void loop() iteration both of these if statements are executed. But that's a timing issue and you cannot assume, that these things happen regularly and always this way. Without completely analyzing your code, the variables mpuIntStatus1/2 seem to indicate, that new data arrived. There is no reason, why this should be synchronized with the void loop() iterations.
To solve this you should rewrite your code to include all these print statements into one single if statement at the end of void loop(). In the if statements from above you can set a flag to indicate, that data arrived. This flag will be tested by the if statement at the end of loop. It is up to you to decide, how this should behave, when only data from 1 sensor arrived. You can only print the values from this sensor, or you can print both and using dummy values, that can be distinguished by humans (for example all values zero). Or you can choose to only print out values, if both sensors have given you results.