text:
Measure lipo voltage while powering arduino
I have a arduino pro micro 5V that I want to power with a 3.7V lipo. I also have a charging module to charge the lipo.
(https://www.banggood.com/nl/TP4056-1A-Lipo-Battery-Charging-Board-Charger-Module-Mini-USB-Interface-p-1027027.html?rmmds=myorder&cur_warehouse=CN).

I want to measure the battery level of the lipo.

Should I use a step up module to 5V?

How can I measure it? I read that you can't just use analogRead because the lipo itself is the reference.

Thanks in advance!

Pro Micro uses the '32U4 processor? http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7766-8-bit-AVR-ATmega16U4-32U4_Datasheet.pdf    Maximum Frequency
– 8MHz at 2.7V - Industrial range
– 16MHz at 4.5V - Industrial range  - so you are operating out of spec with 16 MHz crysta;/resonator and  3.7V-4.2V LiPo battery.  The '32U4 has a Selectable 2.56V ADC Reference Voltage, so you can use the Internal Aref voltage (vs the default External setting), divide down the battery voltage to be less than 2.56V max, and measure that way. Results may not be accurate if Vcc is < 5V with 16 Mhz clock.

But if I use a step up converter and a voltage divider I should be able to measure it? How do I have to wire it?

The reference voltage for analogRead should be from the regulated 5V line, not from the unregulated input to the Arduino.
The real problem is that the voltage out of the battery will drop with current load. You're supposed to measure either the unloaded battery, or under a known, controlled load.
You ask "Should I use a step up module to 5V?" The answer is yes, but that's unrelated to your voltage measurement question. An Arduino requires a source of regulated 5V. The internal voltage regulator is a linear regulator that requires somewhat more than 5V as input (7.5V is about right.) You can't power the internal voltage regulator with a single 3.7V lipo battery. You'd need a step-up regulator, and with that, you could bypass the internal regulator on the Arduino (assuming your step-up regulator puts out 5V.)

But better is a step up to 7.5V then?

No, there's no need for that. Step up to 5V, and then feed that into the 5V input of the Arduino. If you step up to 7.5V and feed that into the Arduino's VIN, it will just regulate the already-regulated 7.5V back down to 5V, turning 2.5v to heat.

On one of my projects I cut a USB cable and fed my regulated 5V into the USB input. That way you take advantage of the input switching circuitry on the Arduino.

So I step it up and feed it into the Vcc pin or the raw pin?

Step up your lipo voltage to 5V, cut a USB cable (One with the square end that plugs into an Arduino), and feed the 5V into the red and black wires of the USB cable. Then plug that USB cable into your Arduino. When you do that it feeds the 5V into the Vcc pin, through a switching circuit that intelligently selects between power sources.

Why wouldn't I just feed it to the Vcc? I'm only using one power source.

That's OK, until you forget to disconnect the power supply and hook up a USB cable to update your code and possibly fry the Arduino.

And then I connect the positive wire of the battery with a voltage divider to an analog input and I can measure it?

Yes, although the variable load on the battery will cause the voltage to drop, throwing off your measurements.


text:
Trying to send .wav files between NodeMCU
Im trying yo send wav files between two nodeMCU. My setup is like this
uSD Card Module -> Arduino Mega -> Node MCU
So this is my setup, where I have 4 devices like this. One will serve as the central network(where I called it "server") where it will create an access point for the 3 other devices("modules") to connect to. The server will send data by using UDP so it can broadcast to the three modules simultaneously.
I'm able to send .txt files which is stored on the uSD module. Pass the .txt file contents to the nodeMCU through serial port, then recieve it on the other NodeMCU which will then send the data to the Arduino Mega also through serial port and will store it on its uSD Shield.
When I would try .wav files. It is able to send the whole .wav file to the NodeMCU from Arduino Mega (since .wav files are too big, I divide the .wav files into sets since the serial port can't handle too large data being sent/recieved. But when it would send the data from the nodeMCU to the other nodeMCU there are parts which are not being sent. When I try to observe what are not being sent, its part of the WAV Header Format, so it needs to be sent. Ill be posting the codes Im using to send and recieve and also a screenshot/example of the wav file as it is being sent.
Server's Arduino Mega Sending data to NodeMCU Serially:
void sendFiletoSerial(char fileSend[12]){
  Serial.println();
  Serial1.println();
  if (!myFile.open(fileSend, O_READ)) {
    sdf.errorHalt("opening test.txt for read failed");
  }
  Serial.print(fileSend);
  Serial.print(" Size:");
  Serial.println(myFile.fileSize());

  Serial1.print(fileSend);
  Serial1.print(" Size:");
  Serial1.println(myFile.fileSize());
  delay(1500);
  fileofSize = myFile.fileSize();
  myFile.close();
  // read from the file until there's nothing else in it:
  char data;
  long int index=0;
    for(int i =0; i<(fileofSize/tempSize);i++){
    if (!myFile.open(fileSend, O_READ)) {
    sdf.errorHalt("opening test.txt for read failed");
  }
    //Serial.println(i);
    myFile.seekSet(index);
  for(int j =0; j<tempSize;j++){
  int temp = myFile.read();
 intTempFile[j]=temp;
  index++;

  }
  for(int k =0;k<tempSize;k++){
  Serial1.write(intTempFile[k]);
  }
    myFile.close();
    delay(1500);
  }
  Serial.println("LAST SET OF DATA");
    if (!myFile.open(fileSend, O_READ)) {
    sdf.errorHalt("opening test.txt for read failed");
  }
    myFile.seekSet(index);
    int lastSetSize=fileofSize-((fileofSize/tempSize)*tempSize);
    Serial.println(fileofSize-((fileofSize/tempSize)*tempSize));
  for(int j =0; j<lastSetSize;j++){
 int temp = myFile.read();

 intTempFile[j]=temp;
  index++;

  }
  Serial.println();
  Serial.println("tempFile");
  for(int k =0;k<lastSetSize;k++){
  Serial1.write(intTempFile[k]);
  }
    myFile.close();

}

Server's code for Sending from NodeMCU to other Node MCU:
    if (Serial.available()) {
          byte readStr[100];
        Serial.readBytes(readStr,100);
       // Serial.write(readStr[i]);
        }

         port.beginPacket("192.168.4.255",2390);
         for(int i =0; i <100; i++){
        port.write(readStr[i]);
         }
         port.endPacket();
      }

Module's Code for NodeMCU to recieve data from other NodeMCU:
void dumpMode(){
  while(1){
    int packetSize = port.parsePacket();
      if (packetSize) {
        port.read(packetBuffer, fileSentSize);
        Serial.write(packetBuffer);

  }
  if(Serial.available()){
    String reply = Serial.readString();
    if(reply == "STOP"){
      break;
    }

    }
  }
}

Server's NodeMCU Sent Data:
RIFFäN  WAVEfmt      À]  À]    dataÀN  €€€€€€€€€€€€€€€€€€€€€€€€

Module's NodeMCU Recieved Data:
RIFFäN€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€

Is there something im doing wrong thats why NodeMCU is not either sending or recieving every content of the wav file?
Thank you for those who will help out. :)

You could just program the NodeMCUs and skip the Megas; they have sufficient pins to drive an SD card. There's so much wrong with your code: opening and closing the same file so many times and then having to seek for every chunk because of the previous nastiness, writing and reading bytes singly instead of just passing in a buffer, among others. I also hope you know that you didn't send only the WAV data to the transmitting NodeMCU; there's a bunch of stuff (CRLF, file size, etc) before that.
Your particular problem's most likely the fact that your Mega "server" is just sending chunks continuously to the NodeMCU, never minding if the latter is reading them quickly enough that its serial buffer doesn't overflow, especially considering you're sending data over the network between chunks. You should also note that UDP isn't exactly the most reliable protocol; it's connection-less and so packets will be lost. It's generally used if packet loss isn't a big deal (in your case, it is) or if upper layers implement error control.
What you need to implement is a way for each party to confirm that they've received the next chunk before the their sender transmits the next. The Mega needs to wait for a 'go-ahead' from the NodeMCU before sending the next chunk; for instance, the NodeMCU can reply each chunk with the number of bytes it actually read, so you can know if you should reduce your chunk size to not overwhelm the NodeMCU buffer.
The packets sent over the network also need to be tagged with a sequence number (because of aforementioned error control). The NodeMCU at the receiver needs to acknowledge the packet it received each packet, perhaps by sending that packet's number to the transmitting NodeMCU. This will help ensure all packets are received and in order. Or you could just use TCP which already implements these and more.

Actually I also have an RFID Scanner connected to the Mega and also playing some WAV Files with the arduino, thats why I still need to use an Mega + NodeMCU.
The "CRLF, file size, etc" you've mentioned is the 44byte Wav Header Right? I am also trying to send that but since its that part thats not being sent, it cant create the wav file completely.
I chose UDP over TCP since I need to broadcast the data between the 3 modules. Based from my researches UDP can implement broadcast while TCP can' but if im wrong please do tell me.

@boomacoh The stuff I mentioned is not part of the official header unless you mean its your own customized header to help parse the data. TCP isn't built for broadcast yes, but if you use UDP, you'll have to find a way to handle lost packets.

source: Stack Exchange

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

sort: votes


text:
Atmega2560 USART UDR r/w conflict possible?
I'm having a really weird issue with my project right now. I have an Atmega2560 using hardware serial, and the software on the other side is doing full duplex read/write at 500kbps. If I change it to be single duplex, everything works fine. But the second I try to run everything truly full duplex, I start to have some data transfer over from the transmit stream to receive stream on the device (characters that its trying to write, that it somehow ends up reading again).
I've simplified things as much as possible- disabling buffering on the arduino side, using mutexes on the client software side (to prevent overlapping read/write commands, despite the fact the underlying driver will do whatever it wants).
So, there's obviously a few potential problems here, but it has to boil down to:
a) Client software/drivers misbehaving
b) Hardware serial implementation misbehaving on the device.
I really want to rule out B, and from all my digging around, it really comes down to one question:
Is there any possible way that data written to the UDR register could somehow be read out again? I understand this register is actually 2 different registers, and just splits out reads and writes. But is there any possible way at all this data could be read again? Like, is it possible to even write to UDR and read that byte ever again? I'd really like to rule that out before I start unnecessarily tracing ISRs and all that garbage.
Here's what I've boiled the hardware serial code down to. Interrupt driven on read and direct write on write:
void MarlinSerial::write(uint8_t c) {
  while (!TEST(M_UCSRxA, M_UDREx));

  M_UDRx = c;
}

ISR(M_USARTx_RX_vect) {
  const unsigned char c = M_UDRx;
  store_char(c);
}

UPDATE: I'm an idiot. Found a buffer overrun way downstream in the device code. It just so happened that the temp response buffer for one routine butted up against the receive buffer, so it delightfully just over-ran into there. I'm happily chugging away now with 2 totally async command streams, total about 400kbps.

