text:
Arduino connected keypad printing wrong numbers
Going crazy here trying to connect a keypad to my Arduino. I followed this article KeypadTutorial, but my guess is something is wrong/different because my keypad only has 9 pins and the far left (pin 1) and far right (pin 9) pins have no traces back to the keypad. I bought it years ago and just got around to finding a use for it. It looks just like this one Arduino Keypad but different with white keys with black font.
The issue is the wrong key shows up (i.e. press 0 and get 9). I used a multi-meter to test for continuity between pins when pressing each key and got results that are kind of stumping me. I would think there would be some kind of pattern (like the first pin would always be a 1, 2, or a 3), but obviously not (or I just have a bad keypad).
KEY(pin1, pin2)
1(2,3)
2(1,2)
3(2,5)
4(3,7)
5(1,7)
6(5,7)
8(1,6)
9(5,6)
0(1,4)
#(4,5)
*(3,4)

in your list, transpose the pins for a couple of keys and a pattern will emerge .... 1(3,2) and 3(5,2) and #(5,4)

@jsotola - I can't believe I completely missed that. Soon as I transposed the keys you pointed out and wrote it out on paper in a square pattern it made perfect sense. Wired it up, correctly, and it worked perfectly. If you want to post it I'll mark it as answered.

Transpose the pins for some of the keys and a pattern will emerge.
KEY(pin1, pin2)      transposed pins
1(2,3)        x        1(3,2)
2(1,2)                 2(1,2)
3(2,5)        x        3(5,2)
4(3,7)                 4(3,7)
5(1,7)                 5(1,7)
6(5,7)                 6(5,7)
8(1,6)                 8(1,6)
9(5,6)                 9(5,6)
0(1,4)                 0(1,4)
#(4,5)        x        #(5,4)
*(3,4)                 *(3,4)


text:
GPS: Not receiving any valid output from ATGM336H
I have an Arduino Pro Mini along with a GPS Unit - ATGM336H. Below is the sketch I'm currently using:
#include <SoftwareSerial.h>
#include "Ublox.h"
SoftwareSerial GPS(4,5);
Ublox serial_gps;

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

void loop(){
  while(GPS.available()){
  char c = GPS.read();
  if(serial_gps.encode(c)){
  Serial.println(serial_gps.longitude);
    }
  }
}

I'm able to receive NMEA stream from the GPS Unit and parse (tried TinyGPS++, TinyGPS and Ublox) the stream but the data is not valid nor does it ever change. I've read that this GPS unit can take up to 32 seconds to get a fixed position and deliver valid co-ords but I cannot receive any.

Is there anything obviously wrong with my sketch or hardware setup?
Any and all help would be greatly appreciated!

remove the if(serial_gps.encode(c)){ Serial.println(serial_gps.longitude); } .... instead, use Serial.println(c); to see if there is any actual data ...... I think that you are sending individual characters to gps.encode(), so you get nothing back

while(GPS.available() > 0) {....
Also is the GPS unit outside?

I have tested the project both indoors and outdoors. I do receive NMEA streams but they seems to be lacking critical info.
I will include the >0 and get back to you with a result

There is no difference between while(GPS.available()) and while(GPS.available() > 0). 0 is false anything else is true and GPS.available() doesn't return negative values.

available() returns the number of bytes in the RX buffer, so if you juts use available() zero will be returned and the sub will run and return zeros which is what his output looks like. If you use available() > 0 then only when 1 or more bytes exist then the sub will run.

If available() returns zero then the while loop will not run, since zero is false.

source: Stack Exchange

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

sort: votes


text:
Adafruit Feather 32u4 FONA KEY Pin
I received a Adafruit Feather 32u4 FONA as a gift and have read the great, comprehensive document Adafruit put have put together surrounding pinouts, examples etc for the board. I am having issue understanding the section on the KEY pin, I understand that it is used to put the cellular module to sleep, but in order to do this it is mentioned to “cut the trace and wire it to a micro controller pin”. Does this mean that in order to utilize the on/off functionality of the SIM module I have to slightly butcher my new shiny board instead of using the pin directly?

When you have to cut a track there is normally an exposed area between two pads, clearly marked as the bit of track to cut.  You are right with what it means, because doing this saves the manufacturer the few cents adding a jumper would have cost :)

Yes, you will need to physically cut the trace to use the on/off feature. This is common on development boards. It could be done with a jumper but that would add cost and/or require a larger board.
You will see on the back of the board there are 2 large pads connected by a thin trace. You can use an exacto knife to cut the trace. To repair the cut you use a blob of solder to bridge the gap between the pads.

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


text:
Is my Arduino dead?
I connected my Arduino Uno to an external power supply, but did not noticed the power supply was on 30 V, I saw the part in the picture smoking and immediately pulled the cable out of the Arduino.
now, each time I connect it to some source of power his "ON and "L" light up ("TX" and "RX" are dark) and the ATmega heats up, and it can't receive sketches from my PC. It says just

Problem uploading to board.

Is my board completely dead or I can somehow save it?

Have you tried powering it via USB?

If the '328P gets hot, it is dead. But, it's replaceable, you can even buy one with a bootloader loaded in already.
The part you circles is a 100nF capacitor, a 10 cents part.
If the PC is not recognizing it when you plug in USB, then the Atmega16U2 that does the USB interfacing is dead. That one is a very small surface mount part that you cannot replace without a hot air rework station, and then you will need a Programmer to reload it with its USB interface program.
And if you killed the 2 regulators, those need replacing too.
Get another board, be more careful next time.
I'd get a 7.5V or 9V wallwart for power. I think you can get the wallwart and a bootloaded '328P from www.dipmicro.com, www.sparkfruit.com, www.adafruit.com, etc.

You could try to replace the SMD part, probably a capacitor (I may be wrong), if you can identify which part it is from the schematic (or any marking on the board).  However, you may have damaged something else as well. You will only know if and once you have replaced the smoking part.
You may be lucky and only that part has been damaged.
The ATmega appears to be socketed so you could try removing it and putting it in another undamaged board to see if it works still.
It looks like the smoking part is next to a regulator, IC2 (I am not 100% sure about that), but that would make sense, seeing as it was a power supply issue that caused the smoking in the first place.  Maybe just the power supply part of the board is damaged (D1, PC1, PC2, C2, IC1 or IC2 - the two big black and white capacitors, with 47 25V written on them in your photo are PC1 and PC2), and you could slowly work your way through it, checking and replacing the sequential parts (again with the use of the schematic).
I wouldn't throw the board away, I have some partially damaged boards that only half function, but the part that still functions will probably suitable for some project or other in the future... or maybe not, depending on the damage.
It is hard to tell from just a photo which being able to check the parts using a multimeter.
Given that the power LED and L LED still work, there is some hope. Try using the USB input for power and see if that helps as the circuit is different from that of the power jack (no regulator). See VIN AND PWRIN versus USBVCC, on the schematic.
Here is the power jack circuit:

Here is the USB input:

However, if, as you say, the PC can not see the Arduino to communicate with it, it will make programming it difficult.
If you do have another UNO board, with a removable ATmega IC, program Blink.ino on to the ATmega and place it in the damaged board to see if the L LED blinks. If it does then at least some of the board still works.
However, to sum up, your Arduino is probably not going to be as useful as it was prior to the over voltage having been applied - unless you are both lucky and replace a few SMD parts.
On the positive side, look at it as a learning experience on how to track down and repair faults on a PCB - a very useful skill to have.


text:
Arduino UART (TX/RX) multidrop 1 master 50 slaves
I'm thinking to connect about 50 slave Arduinos on 1 master using TX/RX. I'm following recommendation of these links:

I'm looking for a way to serially communicate with a multi mesh Arduino slave network, and;
Tx/Rx UART communication between 2 MCU over 1 line

using the cathode of diode connected to slaves TX pins and pulling up this line, like this image:

In Arduino - Digital Pins, when pin is set to input (high impedance), it is "equivalent to a series resistor of 100 MΩ in front of the pin". Slave RX line has input (RX pin) in parallel, then, if this 'equivalent resistor' is true, we have a low resistance (duo parallel configuration) that burn the master TX. Is it make sense?
I have not found either in the Arduino or the ATmega documentation, if TX port have the internal pullup on. In ATmega documentation, TX pin is set as output and RX pin as input. The TTL logic is high on idle, then 5 V must be sourced from somewhere, correct?

Might want to use RS-485.

RS-485 is limited to 32 devices. For now, I need to use only TX/RX to communicate between master and slaves. It works for a master and 2 slaves. But, I'm worried when I connect 50 slaves and burn the master TX.

The number of devices depends on the bus driver. With "Fractional Unit-Load devices" you can have as many as 255 devices on a single bus segment. It is also possible to use multiple segments (repeater).

I checked RX (input) port in Arduino and it have 5 V and drain 0.14 mA. Then, RX is internal pulledup. But, ATmega 328P documentation say that internal pullup resistor is optional and USART section, at same documentation, have not mention about pullup TX.

nice project. Does it work so far? I'm going to do something similar.
which diodes do I have to select for this?

@Chris, I used the 1N4700. I used this to connect 72 arduinos, but I multiplexed the lines to have the max 18. I have some problems because of cables length (some with 10m), but worked with regards.

An input pin draws 1uA or less input current, so more like 1 Megohm resistor, not 100 Megohm.
In an Uno, the USB interface chip typically is what is pulling the Tx and Rx lines high with 5mA drive (high output thru a 1K resistor to D0 or D1).
What you have drawn should work. The pullup resistor will ensure the Rx into the 1st Arduino sees a nice crisp high when the other two stop pulling the line low as they send a message out, and the diodes will prevent the one driving the line high while the other pulls it low.

The Arduino - Digital Pins official documentation inform a 100 Megohms resistance to out the pin as input (high impedance). Reading Arduino Schematic, the RX and TX pins in ATmega 328 is connected to ATmeg82U. Maybe this CI can source 5 V to RX/TX. But I'm not using USB to power up Arduinos. I'm using UNO and Minipro powered up through 5 V Vin. Then, I do not know where come 5 V to pulling pins high.

There are other mistakes in Arduino documentation as well, 100 Megohm is just one of them.     The Atmega328P data sheet clearly says maximum input current is no more than 1uA. V=IR, or V/I = R. 1V/.000001A = 1,000,000 ohm resistor. Maybe 5 Megohm if you want to consider a 5V input and 1uA of current.

@CrossRoads, how does a 100MΩ resistor violate the "max 1μA" requirement?


text:
Arduino - Button to start / stop loop
So basically I'm trying to create a device where when I push a button it starts a loop. When I push this button again, it stops the loop. Right now I have it logged to serial. It starts up correctly with no output. When I press the button the loop begins and it spits out "toggled on" continuously. When I press the button again... nothing happens. What should happen ideally is that it should stop spitting out "toggled on" and just go back to doing nothing.
#include <Bounce2.h>

Bounce bouncer = Bounce();
const int W = 10;
bool wOn = false;

void setup() {
  Serial.begin(9600);
  pinMode(W, INPUT_PULLUP);
  bouncer.attach(W);
  bouncer.interval(5);
}