Not an answer, but are you checking the flag bit that indicates that there is data available, before you try to read the data register?  If that is not indicating that there is data available, it may not be well defined what you would obtain by reading it.

If the bytes you write to the USART came back from it all by themselves, that would be a very serious hardware bug. Hardware bugs do happen, see the Errata section of the datasheet, but that one would be too egregious to go unnoticed.

I am checking the flag before doing a write, im using interrupts for the read so I shouldn't have to check any flags.
As far as hardware bugs, it's a cheap board, supposedly using the same chips as the Arduino 2560, but they could be knockoffs or something, or just bad circuit design.

Is there any possible way that data written to the UDR register could somehow be read out again?

No, there is no possibility. The datasheet says:

The USART Transmit Data Buffer Register and USART Receive Data Buffer Registers share the same I/O address
  referred to as USART Data Register or UDRn. The Transmit Data Buffer Register (TXB) will be the destination for
  data written to the UDRn Register location. Reading the UDRn Register location will return the contents of the
  Receive Data Buffer Register (RXB).

Further on it says:

The transmit buffer can only be written when the UDREn Flag in the UCSRnA Register is set. Data written to UDRn
  when the UDREn Flag is not set, will be ignored by the USART Transmitter. When data is written to the transmit
  buffer, and the Transmitter is enabled, the Transmitter will load the data into the Transmit Shift Register when the
  Shift Register is empty. Then the data will be serially transmitted on the TxDn pin.

And for reception it says:

The receive buffer consists of a two level FIFO. The FIFO will change its state whenever the receive buffer is
  accessed. Due to this behavior of the receive buffer, do not use Read-Modify-Write instructions (SBI and CBI) on
  this location. Be careful when using bit test instructions (SBIC and SBIS), since these also will change the state of
  the FIFO.

So the only thing it is possible to read is data that has been received via the RX pin (and then once and once only). All written data (assuming there is room in the TX buffer) is sent out of the TX pin.
If you are getting TX data appearing in the RX buffer then somewhere there must be some kind of connection between the TX and RX pins - either in software at the remote end (the remote device echoing everything it receives, which is perfectly possible depending on what the remote device is), or though a fault in the cabling or circuit design.

Damn it all. Believe it or not, that rules out the "easy" answer to my problem.
The board is an Elegoo Mega 2560- Should have the same USB chip and everything, but it was cheap as dirt and I definitely would not rule out a bad circuit design somehow allowing cross talk between the lines.
The client side software is run on OSX, and just uses the standard open/ioctl/read/write access to the TTY. So if there's something wrong on the client side, it has to be something with the USB serial drivers (not even sure what drivers its uses for this USB UART).

Just tried a different computer, running Linux this time, and got rid of ALL other USB devices besides this one, still the exact same issue =\ So it's not looking like its the client drivers fault...

@ColinGodsey: Are you sure echo is not enabled on the Unix side?

@EdgarBonet Yea, no echoing. If I simplify the test to just "call and response" (no actual simultaneous r/w), it works fine. Even running a CRC on the other end, I can push about 400kbps of data with 0 errors. It just becomes an issue when I start reading while writing and vice versa.

arg, see note above. was just some downstream buffer overrun issues

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


text:
Could not read ID via SWD with Arduino
So I'm trying to read a bit of data via SWD. I've tried two chips as target - LPC1110 and STM32F030F4 (the first of them I used for other schematic, but I've reset the flash to make sure the pins are not configured improperly).
I use Arduino as a host. I wire D3 to SWCLK and D4 to SWDIO (with pull-up to 3.3V line). I fail miserably with both chips - i.e. when I expect some ACK be read - it only shows HIGH state on the line all the time.
Here is my code. Could anyone have a look and tell where I went wrong:
int swdck = 3;
int swdio = 4;

void setup() {
  pinMode(swdck, OUTPUT);
  digitalWrite(swdck, HIGH);
  pinMode(swdio, INPUT);
  digitalWrite(swdio, HIGH);
  Serial.begin(9600);
}

// write some bits from X (least significant first) to SWD
void clockOut(int x, int bits) {
  pinMode(swdio, OUTPUT);
  while (bits > 0) {
    digitalWrite(swdck, LOW);
    digitalWrite(swdio, (x & 1) ? HIGH : LOW);
    delay(1);
    digitalWrite(swdck, HIGH);
    delay(1);
    bits--;
    x >>= 1;
  }
  pinMode(swdio, INPUT);
  digitalWrite(swdio, HIGH);
}

// read some bits from SWD, least significant first
int clockIn(int bits) {
  pinMode(swdio, INPUT);
  digitalWrite(swdio, HIGH);
  int i, res;
  res = 0;
  for (i = 0; i < bits; i++) {
    digitalWrite(swdck, LOW);
    delay(1);
    if (digitalRead(swdio) == HIGH) {
      res += (1 << i);
    }
    digitalWrite(swdck, HIGH);
    delay(1);
  }
  return res;
}

void loop() {
  int x;
  // unlock sequence though it probably is not needed
  clockIn(26); clockIn(26); // more than 50 clocks
  clockOut(0xE79E, 16); // command to switch to SWD
  clockIn(26); clockIn(26);

  clockOut(0x25, 7); // 0b0100101 - request to read Debug-port-0, i.e. ID
  x = clockIn(5); // there should be ACK bits somewhere... but I get 0x1111
  clockIn(26); clockIn(26); // perform more readings for case anything is returned
  Serial.println(x);
  delay(1000);
}

Please post an explanation of how the ARM-MCU pins are only driven to 3.3V, and not 5V. I assume it is correct, and have only examined the software in my answer. However, it would be helpful to be sure about the pins.

Your concern is correct, but it seems like both ARM chips I used (LPC and STM32) have 5v tolerant inputs. On the other side when 3.3V logic signal is feeded to TTL input it is also higher than threshold value so it works all right. Seems like chip manufacturers take these precautions to save people from inventing interfacing circuits...

I haven't read LPC specs closely, so them having 5V tolerant SWD pins is very useful to know (it might even be worth updating your question to mention this). I am interested in your results. Have you got this working?

I am not a SWD expert; it is several years since I read the spec. So I apologise if you are way ahead of me.
I believe ARM's SWD documentation, e.g. "ARM® Debug Interface v5 Architecture Specification" (ARM IHI 0031A) says that transfers are fixed length, starting with an 8 bits request.
The code:
void clockOut(int x, int bits) {
  pinMode(swdio, OUTPUT);
  while (bits > 0) {
    ...
    bits--;
    ...
  }
  ...
}

is invoked with clockOut(0xE79E, 16)
A packet request is 8 bits, followed by a response from the target. So this doesn't appear to follow the protocol.
Similarly clockOut(0x25, 7) appears to send 7 bits, which also looks wrong, and may explain why the read fails.
Further, there should be a 'turnaround bit' after sending the packet.
This code:
void clockOut(int x, int bits) {
  pinMode(swdio, OUTPUT);
  ...
  pinMode(swdio, INPUT);
  digitalWrite(swdio, HIGH);
}

looks like it is setting up to do that, however, it also needs to signal another clock pulse, e.g.:
void clockOut(int x, int bits) {
  pinMode(swdio, OUTPUT);
  ...
  pinMode(swdio, INPUT);
  digitalWrite(swdio, HIGH);
  /* signal a clock pulse */
  digitalWrite(swdck, LOW);
  delay(1);
  digitalWrite(swdck, HIGH);
  delay(1);
 }

A SWD read should return 33 bits, so x = clockIn(5); looks a bit fragile.
Even so, it should get the three ACK bits. It should leave another pile of bits unread, which is what I mean by fragile.
However, x = clockIn(5); might be incorrect because of the short clockOut(0x25, 7) and lack of a turnaround bit.
Small points:

I'd change that clockOut while loop to be a for loop like clockIn to make it clear that it is running for a specific 'count' (bits) of bits to be transferred.
delay(1) seems to be a long time between bits. I don't remember any
timing restrictions. However, I would expect the transfers to run
10-100x faster.
IMHO clockIn(26); clockIn(26); seems to be an unnecessarily obscure way
to generate the 50 cycle connection/reset sequence. I'd probably have
a slightly simpler function than clockIn which only generates the
connection/reset sequence.

Edit:
The statement res += (1 << i); in clockIn works.
However, I had to read it a couple of times to recognise that it is assembling a binary value, and not doing some tricky arithmetic. It is more common to use bitwise operators to assemble a binary value. It is only a small point of style, however res |= (1 << i); might be more clearly constructing a binary value, than res += (1 << i); because it can only ever effect one bit, and never many bits.

Thank you for elaborate answer! I'll try to answer step by step. SWD Request is 8 bits, yes, but the last bit "should not be driven by host on swdio", i.e. at this point host should disable output and simply send another clock. I assume this is performed inside clockIn(5). That is the reason why I have 5 here - I want to send several clocks so that any parking bit, turnaround bit and ack is clocked at once. If any other value than 0x1F will come I hope I can guess where is the ACK in it...

As about 0xE79E - I believe it is not a part of SWD protocol at all, just some magic sequence to switch from JTAG to SWD (and there is a back switching sequence). I have no idea whether these chips need it so I've tested with and without it. Anyway, you see, I myself know almost nothing of SWD - I only started reading manuals a couple days ago... So of course I could be wrong in anything or everything. Also thank you for valuable style/design recommendations!


text:
The function AnalogWrite is outputting less voltage than digitalWrite on my board
I can't figure out why the output voltage of analogWrite(255) is less than the voltage of digitalWrite(255). My code and an image of my setup are below. Some other useful information is that I am using the NodeMCU by HiLetgo, 3.3k ohm resistors with the meters, and that the meters use 1mA of current DC at full scale. Thanks for your help!
int pPressure       = D2;
int pPrecipProb     = D1;
int pWindSpeed      = D0;

int mTemperature;
int mHumidity;
int mPressure;
int mPrecipProb;
int mWindSpeed;
int mAlert;

void setup() {
  Serial.begin(9600);
  pinMode(pPrecipProb,   OUTPUT);
  pinMode(pWindSpeed,    OUTPUT);
  pinMode(pPressure,     OUTPUT);
  pinMode(LED_BUILTIN,   OUTPUT);     // Initialize the LED_BUILTIN pin as an output
}

// the loop function runs over and over again forever
void loop() {
    mPressure           = (int) constrain(mPressure + 1, 0, 255);
    mPrecipProb         = (int) constrain(mPrecipProb + 1,     0, 255 );
    mWindSpeed          = (int) constrain(mWindSpeed + 1,     0, 255 );

    if(mPressure == 255)
    {
      mPressure = 0;
      mPrecipProb = 0;
      mWindSpeed = 0;
    }

    digitalWrite(pPressure,      HIGH   );
    analogWrite(pPrecipProb,    255 );
    analogWrite(pWindSpeed,     mWindSpeed  );

    delay(10);

}

Left: AnalogWrite(255)
Middle: DigitalWrite(HIGH)
Right: the other one that cycles

Have you tried swapping the meters/resistors?

Those analog meters may be loading (drawing enough current to cause the voltage to droop) the "analog" output.  The digital output likely has a higher drive ability.  I don't know this for sure, so I'm not putting it as an answer.

@slightlynybbled: analogWrite() on a ESP8266 performs (software) PWM on a normal digital output.

First, do something simpler, and eliminate possible causes.

Are you certain the NodeMCU's CPU is an 8bit PWM? If it were
9bits, it would read about 50% full scale, and 10bits would be about
25% of digitalWrite (which is what I think I can see on the photo).
Swap the analogue meters around, and see if the difference is consistent
with the pin, or consistent with the meters.
Use a digital multimeter (DMM) to measure voltage. It should be a
small load. So this should eliminate, or identify, the analogue
meters as a culprit.

If there is still a difference in voltage, do the NodeMCU equivalent of:
void setup() {
  pinMode(10, OUTPUT);  // a pin capable of analogOut and DigitalOut
}

void loop() {
  digitalWrite(10, HIGH);
  analogWrite(9, 255);  // a pin capable of analogOut and DigitalOut

  delay(100);
}

Then swap 9 and 10.
If the DMM shows the analogue output is consistently lower, then go back and check that PWM is 8 bits, and the device output range for PWM is the same output voltage as digitalWrite to a GPIO.

ESP8266's default PWM resolution is actually 10 bits, which would be consistent with the 25% output shown in the picture.

@IgnacioVazquez-Abrams - Ah ha! That was my main suspicion, but I haven't seen a proper data sheet for it.

Eh, the ESP8266 datasheet isn't particularly enlightening. PWM has to be done in software so you'd have to look at the core documentation instead.

@IgnacioVazquez-Abrams - thank you, that clarifies things. I thought I had read that all (most?) pins could supply PWM, but I hadn't realised it was soft. So I was looking for the wrong information.

@user3242816 - You are welcome. If it answers your question, I'd appreciate you accepting my answer. Not only do I get more points ;-), it also marks in the question list that an answer has been accepted, which may help some of the community. I don't know, but web search engines might also pick up the 'answered' flag. However, I'd hope search engines do a good job of indexing ee.se anyway. While editing this, you have. Thank you!

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


text:
How to use map function
if(pin10==HIGH)
  val=analog.read (potpin);
  val=map(val,0,1023,0,180);
  servowrite(val);
else
  val=map(0,1023,0,90);
    servo.write(val);}

That looks vaguely sensible. You'll need to find a way to write the complete code clearly in the question to get useful help I think.

The question doesn't really make sense. Best post what you have and we can try to see the problem.

https://www.tutorialspoint.com/cplusplus/cpp_if_else_statement.htm

It looks like you're using pin 10 to indicate whether sweep your servo through 180-degrees or through 90-degrees. Is that correct? Then you only need the if/else statements to select one of the two 'map()' calls. I see several problems:

Your indentation suggests you tried to select 3 statements with your 'if', but an 'if' only refers to one following statement or block of statements. If you want it to control a block of statements, you need to surround those statements with braces: '{' and '}'.
In this case, you need everything but the 'map' calls to be outside the 'if' statements.
Statements (except 'if' and 'else' by themselves) need to end with a semi-colon.

I think you meant to write:
val=analog.read (potpin);     // read the pot

if(pin10==HIGH)               // pin 10 selects servo range
  val=map(val,0,1023,0,180);  // map the pot value ...
else                          //   into one of
  val=map(0,1023,0,90);       //   the servo ranges

servowrite(val);              // drive the servo

Update:

I had try every thing , but there is some shaking and vibration when
  if condition is satisfied.

Was the shaking near rotation limits? Most servos, especially the inexpensive hobby ones, get unstable near each end of their travel. Some will move smoothly to the limit, others get shaky within a few degrees of the limit. Each one is a little bit different.
Update 2:
Here is a complete, working example based on the Arduino Servo-example and your specifications. There were two bugs above:

I left out the 'val' argument in one of the map commands. This cause a compile error and should have prevented you from testing it. It could not have run, properly or improperly.
In your code example, if(pin10==HIGH) doesn't read any input pin! It just reads some (unseen!) variable named 'pin10' - unless you did read the pin in some code you didn't show us? Which is why we ask for a minimum, complete, & verifiable example.

This code runs and rotates my sg90 servo through 90 degrees, if pin 10 is low, or 180 degrees, if pin 10 is high.