void loop() {
  bouncer.update();
  if (bouncer.read() == LOW) {
    wOn = !wOn;
  }

  if (wOn > 0) {
    Serial.println("toggled on");
  }
}

If you change your sketch to this one, you'll see the issue:
const int W = 10;
bool wOn = false;

void setup() {
  Serial.begin(9600);
  pinMode(W, INPUT_PULLUP);
}

void loop() {
  if (digitalRead(W) == LOW) {
    wOn = !wOn;
  }

  if (wOn) {
    //Serial.println("toggled on");
  }
  Serial.println(wOn);
}

The button's contacts "bounce" (Google "contact bounce"), sending multiple low to high signals. There are several software solutions that will eliminate this issue. Have a look at: arduino.cc/en/Tutorial/Debounce. There are a couple of libraries that simplify de-bouncing buttons: playground.arduino.cc/Code/Debounce and playground.arduino.cc/Code/Bounce

I've added Bounce2 (I believe correctly) and it still has the same result. I added that bit to see the wOn value and it changes correctly between 0 and 1. Still the same end result. I've updated my code snippet to reflect my changes.

It seems that it only changes wOn back to false when I click it then instantly goes back to 1. The problem seems to be that it's infinitely changing the wOn back. Maybe I need to account for state changes?

Fixed. The solution I used was to add state change checking using .fell() which you'll see reflected below. I added state change verification using Bounce2.fell(), like so:
  if (bouncer.read() == LOW && bouncer.fell()) {

Please use the edit link on your question to add additional information. The Post Answer button should be used only for complete answers to the question. - From Review

What I'm suggesting @C Steph is to edit your question and put the original, non-functioning code back. Then you could edit your answer and use your complete, functional sketch with the Bounce2 library. Your current answer is only 7 words long, so it's incomplete. In approximately 24 hours, you will be able to accept your own answer and I encourage you to do so. This will give you addition reputation on the Arduino.SE network.

If you edit your question with the fix, then the answers (and your question) will not make any sense. @VE7JRO - I've have done it for the OP.

I was looking for, Question = broken code, Answer = completely fixed and working code. There were 2 edits by the OP to their original Question. I was hoping the OP would have changed the Question back to the sketch they first posted (it did not use the Bounce2 library and was identical to the sketch in my answer, minus the code comment and extra Serial.println I added). Is there any way to go back through the question editing process to restore the first post by the OP?

I just tried to edit the question and was not able to go back to the OP's first post. More than likely, my reputation level is not high enough to access the information or only a site moderator can make these types of changes.


text:
Why does reading an analog pin give a different results when interfacing with Processing?
I am interested in measuring the voltage over an analog pin (A6). When I use the Arduino IDE to print the results through the serial I get values around 300.
Here's the code
void setup(){
   Serial.begin(57600);
}

void loop(){
   Serial.println(analogRead(A6));
   delay(50);
}

When I try to run a equivalent program using Processing and interfacing it through Firmata and the corresponding library, I get values around 900.
Here's the Processing code:
import cc.arduino.*;
import processing.serial.*;

Arduino arduino;

void setup(){
   arduino = new Arduino(this,Arduino.list()[0], 57600);
   delay(2000);
}

void draw(){
  System.out.println(arduino.analogRead(6));
  delay(50);
}

Does anybody know what could be the issue? I should probably rather trust the values given directly by the Arduino without interfacing, right?
The pin is connected to a circuit with supply voltage.
I also tried reading the values directly using Serial in Processing (so without using the cc.arduino.* - library) and that showed me the values around 300. So I guess the difference is caused by the arduino.analogRead() method. I am puzzled as to whether that's a bug in the library or something else.
The problem seems to be me not properly initialising the pins. But calling
arduino.pinMode(6,Arduino.ANALOG);

in the setup method does nothing, as does Arduino.PWM, SERVO and any combination I tried. I thought, maybe Processing tried to assign D6 as analog instead of A6, but changing the value to 20 (as it's the pin number according to this) simply caused an OutOfBoundsException.

what is connected to the pin?

Have you measured the value on the pin with a voltmeter?

@Craig noup, good idea. Will try that later when I can acces a voltmeter.

You have not provided a schematic of how the Arduino is wired up.
However, if nothing is connected to the pin, i.e. it is not connected to ground or a supply voltage, then the input will float. That means that just by placing your hand near the Arduino, then analogRead() will produce a different value than when your hand in not near it.
I would hazard a guess that if you ran both sets of code multiple times then you will get different answers each time, if you start waving your hand around the Arduino.
Try that first, and then tie the input to either HIGH or LOW and then repeat the previous experiment.
In the second case the results should be consistent, and equal in the Arduino and Processing alike.

However, according to your comment, that is not your issue, as your inputs are not floating.
I think that issue is actually this:

Even with Firmata installed, the Processing application needs to define the pin mode for ALL the pins being referenced, telling the Arduino instance that xPin, yPin, and zPin are ANALOG pins.

Source: Re: Firmata problem with analogRead in Processing Library
Looking at your Processing code the pins are not defined. You need to do so.
With the Arduino code, there is no need to define the analogue pins.

Sorry, forgot to mention: it is connected to a circuit with supply voltage. The values are actually relatively stable around either 900 or 300.

@JorgeAndresQuinteroSerna -  Ah, that is strange then... I strongly suggest that you edit your question and put that information in your original post, to save people having to search around in comments to find it..

@JorgeAndresQuinteroSerna - updated answer with possible reason.

Thank a lot for your help! Unfortunately, I am still not able to properly initialise the pins or that still doesn't fix the issue.

@JorgeAndresQuinteroSerna - oh really? That is a shame. If I find a different solution, I'll try to update my answer. Otherwise if you find a solution yourself, don't forget to post it as your own answer as it will probably help others with the same issue.

Is this solved or not? The answer is accepted, but the comments indicate that it is not solved.

@Juraj - I am not sure. It is probably better to ask the OP. He may have got it working by now (with or without my proposed solution).


text:
How will I solve my problem : expected primary-expression before '>' token
// defines pins numbers
const int trigPin = A0;
const int echoPin = A1;
// defines variables
long duration;
int distance;

#include <moving.h>
#include <Servo.h>

Servo servo;

moving car(6, 2, 3, 5, 4, 7, 11, 8, 9, 10, 12, 13); // setting up a new RC car with pins EN1, IN1, IN2, EN2, IN3, IN4, EN3, IN5, IN6, EN4, IN7, IN8

void setup() {
{
  for (int i=2; i<14; i++)
  {
    pinMode(i, OUTPUT);
  }
  servo.attach(10);
  servo.write(90);
}
{
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
Serial.begin(9600); // Starts the serial communication
}
}

void loop() {
  if (distance) > 10; // this is the problem
  car.set_speed(127);
  car.forward();
  delay(3000);
  if (distance) < 10; // and this
  car.set_speed(0);
  car.forward();
  delay(600);
  car.set_speed(127);
  car.right();
  delay(700);
  car.set_speed(127);
  car.forward();
  delay(700);
}

if (distance > 10). What should be in if condition? ; after it is an empty command. I am sure you do not want to have a condition to execute an empty command. https://www.arduino.cc/reference/en/language/structure/control-structure/if/

@Juraj is 100% correct... Presumably car.set_speed() and car.forward() are meant to be executed conditionally? Otherwise, what is the point of the if() statement? Also, is the delay() meant to be part of the conditionally executed code? Or not?

You need curly brackets around your if block.
if (distance > 10) { // this solves the problem
  car.set_speed(127);
  car.forward();
  delay(3000);
}

etc
Edit: Thanks to the commenter.

That is not sufficient.  The entire condition must be enclosed in parentheses if (distance > 10) {

Maybe you could expand upon your answer.  Your answer is a little terse. Which statements need to be contained in the {} block and why..? Also you need to fix your suggestion as per @Craig's comment.

@karlo: The error message refers to line 38, a badly-formed 'if' statement. You probably meant something like "if (distance < 10){ do something; } else { do somethingelse; }", but as written, it is not correct C or C++.


text:
How do I (easily) power a 5 V 3-pin fan?
I have a 5 V 3-pin fan. I want to be able to:

power it from an Arduino Uno or a Seeeduino Lotus board, and, ideally;
be able to change its speed.

Most resources I can find on the web explain how to connect a standard 12 V fan and moreover complicate the thing by explaining how to get the speed of a fan or to control multiple fans. This is way too complex for me.
If my understanding is correct, I can't just connect a fan to analog output pins, because the absolute max power per pin is 40 mA (recommended: 20 mA), while the fan uses 100 mA.
Instead, I have to somehow connect two of the three pins of the fan to an external power, and use the third pin to control the speed. Am I supposed to use the ground and 5 V pins situated on the left side of the board above ANALOG IN?
If not, what are my other options? The board is powered by an USB cable, and I see no way to split the power at this level between the board and another device without running a risk of damaging the board.

You are correct in your assumption that you can not power a fan from an Arduino directly.
Use a transistor, for example 2N2222 or BC548, which is switched by the Arduino, using a single pin, in order to provide sufficient current to the fan.
Such as this simple circuit (note that the 12V supply would be 5V in your case):

Source: Driving a PC fan - transistor with or without an optocoupler?1
However, as chrisl has pointed out, you fan has three pins and not two. The above circuit will only work for a two pin fan. In your case, for the reasons stated in Chrisl's answer, one pin goes to 5 V supply, one to GND and then third goes directly to the Arduino - let's say pin 3. Then you can use the code below.
Assuming that the fan is connected to pin 3, then the code will look like this:
const int fan = 3;

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

void loop() {
  int fanSpeed = 255;
  analogWrite(fan, fanSpeed);
}

This will run the fan at full blast. However, you can thereafter modify your code to vary the value of fanSpeed.
Furthermore, by reading an analog input pin (let's assume that you have a potentiometer hanging off A0), using analogRead(), you can use the read value to modify the value of fanSpeed directly (by dividing the value returned from analogRead() by four2 and then sending to analogWrite(), like so:
  int potPin = A0;
  fanSpeed = analogRead(potPin)/4;
  analogWrite(fan, fanSpeed);

or even more succinctly, do away with fanSpeed completely and use:
  int potPin = A0;
  analogWrite(fan,analogRead(potPin)/4);

1 Note that the code in the link in incorrect as it attempts to write values greater than 255 using analogWrite(). As stated here, Arduino reference - analogWrite(), analogWrite() takes values of 0-255, whereas analogRead() returns values of 0-1023
2 See the loop() function in Arduino reference - analogWrite() for another example.

The OP has a 3 pin fan for 5V, not 12V. The third pin is already connected internally to a driver (propably a MOSFET), which can be driven with PWM. So the extra MOSFET is not needed here.

@chrisl - ah yes, you are quite right. I read the question in too much of a hurry. Your answer is more correct. I shall modify mine to make note that the voltage is 5 and not 12V. Thanks

Sorry, but command back >.< As VE7JRO pointed out these fans are different than the normal stock fans in that the third pin is actually the pin, which reports back the RPM. Didn't knew that, but we are always learning. I will delete my answer, since it is false. Yours is correct.

@chrisl - eh? Oh dear. I am a bit busy now to understand. Please undelete your answer, as it is probably useful, and I want to read it again anyway.  You can always delete it later - if need be. You were right about outputting 255 and not 1023 anyway. :-)

fyi: Fans like this are often brushless, which already have an internal "pwm" controller. You cannot control these by an external pwm signal, or at least it's speed is a bit unstable/unpredictable.

@ctrl-d - ok thanks. Does that mean that they control their own speed? That is to say that you just connect the power and ground and let it do the rest? TBH, it would appear that without a clear specification (which the product's link does not provide) it is quite difficult to tell.

Yes they control their own speed by having hall sensors to detect the position of the rotor and apply voltage to a specific coil just at the right time. If your pwm signal is low at that moment, it doesn't work. The speed can be controlled by the analogue voltage in these motors.

EDIT:
As VE7JRO pointed out the fan you are using does not have a native PWM pin. The third pin is actually reporting back the RPMs of the fan. So you need to follow Greenonline's answer by using a MOSFET. For now I will leave my answer here for reference. If wanted I will delete it later.

A 3-pin fan is controlled like a servo. The current for actually driving the motor flows through the power pins (5V and Ground). The third pin takes a PWM (pulse width modulation) signal to determine the wanted fan speed. This is just a signal line, there is only very little current flow, so that the Arduinos pin will not be damaged. So the motor driver is already included.
From the programming side you can use analogWrite(), which outputs a PWM signal at one of the PWM-capable pins. The speed of the fan is controlled via the duty cycle of the signal. 100% (value of 255 for UNO) means full speed, 0% (value of 0) stops the motor.
About the power supply: Since your fan uses 100mA at full speed (I assume), it is still possible to power it over the 5V pin of the Arduino. You can source about 500mA over it (including the current for the Arduino itself). When sourcing higher currents over the USB plug, the polyfuse will be fried. This is the value for the UNO r3. A Nano can source only 200mA, because the diode will be fried.
So be carefull how much current you draw from the 5V pin of the Arduino. Or, if you have greater current requirements you have to supply an extra voltage to drive the fan.

The 3rd pin on this particular fan may be a RPM speed signal, not a PWM input signal. See: https://noctua.at/en/support/faq/general-faqs/category/Fans and look for "What pin configuration do Noctua 5V fans use?" on the page.


text:
Query related to Serial communication
I have a Raspberry Pi and an Arduino. On my Arduino I wrote a program, if you see the last two functions i.e. getMove() and SendMove() you will see that I am sending a move serially and the RPi will read the string only after it reads start. It is sending it to the RPi through serial communication using a USB (Note: As you can see the Arduino will send the string only one time and not again and again since once it sends the string the control will go into getMove() which waits for "Rstart").
Once I uploaded the code in the Arduino, I opened the serial monitor to check the output that I should be expecting in my RPi. Then I removed the USB from my laptop and connected the Arduino to the RPi and ran the Python code to read the string sent from the Arduino serially and got the string sent. I ran the code again on the RPi and got the string sent.
Now my question is, the first time when I opened the serial monitor on the laptop there was serial communication between the Arduino and my laptop, so I expected the string I sent to have gone to the laptop. So, when I connected the Arduino to the RPi, I didn't expect a string to be received on the RPi since the string was already sent to the laptop. Then again I ran the code on the RPi but still got the string sent.
Can someone explain how Serial communication works? Once I send something from the Arduino serially, will it always be in the serial buffer?
EDIT:
I have understood that unless the DTR pin of the serial connector is disabled the Arduino will keep resetting itself when connected to something new.
Now my question is, why does Arduino reset itself when I run the Python code (to read the serial buffer) again and again?
ARDUINO CODE
#include "LiquidCrystal.h"

const int rs = 7, en = 6, d4 = 5, d5 = 4, d6 = 3, d7 = 2; // 4 bit mode
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
int SensorValStore_Prev[8][8] = { {0,0,0,0,0,0,0,0}, \
                                  {0,0,0,0,0,0,0,0}, \
                                  {1,1,1,1,1,1,1,1}, \
                                  {1,1,1,1,1,1,1,1}, \
                                  {1,1,1,1,1,1,1,1}, \
                                  {1,1,1,1,1,1,1,1}, \
                                  {0,0,0,0,0,0,0,0}, \
                                  {0,0,0,0,0,0,0,0} };

int SensorValStore_Curr[8][8]={ {0,0,0,0,0,0,0,0}, \
                                {0,0,0,0,0,0,0,0}, \
                                {1,1,1,1,1,1,1,1}, \
                                {1,1,1,1,1,1,1,1}, \
                                {1,1,1,1,1,1,1,1}, \
                                {1,1,0,1,1,1,1,1}, \
                                {0,0,0,0,0,0,0,0}, \
                                {0,1,0,0,0,0,0,0} };
//int SensorValStore_Curr[8][8];
int sum1[8],sum2[8],temp[8][8],k,l,i,j,rank,nextRow;
String file,moveSan,Temp,bestMove;
char Buffer[20];
void doAction();
void ReadSensor();
void Difference();
void binToIntCalc();
void check();
void getMovePlayed();
void SendMove();
void getmove();

void setup()
{
  Serial.begin(9600);
  lcd.begin(16,2);
  pinMode(22,INPUT_PULLUP); // Reed switch - Row1
  pinMode(24,INPUT_PULLUP); // Reed switch - Row2
  pinMode(26,INPUT_PULLUP); // Reed switch - Row3
  pinMode(28,INPUT_PULLUP); // Reed switch - Row4
  pinMode(30,INPUT_PULLUP); // Reed switch - Row5
  pinMode(32,INPUT_PULLUP); // Reed switch - Row6
  pinMode(34,INPUT_PULLUP); // Reed switch - Row7
  pinMode(36,INPUT_PULLUP); // Reed switch - Row8
  pinMode(2,INPUT_PULLUP);// Push Button
  pinMode(38,OUTPUT);
  pinMode(40,OUTPUT);
  pinMode(42,OUTPUT);
  pinMode(44,OUTPUT);
  pinMode(46,OUTPUT);
  pinMode(48,OUTPUT);
  pinMode(50,OUTPUT);
  pinMode(52,OUTPUT);
  pinMode(3,OUTPUT);
  digitalWrite(38,HIGH);
  digitalWrite(40,HIGH);
  digitalWrite(42,HIGH);
  digitalWrite(44,HIGH);
  digitalWrite(46,HIGH);
  digitalWrite(48,HIGH);
  digitalWrite(50,HIGH);
  digitalWrite(52,HIGH);
  digitalWrite(3,LOW);
}

void loop()
{
  //if( digitalRead(10) == 0 )
  //{
  Serial.print("--------------------Initial Matrix-----------------------------\n");
  Print(SensorValStore_Prev);
  // doAction();
  delay(40);
  Serial.print("--------------------Final Matrix------------------------------\n");
  Print(SensorValStore_Curr);
  delay(40);
  Difference();
  delay(40);
  binToIntCalc();
  delay(40);
  check();
  delay(40);
  getMovePlayed();
  delay(40);
  getMove();
  delay(40);
  //}
}

void Print(int matrix[8][8])
{
  for(i=0;i<8;i++)
  {
    for(j=0;j<8;j++)
    {
      Serial.print(matrix[i][j]);
      Serial.print(" ");
    }
    Serial.println();
  }
}

void doAction()
{
  nextRow = 0;
  for(i=0;i<8;i++)
  {
    digitalWrite(38 + nextRow,LOW);
    delay(40);
    ReadSensor(i);
    digitalWrite(38 + nextRow,HIGH);
    delay(40);
    nextRow +=2;
  }
}

void ReadSensor(int iter)
{
  delay(10);
  for(j=0;j<8;j++)
    SensorValStore_Curr[iter][j] = digitalRead(j+2);
  Serial.print("----------------------------------------------");
  Serial.println("Value of sensory board after move is played");
}

void Difference()
{
  for(i=0;i<8;i++)
    for(j=0;j<8;j++)
      temp[i][j] = abs(SensorValStore_Curr[i][j] - SensorValStore_Prev[i[j]);
  Serial.print("-----------------------Difference---------------------------\n");
  Print(temp);
}

void binToIntCalc()
{
  for(i=0;i<8;i++)
    for(j=0;j<8;j++)
    {
      sum1[i] += pow(2,j)*SensorValStore_Prev[i][j];
      sum2[i] += pow(2,j)*SensorValStore_Curr[i][j];
    }
  Serial.print("---------------------sum1 and sum --------------------------\n");
  for(i=0;i<8;i++)
  {
    Serial.print(sum1[i]);
    Serial.print(" ");
  }
  Serial.println();

  for(i=0;i<8;i++)
  {
    Serial.print(sum2[i]);
    Serial.print(" ");
  }
  Serial.println();
}

void check()
{
  k=0;
  l=0;
  for(i=0;i<8;i++)
  {
    if(sum2[i]>sum1[i])
      k = i;
    if(sum2[i]<sum1[i])
      l = i;
    delay(40);
  }
}

void getMovePlayed()
{
  for(j=0;j<8;j++)
  {
    if(temp[k][j] == 1)
    {
      rank =k+1;
      file = String(char(97+j));
      delay(40);
      moveSan = file + rank;
      Temp = moveSan;
    }
  }
  for(j=0;j<8;j++)
  {
    if( temp[l][j] == 1)
    {
      rank =l+1;
      file = String(char(97+j));
      delay(40);
      moveSan = file + rank;
      Temp.concat(moveSan);
    }
  }
}

void SendMove(String movePlayed)
{
  Serial.println("start");
  Serial.print(movePlayed);
  Serial.println();
}

void getMove()
{
  while(1)
  {
    if(Serial.available()>0)
    {
      if(Serial.readString() == "Rstart")
      {
        bestMove = Serial.readString();
        lcd.setCursor(0,0);
        lcd.print(bestMove);
        delay(5000);
        lcd.clear();
        Serial.println(bestMove);
        exit(0);
      }
    }
  }
}

PYTHON CODE
import serial
from stockfish import Stockfish
s1 = serial.Serial('/dev/ttyACM0', 9600)
stockfish = Stockfish('/usr/games/stockfish')
while 1 :
    if str(s1.readline(),'UTF-8').strip('\n\r') == 'start' :
                move_played = str(s1.readline(),'UTF-8').strip('\n\r')
                print(move_played)
                // stockfish.set_position(move_played)
                // print("Rstart")
                // print(stockfish.get_best_move().encoded())
                break

the Arduino resets on new usb connection. and of course at power-up setup() runs

new usb connection is serial.Serial('/dev/ttyACM0', 9600)

It would help to see your code but bear in mind when you connect the serial monitor to your arduino it resets so any code will re-run

true, but the connection from PI resets it too

The arduino doesn't know what's connecting to it, opening the serial port from anything will reset it unless asserting the DTR pin on the serial connector is disabled by whatever is connecting. A quick google seems to indicate python on the pi can't reliably disable DTR but a hardware solution could be implemented

@Ba1n,@juraj I understand that the arduino re-runs, when conected to the rpi or serial monitor. But why does it re-run if I run the code on the rpi again. Shouln't it give back an error that it can't read anything from serial?


text:
7-Segment, 3-digit display not displaying correctly
I have written the code that should work, but for some reason the numbers do not display correctly. When I choose to display 3 times the same number it works correctly (so pin connections are correct) but when trying to display different numbers on each digit things get messy. Can anyone see what is wrong with the code? I don't seem to find it. thanks!
Working when 3 digits are the same:

Not working with different numbers (should be 3, 2, 1:

And the code:
int a = 2;               //Defining segments corresponding to the pins
int b = 3;
int c = 4;
int d = 5;
int e = 6;
int f = 7;
int g = 8;

void setup(void) {      //Setting Pins as output
  pinMode(A0, OUTPUT);
  pinMode(A1, OUTPUT);
  pinMode(A2, OUTPUT);
  pinMode(a, OUTPUT);
  pinMode(b, OUTPUT);
  pinMode(c, OUTPUT);
  pinMode(d, OUTPUT);
  pinMode(e, OUTPUT);
  pinMode(f, OUTPUT);
  pinMode(g, OUTPUT);
}

void WriteNum(int PositionN, int Number) {
  int Position;
  int NumberSegments[10][7] = {{a,b,c,d,e,g},     //Defining segments for forming numbers
                          {b,c},
                          {a,b,d,e,g},
                          {a,b,c,d,g},
                          {b,c,f,d},
                          {a,c,d,f,g},
                          {a,c,d,e,f,g},
                          {a,b,c},
                          {a,b,c,d,e,f,g},
                          {a,b,c,d,f,g}};
  digitalWrite(A0, HIGH);                       //Setting begin conditions (All segments low and no digits turned on)
  digitalWrite(A1, HIGH);
  digitalWrite(A2, HIGH);
  digitalWrite(2, LOW);
  digitalWrite(3, LOW);
  digitalWrite(4, LOW);
  digitalWrite(5, LOW);
  digitalWrite(6, LOW);
  digitalWrite(7, LOW);
  digitalWrite(8, LOW);
  digitalWrite(9, LOW);

  switch (PositionN) {                        //Deciding which digit to turn on
    case 1:
      Position = A0;
      break;
    case 2:
      Position = A1;
      break;
    case 3:
      Position = A2;
      break;
  }
  digitalWrite(Position, LOW);
  for (int i = 0; i < sizeof(NumberSegments[Number]); i++){       //For each segment in number to display
        digitalWrite(NumberSegments[Number][i], HIGH);            //Light that segment
        }
  delay(5);
}

void loop(void) {
  WriteNum(1,2);
  WriteNum(2,2);
  WriteNum(3,2);
}

sizeof(NumberSegments[Number] is 14 (as an int is two bytes; 2*7=14). The least you should do is use sizeof(NumberSegments[0]/sizeof(NumberSegments[0][0]. Since you declare the sub-arrays to be of 7 integers, {b,c}, will actually be interpreted as {b,c,0,0,0,0,0},. So your code is also setting pin 0 to HIGH. Not sure if this have anything to do with your problem.

That was indeed the problem thanks! Because the sizeof() = 14, it will continue reading the next item in the list and light those segments as well. Setting pin 0 high did not appear to cause any problems but I filled the remaining spaces in the list with copies of an already lit segment anyway. I still wonder why this did not cause problems when the three digits were the same?

I have three recommendations for you. @Gerben was correct as to your problem, but doing the following three steps will improve the speed of your code:

Change your definition for NumberSegments to be [10][8], and put the number of active segments as the first number of each array:
 ...[10][8] = {{6,a,b,c,d,e,g},     // ...
               {2,b,c},
               {5,a,b,d,e,g}, // etcetera

Change your for loop as follows:
for (int i = 1; i <= NumberSegments[Number][0]; i++) { // ...
   digitalWrite(NumberSegments[Number][i], HIGH); // ...
}

This will only turn on the minimum number of segments required. Note the loop now starts at 1, and uses <= instead of <.
Put the keyword static in front of NumberSegments:
static int NumberSegments[10][8] = {{ // ...

This last one is a language nicety. Every time the function WriteNum is called, the poor thing has to re-create the (large) NumberSegments array - and it’s the same every time! The keyword static means “only create this variable once”. Next time into the function, it’ll already be available: no processing required!
You might also consider moving int position; below NumberSegments, since it’s convention to put static variables first in a function.
You can also use the keyword const on NumberSegments, since its values never change:
static const int NumberSegments[10][8] = {{ // ...

Thanks John! Much appreciated. Looks way more efficient indeed. I believe I'm getting the hang of it


text:
Arduino MEGA2560 wake up using DS3231 RTC
I am trying to set the Arduino MEGA 2560 R3 into sleep mode and wake it up with an RTC DS3231 via interrupt. I was following this tutorial:
Tutorial
One of the libraries included is the "LowPower" library, you can find it here on GitHub. It produces the following error while compiling:
C:\XX\Arduino\libraries\Low-Power-master\LowPower.cpp: In member function 'void LowPowerClass::idle(period_t, adc_t, timer5_t, timer4_t, timer3_t, timer2_t, timer1_t, timer0_t, spi_t, usart3_t, usart2_t, usart1_t, usart0_t, twi_t)':

C:\XX\Arduino\libraries\Low-Power-master\LowPower.cpp:562:49: error: 'power_usart3_disable' was not declared in this scope

  if (usart3 == USART3_OFF) power_usart3_disable();

                                                 ^

C:\XX\Arduino\libraries\Low-Power-master\LowPower.cpp:597:48: error: 'power_usart3_enable' was not declared in this scope

  if (usart3 == USART3_OFF) power_usart3_enable();

                                                ^

exit status 1
Error while compiling for Arduino/Genuino Mega or Mega 2560.

I dont understand why there should be any functions in the library, which are not declared...This would mean noone could use it?! I am not an expert in C++ so maybe one of you could tell me what the issue could be. I am glad for any help.

after further web research, it looks like this is a bug which hasnt been fixed yet.
it was discussed previously here and here.
My solution was to go into the "LowPower.cpp" scroll down to the lines, where the functions are not declared and I just out-commented them. Compiling works now.


text:
3.3V from 5.0v outlet
I am working with an Adafruit Feather 32u4 FONA board. I want to connect a GPS module I have worked with before (3.3V required) but am not having much luck. I have studied the pinout of the board and have tried the 3.3V pin but it is far too erratic in nature and cannot sufficiently power the module. There is a pin called USB which supplies 5.0V from the pin if a micro USB cable is connected. I have used an LM317 and a potentiometer to make a voltage regulator circuit to convert the 5.0V from the USB pin to the 3.3V I need for the GPS module. This works, as I have measured 3.3V successfully using a multimeter.
The problem is that when I connect the VCC and GND pins of the GPS module to the 3.3V regulated output, the module still doesn't get any power. I measured a significant drop to around 0.89V across GND and VCC after I connect the module. What could be causing this strange behavior?

The bottom left rail is what I am trying to use to power the GPS module, before I connect it I get 3.3V as mentioned earlier, which is the required level.

I don't get what you think that circuit is trying to do. It looks to me like you are just using the LM317 as an expensive diode, and the trimmer pot as a voltage divider. It can never work. If you want to use an LM317 then please, wire it up properly. And never ever ever use a potentiometer to try and drop a voltage for supply.

Ok, well what approach would you yourself take @Majenko ?

I'd probably get a cheap adjustable switching ("Buck") regulator off eBay and use that.

The LM317 also requires some capacitors.

@Majenko, I have one of those, am I able to feed 5V in and trim it to around 3.3V?

I will give it a go

A while has passed since I asked this question but in a bid to resolve it, I used my Buck regulator as suggested and this solved the problem.

According to the datasheet the LM317 has a minimum Vin to Vout of 3v so you'd only be able to get 2v out of it if you put 5v in.  I'd recommend using either an AMS1117 3.3 or one of the cheap modules based on that chip that has an LED and capacitors on board. They definitely deliver 3.3v from 5v in.


text:
A minor confusion in digitalWrite command
Will the Arduino IDE interpret digitalWrite(13,x), where x>0, as digitalWrite(13,HIGH)?
And will it interpret digitalWrite(13,x), where x<=0, as digitalWrite(13,LOW)?

0 is low, everything else is HIGH

but some joker could make an arduino core where LOW is defined as 2. the AVR code for digitalWrite and digitalRead would work. it doesn't assume that LOW is 0. so your code shouldn't do that either. (but in my sketches I often assume that LOW is 0).

the esp8266 core digitalRead and digitalWrite functions ignore LOW and HIGH  and use if (val) and return the state of the register bit

Every other value than 0 or LOW will result in setting the pin to HIGH. In the following I explain why:
The function digitalWrite() can be seen in the file hardware/arduino/avr/cores/arduino/wiring_digital.c. The important lines here are:
if (val == LOW) {
    *out &= ~bit;
} else {
    *out |= bit;
}

As you can see, it checks, if the given value (from the parameter) is equal to LOW and if so will set the corresponding pin to 0. In every other case it will set the pin to 1. The definition of LOW can be found in arduino/hardware/arduino/avr/cores/arduino/Arduino.h:
#define HIGH 0x1
#define LOW  0x0

So the code checks, if the value is equal to 0 and sets the pin also to 0. Every other value will result in a 1 (meaning HIGH). Also have a look at the definition of digitalWrite():
void digitalWrite(uint8_t pin, uint8_t val)

The value is an unsigned type, so every signed type will be casted to an unsigned type. A negative number would result in a positive number inside the function.

Just nitpicking: Also False and anything other, which evaluates as 0, works here :) (And it is common to use boolean variables/expression as the val)


text:
How can I read servo motor readings via serial communication?
I'm new to serial communication. I tried to make Arduino talk to MATLAB, but certain values are allowed to be received like 100 and 101. I tried other values but didn't work. The problem is with ASCII code but I tried to subtract what is read by 48 but failed.
This is the Arduino code that I found on Google and edited it for my servo motor problem:
#include <Servo.h>
const int servoPin = 3;
int recValue; // received value from MATLAB
Servo Servo1;

void setup()
{
  Serial.begin(9600);
  Servo1.attach(servoPin);
}

void loop()
{
  if (Serial.available() > 0)
  {
    recValue = Serial.read();
    if  (recValue == 100)
    {
      Servo1.write(0);
      delay(1000);
    }
    if (recValue == 101)
    {
      Servo1.write(90);
      delay(1000);
    }
  }
}

So how can I read the correct angles that I received from the MATLAB via serial communication? Thanks.

What exaclty are you getting from Matlab over serial?

When using recValue as 100, the motor rotates to the 0 position and if 101, the motor rotates to 90 degrees. When I change recValue to any number, I get nothing from MATLAB and the motor does not rotate to any position in the two cases.

I don't understand, what exactly you want to achieve. Your comment states the exact functionality, that is provided by your code.  When you want to control the sensors angle from Matlab, send an actual value to the Arduino and use it in Servo1.write()

Sorry for not being clear. For example, I want to make the motor rotate 45 degrees. I should write 45 in MATLAB and then it can convert the value to 45 so that I can use Servo1.write(45) afterwards. I will edit the code but I want to know how to convert the value that I receive from MATLAB in order to be the exact 45 value.

Serial.parseInt()?

chrisl is quite right. You need to understand how MATLAB is talking to your Arduino. I suspect it is sending a sequence of characters for each servo angle instead of a single character.  In your code you are waiting for 100 and 101, which are the ASCII 'd' and 'e' characters, and then acting immediately you have read one character. See if the servo will turn if you send 'd' or 'e'. If that works then what you need to do is read a whole line of ASCII characters e.g. '9' (which is 57) and '0' (which is 48) followed by a delimiter e.g. newline (13)
At the beginning of line you can set int angle = 0 and each time you read a character multiply your angle by 10 and add in the new value by subtracting 48 from it.
When you reach the delimiter you can then send the angle to the servo.
Oh - and make sure MATLAB is talking at the right baud rate.

Thanks a lot. I tried to send 'd' and 'e' and the motor really turned. But I still don't understand how the last few sentences. How can I delimit '9' and '0' to become 90?

I now understand that we're making a map between 0-9 values to 0-90 degrees but how can I do that in Arduino? Is this done for the recValue variable in Arduino? or servalue in MATLAB?

If you want to send 90 to the Arduino it will be sent as the character 9 (which is 57) and then character 0.  You will only get a single character at a time in each iteration of your loop. The first time Serial.available() is true Serial.read() will return value 57. Subtract 48 from that to get 9 and store in a variable declared as int angle. The next time Serial.available() is true (which may be a few loops() later) you will read 48.  So then angle = angle * 10 + (value - 48) gives you the angle to send to your servo. You can send to the server when you get a non-digit character from MATLAB

Yes, but what is the value Serial.read()? Is this what we get from MATLAB via serial communication between it and arduino?

Serial.read() will collect the next available ASCII character sent from MATLAB to the Arduino. It only returns one character at a time so if you had sent the number 125 from MATLAB you would need to call Serial.read() three times to get the '1', '2' and '5' characters. You then need to recombine them as I said above to get a single integer of 125 to send to the servo

Rather than trying to get MATLAB to talk to the Arduino immediately, why don't you try just using the Serial connection from your PC. You can type characters in on the Serial monitor and process your keystrokes one by one using Serial.read(). You can then print debugging information using Serial.write() so you can get some idea what is going on in the code.

Let us continue this discussion in chat.

I'm assuming, that you are sending the angle value as a 1-byte value, so no ASCII encoded numbers. This is how the code in your question works, so it should be right.
You don't have to convert anything here. The Serial.read() function already returns an integer value and you are saving it to an integer variable. But in your code you only care for 2 different states (100 and 101), instead of the actual angle value. Now you only have to replace your if-statements and write this value directly to the servo:
Servo1.write(recValue);

EDIT:
You doesn't seem as you know how serial communication (to be exactly USART) functions. So I will explain further:
The data, that is send over serial is just a stream of bytes. All content, that get transmitted are converted to a stream of bytes. Every byte has a numerical value. For example a byte with the bit-content 00100000 has a numerical value of 32. But at some point in history it was necessary to send text with a byte stream. So someone invented ASCII, which assigns a character or control command to every numerical value from 0 to 127. So if you send a byte with the numerical value of 32, you could mean the actual numerical value 32, or you could mean the ASCII equivalent to 32, which is the space character. This is just an interpretation of the byte data, that flows through the serial interface.
So you have to investigate, in which kind you are encoding the angle value. If you use fwrite() in your Matlab code, you are most likely sending the byte value, which you can simply use as described above. If you use fprintf(), you are sending the angle value as an ASCII encoded string. The value 32 from above would then occupy 2 bytes with the characters 3 and 2, which correspond to the byte values of 51 and 50. In this case you should add a delimiter character at the end in fprintf() (for example the newline character "\n") and use Serial.parseInt() to get the angle value from the string.
You can read more of this in many tutorials about Serial communication that you can find in the internet. Also refer to the example, that come with the Arduino IDE.

What do you mean by 1-byte value? Because I tried many ranges from 0 to 180 degrees and the motor still does not rotate.

I have also added delay(1000) after Servo1.write(recValue)


text:
DC motor with L289N driver cannot set RPM lower than 130
My setup is using an Uno r3, and the motor driver is an L289N.
I am going to set it to run at a lower RPM, but when adjusting enA or enB to set to below 130, it won't spin.
// connect motor controller pins to Arduino digital pins
// motor one
int enA = 2;
int enB = 7;
int in3 = 5;
int in4 = 6;
int in1 = 3;
int in2 = 4;

void setup()
{
  // set all the motor control pins to outputs
  pinMode(enA, OUTPUT);
  pinMode(enB, OUTPUT);
  pinMode(in3, OUTPUT);
  pinMode(in4, OUTPUT);
}
void demoOne()
{
  analogWrite(enB, 130);
  // turn on motor B
  digitalWrite(in1, LOW);
  digitalWrite(in2, HIGH);
  delay(500);
  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);
  delay(5000);
  // this function will run the motors in both directions at a fixed speed
  // turn on motor A
  // set speed to 200 out of possible range 0~255
  analogWrite(enA, 130);
  // turn on motor B
  digitalWrite(in3, HIGH);
  digitalWrite(in4, LOW);
  // set speed to 200 out of possible range 0~255
  delay(100); //this function to set masa untuk rotation
  // now change motor directions
  // now turn off motor
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);
  delay(5000);
  digitalWrite(in3, LOW);
  digitalWrite(in4, HIGH);
  delay(200);
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);
  delay(5000);
  digitalWrite(in3, HIGH);
  digitalWrite(in4, LOW);
  delay(200);
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);
  delay(5000);
  digitalWrite(in3, LOW);
  digitalWrite(in4, HIGH);
  delay(100);
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);
  delay(5000);

  analogWrite(enB, 130);
  // turn on motor B
  digitalWrite(in1, HIGH);
  digitalWrite(in2, LOW);
  delay(400);
  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);
  delay(5000);
}

void loop()
{
  demoOne();
  delay(3000);

}

Looks like you are controlling two motor outputs via the H-bridge, where the logic inputs are in1,in2 and in3,in4.  First of all, you need
pinMode(in1,OUTPUT);
pinmode(in2,OUTPUT);

One reason why the motors may not spin for analogWrite value less than 130 is that, coincidentally, the voltage output is too low and motor stalls.  Test this two ways: does (1) changing the motor supply voltage or (2) changing the argument of analogWrite actually change the speed?
If no, it may be that pinMode(enA,OUTPUT); sets the output as digital and should be removed.  In that case a number less than 128 gets interpreted as a logic 0 and the motor will not spin.
P.S. your code can be neatened up using port syntax and bitwise operators.
digitalWrite(in1,HIGH);
digitalWrite(in2,LOW);

can be written on a single line with
PORTD |= _BV(in1);

Also
digitalWrite(in1,LOW);
digitalWrite(in2,LOW);

becomes
PORTD &= ~(_BV(in1) | _BV(in2));

On an Uno, D2 and D7 (enA and enB) do not have true PWM (analogWrite) capabilities- they will be 100% on at values of 128 or higher, and off at 127 and lower.
You will need to use 3, 5, 6, 9, 10 or 11 for PWM (i.e. your enA and enB) on the Uno.
See Arduino Reference - analogWrite() for more info on PWM pin availability on Arduino boards.


text:
Serial communication between 2 arduino's doesn't works when Sending string in a program with a lot of functions
Note :
This question is completely different from the questions that I have asked before although the code snippets might be the same, So please do not waive it as a duplicate right when you see it.
In my setup I have connected two arduino's Serially. An Arduino Mega is the one that is sending the string and a Arduino Uno is the one that's receiving it.

Arduino Mega : TX1(19),RX1(18) - Serial1
Arduino Uno : RX(10),TX(11) - using SoftwareSerial
Gnd is connecetd on both boards

Arduino UNO - code is same for both cases
#include <SoftwareSerial.h>
SoftwareSerial s(10, 11);
void setup()
{
  delay(200);
  Serial.begin(9600);
  Serial1.begin(9600);
  s.begin(9600);
  while (!Serial) ;  // wait for Arduino Serial Monitor
}
void loop()
{
  if(s.available()>0)
  {
     Serial.print("\nrec\n");
     delay(100);
     String b = s.readStringUntil('\n');
     delay(100);
     Serial.print(b);
     delay(40);
  }

}
When the code in my arduino mega has only a print statement to send a string an infinite no. of times to the Uno, The Uno is receiving the string properly.
Arduino Mega
void setup()
{
  Serial1.begin(9600);
}
void loop()
{
  Serial1.println("e2e4");
  delay(100);
}

Now when I send the string an infinite no. of times from the Arduino mega but this time the mega has a lot more functions included in the program as well. In this case the Uno does not receive the string sent.
Arduino Mega - code containing a lot of functions and sedning a string to
                  Uno
int SensorValStore_Prev[8][8] = { {0,0,0,0,0,0,0,0}, \
                                  {0,0,0,0,0,0,0,0}, \
                                  {1,1,1,1,1,1,1,1}, \
                                  {1,1,1,1,1,1,1,1}, \
                                  {1,1,1,1,1,1,1,1}, \
                                  {1,1,1,1,1,1,1,1}, \
                                  {0,0,0,0,0,0,0,0}, \
                                  {0,0,0,0,0,0,0,0} };

int SensorValStore_Curr[8][8]={ {0,0,0,0,0,0,0,0}, \
                                {0,0,0,0,0,0,0,0}, \
                                {1,1,1,1,1,1,1,1}, \
                                {1,1,1,1,1,1,1,1}, \
                                {1,1,1,1,1,1,1,1}, \
                                {1,1,0,1,1,1,1,1}, \
                                {0,0,0,0,0,0,0,0}, \
                                {0,1,0,0,0,0,0,0} };
//int SensorValStore_Curr[8][8];
int sum1[8],sum2[8],temp[8][8],k,l,i,j,rank,nextRow;
String file,moveSan,Temp,bestMove;
char Buffer[20];
void doAction();
void ReadSensor();
void Difference();
void binToIntCalc();
void check();
void getMovePlayed();
void SendMove();
void getMove();

void setup()
{
  Serial.begin(9600);
  lcd.begin(16,2);
  pinMode(22,INPUT_PULLUP); // Reed switch - Row1
  pinMode(24,INPUT_PULLUP); // Reed switch - Row2
  pinMode(26,INPUT_PULLUP); // Reed switch - Row3
  pinMode(28,INPUT_PULLUP); // Reed switch - Row4
  pinMode(30,INPUT_PULLUP); // Reed switch - Row5
  pinMode(32,INPUT_PULLUP); // Reed switch - Row6
  pinMode(34,INPUT_PULLUP); // Reed switch - Row7
  pinMode(36,INPUT_PULLUP); // Reed switch - Row8
  pinMode(2,INPUT_PULLUP);// Push Button
  pinMode(38,OUTPUT);
  pinMode(40,OUTPUT);
  pinMode(42,OUTPUT);
  pinMode(44,OUTPUT);
  pinMode(46,OUTPUT);
  pinMode(48,OUTPUT);
  pinMode(50,OUTPUT);
  pinMode(52,OUTPUT);
  pinMode(3,OUTPUT);
  digitalWrite(38,HIGH);
  digitalWrite(40,HIGH);
  digitalWrite(42,HIGH);
  digitalWrite(44,HIGH);
  digitalWrite(46,HIGH);
  digitalWrite(48,HIGH);
  digitalWrite(50,HIGH);
  digitalWrite(52,HIGH);
  digitalWrite(3,LOW);
}

void loop()
{

  // doAction();
  delay(40);
  Difference();
  delay(40);
  binToIntCalc();
  delay(40);
  check();
  delay(40);
  getMovePlayed();
  delay(40);
  getMove();
  delay(40);
  //}
}

void Print(int matrix[8][8])
{
  for(i=0;i<8;i++)
  {
    for(j=0;j<8;j++)
    {
      Serial.print(matrix[i][j]);
      Serial.print(" ");
    }
    Serial.println();
  }
}

void doAction()
{
  nextRow = 0;
  for(i=0;i<8;i++)
  {
    digitalWrite(38 + nextRow,LOW);
    delay(40);
    ReadSensor(i);
    digitalWrite(38 + nextRow,HIGH);
    delay(40);
    nextRow +=2;
  }
}

void ReadSensor(int iter)
{
  delay(10);
  for(j=0;j<8;j++)
    SensorValStore_Curr[iter][j] = digitalRead(j+2);
}

void Difference()
{
  for(i=0;i<8;i++)
    for(j=0;j<8;j++)
      temp[i][j] = abs(SensorValStore_Curr[i][j] - SensorValStore_Prev[i[j]);

}

void binToIntCalc()
{
  for(i=0;i<8;i++)
    for(j=0;j<8;j++)
    {
      sum1[i] += pow(2,j)*SensorValStore_Prev[i][j];
      sum2[i] += pow(2,j)*SensorValStore_Curr[i][j];
    }
 }

void check()
{
  k=0;
  l=0;
  for(i=0;i<8;i++)
  {
    if(sum2[i]>sum1[i])
      k = i;
    if(sum2[i]<sum1[i])
      l = i;
    delay(40);
  }
}

void getMovePlayed()
{
  for(j=0;j<8;j++)
  {
    if(temp[k][j] == 1)
    {
      rank =k+1;
      file = String(char(97+j));
      delay(40);
      moveSan = file + rank;
      Temp = moveSan;
    }
  }
  for(j=0;j<8;j++)
  {
    if( temp[l][j] == 1)
    {
      rank =l+1;
      file = String(char(97+j));
      delay(40);
      moveSan = file + rank;
      Temp.concat(moveSan);
    }
  }
}

void SendMove(String movePlayed)
{
  Serial.println("start");
  Serial.print(movePlayed);
  Serial.println();
}

void getMove() // SENDING STRING TO THE ARDUINO UNO
{
 while(1){
  Serial1.println("e2e4");
  delay(100);
  }
}

Note: getMove() is the function that sends the string to the arduino through Serial1

I don't see a Serial1.begin()

damn....I can't believe that I made such a ridiculous error. @chrisl should I just delete this question . Since it will have absolutely no use to this site.

My answer might not be what you'd expect but I'll try anyway.
Did you troobleshoot your serial communications ? Try doing a simple programm for both cards and try sending data from one to another.
Uno code
#include <SoftwareSerial.h>

#define rxPin 10
#define txPin 11

SoftwareSerial s(rxPin, txPin);

String buff = "";

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

void loop()
{
    if(Serial.available)
    {
        while(Serial.available())
        {
            buff += char(Serial.read());
        }
        s.print(buff);
        buff="";
    }

    if(s.available)
    {
        while(s.available())
        {
            buff += char(s.read());
        }
        Serial.print(buff);
        buff = "";
    }
}

Mega code
String buff = "";

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

void loop()
{
    if(Serial.available)
    {
        while(Serial.available())
        {
            buff += char(Serial.read());
        }
        Serial1.print(buff);
        buff="";
    }

    if(Serial1.available)
    {
        while(Serial1.available())
        {
            buff += char(Serial1.read());
        }
        Serial.print(buff);
        buff = "";
    }
}

Did you double check your connections ? Tx (mega) to rx (uno) and rx (mega) to tx(uno)
In your setup() on your arduino mega
void setup()
{
  Serial.begin(9600);
  lcd.begin(16,2);
  pinMode(22,INPUT_PULLUP); // Reed switch - Row1
  pinMode(24,INPUT_PULLUP); // Reed switch - Row2
  pinMode(26,INPUT_PULLUP); // Reed switch - Row3
  pinMode(28,INPUT_PULLUP); // Reed switch - Row4
  pinMode(30,INPUT_PULLUP); // Reed switch - Row5
  pinMode(32,INPUT_PULLUP); // Reed switch - Row6
  pinMode(34,INPUT_PULLUP); // Reed switch - Row7
  pinMode(36,INPUT_PULLUP); // Reed switch - Row8
  pinMode(2,INPUT_PULLUP);// Push Button
  pinMode(38,OUTPUT);
  pinMode(40,OUTPUT);
  pinMode(42,OUTPUT);
  pinMode(44,OUTPUT);
  pinMode(46,OUTPUT);
  pinMode(48,OUTPUT);
  pinMode(50,OUTPUT);
  pinMode(52,OUTPUT);
  pinMode(3,OUTPUT);
  digitalWrite(38,HIGH);
  digitalWrite(40,HIGH);
  digitalWrite(42,HIGH);
  digitalWrite(44,HIGH);
  digitalWrite(46,HIGH);
  digitalWrite(48,HIGH);
  digitalWrite(50,HIGH);
  digitalWrite(52,HIGH);
  digitalWrite(3,LOW);
}

I don't see the Serial1.begin(9600) as said by @chrisl but you mentionned it above.
I hope this helps, sorry if I've not solved your problem.

you are correct, I missed it out in my code.


text:
What precision can I expect by syncronising DS3231 with PC serial?
The point here is to syncronise a DS3231 module (on an Arduino) via serial port with NTP time by computer.
The problem here is that I'd like to know how much time is taken by the serial and I2C transmission, because if the PC sends the time at a time t1 and transmit it to the Arduino, the Arduino decodes it and sends it to the DS3231, the time t1 is received at a time t2 greater than t1.
PC (t1) => Serial(t1+x) => Arduino(t1+x+y) => I2C(t1+x+y+z) => DS3231(t2=t1+x+y+z)

t1 -> NTP time recorded by PC
x  -> Time taken by serial transmission
y  -> Time taken by arduino buffering/processing
z  -> Time taken by I2C transmission at 100kHz
t2 -> Time when message is received by DS3231

Is it negligible for a precision at millisecond?
I found a table on Wikipedia that displays time per bit per baudrate. I am planning to use a baudrate of 57600.
I tested offset using a simple echo program available here at 300 baud:
String buff="";

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

void loop() {
  if(Serial.available())
  {
    while(Serial.available())
    {
      buff += char(Serial.read());
    }
    Serial.print(buff);
    buff = "";
  }
}

What Arduino are you using?

I am using an arduino Uno or Nano with an ATMega238P

How is it "faster than expected"? What are you sending, and how are you measuring / calculating how fast it should be?

How is the exact baud rate relevant to time synchronization? You have an NTP client, you are not going to use the serial port itself as a time source, are you? Please, clarify your question and clearly state what you are trying to achieve.

@EdgarBonet I think the concern is that the PC has time X and transmits it at X. The Arduino finishes receiving that stated time at Y - the difference between X and Y being the time taken to do the transfer through serial. If you know Y-X then you can add (Y-X) to X to get the time when the transfer has completed.

@Majenko yes, that's what I'm trying to ask, sorry for not being clear.

@Majenko I've done a simple echo programm that reads from serial and returns the message at 300bauds
So, according to wikipedia, it takes ~3ms to transmit a single bit at 300 bauds, if I transmit 22 characters, the time will be 2228*3 = 1056ms or ~1s to send and read the data back (that's what I get by testing it, so I was wrong in my question sry for that)
In my case I have 35 characters to transmit ; 7.4 micro seconds per bit at 57600 bauds ; so the time taken to send will be 7.4 * 35 * 8 = 2072 so that's 2ms offset.
Sorry for asking a question that I was able to answer by myself...

8N1 is 10 bits not 8 bits. One start bit, eight data bits, and one stop bit. And then there may be gaps between each byte as well. And then of course there is buffering in the Arduino to throw into the mix.

Add the explanation of "faster than expected to your question". The question should stand by itself without needing to search the comments for missing info. "Sorry for asking a question that I was able to answer by myself" That's no problem, just write an answer to your question to help others who have the same question. In fact, this is encouraged on Stack Exchange.

@Majenko If I understand correctly, I have to add 2 more bits to each byte to get an idea of the transfer time, that would do 7.4 * 35 * (8+2) ~ 2.6ms offset

@per1234 the "faster than expected" was a mistake from me, I belived that the serial transmited data faster than it should, but I was wrong.
Btw thanks to everyone trying to help me :)

I second the general idea of Dmitry Grigoryev’s answer: your best option
is to measure a round-trip time and use half of that as an estimate of
the one-way time. Otherwise you will have too many unknowns. For
example, you don't know how long your OS takes to process the outgoing
message and send it through USB to the USB/serial bridge inside the
Arduino. As an optimization, I would send the time information and the
synchronization strobe as two separate messages, with the latter being a
single byte. This way the latency of the synchronization strobe (the
only latency that matters) is minimized.
Latency of serial communication
I did some research to try to nail this one down. At 57600 bits/s,
the theoretical time per bit is about 17.4 µs, as stated in the
Wikipedia article you linked to. In practice, the actual time can be
rounded more or less depending on the UART capabilities and the clock
speed. You did not specify what Arduino you are using. In the following,
I will assume an AVR-based Arduino clocked at 16 MHz, which is
presumably the most common.
The UART in the AVR constrains the bit time to be a multiple of
8 CPU cycles, i.e. 0.5 µs when running at 16 MHz. The
closest you can get to the ideal timing is therefore 17.5 µs.
However, the Arduino core library has a hard coded compatibility
exception which, in this very specific case, sets the bit
duration to 17 µs instead. Since you are presumably configuring the
port at /8N1, which is the default, the time per byte is then
170 µs (1 start bit, 8 data bits and 1 stop bit).
Actually, when transmitting a single byte, the transmission time is
slightly less than that. The UART can report the byte as received as
soon as it is done taking the required three samples of the stop bit,
which happens slightly after the middle of that stop bit. The
theoretical time it takes to transmit a single byte is then about
9.56 times the single-bit duration, or about 162.56 µs at
57600/8N1.
I did a simple loopback test with the TX and the RX of my Uno shorted
together. I used a timer to time the execution of the following code:
Serial.write('.');
while (!Serial.available()) continue;

The result was 182.38 µs, or about 10.73 bit durations. A
fraction of this time is taken by the execution of Serial.write() and
Serial.available(). In order to get closer to a bare hardware latency,
I also timed a low-level version of the two lines above:
UDR0 = '.';
while (!bit_is_set(UCSR0A, RXC0)) continue;

This has to be run with interrupts disabled. The execution time was now
between 164.19 and 164.81 µs, i.e. 9.66 to 9.69 bits
durations.
Alternative approach
As a final note, I would recommend you consider buying a GPS module with
a 1PPS output. This 1PPS is a 1 Hz logic signal with the rising
edges tightly aligned to the start of the UTC seconds. You typically get
an accuracy in the tens of nanoseconds. Since this is just a logic
signal that you can easily compare with the 1 Hz output of your RTC
module, you get rid of all the latency issues that come with computers
(your NTP client), or data links (USB, serial, I2C).

Thank you for the answer :) ; gps utc time sync might also be a good option for precise time syncronisation

Transmission time will certainly not be negligible. To estimate it, you could use the roundtrip delay calculation, which is (roughly) how the NTP protocol is implemented in the first place.

at PC time T1, PC sends current time T1 to Arduino via UART
Arduino sets the time T1 in DS3231 via I2C
Arduino reads the time T2 from DS3231 via I2C
Arduino sends the time T2 to PC via UART. This happens at time T3 from PC's point of view.

Now the PC can estimate the half-roundtrip delay R as (T3-T2)/2. See the following chart which denotes current time form POW of PC and RTC
        |--UART--|--I2C--|--------|--I2C--|--UART--|
PC      T1              T1+R     T2+R           T3=T2+2R
DS3231  -                T1       T2              T2+R

Next, at time T4, the PC sends the value (T4+R) via UART. This will result in  DS3231 to be set to (T4+R), which happens exactly R time after T4, so that both clocks are now set to the same value.
Estimation of R can be repeated several times. In this case you can calculate the standard deviation which tells you how much "jitter" your clocks have.

This is the way I'll go for my project, I think it is a cheap way to get a correct precision of a millisecond :)


text:
How do I clear previous values while using strcat() to add strings?
Is there any other function to add strings into buffer and updating values as well.
This is the problem I am coping with while using strcat()

char temp[2] = "A";
char temp_end[2] = "a";
char buf_adc[20]="alok";
char buf_hum[20]="lok";
char buf_temp[20]="vjf";
char buf[100];
void setup() {
Serial.begin(115200);

}

void loop() {
  strcat(buf,buf_adc);
strcat(buf,temp);
strcat(buf,buf_hum);
strcat(buf,temp);
strcat(buf,buf_temp);
strcat(buf,temp_end);

Serial.println(buf);

}

strcat always concatenates to the end of the string. Instead, for your first strcat you should really be using strcpy, which copies one string over the top of the other - that is, it places it at the start of the string, effectively starting a new string.
However, unless you really need the data in a string for some specific reason, you don't need to build a string up - just print each part to serial separately with its own Serial.print function.


text:
Integrating Java program with arduino mega is it possible?
I have just written a java algorithm to get a chess move when a chess move is inputted in SAN notation the algorithm used : Monte Carlo. Is it possible to integrate this program with an Arduino mega and How?
My mega will be getting inputs from a sensory board and I want to send these inputs to the java program without using any additional board.
Note:
By integrate I mean that the Java program should run in the Arduino mega itself
Can anyone suggest a solution?

Do you want to run the Java program inside the Arduino, or do you want to use the Arduino as an IO device for a PC running the Java program?

@EdgarBonet I want to run the java program inside the Arduino.

Now click on the “edit” link just below your post and revise your question to make that clear. The question should be self contained, one should not have to read through the comments to understand it.

There is a project called uJ by Dmitry Grinberg that enables you to do that, somehow. It has been tested on AVR devices too, not your particular one however. Knowing AVRs, that shouldn't be a stopper at all.
That said, I don't think it's a very good idea. The overhead of the JVM may only let you handle some 'slow' signals, unless you heavily rely on peripherals and wit to do stuff. Though in your particular application, that shouldn't be that much of an issue.
Instead of having the trouble of running a JVM and such, you may just as well rewrite the code in C/C++ or whatever, even for increased efficiency. There may also be some Java to C transpilers, I haven't looked, wary of the dragons.
However, if you eventually decide against that and instead choose to talk to the microcontroller over serial or something else, there is the dreadful excellent RxTx library for Java that works pretty fine after all, or the Firmata library.


text:
ESP send data to Arduino
I'm trying to send data from my esp to my arduino using serial using the following codes :
esp :
server.on("/drive",HTTP_GET, handleDrive);
void handleDrive()
{
    server.send(200,"text/html", "Drive!");
    String sendToArduino = "";
    for (int i=0;i<server.args();i++)
    {
   sendToArduino = sendToArduino+server.argName(i)+"="+sendToArduino.arg(i)+"&";
    }
    Serial.println(sendToArduino);
}

and on arduino :
Serial.begin(9600);
esp8266.begin(115200);

if (esp8266.available())
{
   String  readString="";
   while (esp8266.available())
   {
     delay(2);
     char c = esp8266.read();
     readString += c;
   }
}

but when i send data from esp to arduino i get it with "noise"
Ex : "variable1=1234"   i recive it on arduino "variab@e=12"
What can i make to make sure that what i send is same in arduino ?

Two things: 1. read the serial properly (https://majenko.co.uk/blog/reading-serial-arduino), and 2. what baud rate are you communicating at?

Serial.begin(9600);  esp8266.begin(115200);   in arduino

Sorry, what is that delay(2)? You send one byte from the ESP in roughly 87us, and force to read it once every 2ms?

Firstly you need to write a more reliable serial reading routine on the Arduino. As it stands your routine is lucky you even get what you do. You need to write a routine that doesn't care about time, but instead cares about the terminating character of the line you are receiving.

Here is an article I wrote all about it.

Secondly, you cannot communicate reliably using SoftwareSerial at 115200 baud.  While the Arduino is capable of receiving a byte at that baud rate using bit banging, there typically isn't enough time between successive bytes to allow the Arduino to store what it has just received, and so it starts receiving partway through the next byte, corrupting both it and the following byte. That's the cause of the corruption you are seeing.
You should either slow down the baud rate (9600 is a good choice), or send the data one byte at a time and add a delay between each byte (somewhat hacky...).


text:
Why doesn't Serial.read() read multiple character?
I used multiple of Serial.read() and Serial.parseInt() to get characters and a number ( like "xy123" ) on an Arduino UNO.
Then I checked the result on Serial monitor.
Unfortunately I couldn't get the character with second Serial.read().
Here's the code:
void setup(){
    Serial.begin(9600);
}

void loop(){
  if (Serial.available() >0) {

    // I want to reacive the characters like "xy123"
    char input1 = Serial.read();
    char input2 = Serial.read();
    int value = Serial.parseInt();

    Serial.println(input1); // ok
    Serial.println(input2); // * no good * (-1)
    Serial.println(value);  // ok

    // Writing some codes with input1 ,input2 and value ...
  }
// I don't want to use delay().
}

How do I get the second character?
Thanks.

Everything is explained here: https://majenko.co.uk/blog/reading-serial-arduino

what second character?

  if (Serial.available() >0) {

This is like saying "I won't go into that room until there is at least one dog in there".  Someone tells you there is a dog there. You go into the room and say "Hey, why aren't there two dogs there?".
If you want to read two bytes one approach is to wait until they are available:
  if (Serial.available() >= 2) {

but you did send two dogs into the tunnel leading to that room :-)

Exactly! But one hasn't arrived yet. :) Dogs move at a finite speed, the same way that serial communications does. In fact I think everything moves at a finite speed.

You did not read the second character, because the character did not arrive yet. Wait until it is available. read doesn't wait. parseInt has the waiting build-in.
You can wait for the second character by reading the two characters with the waiting function readBytes. It will wait a second for the next character.
char buff[2];
if (Serial.readBytes(buff, 2) == 2) {
  char input1 = buff[0];
  char input2 = buff[1];
...

If you send only one character, readBytes will wait one second for the next and the returns that one char was read.


text:
Print output on 16x2 LCD and Serial Monitor
I'm trying to print an int on both an LCD and the Serial Monitor, but its only being displayed on the LCD. The Serial Monitor is printing question marks.
Here is my Arduino code:
#include <LiquidCrystal.h>
LiquidCrystal lcd(1, 2, 4, 5, 6, 7);
int x = 10;

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

void loop()
{
  x++;
  lcd.setCursor(0, 0);
  lcd.print(x);
  Serial.print(x); // print Serial
}

reduce your code to print to serial monitor only and try again .... post your results .... note: question mark ? .... exclamation mark !

If you are using clasical UNO, then pins 0 and 1 are Serial. Declaring lcd(1,... make LCD use the pin 1 too, so Serial is confused and garbled.
Use other pins for lcd and adjuct the wires acordingly.

@aloush You should select the green tick next to the vote button in the left if you think this answer solved your problem.


text:
Error handling strings and chars
I'm having an error in buffers that handle strings and I can not figure out what the problem is. The example below shows what is happening. Can someone help me?
void setup() {
   char* ss1 = "";
   char* ss2 = "";
   String txt = "";

   Serial.begin(115200);

   txt = "1234560001a";
   txt.toCharArray(ss1, txt.length());

   Serial.printf("\n\n");
   Serial.printf("ss1 = %s\n", ss1); // It prints "1234560001" whithout last char "a"

   // Force incorrectly "ss1" to be equal to "ss2" and still removes the last character.
   txt = "abcdef";
   txt.toCharArray(ss2, txt.length());

   Serial.printf("ss1 = %s\n", ss1); // It prints "abcde" whithout last char "f"
   Serial.printf("ss2 = %s\n", ss2); // It prints "abcde" too
}

see what happens if you make a change in this line  ... txt.toCharArray(ss1, txt.length()); .... think about it

What kind of change do you mean? There are two problems occurring in the code: 1) the string is removing the last character when copying; 2) The contents of the second variable are overwriting the contents of the first variable.

I understand that you meant that It have problem in length() and that doing length() + 1 works. if string = 'abc', then string.length () should be 3, isn't it? But I insist: So is this an IDE problem? About the second problem, the pointers, why are they overwriting the contents?

strings are null terminated .... the char array must have space for that null

i am not sure about the ss1 and ss2 pointers ..... maybe, because the ss1 and ss2 are created without a size, ss2 points to memory ss1+0

found this ... https://stackoverflow.com/questions/13294067/how-to-convert-string-to-char-array-in-c#13294114

Copy works correctly with these modes of operation, but they are still overwriting the contents of the variables. I can not understand ... Thanks!

Read: https://majenko.co.uk/blog/arrays-pointers-what-c

Great article! But I have not been able to solve the problem that is overwriting the contents of the variables, since the use of the pointers in my example seems to be correct according to your article. Thanks.

toCharArray is alias for getBytes. getBytes is documented as "Copies the String’s characters to the supplied buffer." You did not allocate the memory for the copied characters.
the right use of 'getBytes' and 'toCharArray' is
char buffer[BUFF_SIZE];
str.getBytes(buffer, sizeof[buffer]);

note: getBytes functions sets the terminating zero of the c-string in buffer

About the problem with losing the last character:
As already said in the comments, the toCharArray() method is only an alias for the getBytes() method of string objects. We can see it's implementation in the IDEs folder under hardware/arduino/avr/cores/arduino/WString.cpp:
void String::getBytes(unsigned char *buf, unsigned int bufsize, unsigned int index) const
{
    if (!bufsize || !buf) return;
    if (index >= len) {
        buf[0] = 0;
        return;
    }
    unsigned int n = bufsize - 1;
    if (n > len - index) n = len - index;
    strncpy((char *)buf, buffer + index, n);
    buf[n] = 0;
}

We give the length as parameter, which is then reduced by 1. The function strncpy(), that is used here, will only copy n = bufsize - 1 bytes. In the end, the nth byte will be set to 0 as the terminating null character.
This means, that the length, that we give as parameter, already includes the space for the null character. But the method String::length() will not include the null character in length calculation (in most cases this is not wanted). So you can simply add 1 to the length before giving it to toCharArray().
About the overwriting problem:
As stated in this question's answer and in several other discussions about C/C++ (for example here), string literals are meant to be immutable. The mentioned sources say, it is different, if you define a string variable as
char *str = "test";

or
char str[] = "test";

In the second case a normal mutable array is created. In the first case the string will be placed in read only memory. From your problem I read, that on Arduino this is placed in RAM, thus technically mutable. But the compiler thinks of it as immutable. A common optimization, when dealing with immutable strings, is to let every used string literal with the same content be saved at the same memory address.
In your code you are initializing 2 strings with only the terminating null character in them. The compiler thinks "Oh, wait, these two string literals are immutable and equal, so I can save memory by only saving it once and let both pointers point to this memory address". When writing to the strings in Arduino the behavior doesn't seem to be defined. As the Arduino cannot throw an exception it will most likely do the write. Since both pointers are pointing to the same memory address, they show both the same content. Also, when writing a string longer than the initialized value, memory space outside from the original string will be written. If other variables are saved there, they will get overwritten. This is the reason, by you should always explicitely allocate the memory (static or dynamic) for a string, until another function does it for you. When using a dynamic allocation of memory, you should also consider heap fragmentation, which can easily lead to strange behavior.
If you turn on verbose output for compilation, the compiler also warns you, that you try to convert a constant string literal to a non-constant char pointer:
sketch_jul09a.ino:3:15: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]

To conclude, you should not declare string variables like this. If you have a variable string buffer with initialized values, you should use
char str[]="test";

If you want to define a constant string, use the keyword const:
const char *str = "test";

Then writing to it will result in a compiler error, so that you sense, if you are doing this.

Thank you for your tips. I have not yet solved the second problem either, but I'm using a palliative solution (even against my own will, for lack of a better option). I'm using a fixed length buffer and copying the string with getBytes as pointed out by @Juraj. Thanks.


text:
Trying to connect FT sensor to Arduino Mega using RX TX
I am trying to interface this sensor, https://www.robotous.com/forcetorquesensor (RTF60-HA01-C), with the Arduino Mega. The sensor has an input voltage of 5Vs and communicates using CAN/RS232/RS422. I am using the RS232 and have connected wires properly and have tried to establish Serial Communication using the below code.
#include<String.h>
# define BuffSize 32

byte buff[BuffSize];
unsigned char data_field[16];
byte comm[11]  = {0x55, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xAA};
// SOP == 0x55, EOP == 0xAA, Checksum == summation of each data in data_field
void setup() {

  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial2.begin(115200);
  for (int i = 0; i < BuffSize; i++) {
    buff[i] = 13; //Number to initialise buffer
  }

}

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

     Serial2.write(comm, 11);
    //Serial.println(Serial2.available());
    if (Serial2.available() > 0) {
      //int read = Serial2.readBytes(buff, BuffSize);
        String output = "";
        for(int i=0;i<BuffSize;i++){
        buff[i]=Serial2.read();
        output = output + buff[i] + "|";
     }
  //Serial.println(read);
    Serial.flush();

    Serial.println(output);
    Serial.println();

    }
  }

The output I receive is just 0s and the occasional 10. Like below
0|0|0|0|0|0|0|0|10|0|0|0|0|0|0|0|0|10|0|0|0|0|0|0|0|0|10|255|255|255|255|255|

I am new to this and hope this is not a stupid question.
Let

It seems I am posting this link on every other question at the moment: https://majenko.co.uk/blog/reading-serial-arduino I don't know where people are getting such bad code from for working with serial.

The Serial RX and TX pins of an Arduino are not RS-232 compatible without using some type of circuit to give you the proper voltage levels.
**RS-232 logic and voltage levels**
0 (space)   Asserted    +3 to +15 V
1 (mark)    Deasserted  −15 to −3 V

Connecting the RX/TX pins of an Arduino directly to an RS-232 device may fry your Arduino in addition to just not working for communication.  This circuit given below is an example what you'll need.  There are pre-made adapter boards available for a few dollars.

You obviously haven't understood the way this device communicates over serial. You don't just throw an "11" at it to get it going - you have to craft a proper command packet and send that, and the device then starts responding with response packets that you must parse properly.
A command packet starts with 0x55, then has the command and data (8 bytes in total), then a checksum and EOP byte (0xAA).
For example:
0x55, 0x0B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0B, 0xAA

When reading you do not look for "at least one byte" then try and read 32 bytes. That's just never going to work.  You need to wait for 0x55 to arrive, then wait for each of the 16 following command+data bytes to arrive, one at a time (they do NOT arrive all at once!), and store them - then calculate the checksum for those command and data bytes, and read the next byte and make sure it matches the checksum. Finally, confirm you have a proper packet by reading the EOP byte of 0xAA.
Ideally, you want to implement a sliding window algorithm whereby you have an array of 19 bytes and incoming bytes filter down from one end of the array to the other. When the first byte is 0x55 and the last byte is 0xAA, and the penultimate byte equals the (truncated) total of bytes 2 to 17 inclusive, do you have an actual packet and can act on the data.


text:
How to install your own library with Arduino IDE 1.8.5?
I'm struggling a bit with Arduino language + its IDE not being 100% real C++. I wrote my own I2C library for a sensor but can't get the IDE's compiler to recognise it. I'm using Ubuntu 18.04.
I get no such file or directory for all of these things I've tried:

Include the .h file by absolute and relative path in the .ino code
Put .cpp +  .h files in ~/Arduino/libraries
Put .cpp +  .h files in ~/sketchbook/libraries
Put .cpp +  .h files in ~/sketchbook/libraries/mylibrary
Put .cpp +  .h files in ~/sketchbook/libraries/mylibrary and try to "install" the library in the IDE (Sketch -> Include library -> Manage libraries; it's not listed)

I'm following the official guide here. Any ideas on how to get the compiler to recognise my library?

You need to:

Create the folder ~/Arduino/libraries/MyLibrary
Place the library files in there named as:

~/Arduino/libraries/MyLibrary/MyLibrary.h
~/Arduino/libraries/MyLibrary/MyLibrary.cpp

Restart the IDE if it is running
Use #include <MyLibrary.h> in your sketch

This is assuming your sketchbook is set to ~/Arduino - change that to wherever the sketchbook is set to (check in Preferences for that location).
Note that in Linux capitalisation is important. The filesystem is case sensitive, and the name of your folder should have the same name and capitalisation as the name of your header file.

No, but what capitalisation you use on your files you should also use on the folder, and you must use in the #include.

I'm not sure how critical it is, but it should be the same as the .h file.

You're right, it was the sketchbook location. I had fiddled with my installation a few times, and hadn't updated the preferences. Thank you.

Have you confirmed where you sketchbook folder actually is? Mine is ~/Arduino (I updated the answer to reflect that).

I would add that the source files can be in src subfolder of the library folder to not mix them with library configuration files and github readme file if you want to publish the library. ~/Arduino/libraries/MyLibrary/src/MyLibrary.h https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification

Only if you have a library.properties (or whatever it is) to describe the library...

"I'm not sure how critical it is" When multiple files match the #include directive, the IDE uses folder name matching as one of the factors for determining which gets preference. That's the only time a matching folder name matters.

@per1234 UECIDE is more strict and needs the folder named properly so it can identify precisely what a library is. It needs that so it can do proper recursive library inclusion, which is something the Arduino IDE sadly lacks.


text:
Sending PUBX commands to GPS Board (Ublox NEO-6M) through SoftwareSerial
I am having trouble parsing NMEA sentences coming from a GY-NEO6MV2 board (https://www.cytron.io/p-gps-neo6mv2), using the TinyGPS (https://github.com/mikalhart/TinyGPS) library. The GPS board itself is connected to an Arduino Pro Mini 3v3 8MHz (ATmega328)
First of all, to start debugging I want to disable all NMEA sentences other than GGA and RMC (which are the only ones I need for this project)
According to the manual, this can be done by sending PUBX commands through the SoftwareSerial (no need for binary UBX)
I am doing this in the following way
#include <SoftwareSerial.h>
#include <TinyGPS.h>

// GPS SoftwareSerial
// Shares pins with (MISO 12/ MOSI 11) used for SPI

#define GPS_RX_PIN 12
#define GPS_TX_PIN 11

TinyGPS gps;
SoftwareSerial GPSSerial(GPS_RX_PIN, GPS_TX_PIN);

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

      GPSSerial.print("$PUBX,40,GLL,0,0,0,0*5C\r\n");
      GPSSerial.print("$PUBX,40,ZDA,0,0,0,0*44\r\n");
      GPSSerial.print("$PUBX,40,VTG,0,0,0,0*5E\r\n");
      GPSSerial.print("$PUBX,40,GSV,0,0,0,0*59\r\n");
      GPSSerial.print("$PUBX,40,GSA,0,0,0,0*4E\r\n");
}

void loop()
{
// ...
}

However, the GPS board will not respond to these commands and keep sending all the NMEA sentences.
FWIW, this is the original code I'm building my project on - https://github.com/billygr/arduino-aprs-tracker/blob/master/arduino-aprs-tracker.ino
Any thoughts would be appreciated...

I've tried your code sending those PUBX commands to a ublox module and they work successfully for me.
There are a lot of fakes about on the internet using AT6558 chips repackaged as ublox. Check the GPTXT messages that are output when the GPS module is powered up to see if its really a ublox module or a fake one like this:
$GPTXT,01,01,02,MA=CASIC*27
$GPTXT,01,01,02,HW=ATGM332D,0080113573899*18
$GPTXT,01,01,02,IC=AT6558-5N-31-0C500000,J7M911C-B2-008827*50
$GPTXT,01,01,02,SW=URANUS4,V4.3.0.5*18