You need a (val,... in the second map function:  https://www.arduino.cc/reference/en/language/functions/math/map/  Also, maybe a val = map(val,0,1023,0,90+90*pin10) would be sufficient.

"These code r not working" - Please be specific: What were you expecting? What happened instead? What code did you use this time? Edit this into the question. "I use sg90 was there any prblm with this" - Nothing wrong with it. sg90 is an inexpensive, light-duty servo so just know that most of them will 'jitter' or shake near either end of their travel. If you keep them between 10 and 170 degrees, you should have no trouble. Or if you need the most range you can get, test each one to find its useful limits,

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


text:
Motors triggering Interrupt
I am using a 4wd robotic car to measure straight distances. I have attached two encoders on the front two wheels to measure the distance and I am using the back two wheels to adjust the car and keep it driving straight by using a compass as a reference. The Problem is that when my program is executing the section that drives the back wheels this somehow triggers the interrupt and increments the number of ticks. What is causing this issue?
volatile unsigned long enc_l = 0;
volatile unsigned long enc_r = 0;

void driveStraight(float drive_distance, int motor_power)
{
  Serial.print("\n");
  Serial.println("num_tick_l \t num_tick_r \t diff_l \t diff_r \t enc_1_prev \t enc_r_prev \t Power_l \t Power_r \t Power_a \t Power_b ");

  unsigned long num_ticks_l;
  unsigned long num_ticks_r;

  // Set initial motor power
  int power_l = motor_power;
  int power_r = motor_power;

  // Used to determine which way to turn to adjust
  unsigned long diff_l;
  unsigned long diff_r;

  // Reset encoder counts
  enc_l = 0;
  enc_r = 0;

  // Remember previous encoder counts
  unsigned long enc_l_prev = enc_l;
  unsigned long enc_r_prev = enc_r;

  // Calculate targer number of ticks
  float num_rev = (drive_distance * 10) / wheel_c;   // Convert to mm
  unsigned long target_count =  29; //num_rev * counts_per_rev;

  /*
    // Debug
    Serial.print("Driving for ");
    Serial.print(drive_distance);
    Serial.print(" cm(");
    Serial.print(target_count);
    Serial.print(" ticks) at ");
    Serial.print(motor_power);
    Serial.println(" Motor Power");
  */

  //Drive until on of the encoders reaches desired count
  while ((enc_l < target_count) && (enc_r < target_count))
  {

    bluetooth();                                // if new bluetooth value received break from loop
    if (blueToothVal == 5) {
      break;                                    // If a 'Stop' Bluetooth command is received then break from the Loop
    }

    // Sample number of encoder ticks
    num_ticks_l = enc_l;
    num_ticks_r = enc_r;

    // Sample out current number of ticks
    Serial.print(num_ticks_l);
    Serial.print("  \t\t");
    Serial.print(num_ticks_r);

    // Drive
    drive(power_l, power_r);

    // Number of ticks counted since last time
    const int StraightDriveOffset = 1;                    // Increase this or even make it a negatie number to tweak the

    diff_l = num_ticks_l - enc_l_prev;                    // + StraightDriveOffset;
    diff_r = num_ticks_r - enc_r_prev;

    Serial.print("  \t\t");
    Serial.print(diff_l);
    Serial.print(" \t \t");
    Serial.print(diff_r);

    // Store current ticks counter for next time
    enc_l_prev = num_ticks_l;
    enc_r_prev = num_ticks_r;

    Serial.print("   \t \t");
    Serial.print(enc_l_prev);
    Serial.print(" \t \t");
    Serial.print(enc_r_prev);

    // If left is faster, slow it down and speed up right
    if ( diff_l > diff_r) {
      power_l -= motor_offset;
      power_r += motor_offset;
    }

    // If right is faster, slow it down and speed up right
    if ( diff_l < diff_r) {
      power_l += motor_offset;
      power_r -= motor_offset;
    }

    // Debugging
    Serial.print(" \t\t");
    Serial.print(power_l);
    Serial.print(" \t\t");
    Serial.println(power_r);

    // Brif pause to let motors respond
    delay(20);
  }

  StopCar();
  //Buzzer();
}

void drive(int power_a, int power_b)
{
  getCompass();                                                     // Update Compass Heading
  bluetooth();                                                      // Check to see if any Bluetooth commands have been sent

  if (blueToothVal == 5) {
    break; // If a Stop Bluetooth command ('5') is received then break from the Loop
  }

  // Constrain power to between -255 and 255
  power_a = constrain(power_a, -255, 255);
  power_b = constrain(power_b, -255, 255);

  if ( abs(desired_heading - compass_heading) <= compass_dev )      // If the Desired Heading and the Compass Heading are within the compass deviation, X degrees of each other then Go Forward
    // otherwise find the shortest turn radius and turn left or right
  {
    // Left motor direction
    if ( power_a < 0)
    {
      motor2.setSpeed(abs(power_a));       // Motor is the front left wheel
      motor2.run(BACKWARD);

    }
    else
    {
      motor2.setSpeed(abs(power_a));       // Motor is the front left wheel
      motor2.run(FORWARD);

    }

    // Right Motor direction
    if ( power_b < 0)
    {
      motor4.setSpeed(abs(power_b));       // Motor is the front left wheel
      motor4.run(BACKWARD);

    }
    else
    {
      motor4.setSpeed(abs(power_b));       // Motor is the front left wheel
      motor4.run(FORWARD);

    }

  }

  else
  {
    int x = (desired_heading - 359);                          // x = the GPS desired heading - 360
    int y = (compass_heading - (x));                          // y = the Compass heading - x
    int z = (y - 360);                                        // z = y - 360

    if ((z <= 180) && (z >= 0))                               // if z is less than 180 and not a negative value then turn left
    { // otherwise turn right
      motor1.setSpeed(190);
      motor3.setSpeed(190);
      motor1.run(BACKWARD);
      motor3.run(FORWARD);
    }
    else
    {
      motor1.setSpeed(190);
      motor3.setSpeed(190);
      motor1.run(FORWARD);
      motor3.run(BACKWARD);

    }
  }
}

void countLeft()
{
  enc_l ++;
}

void countRight()
{
  enc_r ++;
}

and this is what is on the setup function
const int enc_l_pin = 18;
const int enc_r_pin = 19;

void setup()
    {
      Serial.begin(115200);                                            // Serial 0 is for communication with the computer
      Serial3.begin(9600);                                             // Serial 1 is for Bluetooth communication - DO NOT MODIFY - JY-MCU HC-06 v1.40

      Wire.begin();                                                    // Join I2C bus used for the HMC5883L compass
      compass.begin();                                                 // initialize the compass (HMC5883L)
      compass.setRange(HMC5883L_RANGE_1_3GA);                          // Set measurement range
      compass.setMeasurementMode(HMC5883L_CONTINOUS);                  // Set measurement mode
      compass.setDataRate(HMC5883L_DATARATE_30HZ);                     // Set data rate
      compass.setSamples(HMC5883L_SAMPLES_8);                          // Set number of samples averaged
      compass.setOffset(118, 473);                                      // Set calibration offset

      // Buzzer
      pinMode(Buzzer_pin, OUTPUT);

      // Set up pins
      pinMode(enc_l_pin, INPUT);
      pinMode(enc_r_pin, INPUT);

      // Set up interrupts
      attachInterrupt(digitalPinToInterrupt(enc_l_pin), countLeft, CHANGE);
      attachInterrupt(digitalPinToInterrupt(enc_r_pin), countRight, CHANGE);

I don't see any interrupt code. Please provide a complete (!) working minimal example code, that shows your problem.

Yes, sorry I just added them in

Do you have a pullup or pulldown resistor? If not, the pin will be floating.

When I try to put a pull up resistor accross the +vcc and output pin of the hall effect sensor as shown in the picture the voltage stays constant

What type of hall sensor do you use exactly?

UGN3503UA Hall Effect Sensor    https://www.jaycar.com.au/medias/sys_master/images/9168322953246/ZD1902-dataSheetMain.pdf

I think you have 2 problems:

The used Hall sensor is an analog device, not a digital one. This means it will not output either Vcc or 0V, but instead an analog (continuous) voltage depending on the magnetic field. With zero magnetic field, it will output about half the supply voltage (in this case 2.5V, since Vcc is 5V for you). For analog signals pullups or pulldowns do not make sense. Digital pins have a hysteris, which means, that they will detect a LOW between 0V and 1.67V and a HIGH between 3.33V and 5V (see this answer). This is also called a Schmitt trigger. I assume, that you just want to measure, that the magnet comes near the sensor (so only one polarity matters). This means, that the voltage will stay - let's say - above 2.5V (depending on polarity) and only going from 2.5V to 5V and back. In this condition the pin state will stay high, since it is set high, but never reaches voltage low enough for setting it to low. No interrupt will be triggered. Depending on what you want and the next problem, you can instead use a comparator (which is a special peripheral of the microcontroller) to trigger the incrementation, when a specified threshold voltage is reached (this also mean it would trigger due to small changes around the threshold), or you can buy or build an external Schmitt trigger, where you can change the threshold voltages for LOW and HIGH changes.
Motors send out quite a bunch of electromagnetic noise, which can distort analog Signals nearby. Most likely the noise from the motors is high enough to falsely trigger a state change at the pin. Maybe you should look at the analog signal with an oscilloscope, which can show you, how much noise do you really have in this situation. There are many ways to reduce noise on an analog signal. One is to add a low pass filter to cancel out the mostly higher frequency noise. This only works, if the frequency of your signal is considerably lower (so that you can trim the low pass filter to let your signal pass).

From the picture I cannot see, how the magnets and the sensors are moving in the car. Be sure to measure the different voltages in the different states (magnet near sensor, magnet for away). If the sensor is too sensitive or your magnet too strong, you might end up with an even smaller voltage range, than the 2.5V, that you already have.

Thanks for the valuable information. I will work on designing the schmitt trigger and let you know how I go.

I built a non-inverting Schmitt Trigger. The circuit diagram can be seen in the post. The issue I am having is that once I connect the output pin of the hall effect sensor to the input of the schmitt trigger the input stays 3.3V and the output reads about 4.22V.


text:
Code getting stuck waiting for GPS Output
I'm basically trying to make a device that pulls the GPS information from a SIM808 and pushes it to a server online via GPRS.
I am sorry as I am not good at programming so ive spent days trying to debug this but i have not been able to figure out whats wrong.
Ill get the basics out of the way.
Board: Mega2560 (I know its overkill but its what i had in hand)
SIM+GPS sensor: SIM808 Module  TinyGPS v13
RTC: DS1307
Arduino IDE v1.8.8
Down to the specifics,
I started with SoftwareSerial Library but i heard it was inefficient so i switched to AltSoftSerial.
The serial library is working as I do get output using AT commands.
The problem is that when i load up the stock TinyGPS example sketch sometimes it works sometimes it gives me error saying the GPS module wasn't detected.
i tried using AT commands directly or a different GPS library but i cant figure out how to pass on data to a database over GPRS.
but basically I am sure the wiring isn't faulty nor is the GPS module (i hope) as it gives an output at ATCommands, even the RTC module is confirmed working. I know the URL in the ATCommand is fake but that is for demonstration purposes.
Coming to the code below. If i change the bool newData = false; to bool newData = true; the the code works just once with wrong GPS information.
any help would be greatly appreciated. Thank You
Edit 1: The problem has been solved, it wasn't working when i used both GPS and GPRS on SIM808 i switched to NeoGPS 6m module and GPRS from SIM800/808 it worked. Thank You.
#include <AltSoftSerial.h>
#include <TinyGPS.h>

#include <Wire.h>
#include <DS1307new.h>

TinyGPS gps;

SoftwareSerial sGPS (46,48);

uint16_t startAddr = 0x0000;  //Start address to store in NVRam
uint16_t lastAddr;        //New address to store in NVRam
uint16_t TimeIsSet = 0xaa55;  //Helper that time must not be set again

int currentDay = 0;
int currentMonth = 0;
int currentYear = 0;
int currentHour = 0;
int currentMinute = 0;

float flat, flon;
float previousFLat = 0.0;
float previousFLon = 0.0;

void setup()
{

  Serial.begin(9600);
  sGPS.begin(9600);

  /*
  Control the clock.
  Clock will only be set if NV-RAM Address does not contain 0xaa.
  DS1307 should have a battery backup.
  */

  RTC.getRAM(54, (uint8_t *)&TimeIsSet, sizeof(uint16_t));
  if (TimeIsSet != 0xaa55)
  {
    RTC.stopClock();

    RTC.fillByYMD(2011,4,8);
    RTC.fillByHMS(22,7,0);

    RTC.setTime();
    TimeIsSet = 0xaa55;
    RTC.setRAM(54, (uint8_t *)&TimeIsSet, sizeof(uint16_t));
    RTC.startClock();
  }
  else
  {
    RTC.getTime();
  }

  /*
   Control Register for SQW pin which can be used as an interrupt.
*/
  RTC.ctrl = 0x00;                      // 0x00=disable SQW pin, 0x10=1Hz,
                                        // 0x11=4096Hz, 0x12=8192Hz, 0x13=32768Hz
  RTC.setCTRL();
  delay(5000);
  }

  void loop()
{
    RTC.getTime();

    currentDay = RTC.day;
    currentMonth = RTC.month;
    currentYear = RTC.year;
    currentHour = RTC.hour;
    currentMinute = RTC.minute;

  bool newData = false;

  //For one second we parse GPS data and report some key values

  for (unsigned long start = millis(); millis() - start < 1000;)

  {
  while (sGPS.available())
    {
      char c = sGPS.read();
      Serial.write(c); // uncomment this line if you want to see the GPS data flowing
      if (gps.encode(c)) // Did a new valid sentence come in?
      newData = true;
    }

  }

  if (newData)
  {
    unsigned long age;
    gps.f_get_position(&flat, &flon, &age);

    if ((flat !=previousFLat)||(flon !=previousFLon))
    {
      previousFLat = flat;
      previousFLon = flon;
      Serial.print (previousFLat,6);
      Serial.println(previousFLon,6);
      SendSQL();
    }
  }

}

  void SendSQL()
  {

    //Serial.println("Start Send");
    Serial.println("AT+SAPBR=3,1,\"Contype\",\"GPRS\"");
    delay(500);
    Serial.println("AT+SAPBR=3,1,\"APN\",\"airtelgprs.com\"");
    delay(500);
    Serial.println("AT+SAPBR=1,1");
    delay(500);
    Serial.println("AT+SAPBR=2,1");
    delay(3000);
    Serial.println("AT+HTTPINIT");
    delay(500);
    Serial.println("AT+HTTPARA=\"CID\",1");
    delay(500);
    Serial.print("AT+HTTPARA=\"URL\",\"www.google.com/add_data.php?");
    Serial.print("addDay=");

      if (currentDay <10)
        {
        Serial.print("0");
        Serial.print(currentDay);
        }

      else
        {
        Serial.print(currentDay);
        }

      Serial.print("/");

      if (currentMonth < 10)
        {
          Serial.print("0");
          Serial.print(currentMonth);
        }

      else
        {
          Serial.print(currentMonth);
        }

      Serial.print("/");
      Serial.print(currentYear);
      Serial.print("&addHour=");

      if (currentHour <10)
        {
          Serial.print("0");
          Serial.print(currentHour);
        }

        else

        {
          Serial.print(currentHour);
        }

        Serial.print(":");

        if (currentMinute <10)

        {
          Serial.print("0");
          Serial.print(currentMinute);
        }

        else

        {
          Serial.print (currentMinute);
        }

          Serial.print ("&addLati=");
          Serial.print(previousFLat, 6);
          Serial.print("&addLongti=");
          Serial.print(previousFLon, 6);
          Serial.println("\"");
          delay(3000);
          Serial.println("AT+HTTPACTION=0");
          delay(15000);
          Serial.println("AT+HTTPTERM");
          delay(500);
          Serial.println("AT+SAPBR=0,1");
          delay(500);
          Serial.println("Finish");
        }

what did you do to debug the problem? .... which parts worked? .... which parts failed?

tip: replace if (currentDay <10) block with only two lines if (currentDay <10) Serial.print("0"); and Serial.print(currentDay);  ...... do the similarly for the other if blocks

I agree with above answer use the Serial ports available and do something in your setup to probe the sim808 until you get some feedback I am using SIM868 in one of my projects and had the same problem of not getting any feedback until i set a while loop up in the setup that was probing by only sending 'AT' to the module (I did not use tinyGPS i only used Serial and sent it AT commands)
Here the application notes with the AT commands for the GPS side of SIM808
This approach will give you a better idea of what is happening and where you are going wrong

You have a Mega with 4 hardware serial ports. Use of those - Serial1, Serial2, Serial 3 - to talk to the GPS.
I did a project with a SIM808 module from DF Robotics.  I spent some time just powering the GPS part of it up and watching what came out.  Do the same with some simple serial print statements.
if (Serial1.available() >0){
Serial.print(Serial1.read());
}

Then when you understand what comes out, you can watch in setup() for the end of messages that indicate you have good GPS data, or just send AT commands until you get a good reply back. My module took I think 7-8 seconds before it would talk, so I just waited in setup() until I started getting messages. I knew what to expect from the above testing, it was always a fixed amount, so I grabbed all that, looked at the last few to make sure it was as expected, then started the GPS commands to see if it had good data from the satellites before continuing. I suspect the TinyGPS library does similar, but the SIM808 module added some extra characters, or you had to add extra characters, to identify GPS commands from the text message commands the SIM808 expected.

The problem has been solved, it wasn't working when i used both GPS and GPRS on SIM808 i switched to NeoGPS 6m module and GPRS from SIM800/808 it worked. Thank You.


text:
With what can I replace this for loop so my Arduino doesn't spit jibberish?
I have this:
for (int i = 0; i < (DELAY_SIZE - 1); i++) {
   if (check_tag_in_char(delay_chars[i], BOOK_UPLOAD_END_TAG)) {
       tag_pos = 0;
       Serial.println("Uploaded");
       is_uploading_book = false;
   }
}

where
#define DELAY_SIZE 50
const char* BOOK_UPLOAD_END_TAG = "(__BOOK_UPLOAD_END__)";
char delay_chars[DELAY_SIZE];

int check_tag_in_chars(char a, const char* TAG_STR) {
   if (a == TAG_STR[tag_pos]) { tag_pos++; } else if (a == TAG_STR[0]) { tag_pos = 1; } else { tag_pos = 0; }
   if (TAG_STR[tag_pos] == '\0') {
      return true;
   } else {
      return false;
   }
}

The for loop above with the check_tag_in_chars check seems to make my Arduino spit jibberish on Serial.write() (which you can see in the full code).
I suppose the for loop is somehow overloading the Arduino.
The Serial.write() starts normal and then turns into jibberish like that:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla est purus, ultrices in porttitor
  in, accus⸮o⸮a⸮a⸮nct⸮oto⸮ou⸮ubt⸮ue⸮tl⸮ei⸮at⸮e⸮i⸮rm⸮⸮tlu⸮or⸮tatcsu⸮om⸮lu⸮oaess⸮vi⸮pdteea⸮aestp⸮r⸮tda⸮lcp⸮ddt⸮ir⸮eo⸮oe⸮i⸮g⸮u⸮aacdeu⸮bt.Qiu⸮pdtiu⸮l
  g⸮ie⸮ur.Csveamei⸮n⸮ievtumtp⸮vi⸮d⸮eil⸮oi⸮ruiusbeu⸮rs⸮l⸮ae⸮ai⸮t,⸮⸮oe⸮om
  l⸮cdo⸮aesua⸮i⸮iin⸮⸮ab⸮e⸮vil⸮⸮u⸮u⸮an⸮fiiamssa. C⸮oi⸮tque petu⸮⸮ai⸮sptitmts⸮st⸮ril⸮u⸮tcsu⸮lie⸮t⸮nrnumuscg⸮oa⸮vu⸮vr⸮uci⸮l⸮g⸮oinm⸮msi⸮aq⸮ptb⸮tmn⸮i⸮rrn⸮oe⸮aerrdlsm.Ierbeu⸮gtslu,n⸮aisnl⸮ott
  t.C⸮oi⸮tu⸮etu⸮⸮ai⸮sptit⸮ns⸮st⸮icu⸮s⸮

Here's the full code:
#include <SoftwareSerial.h>
SoftwareSerial BTserial(2, 3); // RX, TX

void setup() {
    Serial.begin(9600);
    BTserial.begin(9600);
    Serial.println("Communication with HC-05 successfully started.");
}

const char* BOOK_UPLOAD_START_TAG = "(__BOOK_UPLOAD_START__)";
const char* BOOK_UPLOAD_END_TAG = "(__BOOK_UPLOAD_END__)";
int tag_pos = 0;
char c;
bool is_uploading_book = false;

#define DELAY_SIZE 50
char delay_chars[DELAY_SIZE];
int update_count = 0;

void loop(){
    if (BTserial.available()) {
        c = BTserial.read();
        if (is_uploading_book) {
          Serial.write(c);
          if(update_count < DELAY_SIZE) {
            delay_chars[update_count] = c;
            update_count++;
          } else {
            for (int i = 0; i < (DELAY_SIZE - 1); i++) {
                delay_chars[i] = delay_chars[i + 1];
            }
            delay_chars[DELAY_SIZE - 1] = c;
            // Checking if the end tag is in the delay_chars
            for (int i = 0; i < (DELAY_SIZE - 1); i++) {
              if (check_tag_in_chars(delay_chars[i], BOOK_UPLOAD_END_TAG)) {
                tag_pos = 0;
                Serial.println("Uploaded");
                is_uploading_book = false;
              }
            }
          }
        } else {
          if (check_tag_in_chars(c, BOOK_UPLOAD_START_TAG)) {
            tag_pos = 0;
            Serial.println("Starting");
            is_uploading_book = true;
          }
        }
    }

}

int check_tag_in_chars(char a, const char* TAG_STR) {
  if (a == TAG_STR[tag_pos])
    { tag_pos++; }
  else if (a == TAG_STR[0])
    { tag_pos = 1; }
  else
    { tag_pos = 0; }

  if (TAG_STR[tag_pos] == '\0') {
    return true;
  } else {
    return false;
  }
}

Is there something that is overloading and torturing the Arduino? Are there any alternatives to go about the problem that will not create this problem?
NEW: It turns out that as I decrease the DELAY_SIZE value, the jibberish slowly starts to look normal. Somehow that for loop tortures the Arduino (and it's not so much the for loop but the check it's done in it)
NEW NEW: I tried looping a loop and it seems that making extensive loops overloads the Arduino and it starts jibberish. Is this normal or there's something with my Arduino?
NEW NEW NEW: If my void loop() looks like this:
void loop(){
   if (BTserial.available()) {
      c = BTserial.read();
      Serial.write(c);
      for (int i = 0; i < (DELAY_SIZE - 1); i++) {
         if (check_tag_in_chars(delay_chars[i], BOOK_UPLOAD_END_TAG)) {
            tag_pos = 0;
            Serial.println("Uploaded");
            is_uploading_book = false;
         }
      }
   }
}

The problem of jibberish persists (the jibberish is less but it's still jibberish). The fact that I'm looping through the check_tag_in_chars 50 times every new character is torturing the Arduino.
I don't know what to do.

You didn't read my typo correction in your other correction.                 delay_chars[DELAY_SIZE - 1] = c; } should be } delay_chars[DELAY_SIZE - 1] = c;

@Majenko Sorry, fixed it (I got the delay_chars[DELAY_SIZE - 1] = c; out of the loop) but the problem stays. I did some debugging and the jibberish issue originates from the loop I've stated above.

@Juraj Please take a look at the full code.

I suspect that the problem is actually SoftwareSerial being a pile of rancid badger vomit.

or the BT module is on different baud rate

@Juraj How can that be? When the for loop is gone, everything works fine.

I just checked the HC-05 baud rate through AT, it's 9600.

If it helps, I has problems sending data through SoftwareSerial with the HC05 but receiving it was fine. Hardware serial never had this problem for me

"rancid badger vomit"? Is that a technical term? :)

I had a hard time trying to understand, why you use the delay_char array. I did not succeed. What is the intention of it? Why do you not check each character as it comes in from the bluetooth module? Do you need it for future uses? With the shift operation you have a good chance to create failure code. e.g. You shift only the chars until DELAY_SIZE - 2 because of the < operator (you do not use a <=- Then you write over the last character in the array. That could be problematic;-).

I would also check the charset of the text you send over bluetooth. Is it UTF 8 or a Windows charset or another non ASCII code?


text:
The sketch burned two H Bridges, need help to find out how to modify
This is Arduino RC control car, the sketch tested good in a small motor, but burned two 60A drivers when put into 24V,500W motors, need help to find out whats wrong?
#include <VirtualWire.h>

//motor A connected between A01 and A02
//motor B connected between B01 and B02

int STBY = 2; //standby  // mod: was 10 --2 ??

int count;

//Motor A
int PWMA = 9; //Speed control   // need mod: was 3 change into 9
int AIN1 = 8; //Direction  // was 9
int AIN2 = 7; //Direction

//Motor B
int PWMB = 10; //Speed control   // need mod: was 5 change into 10
int BIN1 = 5; //Direction   // was 6
int BIN2 = 4; //Direction   ///was 16 put into p7 cause of Arduino uno no p16.

const boolean FORWARD = HIGH;
const boolean REVERSE = LOW;

float speed_Max = 252; //pwm usually goes from was:0-255 ////0-255 changed into 0-252

float speed_Min = 0;
float analogInput_Max = 1023;
float analogInput_Min = 0;
float analogInput_Middle_X = 515;//ideally it would be analogInput_Max / 2
float analogInput_Middle_Y = 495;//ideally it would be analogInput_Max / 2
float deadBand = 0;
float middleMax = (analogInput_Max / 2) + deadBand;
float middleMin = (analogInput_Max / 2) - deadBand;
boolean pastDirection = FORWARD;

void setup()
{
  // Configure Timer 2 for PWM @ 14 kHz.
  TCCR2A = 0;           // undo the configuration done by...
  TCCR2B = 0;           // ...the Arduino core library
  TCNT2  = 0;           // reset timer

  TCCR2A = _BV(COM2A1)  // non-inverted PWM on ch. A
           | _BV(COM2B1)  // same on ch; B
           | _BV(WGM20);  // mode 10: ph. correct PWM, TOP = ICR1

      TCCR2B = (TCCR2B & 0b11111000) | 0x01; //3.92116 [kHz] //** use this code got 3.9khz but joystick works not too good
    {

    Serial.begin(9600);  // Debugging only
    Serial.println("setup"); //Prints "Setup" to the serial monitor

    vw_set_rx_pin(6);       //Sets pin D12 as the RX Pin
    vw_set_ptt_inverted(true); // Required for DR3100
    vw_setup(2000);      // Bits per sec
    vw_rx_start();       // Start the receiver PLL running

    pinMode(23, OUTPUT); //Relay one ////M1 added 2 was 2 -- 4
    pinMode(25, OUTPUT); //Relay two
    pinMode(27, OUTPUT); //Relay four
    pinMode(29, OUTPUT); //Relay five
    pinMode(31, OUTPUT); //Relay sex
    pinMode(33, OUTPUT); //Relay seven
    pinMode(35, OUTPUT); //Relay eight
    pinMode(37, OUTPUT); //Relay three
    pinMode(39, OUTPUT); //Relay three
    pinMode(41, OUTPUT); //Relay eight
    pinMode(43, OUTPUT); //Relay three
    pinMode(45, OUTPUT); //Relay three

    digitalWrite(23, HIGH);
    digitalWrite(25, HIGH);
    digitalWrite(27, HIGH);
    digitalWrite(29, HIGH);
    digitalWrite(31, HIGH);
    digitalWrite(33, HIGH);
    digitalWrite(35, HIGH);
    digitalWrite(37, HIGH);
    digitalWrite(39, HIGH);
    digitalWrite(41, HIGH);
    digitalWrite(43, HIGH);
    digitalWrite(45, HIGH);
     }

  pinMode(STBY, OUTPUT); //// pin: the number of the pin whose mode you wish to set; mode: INPUT, OUTPUT, or INPUT_PULLUP.

  pinMode(PWMA, OUTPUT);
  pinMode(AIN1, OUTPUT);
  pinMode(AIN2, OUTPUT);

  pinMode(PWMB, OUTPUT);
  pinMode(BIN1, OUTPUT);
  pinMode(BIN2, OUTPUT);
}

void loop() {

button(); //// disable 'button', no work. remove '//' enable, button works good
joystick(); //// disable 'joystick', no work. remove '//' enable, joystick works good, but no motor control yet

 }

void joystick() {

  uint8_t buf[VW_MAX_MESSAGE_LEN]; // This declares a variable array. instead of 7 variables buf1, buf2 etc...
  uint8_t buflen = VW_MAX_MESSAGE_LEN;
  if (vw_get_message(buf, &buflen)) // Non-blocking
  {
    int i;
    int column = 0;
    String message;
    int commands[30];
    // Message with a good checksum received, dump it.
    for (i = 0; i < buflen; i++)
    {
      //DEBUG:
      //Serial.print(char(buf[i]));

      if (char(buf[i]) == '|') {
        commands[column] = message.toInt();
        message = "";
        column++;
      } else {
        message += char(buf[i]);
      }
    }

    //one more time to capture the last value since the message does not end with |
    commands[column] = message.toInt();

    // DEBUG
    //    Serial.print("X: ");
    //    Serial.print(commands[0]);
    //    Serial.print(" Y: ");
    //    Serial.println(commands[1]);

     motorControl(commands[0], commands[1]);

  }

}

void move(int motor, int speed, boolean direction) {
  digitalWrite(STBY, HIGH); //disable standby

   if (motor == 1) {
    digitalWrite(AIN1, direction);
    digitalWrite(AIN2, !direction);
    analogWrite(PWMA, speed);
  } else {
    digitalWrite(BIN1, !direction);
    digitalWrite(BIN2, direction);
    analogWrite(PWMB, speed);
  }
}

void motorControl(float x, float y) {
  boolean currentDirection = y >= analogInput_Middle_Y;

    //map(value, fromLow, fromHigh, toLow, toHigh);
  if (currentDirection == REVERSE) {
    y = map(y, analogInput_Middle_Y, analogInput_Min, speed_Min, speed_Max) ;
  } else {
    y = map(y, analogInput_Middle_Y, analogInput_Max, speed_Min, speed_Max);
  }

  int subtractFromLeft = map(x, analogInput_Middle_X, analogInput_Min, speed_Min, y);
  int subtractFromRight = map(x, analogInput_Middle_X, analogInput_Max, speed_Min, y);

  if (subtractFromRight < 0) {
    subtractFromRight = 0;
  }

  if (subtractFromLeft < 0) {
    subtractFromLeft = 0;
  }

  int Throttle_RIGHT = y - subtractFromRight;
  int Throttle_LEFT = y - subtractFromLeft;

  boolean currentDirection_LEFT = currentDirection;
  boolean currentDirection_RIGHT = currentDirection;

  if (Throttle_LEFT < 1 && Throttle_RIGHT > 1) {
    currentDirection_LEFT = !currentDirection;
    Throttle_LEFT = Throttle_RIGHT;
  }

  if (Throttle_RIGHT < 1 && Throttle_LEFT > 1) {
    currentDirection_RIGHT = !currentDirection;
    Throttle_RIGHT = Throttle_LEFT;
  }

  move(1, Throttle_LEFT, currentDirection_LEFT);
  move(2, Throttle_RIGHT, currentDirection_RIGHT);

  }

void button()
{
  uint8_t buf[VW_MAX_MESSAGE_LEN];
  uint8_t buflen = VW_MAX_MESSAGE_LEN;
  if (vw_get_message(buf, &buflen)) // Non-blocking
  {
    int i;
    digitalWrite(13, true);  // Flash a light to show received good message
    // Message with a good checksum received, dump it.
    Serial.print("Got: ");

    for (i = 0; i < buflen; i++)
    {
      int c = (buf[i]);
      Serial.print(c);
      Serial.print(" ");
      if (c == 65 ) {
        digitalWrite(23, !digitalRead(23));  //// A--RELAY A1
      }

      if (c == 66 ) {
        digitalWrite(25, !digitalRead(25));  //// B--RELAY A2
      }

      if (c == 67 ) {
        digitalWrite(27, !digitalRead(27)); //// C--RELAY B1
      }

      if (c == 68 ) {
        digitalWrite(29, !digitalRead(29)); //// D--RELAY B2
      }
/*
      if (c == 69 ) {
        digitalWrite(37, !digitalRead(37)); //// E--
      }

      if (c == 70 ) {
        digitalWrite(39, !digitalRead(39)); //// F--
      }
*/
      if (c == 71 ) {
        digitalWrite(31, !digitalRead(31)); //// G--RELAY C1
      }

      if (c == 72 ) {
        digitalWrite(33, !digitalRead(33));  //// H -- RELAY C2
      }

      if (c == 73 ) {
        digitalWrite(43, !digitalRead(43));  //// I --
      }

       if (c == 74 ) {
        digitalWrite(35, !digitalRead(35));  //// J --
      }

       if (c == 75 ) {
        digitalWrite(37, !digitalRead(37));  //// K --
      }

      if (c == 76 ) {
        digitalWrite(39, !digitalRead(39));  //// L --
      }
      if (c == 77 ) {
        digitalWrite(41, !digitalRead(41));  //// M --
      }
      if (c == 78 ) {
        digitalWrite(35, !digitalRead(35));  //// N --
      }

    }
    count++;
    // Serial.print(count);
    Serial.println("");
    digitalWrite(13, false);
  }
}

My new driver is came, I just scare to use it, heard that DC motor will draw upto 300A at the start, what should I do to reduce the start current?

What kind of drivers?

this one: https://www.ebay.com/itm/60A-DC-Motor-Driver-Module-High-Power-motor-Speed-Control-Dual-Channel-H-bridge/122479397950?hash=item1c84574c3e:g:ZHAAAOSww9xZC0wa:rk:2:pf:0

There are lot of edits, what should I do with them?

how do you know that the sketch is the cause of the failure?

@jsotola I'm not sure, I checked online the driver was sold and used quite much, that's why I guess maybe wrong sketch resulted in the 'shoot through'?

it seems to me that your code is overly complicated for just a simple motor run test ...... for instance, what is the reason for all the relays?

It is. but the testing runs good in 12V out, it can control the two 12V motor's speed and direction. The all relays for relative to the Gamepad's button in Transmit side.

I can't resist: "Haven't you heard that you shouldn't burn bridges"

unfortunately. I guess the "Haven't you heard that you shouldn't burn bridges" saying come out after 100s burned. solution please.

As you wrote in comment you use this H bridge:
https://www.ebay.com/itm/60A-DC-Motor-Driver-Module-High-Power-motor-Speed-Control-Dual-Channel-H-bridge/122479397950
The description how to use it is clear:

But the listing doesn't say what will happen when you set state of A1,A2=1.1 to that H-bridge.
When you set value of A1,A2=1.1 to a unprotected (cheap) H-Bridge you get a direct short to ground through 2 transistors burning them instantly

Your code actually does not protect against that:
   if (motor == 1) {
    digitalWrite(AIN1, direction);
    digitalWrite(AIN2, !direction);
    analogWrite(PWMA, speed);
  } else {
    digitalWrite(BIN1, !direction);
    digitalWrite(BIN2, direction);
    analogWrite(PWMB, speed);
  }
}

If previous value of direction is 0 (A1,A2=0,1) and you want to set direction to 1 (A1,A2=1,0) when arduino runs the line digitalWrite(AIN1, direction); for few cycles you actually end up with A1,A2=1,1 and MOSFETs go bye bye.
Try setting AIN1, AIN2 (or BIN1, BIN2) to 0 before adjusting the direction
   if (motor == 1) {
    digitalWrite(AIN1, LOW);
    digitalWrite(AIN2, LOW);

    digitalWrite(AIN1, direction);
    digitalWrite(AIN2, !direction);
    analogWrite(PWMA, speed);
  } else {
    digitalWrite(BIN1, LOW);
    digitalWrite(BIN2, LOW);

    digitalWrite(BIN1, !direction);
    digitalWrite(BIN2, direction);
    analogWrite(PWMB, speed);
  }
}

This way you are guaranteed that you always have at least one 0 there.
EDIT:
You wrote that the module contains IR2103s it should protect you from the problem I described above. (But my suggested fix is not dangerous so you can use it just in case)
There is another possibility. Maybe the rapidly changing of the direction induces high voltage spikes in the motor, and that burns the circuit. Do you see any power diodes there? Look at the image I pasted above it has 4 diodes that should safely discharge those spikes. Make sure your code does not change direction every few milliseconds.

Thank you Filip Franik, you are right. I remember that burned after be tested a while. Can you help me modify the sketch to avoid this?

Or is that possible to avoid this by use the circuit below: https://www.mycontraption.com/wp-content/uploads/2013/06/Super-Simple-MOSFET-H-Bridge.png

Couldn't you repair the H-bridge by replacing the dead MOSFETs?

I guess it is possible, I checked the PCB plate was burned, the MOSFETs may be still usable, sure I can also replace new MOSFETs. I even purchased 2 pics new drivers on the way. Still I need the problem solved.  Thanks.

@laoadam If you can read the part numbers on the ICs from that driver i can check the datasheet if that's actually the case. Usually the H-bridge drivers are protected.

@  Filip Franik, the board used 8 pcs LR7843 / MOSFET 30V 161A  1 N-CH HEXFET  and  4 x IR 2103s / Half-Bridge Driver

Thank Filip Franik, I'll test it when my new order driver come.

Hi Filip Franik, The driver has 8 pcs ss32 schottky diode in the back.

This H bridge driver looks pretty well designed. Only reason for it failing would be possible rapid switches that turn motors for a moment into high voltage sources.

@Filip Franik Thank you , When checked the SOA of the MOSFET, the higher the current, the less the time, say 80A at 100us, is this means that I can use the cycle less than 100us PWM at 80A?

@Filip Franik  Hi Frank, My new driver came, and I modified the sketch. I heard that the died band may be useful here, can you help me how to sketch it here? I want to try as much as I can before hook the new drive up, Lot of thanks.


text:
Analog output gives a close range of values
I try to get a good range of values from VMA309 sound sensor.
However, when I connect it properly it gives me a range of values  +/-5 like below. The documentation says it should give numbers between 0 and 1024.
I turned the potentiometer both sides all the way and that only changed the number, but it keeps gives number in a range of 5 numbers:
An example:
626
623
624
624
624
624
623
624
624

My code:
int sensorPin = A5;
int sensorValue = 0;
void setup ()

{
  Serial.begin (9600)  ;
}

void loop()
{
  sensorValue = analogRead(sensorPin);
  delay (500);
  Serial.println (sensorValue, DEC);
}

What am I doing wrong here?
An image of the wires:
I also tried the wiring directly without a breadboard. But that gave the same results.

I used the code as given from the VMA 309 documentation.

The original maker could be velleman: https://www.velleman.eu/products/view/?id=435532 They also have a schematic: https://www.velleman.eu/downloads/29/infosheets/vma309_scheme.pdf The analog output is the signal directly from the microphone output. That is a silly circuit. When the wrong microphone is used or when the microphone is 180 degrees rotated and soldered on the board, it won't work. You are doing probably nothing wrong, but to be sure you can show the code that you use and a photo of the wiring. Have you tried blowing into the microphone?

Thanks for your reply, yes i tried that. That resulted in a range difference of about 30 at maximum. I added the code aswell as a picture of the arduino with the sensor.

I don't understand from picture if sensor is powered by 5V or 3.3V. If it's powered from 3.3V , you are wrong.

I tried 3.3 and 5V the back of the product says that both should work. At both voltages i get the same results, only different values

Give a try to exclude issue from Arduino, you run code for all analog pins (A0, A1 etc...) and check if result is the same..

Try to understand first how the ADC  module works. Test it with a simple potentiometer and learn how the values change according to the voltage divider from the potentiometer. Also, the title from your question is misleading since 'analog output' in the Arduino world refers to writing PWM values through a pin from the Arduino using the analogWrite function. In your case, the problem involves an analog signal fed to an analog 'input' pin

I have had a smimilar issue extracting the data to ardino module.
-with 5V power supply the counts were varying from 1009~1023.
-with 3.3V power supply the counts were in the range of 610~640
I connected an scope and found out the MIC module gives an AC outputput of 340mV max sitting over DC signal of 3.3(at 5V supply) and 1.7(at 3.3Vsupply).
On thing was very clear that However the MIC is giving and out put, we need to consider the analoag ref. voltage, for an ADC the input can never be higher than Vref. i.e. 2.56V.So 5V suppy is not going to work. Also if 1.1 Vref is selected the ADC  will remain saturaed alaways at 1023 and won't work.
Also consider a need to subtruct and offset of 1.7V while working with 3.3V supply.
As a summary,
1- Set Vref of Arduino ADC module to 2.56V
2- Use 3.3V supply for VMA309 sound sensor
3- Consider a DC offset of 640 counts approx and the actual voice signal will be sitting on this offset value. May need to decouple in a software code.
4- Set a VMA309 sound sensor module threshold at a reasonable point to capture the full spectrum of voice.
5- The delay(ms) in a code shall be removed to get max capture rate or Set an ADC in a free running mode to caputure at max sampling rate(15KSPS for ATmega2560).

Arduino is a lot of fun, but you better stay away from such modules.
The module is a resistor and a electret microphone. There is also a comparator for the digital output. When you have an electret microphone, and add a resistor of 4k7 or 10k, then you have the same.
The signal from the microphone is not amplified and the Arduino only gets the analog value of the audio. The module does not measure how loud the audio is.
I think Velleman makes them: www.velleman.eu/products/view/?id=435532
They are so kind to have a schematic available: vma309_scheme.pdf
Can you move on and use the Arduino for something else?
This module with this microphone is probably not going to work.
If you want to measure the sound level, then perhaps you can make a circuit yourself or buy a better module.
The "Sound Pressure" is how loud audio is.
The most used standard is called "Sound Pressure Level" or "SPL" and is measured in dB (deciBell).


text:
Arduino Driving Pump via MOSFET
I want to turn on a pump that is running 12V and draws a current of max 1.7A with my Arduino Uno.
To do this, I bought the RFP30N06LE MOSFET and followed these instructions to wire it all up.
I connected the red wire from the pump to VIN of the Arduino and plugged a 12V 2A power brick into the Arduino. However, when I put the output pin to HIGH, the pump only pumps weakly and the MOSFET gets very hot.
When I connect the pump straight to VIN and GND, it works as expected, so the Arduino is able to provide the required current. I'm thinking that there is something to the MOSFET that I am not understanding correctly. I measured VGS at 4.5V, so the MOSFET should be able to handle the current. Is there anything I am missing?
This is the wiring:

This is the (very simple) sketch I'm using to test it all:
#define PIN_PUMP_ON 7

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

void loop() {
  digitalWrite(PIN_PUMP_ON, HIGH);
  delay(1000);
}

Can you show a photo of the wiring? or a schematic. Can you show the sketch that you use. Be careful with 12v. Never power the motor via the VIN pin. Use the 12v to power the arduino board and the motor. Do you use a breadboard, that will go wrong. A breadboard can not handle the high current of the motor. The mosfet is a very nice mosfet, it should not get hot.

followed these instructions .... no you did not .... the instructions do not say to connect the motor to the Arduino Vin

I added the sketch and a wiring diagram. What is the issue with using VIN? According to the Arduino docs, it can be used to access the 12V I'm supplying with the power jack: You can supply voltage through this pin, or, if supplying voltage via the power jack, access it through this pin.

Between the barrel jack power plug and VIN is a diode. It depends on the arduino uno or clone how much current that diode can take, but 1.7 amps is too much. You also let the ground current of the motor go through the arduino board via the GND pin. I don't like that either.

I would expect the diode to release it's magic smoke within seconds of motor on.

A higher VGS voltage may reduce the RDS resistances. Try adding a pull-up to to the 12V on the Gate. The add a regular NPN transistor to allow the arduino to pull this gate voltage down to ground to turn the motor of. This transistor is needed because the arduino pins can't handle 12V. See this answer for a nice schematic

The code void loop() {
digitalWrite(PIN_PUMP_ON, HIGH);
delay(1000);
}  does not turn the pump off - the pin needs a LOW written to it after the delay to turn things off.

Vin is only rated to supply at most 1A due to the reverse polarity protection diode in series from the barrel jack to the Vin pin.  You try and draw 1.7A thru that and you may smoke it.
The Vin header is also only rated for 1A.
Connect the motor to the supply directly. The Arduino Gnd must also connect to the supply.
R2 limits Arduino IO pin current to a safe level. R1 keeps the MOSFET off while the Arduino boots up. Diode dissipates motor generated current when the MOSFET goes from On to Off. The RFP30N06LE looks to be rated for full turn on with Vgs of 5V, and Rds of 47milliohm, that part should be ok to use.
Powering the Arduino from the same source as the motor may cause issues. If you can power the Arduino from USB or a seperate battery pack and not the same 12V that powers the motor, that will probably yield better results, especially if the 12V droops at all under heavy loads from the motor. That could cause Arduino resets.

simulate this circuit – Schematic created using CircuitLab

Rewire the motor power so that it is not using any Arduino Power or GND pins.  Only connect the MOSFET gate to an Arduino pin using a suitable resistor.  The MOSFET drain needs to go directly to your power supply ground.  This way you're not cooking your Arduino.  A relay instead of the MOSFET would prevent the MOSFET resistance from reducing the power of your motor.
The 3 big pins under the Arduino's power connector (2 GND and 1 +V) can be used to power your motor, just solder directly to them for Motor +V and GND for MOSFET drain.  This bypasses the Arduino's diode.

Why do you say not to connect the ground of the arduino and the motor power supply?  I've seen other high amperage projects for Arduino that specifically suggest to do just that, e.g. powering a long string of WS2812b RGB LEDs.  Is there a criteria that is different here (like a motor) that I'm not understanding?

If you connect the ground directly to the barrel jack pins it will prevent the current from running through the Arduino PCB.

I found a reference to the situation that has me confused, see point #7 in this answer: https://arduino.stackexchange.com/a/34531/42061 about running a motor with a separate power supply but connecting the grounds of both supplies.  Maybe this should be a question of its own?

Under no circumstances should you connect the motor to VIN on the Arduino. A motor draws far too much current.
You want to have the ground on the arduino connected to the ground for the motor, but you want different positive supplies for the 2 different devices. You also need to make sure you have a properly sized protection diode wired in parallel with the motor, but pointing against the flow of current.


text:
Can I have help interperting this code? char variable somehow storing big numbers
I have this GSM module I got for my arduino project and I am trying to access the call feature, but the function makes no sense.
  boolean Adafruit_FONA::callPhone(char *number) {
  char sendbuff[35] = "ATD";
  strncpy(sendbuff+3, number, min(30, strlen(number)));
  uint8_t x = strlen(sendbuff);
  sendbuff[x] = ';';
  sendbuff[x+1] = 0;
  //Serial.println(sendbuff);

  return sendCheckReply(sendbuff, "OK");
  }

This is the function however how is char being used to display a phone number in the parameter?

This is bad code. It uses magic numbers (3, 30, and 35) instead of calculating values based on the actual sizes. The second call to strlen isn't needed; x is the sum of the length of the first string and the number of characters that were copied. Setting aside the incorrect use of strncpy that I mention in a comment below, if the input string is to long, the code truncates it and dials the truncated number! It shouldn't do that; it should return an error code. Don't try to learn programming from stuff like this. You'll pick up lots of bad habits.

It's passed as a char*. This can be derived from either a string literal (e.g. "212555121") or from a String via its c_str() method.

so if i wanted to use the function all i have to do is enter a string with the number inside?

If you want to use a fixed string then you can call it with the literal. If you have a char* with the string then you can pass it directly. If you have a String then you need to call the c_str() method. Arduino string reference

can u give an example of how i would create the char* with the string

What's wrong with how your posted code does it (other than that fiasco with strncpy(), of course)?

Keeping it simple:
char *number; a variable pointing to a character (or string of them).
char sendbuff[35]; 35 characters in a row, making a string.
The first 3 chars at locatiion sendbuff are initialised to "A", "T", & "D", then the string at "number" is copied to it (to a maximum of 30 characters, by taking the lesser of the length of "number" or 30. This is important to avoid over-running the space allocated.
This string of characters gets sent out; & a check is made for an "O" & a "K"
If you don't 'get' pointers, you need to look it up, as it's pretty central stuff.

I don't know why strncpy has become so popular as a "safe" replacement for strcpy. It isn't. If the number string is longer than 30 characters strncpy will copy the first 30 characters and stop without adding a NUL terminator. The subsequent call to strlen can then run off the end of the buffer, and if that happens, the two bytes subsequently stored will go outside the buffer.


text:
Serial data showing up weird
I have a simple sketch that prints out "Hello World" to the serial, but I'm getting a bunch of gibberish instead.
void setup() {
    Serial.begin(9600);
}

void loop() {
    Serial.println("Hello World");
    delay(1000);
}

Why isn't it printing "Hello World" like the code says?

Have you checked if initialization of serial port is proper and matches with PC serial terminal ?  The setup() should have something like Serial.begin(9600);

@Rajendra that line is in the code example I gave. Besides, I'm not actually having the problem. It's a common issue for beginners and I answered the question below.

The board and terminal are probably not using the same baud rate. Check the bottom right corner of the Arduino Serial Terminal and make sure it is set to 9600.
Serial Data
Serial communication works by sending the entire data stream one bit at a time. This is in contrast to the standard parallel port which sends one byte at a time. Both devices need to know at what speed the data is being sent. Furthermore, both devices need to be operating at the same speed. This is called the baud rate.
Baud Rate
Baud really just means pulses per second. In the context of serial communication, it means how many bits are transmitted per second. One of the most common values is 9600, but there are other common ones which are factors or multiples of 9600. It doesn't really matter, though, as long as both devices operate at the same speed.
If I'm sending you messages faster than you are getting them, you lose data. If I am sending you messages slower than you are receiving them, you get nonsense mixed in with what I sent you.
Data, Parity, Stop bits
If you look at the documentation for begin(), you'll see it can take two parameters:
Serial.begin(speed)
Serial.begin(speed, config)

Hopefully you understand speed now, it is the bits per second at which the Arduino will communicate.
The second parameter, config, lets you configure some other things about the serial data transmission. These are the Data, Parity, and Stop bits. You'll see on the page it has values like 5N1, 6N1 and SERIAL_8N1 (the default)
The first number represents how many data bits. The second character tells you what kind of parity bit there is. E for even parity, O for odd parity, or N for no parity. The third number tells you how many stop bits.
So really, with 8N1, we have 10 bits being sent for each 8 bits of "your" data. 1 start bit, 8 data bits, and 1 stop bit.
Anyway, both sides need to agree on this information as well as the speed. The Arduino Serial Terminal doesn't give you the option of changing these settings, but others do, so you'll need to be sure all of these configuration settings are the same.
More info on wiki: Asynchronous serial communication

Sachleen's answer (above) says:
The board and terminal are probably not using the same baud rate.
Check the bottom right corner of the Arduino Serial Terminal
and make sure it is set to 9600.

If this number is 9600, and you still get garbled data, check the output you obtained when uploading the code. It should read something like:
Sketch uses 2754 bytes (8%) of program storage space. Maximum is 30720 bytes.
Global variables use 195 bytes (9%) of dynamic memory, leaving 1853 bytes for local variables. Maximum is 2048 bytes.
C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM5 -b57600 -D -Uflash:w:C:\Users\Owner\AppData\Local\Temp\arduino_build_457862/LockCode.ino.hex:i

avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM5
         Using Programmer              : arduino
         Overriding Baud Rate          : 57600

This bottom line (of what I have posted) says what your device's default baudrate is. For me, I changed Serial.begin(9600); --> Serial.begin(57600); and checked that the bottom right corner of my Arduino Serial Terminal read 57600.
After I ran this, and it worked, I was able to switch back to 9600 and get non-garbled data. Arduino seems to be finicky...

I spent half an hour trying to solve that, and it was my Arduino Pro Mini that is 3.3V and I had selected 5V in the Arduino IDE (on PC).   Serial print never works like that even with same baud rate defined.
Select the correct board in the Arduino IDE.
To be clear, the correct processor (voltage/clock speed) under the Tools tab has to be selected.


text:
Can anyone explain how to use MPL sensor with Arduino MEGA?
I am trying to connect a MPL3115A2 Altitude/Pressure/Temp Sensor Breakout which I bought from Hobbytronics to my Arduino Mega. What I had in mind was (Breakout -> Arduino):
3.3V -> 3.3 V
GND -> GND
SDA -> A4
SCL -> A5
The information which I've found so far is very conflicting and I'm not sure whether or not I should be using pull-up or in-line resistors, and if so, what value?
The code which the product page links to also differs, with one stating that the Wire library is unsafe to use with a 3.3V rated sensor due to the internal pull-ups, but the other code uses the Wire library?
If anyone could advise me on how best to use this sensor without frying it, it would be much appreciated!

Product information
Code

Since the device is 3.3V and the Arduino is 5V, you will need a I2C level converter such as the TCA9517. Simply supply the Mega side with 5V and the device side with 3.3V and attach 4.7kohm pull-ups to 5V on the Mega side, and it will convert both SDA and SCL for you. You won't need pull-ups on the device side since it includes pull-ups on the board.
For I1 and I2 (push-pull outputs) you can use either normal level converters or you can use a SN74LVC2G07 along with the pull-ups found on the Mega inputs.

Thanks very much for the response, but I really would prefer to do it without another device if possible. Do you think it would be an option to do it just using resistors?

Not reliably. 3.3V is marginal for a Mega input (3.0V minimum Vih), which means that your system will be moderately susceptible to noise. And you certainly don't want to apply 5V to the device.

I just want to power the board using the USB port, since I'd like to read the live data from the COM port. What do you think of the idea of using inline resistors for SDA and SCL as per this tutorial for a slightly different breakout board? https://learn.sparkfun.com/tutorials/mpl3115a2-pressure-sensor-hookup-guide/hooking-it-up

It might work, but it will still be subjecting the device to undesired stress.

Thanks, I don't know how quickly I would be able to get hold of a converter, but I'll definitely look into it. For now I'll try with the pull-up resistor method, and perhaps if the resistance is high enough, like 10k, then this should be enough to safe-guard the sensor...

TI gets samples out fairly quickly (if they're in-stock with the distributor), and you can use point-to-point soldering until you get an adapter in.

Great, so can I just check that I understand you correctly: The converter would only be used for the SDA and SCL, and on the Arduino side there would need to be pull-up resistors on each line going to 5V? To correctly connect the converter.

For the I2C connection, yes. Don't forget the (external) pull-ups.


text:
Is there a semi-permanent way to attach wires to the Nano?
At least for prototyping, is there a semi-permanent way to attach wires to the Nano posts?

And yes, usually the Nano is hanging in free space by its wires (yes I know, quick and dirty, should be using something cleaner, even for prototypes).  So I'm hoping for the best of both worlds, sturdy "enough" to stay attached, yet possible to remove and switch around.  Having no luck finding such advice on the internet, perhaps searching for the wrong terms.
EDIT:  I neglected one important point, each wire is attached individually just like the SparkFun wires with the female header as mentioned in @TheDoctor's answer below.

Not sure exactly what you're looking for.  Dupont connector, maybe?

What about a breadboard? They're useful so the wires are a little more secure.

Don't forget about soldering. It is a time proven semipermanent to permanent way of attaching wires.

You are trying to do something in a harder and less effective manner than you could be. Yes, there are ways of doing what you want. No, it is almost certain that not using a breadboard makes sense. There may be constraints which make various solutions unsuitable but, if so, you should include them in your question.

There are jumper wires that have a female header on one end and a male header on the other. Example: https://www.sparkfun.com/products/9140

You could also attatch several wired to a strip of breakaway female headers, such as https://www.sparkfun.com/products/115

The row of female headers, shown in the second link, is the way to go, since the individual wires have a tendency to pop out every now and then, whereas the entire row is much more secure.

The entire premise behind Gravitech's design of the Arduino Nano was for it to be plugged into a breadboard. If done so, then none of the pins are left dangling. From Arduino's webpage for the Nano:

The Arduino Nano is a small, complete, and breadboard-friendly board based on the ATmega328 (Arduino Nano 3.x) or ATmega168 (Arduino Nano 2.x). It has more or less the same functionality of the Arduino Duemilanove, but in a different package. It lacks only a DC power jack, and works with a Mini-B USB cable instead of a standard one. The Nano was designed and is being produced by Gravitech.

From Gravitech's webpage for the Nano:

Arduino Nano is a surface mount breadboard embedded version with
  integrated USB. It is a smallest, complete, and breadboard friendly.
...
Nano’s got the breadboard-ability of the Boarduino and the Mini+USB
  with smaller footprint than either, so users have more breadboard
  space.

If you have a Nano in such a dangling state, then you are using the wrong sort of Arduino board for the wrong purpose.
Obviously a Nano will work just fine when loose on a surface, i.e. not plugged into a breadboard, but that is not what it was intended for, and maybe you should employ an UNO in its place.
However, if you have to use your Nano without a breadboard, then in addition to the wire wrapping, wires with female DuPont connectors, or female header strips, you could just solder wires to the holes in the nano board, if you do not already have header pins already soldered in to them.

A wire wrap tool can work well for this - the wrappings tend to be fairly secure if done right, though the wire itself can break if stressed.

Here's what I use, repeatedly, successfully. It fits the Nano headers, and gives you screw terminals for proto work.

Ooh! that's pretty.


text:
How to get string parts from string?
I have this method:
void getWeatherData() {
    String resp = "";

    Process p;
    p.begin("python2.7");
    p.addParameter("/root/weather.py");
    p.run();

    while (p.available() > 0) {
        char c = p.read();
        resp = resp + c;
    }

    Serial.print(resp);
    Serial.flush();
}

In the serial monitor, I see the string 70.7|45|1030.29|06:05|20:04|04 May 2015 22:24. The delimiter here is the pipe. Now, the parts I take a send them to methods that puts the values on the TFT screen.
However, I fail to understand how to split this long string into individual parts.
Can somebody help?
Thanks
EC

Would you like to share the platform in use?

Do you mean which Arduino? If so, it is the Yun. I've also added a tag for it.

I used to have my own String class with a member method called Chomp which did exactly what you are requiring.  The body was something similar to this untested code:
String chomp(String& pSrc, char pMatch)
{
    int matchPos = pSrc.indexOf(pMatch);    // Find the first occurrence of the separator
    if (matchPos < 0)   // Separator was not found.
    {
        String ret = pSrc;  // Return the remainder of the source string.
        pSrc = "";          // Clear the source string
        return ret;
    }

    String ret = pSrc.substring(0, matchPos - 1);   // "Chomp" the start of the string up to the separator into the return value
    pSrc.remove(0, matchPos);                       // Remove everything up to and including the separator.
    return ret;
}

Hopefully the above code should be pretty understandable and fixable if there are any errors.  Our version worked on a "this" pointer rather than passing in the source string, so we would have something like:
String sourceCoords = "12,47,292,85";
int x1 = sourceCoords.chomp(",").toInt();
int y1 = sourceCoords.chomp(",").toInt();
int x2 = sourceCoords.chomp(",").toInt();
int y2 = sourceCoords.chomp(",").toInt();

Hope this is of some use.