text:
GSM and GPS module don't work together
I am trying to create a project which involves getting latitude and longitude via GPS Module and send it via GSM Module. My problem here is that individual code is working perfectly. However, if am to initialize both together, none will work.
#include "GSM.h"//wrapper class for Sim800l library
#include "GPS.h"//wrapper class for TinyGPS library
GSM *gsm;
GPS *gps;
void setup()
{
    Serial.begin(9600); // Debugging only
    gsm = new GSM();//initializes SIM800l
    //gps = new GPS(11,10 );//initializes NEO6MV2//uncommmenting this line won't make both modules work
}
String telNum;
int i = 1;
void loop()
{
    /*
    Serial.println(gps->getLongitude(),6);
    Serial.println(gps->getLatitude(),6);
    */

    Serial.println(gsm->read(i,telNum));
    Serial.println(telNum);
     ++i;
}

sounds like you need to specify software serial pins.

also, that's not a 5v device, and your red wire goes nowhere ;)

The original libraries uses software serial. Or maybe I didn't understand you @dandavis

I got it working by initializing and  deleting the pointer to the GPS and GSM object.
Initialization and freeing of the objects are made in the loop function. I initialize the GPS, run it in a loop for sometime, destroy it and initialize the GSM and same procedure as GPS.
Though I don't know if it'll have any effects but its working perfectly
#include "GSM.h"
#include "GPS.h"
GSM *gsm;
GPS *gps;
void setup()
{
    Serial.begin(9600); // Debugging only
}

unsigned long previousMillis = 0;//could be any value depending on how quick you want it to elapse
const long interval = 100; //could be any value depending on how long you want it to run
void loop()
{
    gps = new GPS(6, 7);//initialization <SoftwareSerial::begin() function called here>
    while (previousMillis <= interval)
    {
        //GPS codes here
        ++previousMillis;
    }
    delete gps;         //destory initialized object
    previousMillis = 0; //reset value

    gsm = new GSM();    //initialization <SoftwareSerial::begin() function called here>
    while (previousMillis <= interval)
    {

        //GSM codes here
        ++previousMillis;
    }
    delete gsm;//destory initialized object

    previousMillis = 00;//reset value
}

You can use Listen function
for example:
First_softwareserial.listen();// when you need gsm serial

Second_softwareserial.listen();// when you need gps serial

but both libraries in the Question have the SoftwareSerial built in. so show how to use them the way you describe

You can't use two softwareserial devices together (or not reliably, and not without knowing exactly what you are doing).
It's not even easy using one software and one hardware serial together unless you know what you are doing.
SoftwareSerial blocks everything else from happening while it's sending or receiving, so using it for things that send unsolicited messages (as GPSs do all the time) causes havoc.
The best you can hope for is to use HardwareSerial for the GPS and SoftwareSerial for the GSM, which is call-and-response most of the time.
Better would be to use a better board that has multiple hardware serial ports.

Ok. Do you have any link that can  guide me through the hardware serial? Gooogling it just keeps bringing up libraries and no examples.


text:
Measure Water Flow in literes using Arduino Mega 2560 Board and Water Flow Sensor
I have a water flow sensor with Arduino Megs 2560 board. I am trying to conceptualize the concept to calculate amount of water getting dispensed esp. in 1,2,3,4 and 5 liters quantity.
Water flow sensor specification:
http://www.seeedstudio.com/wiki/images/b/b7/Water_flow_sensor_datasheet.pdf
I would connect the sensor input to any pin from 22-53 pin.
Suppose I connect to ping 23 so in my setup() function I would add:
attachInterrupt(23, pulseCounter, FALLING);

where pulseCounter is an interrupt function triggered on each signal generated from sensor and increments a variable
void pulseCounter()
{
  // Increment the pulse counter
  pulseCount++;
}

Now how do I calculate the flowrate and water dispensed in milliliters using this information?  How do I know the freqz of the MCU (which is required as water dispensed per pulse is different for different MCUs)?

If your sensor really gives pulses/second, the water amount per second must be constant, i.e. the water pressure must be constant, because the pipe diameter is surely constant. Otherwise there's no way to calculate the volume. I'm quite sure this is not the case, but your sensor gives a certain number of pulses per volume. Am I right? Would you share the sensor datasheet with us?

Sorry it would be pulses per volume of water,. I have updated the question accordingly

the pulse rate can be derived without knowledge of the CPU clock speed. To achieve the pulse rate from your sensor input you can do two things:

count the pulses dn within a certain (i.e. fixed) interval T of time) or
measure the time dt between two pulses.

I'll come back later on this concerning accuracy.
To measure time, you can use the function millis(). This function returns you the milliseconds since bootup as an integer upon calling it. Method 2 is rather simple to implement.

Setup three global integers a, b and c.
At the end of setup set a to current millis();
In your ISR set b to current millis();
Also in ISR: set a=b;
calculate c=b-a (i.e. your dt);

c holds your current full wave pulse length in milliseconds, which is updated every pulse. You can derive your flow then from it.
The first method uses a counter as demonstrated in your suggestion. You then need a timer outside your ISR, two variables d and e. Either you poll millis() in your main "loop()" or you install a timer interrupt, both will work here.

At the end of setup set d to current millis();
If your predefined time T is passed (by comparing d with millis(),
save your counted pulses to e=pulseCount
reset: pulseCount=0

e holds your pulse count during interval T, from which you can derive your pulse rate.
Accuracy
Method 1's accuracy increases with higher T and higher flow speeds. Therefore the update rate of your measurement is low. By changing T you can easily increase accuracy on cost of responsiveness. This is perhaps a good idea, if you have pulsating flows in your tubings, or the sensor is a bit rattling.
Method 2's accuracy increases with lower flow speeds. It is best to measure very low flow speeds. Update frequency is minimal (1/dt).
Regarding this sensor you should calibrate it yourself. It is a cheap and rugged device (I'm using it, too), but its output depends on several parameters like mounting position, fluid viscosity and so on. Make sure, there are no bubbles, foam or contaminants in your fluid systems as they garble the results effectively.
n.b.: make sure to take care of an overflow of millis().

source: Stack Exchange

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

sort: votes


text:
Self answering a Intercom and playing louldy for person to response
We have two labs - one in 1st floor and other at 2nd floor. We are connected by intercom - both the labs has one device each. The issue is that the person who sits near the intercom is busy through out day answering the intercom and reaching out to the person for whom the call is made for.
This is very tiresome and hence I wish to automate this. I have an Arduino Mega 2560 board. My plan is to make Arduino receive the call ask for the person whom the caller is reaching out and play the name loudly over speaker in all rooms of labs (to attended the phone). If the user does not turns up even after 3 repeated times of calling - disconnect the call. If the user answers the phone by picking up the receiver then turn the conversation speaker mode off until call has not ended.
I have Arduino Mega 2560 board which has 4 serial ports but I am not user what would be the circuit to make this functionality workable? What are the extra h/w required and concept of its implementation.

There are several components here, each can be pretty complex by itself; do you want to programatically voice-recognize the person's name? do you know what interface the intercom is using? POTS? do you want the Arduino to play a wave files with every name pre-recorded or do you want voice synthesis? will the person/user answer from his desk or should he reach the intercom itself?

No I do not want to recognize any user voice - it just that when intercom rings the playback should state - "Whom do you want to speak to?". The user would reply with a person name. This name has to be played on an Audio system for the person to attend the call

and the intercom is plain old telephony system or some kind of digital system? if digital, which kind?

Well its plain old telephony type

Let's try to break it down to several components:

Interfacing with POTS (Plain Old Telephony System):
There is a nice article by Joe Doll describing how to interface an Arduino and POTS. POTS involves high voltage during both idle and ringing time (48 V DC, superimposed 90 V AC) and the circuit itself is mostly analog. You can find the required parts and their values in his article, which goes down into the nasty details in a spectacular fashion. Here is the analog circuit, involving the Arduino, from his post:

Consider that there are other projects performing similar task in a different manner, like this one, and this one which specifically explains how to record sound from an old rotary phone.

Play/Record sound from Arduino Mega 2650:
There are many projects that describe how to Play or Record sound using Arduino. Most involve a SD card to store the wav files. There is also the option of an MP3 shield, that comes with a pre-built SD card slot, such as this one. They are fully documented and are easy to interface with.
Code that encapsulates the Logic:
Here you could decide how many times the Arduino should play the recorded name, and what happens if the user won't answer. The disconnection will be done utilizing the POTS interface you created in bullet #1. In addition, you should handle the logic of what happens when the user does answer. It is not clear what you mean by 'receiver', but if you plan to have a remote extension or similar, some extra work will be required.

As a side note, it might be easier to create/re-use a walkie-talkie kind of wireless communicator, accompanied by an Arduino, to signal or broadcast the names of the people called. This might not include reuse or interfacing with the current intercom device, but by thus I believe it will make development easier and faster.

Thanks for all the information and links. Can you please let me know how to use Arduino with walkies-talkie for the same functionality?

it depends on many factors; what kind of walkie talkie and if you interface it or build it yourself. There are many projects on the web. I suggest you take one as an example, study it, and open specific questions when you're stuck

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


text:
Data Loss over Serial Communication thru GSM SIM9000A Modem
I have an Arduino Megs 2560 board and using Serial 2 for communication with SIM9000A GSM Modem. I send over a HTTP get request by using appropriate AT command strings.
The GSM modem TX/RX pins are crossed with Arduino's Serial 2 port while the GSM modem card which also has DB9 pins is connected to a Hyper terminal - to see what it is receiving / rendering.
My issue is when I have to read after I get a response for my HTTP Get request.
Below is my code:
int Read(String message)
{
      char temp = '\0';
      int i=0;
      numbytes = 0;
      message= "";
      int endCnt = 0;
      debug_println("Reading Data!");
      Serial2.println("AT+HTTPREAD");
      delay(200);
      while(endCnt < 4) {
      while((Serial2.available())>0) {
          temp = Serial2.read();
          Serial.print(temp);
          switch(temp) {
            case '\r' : endCnt = 1; break;
            case '\n' : if(endCnt == 1) endCnt = 2; else endCnt = 0; break;
            case 'O'  : if(endCnt == 2) endCnt = 3; else endCnt = 0; break;
            case 'K'  : if(endCnt == 3) endCnt = 4; else endCnt = 0; break;
            default   : endCnt = 0; break;
          }
          if(endCnt == 4) break;

        }
     }
     debug_println("Read Data Ret: ");
     return i;
}

Note the Terminal shows me correctly when a HTTPREAD command is passed to GSM modem:
+HTTPACTION: 0,200,286

+HTTPREAD: 286

{"first_name":"dddddddddddddd","last_name":"dddddddddddddddd","start_date":"2000-12-31","chargeamt":"09.80","status":"ok","id":"68"}

<!-- Hosting24 Analytics Code -->

<script type="text/javascript" src="http://stats.hosting24.com/count.php"></script>

<!-- End Of Analytics Code -->

OK

But Serial port printing shows me :
Reading Data!

+HTTPREAD: 286
{"first_name":"dddddddddddddd","last_name":"ds Code -->
<script type="text/javascript" src="http://stats.hosting24.com/count.php"></script>
<!-- End Of Analytics Code -->

OK

So after reading 45-46 th character at Serial2 port I am loosing data. I have tried all ways but unable to understand why my data at serial port is lost / overwritten?
Please let me know how can I resolve this?
====UPDATE====
After struggling a lot I was able to resolve the issue.
The code "delay(200);" after Serial2.println("AT+HTTPREAD"); was causing the issue. When I reduced the time I got the response as required.

You probably shouldn't use that delay at all - it certainly isn't needed, unless your reading code is buggy.  Also note that if you are re-echoing characters, your "Serial" baud rate needs to equal or exceed that of your "Serial2" or you will start to fill up your receive buffer and possibly overflow it for longer messages.


text:
Uploading image to Google Drive with Arduino/ESP8266
I have a toucscreen tft connected to an ESP8266 the aim for which is to take a screeenshot (.bmp format) and upload to Google Drive. I have been following this tutorial.
Where I am stuck in how to proceed is the actual upload part. I have used the code in the tutorial up to line 264, and it is thereafter I don't know how to solve for. This reference project uses a function in a special library for the camera to parse it into packets and use client.write() to upload the packets. Relevant code here:
int i;
int packet_num = cameraPacketNum();
char packet[PIC_PKT_LEN] = {0};

for(i = 0; i < packet_num; i++)
{
    long packet_len = cameraGetPacket(i, packet);
    client.write((const uint8_t *)&packet[4], packet_len - 6);
    total += packet_len - 6;
}

cameraGetPacket(i, packet);
client.print(end_boundary);

I looked at the code for the function but can't figure out what it's doing and how to replicate it. This is it here:
long cameraGetPacket(unsigned int i, char* buf) {
    char cmd[] = { 0xaa, 0x0e | camera_address, 0x00, 0x00, 0x00, 0x00 };

    Serial.setTimeout(100);

    if(i < camera_packet_num) {
        cmd[4] = i & 0xff;
        cmd[5] = (i >> 8) & 0xff;

        cameraClearRxBuf();
        cameraSendCmd(cmd, 6);

        int pkt_len;

        if(i < (camera_packet_num - 1))
            pkt_len = PIC_PKT_LEN ;
        else
            pkt_len = camera_last_packet_len;

        uint16_t cnt = Serial.readBytes((char *)buf, pkt_len);

        return cnt;
    } else {
        cmd[4] = 0xf0;
        cmd[5] = 0xf0;
        cameraSendCmd(cmd, 6);
    }

    return "";
}

The Google Drive API reference states: "Add the chunk's data to the request body. Create chunks in multiples of 256 KB (256 x 1024 bytes) in size, except for the final chunk that completes the upload. Keep the chunk size as large as possible so that the upload is efficient."
How can I take an image saved to the SD on the tft and cut it into the appropriate sized chunks and use client.write() to upload it to Google Drive? This example (which received no responses) seems to have divided the image file into 1,000's to upload but I don't know if that is correct or efficient.
int Index;
for (Index = 0; Index < imageFile.length(); Index = Index+1000) {
  client.print(imageFile.substring(Index, Index+1000));
}

Another thing I am unsure about is whether I need to have the image file itself converted into Base64 or URLencoded. I have seen examples for the ESP32 CAM which do that, but I wonder if that is just the way that camera encodes images which then need to converted. The first example cited above doesn't have conversion code as it isn't an ESP32 CAM, but maybe it's happening in the background. The Google API doesn't make mention of it.
Any help would be greatly appreciated. Or any examples you can point me to that do this would be helpful too.

my StreamLib has ChunkedPrint. the library is in Library Manager. see the example

Thanks for pointing me to that. how might I might I adapt that for an image file? I've seen a few examples of chunking and uploading text, but an image file is something altogether different.

It's really not. It's a file.

what would be more helpful is offering how i can implement base64 with an image file since the examples only show a text string.

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


text:
I need help with code for my automated garbage bin compressor
Here is my problem, I'm working on an automated garbage bin compressor. When the garbage is near the sensor, the compressor mechanism will trigger. I'm using Arduino Uno as the controller, a 12v AC window motor, an L298N motor driver, a 12v AC battery, an ultrasonic sensor, and 2 led indicators. The flow chart is as follows the sensor will detect if there is garbage in the garbage bin, if there is no garbage then the motor will not spin. If there is garbage then the motor will start spinning for 20-30 seconds and after the motor stops spinning then it will stop for 5 seconds before returning to its original position. There are 2 LED indicators, the green indicator will indicate if the motor doesn't spin and the red LED will indicate if the motor is in use. So far I'm able to program the motor to spin in 1 direction without a command to stop.
const int trigpin = 11;
const int echopin = 10;
int enA = 4;
int SPEED = 250;
int motordirection1 = 3;
int motordirection2 = 2;
int duration = 0;
int distance = 0;

void setup(){
  pinMode (trigpin, OUTPUT);
  pinMode (echopin, OUTPUT);
  pinMode (enA, OUTPUT);
  pinMode (motordirection1, OUTPUT);
  pinMode (motordirection2, OUTPUT);
  pinMode (trigpin, OUTPUT);
  pinMode (echopin, INPUT);

}

void loop(){
  digitalWrite (trigpin, LOW);
  delayMicroseconds (2);
  digitalWrite (trigpin, HIGH);
  delayMicroseconds (10);
  digitalWrite (trigpin, LOW);

  duration = pulseIn (echopin, HIGH);
  distance = duration*0.034/2;

  if (distance < 1){
  digitalWrite (enA, 0);
  digitalWrite (motordirection1, LOW);
  digitalWrite (motordirection2, LOW);
  }
  else if (distance > 2 && distance <25){
  digitalWrite (enA, SPEED);
  digitalWrite (motordirection1, HIGH);
  delay (10);
  digitalWrite (motordirection2, LOW);
  delay (50);
  digitalWrite (motordirection1, LOW);
  digitalWrite (motordirection2, LOW);
  }
  else if (distance > 15){
  digitalWrite (enA, SPEED);
  digitalWrite (motordirection1, LOW);
  delay (10);
  digitalWrite (motordirection2, HIGH);
  delay (50);
  digitalWrite (motordirection1, LOW);
  digitalWrite (motordirection2, LOW);
  }
}

Here is the program that I have. I'm not sure if it's good or not.
EDIT: I made the adjustment in the code and it works but now the problem is the motor only moves in 1 direction when the sensor detects something but after it's out of range the motor doesn't spin back.

We can't do the work for you. Please try yourself and come back when you have a concrete problem, not a whole range of problems.

returning its original position ... how will you know the position?

PMF - so far im able to code 2 separate program. The first program is when the program is started the motor will start spinning until the program is shutdown. The second program is to detect using the ultrasonic sensor. Based on the problem you can see that im incompetent at programming as i only started programming in this August. So yes im not very experienced in this subject

jsotola - from the question that i posted, the motor will start spinning in whatever direction for 20-30 seconds then it will simply turn back for 20-30 seconds in the opposite direction from when it started.

@Atek, are you not aware that a motor slows down when it is doing work?

@jsotola this project is still in its testing phase, that's why i need confirmation if the code i wrote is good to use or not. Im not sure what you mean by the motor slows down, do elaborate

do you not have any experience with machines? ... what about yourself, do you move just as fast when you carry a heavy weight?

the code is irrelevant ... start with some code that runs the motor in one direction ... pauses for 1 second and repeats ... change code that runs in reverse ... ... then combine the two ... etc. etc.

@jsotola I'll try to code what you just said

You wrote:

The flow chart is as follows [...]

Rather than a flow chart, you should think of your system as a finite
state machine, and draw its state diagram.
Superficially, a state diagram may look like a flow chart, but it has
some specific properties:

Within the states represented in the diagram, the machine does nothing
but wait for some event to happen.
Events trigger transitions between states.
Whatever actions the machine may perform can only happen on state
transitions.

Here is a state diagram that may represent your system:

In this diagram, the actions are implicit (because I am lazy), but you
may want to write them down explicitly. For example, on the transition
IDLE → MOVING_FORWARD the motor should be started, and on the next
transition (MOVING_FORWARD → WAITING) it should be stopped.
Note also that this only represents my understanding of your
specifications. You will probably have to amend it in order for it to
reflect what you really want to do.
Once you have the state diagram, the next step is... to debug it! It is
essential that you do this debugging before you start to write any
line of code. At this stage I can already spot a couple of issues:

One transition is conditioned on the “compressor” reaching its home
position. This means that you will need some means to detect this
event, like an endstop.
After compressing some garbage... there is still garbage in the bin.
Then, after the transition MOVING_BACK → IDLE, garbage will be
detected, the system will immediately transition to MOVING_FORWARD,
and it will get stuck in an endless loop.

Once you are done debugging the state diagram, and only then, can
you start writing the code. I suggest you follow the steps of Majenko's
tutorial on finite state machines: translating the diagram to
code should be quite straight forward.

I'll try to understand then try to implement it

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


text:
Arduino Serial buffer
I am trying to write one code that takes data from serial
ie. 0x4E, 0x20, 0x--, 0x0D.
0x-- may be any hex in --
The user will input these hex one by one and raspi will take all of them in buffer.
Whenever 1st, 2nd and 4th data is matched, the 3rd one will be printed in serial
ie.
Serial.print(3rd); //Decimal value
else Serial.print() // may be 00

I was trying with this code:
byte buffer[4];
int cnt = 0;

void setup()
{
 Serial.begin(9600);
 Serial.println("Start");
}

void loop(void)
{

 // read max 12 bytes
 if ((cnt <= 4) && Serial.available()) buffer[cnt++] = Serial.read();

 if (cnt == 4)  // all bytes read...
 {
   // assume the arrays are the same
   boolean same = true;

   // the ans array holds the right answer
   byte ans[]={0x4E,0x20,0x01,0x0D};

   for (int i=0; (i<= 4) && same; i++) same = (buffer[i] == ans[i]);

   if (same)
   {
     Serial.println("Yes");
   } else {
     Serial.println("Enter another number");
   }
   Serial.flush();
   cnt = 0;
 }
  //Serial.print("Done");
 // do something
}

But I was not able to do it. Anyone have a suggestion?
Edit: I have tried this state machine in Arduino :
It accepts those data and according to it, it should bi color LED light. But not working properly. Not lighting up anything
//int currState;
//int reChk, data, confirm;
const int pingPin = 13;
int inPin = 12;

void setup()
{
  Serial.begin(9600);
    // initialize digital pin 13 as an output.
  pinMode(32, OUTPUT);
  pinMode(34, OUTPUT);

  digitalWrite(32, LOW);
  digitalWrite(34, LOW);
  //currState = 0;
  //reChk = 0;
  //confirm = -1;

}

void loop() // run over and over
{
  static int currState = 0, reChk = 0, confirm = -1;
  int data;
  if(reChk == 0)
  {
    //ultrasonic();
    if(Serial.available())
    data = Serial.read();
    else
    currState = 5;
  }

  switch(currState)
  {

    case 0:
    reChk = 0;
    if(data == 78)
      currState = 1;
    else
      currState = 0;
    break;

    case 1:
    reChk = 0;
    if(data == 32)
    currState = 2;
    else
    {
      currState = 0;
      reChk = 1;
    }
    break;

    case 2:
    reChk = 0;
    switch(confirm)
    {
      case -1 :
      confirm = data;
      currState = 3;
      break;
      case 0 :
            digitalWrite(32, LOW);
            digitalWrite(34, LOW);
            delay(10);
      confirm = -1;
      currState = 0;
      break;
      case 1 :
            digitalWrite(34, HIGH);
            digitalWrite(32, LOW);
            delay(10);
      confirm = -1;
      currState = 0;
      break;
      case 2 :
            digitalWrite(32, HIGH);
            digitalWrite(34, LOW);
            delay(10);
      confirm = -1;
      currState = 0;
      break;
      default :
      confirm = -1;
      reChk = 1;
      currState = 0;
    }

    case 3:
    reChk = 0;
    if(data == 20)
    {
      reChk = 1;
      currState = 2;
    }
    else
    {
      confirm = -1;
      currState = 0;
    }
    break;

    default:
    reChk = 0;
    currState = 0;
    confirm = -1;
  }
  delay(10);
}

void ultrasonic () //ultrasonic
{
      const int pingPin = 13;
      int inPin = 12;
      //raw duration in milliseconds, cm is the
      //converted amount into a distance
      long duration, cm;

      //initializing the pin states
      pinMode(pingPin, OUTPUT);
      //pinMode(greenLed, OUTPUT);
      //pinMode(redLed, OUTPUT);

      //sending the signal, starting with LOW for a clean signal
      digitalWrite(pingPin, LOW);
      delayMicroseconds(2);
      digitalWrite(pingPin, HIGH);
      delayMicroseconds(5);
      digitalWrite(pingPin, LOW);

      //setting up the input pin, and receiving the duration in
      //microseconds for the sound to bounce off the object infront
      pinMode(inPin, INPUT);
      duration = pulseIn(inPin, HIGH);

      // convert the time into a distance
      cm = microsecondsToCentimeters(duration);

      if(cm > 50)
      {
      //printing the current readings to ther serial display
      Serial.print("5");
      }
      else
      {
      Serial.print("0");
      }
      //Serial.print("cm");
      //Serial.println();

      //checking if anything is within the safezone, if not, keep
      //green LED on if safezone violated, activate red LED instead
      //if (cm > safeZone)
      //{
      //  digitalWrite(greenLed, HIGH);
      //  digitalWrite(redLed, LOW);
      //}
      //else
      //{
      //  digitalWrite(redLed, HIGH);
      //  digitalWrite(greenLed, LOW);
      //}

delay(1000);
}

long microsecondsToCentimeters(long microseconds)
{
// The speed of sound is 340 m/s or 29 microseconds per centimeter.
// The ping travels out and back, so to find the distance of the
// object we take half of the distance travelled.
   return microseconds / 29 / 2;
}

how are you typing in the values?

4E
then in next input others one by one. it may be in decimal values of those numbers too

as @Kitana said, Serial.read() takes one byte from buffer. If you enter 4E then buffer[0] = 4, buffer[1] = E and so on. Arduino isn't mind reader :))

It's rather unclear that this should have been migrated: although the target is an Arduino, the issue here is entirely generic to any serial-connected system.

actually a bit serial but also related to arduino as well


text:
esp-01 with rf receiver keeps crashing
SOLVED:
after may hours of testing i have solved the problem.
it turned out to not be a software issue. the power supply i was using did not have a flyback diode and thus caused large voltage spikes that would crash the esp. the solution was to add a diode on the inductive load to remove those voltage spikes.
I have an esp-01 running some code that checks for a rf remote signal using the rc-switch library, it is also running some blynk and ota code.
when i press one of the buttons on my rf remote the buzzer pin keeps being triggered but will not shut off, eventually the esp will crash..
the device is in a permanent location thus the reason for the ota updates and i cant easily hookup a serial monitor to see what the esp crash code is.
the troublesome code is,

    void newloop() {
      if (mySwitch.available()) {
        // int recieved = mySwitch.getReceivedValue();
        if (mySwitch.getReceivedValue() == 5099665) {
          digitalWrite(buzzer, LOW);
          delay(200);
          digitalWrite(buzzer, HIGH);
          mySwitch.resetAvailable();
        }
        else if (mySwitch.getReceivedValue() == 5099666) {
          digitalWrite(buzzer, LOW);
          delay(2000);
          digitalWrite(buzzer, HIGH);
          mySwitch.resetAvailable();
        }
      }
      // Blynk.run();
    }

the full code, with redacted passwords/keys is,
#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>
#include <ESP8266WebServer.h>

#define BLYNK_PRINT Serial
#include <RCSwitch.h>
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#define buzzer 2
char auth[] = "<blynk auth>";
RCSwitch mySwitch = RCSwitch();

const char* ssid = "HansenHome";
const char* password = "<wifi password>";
ESP8266WebServer server;

bool ready = false;
bool ota_flag = true;
uint16_t time_elapsed = 0;

void setup() {

  Serial.begin(115200);
  Serial.println("Booting");
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

  pinMode(buzzer, OUTPUT);
  digitalWrite(buzzer, HIGH);
  Blynk.begin(auth, ssid, password);
  mySwitch.enableReceive(0);

  while (WiFi.waitForConnectResult() != WL_CONNECTED) {
    Serial.println("Connection Failed! Rebooting...");
    delay(5000);
    ESP.restart();
  }

  // Hostname defaults to esp8266-[ChipID]
  ArduinoOTA.setHostname("lock");

  // No authentication by default
  ArduinoOTA.setPassword("<uploading password>");

  ArduinoOTA.onStart([]() {
    String type;
    if (ArduinoOTA.getCommand() == U_FLASH) {
      type = "sketch";
    } else { // U_SPIFFS
      type = "filesystem";
    }

    // NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end()
    Serial.println("Start updating " + type);
  });
  ArduinoOTA.onEnd([]() {
    Serial.println("\nEnd");
  });
  ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
    Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
  });
  ArduinoOTA.onError([](ota_error_t error) {
    Serial.printf("Error[%u]: ", error);
    if (error == OTA_AUTH_ERROR) {
      Serial.println("Auth Failed");
    } else if (error == OTA_BEGIN_ERROR) {
      Serial.println("Begin Failed");
    } else if (error == OTA_CONNECT_ERROR) {
      Serial.println("Connect Failed");
    } else if (error == OTA_RECEIVE_ERROR) {
      Serial.println("Receive Failed");
    } else if (error == OTA_END_ERROR) {
      Serial.println("End Failed");
    }
  });
  ArduinoOTA.begin();
  Serial.println("Ready");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  server.on("/restart",[](){
    server.send(200,"text/plain", "Restarting...");
    delay(1000);
    ESP.restart();
  });

  server.on("/setflag",[](){
    server.send(200,"text/plain", "Setting flag...");
    ota_flag = true;
    time_elapsed = 0;
  });

  server.begin();
}

void loop() {
  if(ota_flag)
  {
    uint16_t time_start = millis();
    while(time_elapsed < 10000)
    {
      ArduinoOTA.handle();
      time_elapsed = millis()-time_start;
      delay(10);
    }
    ota_flag = false;
  }
  if(ready == false) {
    ready = true;
    digitalWrite(buzzer, LOW);
    delay(20);
    digitalWrite(buzzer, HIGH);
    delay(20);
    digitalWrite(buzzer, LOW);
    delay(20);
    digitalWrite(buzzer, HIGH);
    delay(20);
    digitalWrite(buzzer, LOW);
    delay(20);
    digitalWrite(buzzer, HIGH);
    delay(20);
    digitalWrite(buzzer, LOW);
    delay(20);
    digitalWrite(buzzer, HIGH);
    ready = true;
  }
  server.handleClient();
  newloop();
}

BLYNK_WRITE(V1) {
  digitalWrite(buzzer, LOW);
  delay(200);
  digitalWrite(buzzer, HIGH);
}

void newloop() {
  if (mySwitch.available()) {
    // int recieved = mySwitch.getReceivedValue();
    if (mySwitch.getReceivedValue() == 5099665) {
      digitalWrite(buzzer, LOW);
      delay(200);
      digitalWrite(buzzer, HIGH);
      mySwitch.resetAvailable();
    }
    else if (mySwitch.getReceivedValue() == 5099666) {
      digitalWrite(buzzer, LOW);
      delay(2000);
      digitalWrite(buzzer, HIGH);
      mySwitch.resetAvailable();
    }
  }
  // Blynk.run();
}

EDIT:
so after so further testing it appears to be a power supply issue, the power supply i was using was hooked up to a large inductive load. once that load is turned off there is a huge power spike and for some reason causing the esp to crash.
the board the esp is on has 2 voltage regulators and a few input caps
i added a large cap to the main supply and a 100uf to the 3.3v rail directly on the esp. it is still crashing..

try printing a message to serial, instead of buzzer and delay code

i cant get a proper serial output.. i may be able to move it around and get a monitor hooked up to it but it will take time

i changed the power supply while testing and it has not broke yet, so it may have to do with that

I believe you are allowed to post answers to your own questions as weird as that sounds.

By which I mean via "Post Your Answer" button rather than placing it into the question.  You could, if you wanted, have you edit say "I solved this myself, see my answer below" I suppose.


text:
How to make Arduino communicate with MySQL?
I am trying to send data from my Arduino to my database but it seems that the process is not successfully beginning. Here is my code for Arduino:
#include <Process.h>
#include <Bridge.h>
int temperature;
void setup() {
  Bridge.begin();  // Initialize Bridge
}
void loop() {
  int temperature = random(0, 100);
  Process p;
  p.begin("143.248.181.36/db.php");// 143.248.181.36 address of localhost.
  p.addParameter(String(temperature));
  p.run();
  delay(5000);
}

I am using xampp and I put db.php inside the htcocs folder. Can anyone point out why it does not work?

I'm not familiar with those libraries, but a quick look gives me the impression that Bridge and Process are used together to make system calls over serial connection on the host system. Based on that..
First, looking at Arduino Process Tutorial Process.begin() should call the process that you want to call. Maybe something like this:
p.begin("curl"); // Assuming you have curl installed on your host system
p.addParameter("http://143.248.181.36/db.php?temperature=SOMEVALUE");

Second, your PHP script is broken.
/ check connection

^ That comment is missing a second slash /
You should definitely get the PHP/MySQL part working standalone before attempting to integrate Arduino in the process. I'm a bit doubtful that $argv gets populated unless you're running the script from command line. If you're making a GET HTTP request (as you would with curl) you might wanna try instead
$temperature = $_GET['temperature'];

If the above works as a workaround, you should get an entry into your MySQL table if you visit the URL below with your browser.
"http://143.248.181.36/db.php?temperature=100"

In any case, get the PHP script working first in your browser. One step at a time.


text:
Arduino: The program exited the loop early and execute setup() repeatedly
I'm working with Arduino Uno, Adafruit PN532 NFC/RFID Shield and along with other modules. I'm posting this test program because I found there's conflict with the serial output while writing code to integrate all the modules together. I tried troubleshooting by running this code. The result wasn't what I'd expected.
In Arduino, as far as I know, setup() only runs once after starting the program and then loop() will be executed repeatedly. I ran the example sketch called readMiFare provided by Adafruit alone and it was fine. This code can be found at https://github.com/adafruit/Adafruit_NFCShield_I2C/blob/master/examples/readMifare/readMifare.pde. However, when I did the following in main,
void setup()
{
  Serial.begin(115200);
  nfctestsetup();
}

void loop(void)
{
  nfctestloop();
}

the following conflict showed up. When happened was that whenever I scanned a card to the reader it executed the loop() partially and exited the loop. Even worse, it executed the setup() again and again whenever I scanned a card.

In nfctestsetup(), I just commented out    Serial.begin(115200); from readMiFare.
My hardware setup was a no brainer since I'm using I2C.

Appreciate the help.
After spending a good amount of hours on troubleshooting, I found something interesting. When I commented out all other files except NFC and main, it worked like a charm. So I suspect there could be redefinitions on the pins that the NFC shield uses on other files. I suspect the following code in the other file gave me the problem because I commented out the rest of the code in this file and ran this block of code together with NFC and main. In fact, it's the last line of code in this block that gave me the problem.
Also, I probed on the RESET pin (see the readMiFare link above). It generated a high-low-high pulse whenever I scanned a card. Is this related to the problem?
#include <SPI.h>
#include "Adafruit_BLE_UART.h"

// Connect CLK/MISO/MOSI to hardware SPI
// e.g. On UNO & compatible: CLK = 13, MISO = 12, MOSI = 11
#define ADAFRUITBLE_REQ 10
#define ADAFRUITBLE_RDY 3     // This should be an interrupt pin, on Uno thats #2 or #3
#define ADAFRUITBLE_RST 9

Adafruit_BLE_UART BTLEserial = Adafruit_BLE_UART(ADAFRUITBLE_REQ, ADAFRUITBLE_RDY, ADAFRUITBLE_RST);

Any thought is appreciated.

Sounds like you're not providing enough power and the board is brownouting.

In setup after Serial.begin put Serial.println(MSUSR,BIN); MCUSR = 0x00; This will print the reset reason:
• Bit 3 – WDRF: Watchdog System Reset Flag
• Bit 2 – BORF: Brown-out Reset Flag
• Bit 1 – EXTRF: External Reset Flag
• Bit 0 – PORF: Power-on Reset Flag

This can happen when your sketch uses too much memory - the board can no longer assign addresses so it resets leading to an endless loop. Try reducing the amount of memory you are allocating.

Adafruit support team helped me out on this. I just had to reduce the memory size used by adding wrapping the strings in the print function with F().

Please mark this question as answered in that case :)


text:
ESP12F module not working as an access point
I have an ESP12F WiFi module and I need it to work in access point mode. I burned the example code to it using Arduino IDE and it worked at first. I could connect to the WiFi provided by it using my laptop. But when I removed it from power and connected it again it was not working. I couldn't even see its hotspot in my laptop WiFi. What happened to it? Can you please help trouble shoot it?
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#ifndef APSSID
#define APSSID "ESPap"
#define APPSK  "thereisnospoon"
#endif
const char *ssid = "ESPap";
const char *password = "thereisnospoon";

ESP8266WebServer server(80);

void handleRoot() {
server.send(200, "text/html", "
You are connected
");
}

void setup() {
delay(1000);
Serial.begin(115200);
Serial.println();
Serial.print("Configuring access point...");

WiFi.softAP(ssid, password);

IPAddress myIP = WiFi.softAPIP();
Serial.print("AP IP address: ");
Serial.println(myIP);
server.on("/", handleRoot);
server.begin();
Serial.println("HTTP server started");
}

void loop() {
server.handleClient();
}

it broke and you've got all the pieces ... try adding some debugging Serial.print statements in your code ... see if/where it breaks

Post your code.

i tried. I got connected to it and again I lost connection. this happened two or three times. its getting connected, then it loses connection and again it gets connected.

wrong RF parameters. let it on so it can calibrate. if it doesn't help, clear the flash with esptool and then upload some simple STA sketch and let it for some minutes to calibrate RF

Can you please explain what are RF parameters?

RF - radio frequency


text:
Getting individual outputs from 4 load cells
This is my first time using an Arduino, and I want to connect 4 load cells to one Arduino board and then get 4 separate outputs for each load cell on a computer.
What would I need to accomplish this and how would I set it up?
Can all four load cells connect to a single Arduino?
Also, could I get it to work with these load cells in particular:
https://www.amazon.co.uk/HALJIA-Weighing-Resistance-Half-bridge-Original-Silver/dp/B0792WCGJC/
or would I have to use ones with a 4 wire output?

connect each load cell to a separate analog input .... number of analog inputs depends on the Arduino board that you have, but it is most likely six analog inputs.

Sparkfun also sells the same load cells, and has a lot of good information regarding their use: https://learn.sparkfun.com/tutorials/getting-started-with-load-cells

For this purpose there are 'simple' interface boards like the HX711 (google on HX711). A guy named Bogde has written an Arduino library to manage this board which you can find on GitHub (https://github.com/bogde/HX711). There you can also subscribe to the corresponding email group, which is rather lively and also handles similar questions as yours.
Also Sparkfun sells these sort of interface boards and has very good and extensive documentation and tutorials on the site (see comment from VE7JRO below your question).
You can manage 4 load cells with one Arduino depending on the frequency with which you want to read them. If all 4 load cells are used to weigh one platform then Sparkfun sells an interface board to combine them in one "weight sensor" making it even more simple to interface with the Arduino.

And would I be able to connect four HX711 boards to a single Arduino at once?

Yes, each HX711 board requires connection with only 2 pins of the Arduino. I advise you to read the information at the site of Sparkfun.


text:
What if Ultrasonic sensor doesn't detect object?
I am trying to write a sketch where a function will only be triggered when the ultrasound doesn't return back. Thus when the echo pin is checked after 1 second after the trigger pin was written high, it must be low. Will it be a digitalRead function?

Many people use the PulseIn function (https://www.arduino.cc/en/Reference/PulseIn). You can set a time-out in there.
When it doesn't return before the timeout, it will return a 0.
This way you can check if it's 0 (nothing) or a distance ( 0> ).

can you give me some reference on the timeout function

The timeout isn't a function. PulseIn is the function (check the reference), timeout is an argument of that function.
You can do PulseIn(echoPin, HIGH, timeout); to receive the time that pin is high. When it's longer as the set timeout, it'll return 0.

What type of Ultrasonic sensor do you have?
I'll go with HC-SR04, since I've got one of those laying around here. The other ultrasonic sensors should be working in the same way.
Before you start!
Read the datasheet. A fast search on google with: "[manufacturer][device id][device description] datasheet .pdf" will do good.
Example: http://www.micropik.com/PDF/HCSR04.pdf
The datasheet will tell you important things/values and sometimes even interfacing examples or code.
Like:

Max input voltage
Max current
Pin-out diagrams
How to interface with the device
Min/max operating temperature

Wiring up
The datasheet will tell you what to connect, to which pins.
We've got 5V, Trigger (input), Echo (output), 0V (ground).
(As per datasheet)
It's best to do the wiring before you put power on it, because you can accidently short it when moving wires around.
Interfacing
I would recommend checking some code examples before you attempt to roll your own. Or just start from an example and edit it to your specifications.
The timing diagram shows us it needs a 10uS pulse on the trigger input.
And the duration of the echo will show the distance (58 uS per cm or 148 uS per inch).
The datasheet also suggest to use over 60ms measurement cycles.
Code
Taking all that into account:
#define trigPin 13
#define echoPin 12
#define led 11
#define led2 10

const unsigned long timeout = 400*58; //Max of 400CM, adjust this to your own max.

void setup() {
  Serial.begin(115200);//Stop using 9600 as default, it's not fast.
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(led, OUTPUT);
  pinMode(led2, OUTPUT);
}

void loop() {
  unsigned long distance;//unsigned, since we don't get negative distances.
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10); //10 uS pulse.
  digitalWrite(trigPin, LOW);

  distance = round(pulseIn(echoPin, HIGH,timeout) /58);//Distance in CM's, use /148 for inches.
  if (distance == 0){//Reached timeout
    Serial.println("Out of range");
  }
  else {
    Serial.print(distance);
    Serial.println(" cm");
  }
  delay(60);//Wait 60 ms for next cycle.
}

To be honest, I'm not even slightly sure if this code is working.
I modified this code: http://www.instructables.com/id/Simple-Arduino-and-HC-SR04-Example/
So that you're actually using the timeout right, and do the timing according to the datasheet.

This is my first time working with arduino so I was having trouble grasping the format of the PulseIn function. Do we need to put some time in place of time-out or does it use the delayMicroseconds(10) value...

@Reptile1234 in my example, I added the line const unsigned long timeout = 400*58; //Max of 400CM, adjust this to your own max.  effectively storing the value of 400*58 in the variabel named timeout, and used this as an argument to the PulseIn function. You could also just put the value in the arguments of that function. The delayMicroseconds is to put the trigger pin high (wait 10uS) and then low, so the ranging will start.

What is the use of making the variable?

Not much really, it's more readable and easier to change I guess.

so what is meant by the 400cm there... I thought that timeout will have a specific amount of time.

@Reptile, the max ranging of the sensor (according to datasheet is 400cm. The time a pulse takes to Travel 400cm is 400*58, so yes, it's a time out in time. But I linked it to the distance, so it's easier configurable. You can set it to defect items at a distance lower than 50cm, or 100cm, really anything below the max. If it won't find an object, it'll just time out, which can be really usefull.

Thnx...I get it now.

@Paul Is there anyway I could translate this piece of code to Python?

@ItrysohardbutIcryharder Yes, you can look at what it functionally does and implement the same in Python. But searching for "HC-SR04 raspberry pi" will also do the trick. For example: https://tutorials-raspberrypi.com/raspberry-pi-ultrasonic-sensor-hc-sr04/


text:
How to make two wheels turn only for a particular amount of time?
I am trying to make a robot turn (dc motors are being used) back 180 degrees. So I used an l289n for it and made one wheel turn clockwise and vice-versa.
But as I wan't it to make only a 180 degrees turn, I wanted to set an amount of time for it to turn.  Is there any other way to do the same thing, if yes, please tell, if no, help me...

delay()

@CharlieHanson how do you plan on using the delay function. It occurred to me once but it will just be like the wheels will turn for an undefined period of time and then there will be a delay.

Really? turn motor 1 CW; turn motor 2 CCW; delay for some time; turn motor 1 off; turn motor 2 off.

yea maybe thats a good idea....Thnx..

Use the delay() function.
Pseudo code as follows:
1) Turn clockwise motor on;
2) Turn counterclockwise motor on;
3) delay(<time>);
4) Turn CW motor off;
5) Turn CCW motor off.

Thank you very much....I still can't believe that this simple logic didn't occur to me :P


text:
How to check if a GSM module is working or not?
I wanted to know if my GSM sim800 is working or not. A mishap occured while I was experimenting around with my GSM module and I arduino uno. The link to the module which I bought: http://www.ebay.in/itm/SIM800-Quad-Band-GSM-Module-with-SMA-Antenna-Better-than-SIM900A-or-SIM900-/301782413058?hash=item4643a22f02:g:8LsAAOSwwbdWMidW I want to know ow can I check if my module is fine?

Plug it in to something and try using it. How do you tell if your car is working? You try using it. You don't just stand next to it and say "Oi, car, are you working?"

Can I check its working without an Arduino? Because the last one I had is now dead.

I do not know, since I do not know WHAT you DO have. The GSM has a PC interface, so if your PC has a 9 pin serial port, or you have a 9-pin USB adapter (how am I supposed to know that kind of thing?) then yes, you can. If not, then no.

@Majenko It would be nice though if your car could do that ;-)

It works ON and OFF. Suddenly it works. I tried with others too they work. It does not respond to AT commands. How can we try AT commands to check.

Power it up and check the 'status' light.  If it blinks with a 1 blink per second cycle, it is attempting to connect to the network.  If it connects, it does a slow blink at 1 blink/3s, it made the network connection.
I don't know if your board does an auto-power-on, but you might need to push the power button or reset button.

Status light is ON as soon as the SIM900 starts. It do not blink and remains ON all the time. It is the Net light which then blinks and try to get the network.!


text:
Sim900 data logging through Sparkfun
I've been trying to upload data to data. Sparkfun's servers using HTTP commands, but I've hit errors every time I try.
This is my code:

#include <String.h>

void setup()
{
  Serial1.begin(9600);               // the GPRS baud rate
  Serial.begin(9600);    // the GPRS baud rate
  delay(500);
}

void loop()
{
  if (Serial.available())
    switch(Serial.read())
   {
     case 'h':
       SubmitHttpRequest();
       break;
       case 'j':
       http();
       break;
        }
  if (Serial1.available())
    Serial.write(Serial1.read());
}

///SubmitHttpRequest()
///this function is submit a http request
///attention:the time of delay is very important, it must be set enough
void SubmitHttpRequest()
{
  Serial1.println("AT+CSQ");
  delay(100);

  ShowSerialData();// this code is to show the data from gprs shield, in order to easily see the process of how the gprs shield submit a http request, and the following is for this purpose too.

  Serial1.println("AT+CGATT?");
  delay(100);

  ShowSerialData();

  Serial1.println("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"");//setting the SAPBR, the connection type is using gprs
  delay(1000);

  ShowSerialData();

  Serial1.println("AT+SAPBR=3,1,\"APN\",\"airtelgprs.com\"");//setting the APN, the second need you fill in your local apn server
  delay(4000);

  ShowSerialData();

 // Serial1.println("AT+SAPBR=1,1");//setting the SAPBR, for detail you can refer to the AT command mamual
  //delay(2000);

  ShowSerialData();

  Serial1.println("AT+HTTPINIT"); //init the HTTP request

  delay(4000);
  ShowSerialData();

  Serial1.println("AT+HTTPPARA=\"URL\",\"http://data.sparkfun.com/input/[public key]?private_key=[private key]&gas=24\"");// setting the httppara, the second parameter is the website you want to access
  delay(10);

  ShowSerialData();
  Serial1.print(" HTTP/1.1\r\n");
  delay(500);
  ShowSerialData();

  delay(1000);
  ShowSerialData();

  Serial1.println("AT+HTTPACTION=1");//submit the request
  delay(10000);//the delay is very important, the delay time is base on the return from the website, if the return datas are very large, the time required longer.

  ShowSerialData();

  Serial1.println("AT+HTTPREAD");// read the data from the website you access
  delay(300);

  ShowSerialData();

  Serial1.println("");
  delay(100);
}
void http()
{
  Serial1.println("AT+CGATT?");
  delay(300);
  ShowSerialData();
Serial1.println("AT+SAPBR=3,1,\"APN\",\"airtelgprs.com\"");//setting the APN, the second need you fill in your local apn server
  delay(1000);
  ShowSerialData();

 Serial1.println("AT+CIFSR");//get local IP adress
  delay(2000);
  ShowSerialData();

  Serial1.println("AT+CIPSPRT=0");
  delay(3000);
  ShowSerialData();

  Serial1.println("AT+CIPSTART=\"TCP\",\"http://data.sparkfun.com\",\"80\"");//start up the connection

  delay(2000);
  ShowSerialData();
  Serial.println();
  Serial1.println("AT+CIPSEND");//begin send data to remote server
  delay(4500);
  ShowSerialData();

  Serial1.print("PUT /input/[public key]?private_key=[private key]&gas=4");
  delay(10);
  ShowSerialData();

  Serial1.print(" HTTP/1.1\r\n");
  delay(500);
  ShowSerialData();

  Serial1.println("Host: http://data.sparkfun.com\r\n");
  delay(500);
  ShowSerialData();

  Serial1.print("Connection: keep-alive");  //working
  Serial1.print("\r\n");
  Serial1.print("\r\n");
  Serial1.println();
  delay(500);
  ShowSerialData();

Serial1.println((char)26);
  Serial1.write(0x1A);
  delay(500);//waitting for reply, important! the time is base on the condition of internet
  Serial1.println();
  ShowSerialData();

  Serial1.println("AT+CIPCLOSE");//close the connection
  delay(100);
  ShowSerialData();

  Serial1.println("AT+CIPSHUT=0");
  delay(100);
  ShowSerialData();

}

void ShowSerialData()
{
  while(Serial1.available()!=0)
    Serial.write(Serial1.read());
}

For the first function (httprequest) I don't get a response on the server, even though the at commands all work. The second function(http) At At+CIPSEND, I get this:
ERROR

STATE: IP STATUS

CONNECT FAIL

And I've changed the URL but no luck. I still get the same response.
I'm using an Arduino Mega and a GSM SIM900

Post the results of all the AT commands for one iteration of loop(). Is this an example provided by Sparkfun? Did you deliberately omit the public and private keys in you sketch? How are you powering the SIM900?

Heya. The remaining AT commands all returned OK. nothing else.The SIM is powered with 12v and 3A. The example was pieced together from these: http://forum.arduino.cc/index.php?topic=116867.0   http://www.seeedstudio.com/wiki/GPRS_Shield_V1.0

Use an interactive sketch instead and enter commands and HTTP requests with the serial monitor. It is possible that one of the delays wasnt long enough. I also asked if you intentionally omitted the private and public keys in your request.

Hm, alright, thanks. And Yea, I did. I use the public and private keys when I run it.

This is what i mean by an interactive sketch: http://arduino.stackexchange.com/questions/19041/read-a-string-from-serial-to-debug-the-at-commands-sent-to-my-gps-shield/19050#19050. Try the code in the answer.


text:
How to get current Date
How to get Current date, month and year. I have used RTC, NTPClient, but it didn't work. This gives default output of 1970. What can I do for fixing it.

time_t now = time(nullptr);
struct tm* newtime = localtime(&now);
String tmpNow = "";
tmpNow += String(newtime->tm_year + 1900);
tmpNow += "-";
tmpNow += String(newtime->tm_mon + 1);
tmpNow += "-";
tmpNow += String(newtime->tm_mday);
tmpNow += " ";

I don't think that the Arduino knows what date it is. To use NTPClient you need to connect Arduino to internet somehow so the date can be downloaded from NTPServer.

It is already connected to internet

Then you probably have a bug somewhere. Post your code here so we can check what's wrong. Use "code" button to format it in readable way.

From what library you get the "localtime" function? I can't find it in any of the libraries you referenced above.

An example how to use NTPClient is available at the projects github
#include <NTPClient.h>
// change next line to use with another board/shield
#include <ESP8266WiFi.h>
//#include <WiFi.h> // for WiFi shield
//#include <WiFi101.h> // for WiFi 101 shield or MKR1000
#include <WiFiUdp.h>

const char *ssid     = "<SSID>";
const char *password = "<PASSWORD>";

WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP);

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

  WiFi.begin(ssid, password);

  while ( WiFi.status() != WL_CONNECTED ) {
    delay ( 500 );
    Serial.print ( "." );
  }

  timeClient.begin();
}

void loop() {
  timeClient.update();

  Serial.println(timeClient.getFormattedTime());

  delay(1000);
}

Form what I found TimeRTC requires an external device called DS1307RTC to keep track of the time as shown in video here and with it we should be able to get the real time as seen in github example
#include <TimeLib.h>
#include <Wire.h>
#include <DS1307RTC.h>  // a basic DS1307 library that returns time as a time_t

void setup()  {
  Serial.begin(9600);
  while (!Serial) ; // wait until Arduino Serial Monitor opens
  setSyncProvider(RTC.get);   // the function to get the time from the RTC
  if(timeStatus()!= timeSet)
     Serial.println("Unable to sync with the RTC");
  else
     Serial.println("RTC has set the system time");
}

void loop()
{
  if (timeStatus() == timeSet) {
    digitalClockDisplay();
  } else {
    Serial.println("The time has not been set.  Please run the Time");
    Serial.println("TimeRTCSet example, or DS1307RTC SetTime example.");
    Serial.println();
    delay(4000);
  }
  delay(1000);
}

void digitalClockDisplay(){
  // digital clock display of the time
  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  Serial.print(" ");
  Serial.print(day());
  Serial.print(" ");
  Serial.print(month());
  Serial.print(" ");
  Serial.print(year());
  Serial.println();
}

void printDigits(int digits){
  // utility function for digital clock display: prints preceding colon and leading 0
  Serial.print(":");
  if(digits < 10)
    Serial.print('0');
  Serial.print(digits);
}

If what I understand from your code you are actually not using any RTP or NTP. You are only creating a Time object with no values and you read it default values.
Check some more examples here

using RTC it gives output like -jan 8 2013 . How to get current date and year

@ShivaniDongre Are you 100% sure that the DS1307RTC has correct date setup? It depends on it's battery to keep date updated. If at any point the battery was removed date is reset to default value, and then inserting a new battery makes it count time from January first.


text:
Mixed structure with int and string
I want to create a structure like this:
 struct commands
{
  int   cmd;
  char  descr[25];
};

commands cmds[] =
{
  {16, "Hammond Organ"},
  {17, "Percussive Organ"},
  {18, "Rock Organ"},
  { 0, "" }                   // end of list marker
};

The compiler doesn't protest, but in a simulator the values of cmds[i].descr are all zeros.
And the line
Serial.write(cmds[1].descr);

prints nothing.
Please recommend how to rewrite the code.
Thanks.
EDIT
Thanks for your answer. It helped me a lot.
There is something wrong with the simulator (Simulator for Arduino - version 1.11E Designed by Virtronics). In the meantime I received the Mega 2560 board and the code works well with the board.

What version of the IDE and avr-g++ are you using? If you enable verbose compilation, you should see the location of the avr-tools (avr-g++, avr-objdump...) and the generated elf file. Run avr-nm -Cn path_to_the_elf_file to see the memory address where cmds is stored, then avr-objdump -s -j .data path_to_the_elf_file to see its contents. Does it look as expected?

Arduino IDE 1.8.10. As I am a beginner, I don't understand the rest of your question.

My issue is now resolved by the answers of VillageTech and VE7JRO.

There must be something wrong with the simulator you're using, because your code works for me (Arduino IDE 1.8.9, OSX, Arduino Uno).
struct commands
{
  int   cmd;
  char  descr[25];
};

commands cmds[] =
{
  {16, "Hammond Organ"},
  {17, "Percussive Organ"},
  {18, "Rock Organ"},
  { 0, "" }                   // end of list marker
};

void setup(){
  Serial.begin(9600);
  Serial.write(cmds[1].descr);
}

void loop(){}

The above sketch produces no errors or warnings using my OS and IDE version.

Same here. Compiles cleanly with -Os -Wall -Wextra and works perfectly with both avr-g++ 5.4.0 (shipped with Ubuntu 19.10) and 7.3.0 (shipped with the Arduino IDE 1.8.10).

Try to use char pointer notation (char *) instead of array notation (char[]) in structure declaration:
struct commands
{
    int   cmd;
    char*  descr;
};

OR -

use struct declaration as-is, but change the array initialization like below:
commands cmds[] =
{
    {16, {"Hammond Organ"}},
    {17, {"Percussive Organ"}},
    {18, {"Rock Organ"}},
    { 0, {""}}                   // end of list marker
};

Additionally, it seems that it always should be written as:
struct commands cmds[] =
{
    // here your code
};

If you have disabled warnings in your compiler, enable them again - and try to write program the way that you will newer receive warnings.
Thanks for your answer. It helped me a lot.
There must be something wrong with the simulator (Simulator for Arduino - version 1.11E Designed by Virtronics).
In the meantime I received the Mega 2560 board and both char pointer notation (char ) and array notation (char[]) work well with the board.
The compiler (Arduino IDE v. 1.8.10) really produces warnings:
ISO C++ forbids converting a string constant to 'char' [-Wwrite-strings].
Perhaps the simulator is more meticulous than the compiler and therefore refuses to work with a code thar generates warnings.


text:
PIR sensor and sleep (interrupt) on Mega2560
So I was starting to gain some knowledge on the PIR sensor and how to let the Arduino 'sleep' while there is no movement detected by the PIR.
I found the following code somewhere and looked fairly simple. So  I thought I would give it a try and grabbed my Mega2560, a LED and a PIR sensor.
While it was seeming to work at first sight, the Arduino is doing the opposite from what I was expecting. It turns off the LED and the Arduino when there is movement, instead of turning off the Arduino when there is NO movement. As I said before, it is doing pretty much the inverse.
Probably an easy solution, but can't figure it out on my own.
The code:

#include <avr/sleep.h>

int wakePin = 2;                 // pin used for waking up
int led = 13;

void wakeUpNow() {
}

void setup() {
  pinMode(wakePin, INPUT_PULLUP);
  pinMode(led, OUTPUT);
  attachInterrupt(0, wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function wakeUpNow when pin 2 gets LOW
}

void sleepNow() {
    set_sleep_mode(SLEEP_MODE_PWR_DOWN);   // sleep mode is set here
    sleep_enable();          // enables the sleep bit in the mcucr register
    attachInterrupt(0,wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function
    digitalWrite(led,LOW);
    sleep_mode();            // here the device is actually put to sleep!!
    // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP
    sleep_disable();         // first thing after waking from sleep: disable sleep...
    detachInterrupt(0);      // disables interrupt 0 on pin 2 so the wakeUpNow code will not be executed during normal running time.
    digitalWrite(led,HIGH);
}

void loop() {
  sleepNow();     // sleep function called here
}

Thanks in advance.
EDIT
Adapted the code to the following and seems to work now. When motion is detected by the PIR it turns on the LED on pin 13; when no motion is detected, the LED is turned off.
Two questions still remain:
1) How can I be sure that the Arduino really sleeps now?
2) When the Arduino just entered sleep, it takes a couple of seconds (+/- 6s) before it can pick up another motion. Can I get a faster detection or another 'sleep' or 'powersave' method that lets the Arduino react faster to motion?
#include <avr/sleep.h>

const int wakePin = 2;                 // pin used for waking up
const int led = 13;

int wakeVal = 0;
int wakeState = LOW;

void wakeUpNow() {

}

void setup() {
  Serial.begin(9600);
  pinMode(wakePin, INPUT_PULLUP);
  pinMode(led, OUTPUT);
  //attachInterrupt(0, sleepNow, LOW); // use interrupt 0 (pin 2) and run function wakeUpNow when pin 2 gets LOW
}

void sleepNow() {
    set_sleep_mode(SLEEP_MODE_PWR_DOWN);   // sleep mode is set here
    sleep_enable();          // enables the sleep bit in the mcucr register
    attachInterrupt(0,wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function
    sleep_mode();            // here the device is actually put to sleep!!
}

void disSleep(){
  // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP
    sleep_disable();         // first thing after waking from sleep: disable sleep...
    detachInterrupt(0);      // disables interrupt 0 on pin 2 so the wakeUpNow code will not be executed during normal running time.
}

void loop() {
  wakeVal = digitalRead(wakePin);
  if (wakeVal == HIGH){

    disSleep();

    digitalWrite(led,HIGH);
    delay(1000);

    if (wakeState == LOW){
      Serial.println("Motion detected");
      wakeState = HIGH;
    }
  }
  else{
    digitalWrite(led,LOW);
    delay(1000);

    if (wakeState == HIGH){
      Serial.println("Motion stopped - Going to Sleep Mode !");
      wakeState = LOW;
      delay(1000);

      sleepNow();     // sleep function called here
    }
  }
}

Are you assuming that your sensor gives a low output when it detects movement? Perhaps it's the other way around?

@uint128_t is right. Most PIR sensors go HIGH when they detect movement.

attachInterrupt(0,wakeUpNow, HIGH); maybe?

Yes I know movement = high & no movement should be low. I tried attachInterrupt(0,wakeUpNow,HIGH) already. Doesn't seem to resolve it.

This is a problem with the Arduino Mega board. On the Mega, D2 is not INT0 as it is on the Uno. It's INT4. There's a footnote in the spec sheet that says only level interrupt is supported. That means you can't use RISING, FALLING or CHANGE. Your only choice is to use LOW. So the Arduino will be woken up when the motion turns OFF, not on. That's why it's backward. If you use an Uno instead of a Mega, you can use RISING and it will work as you think it should.


text:
Arduino Leonardo based h keyboard
I just want to configure my laptops keyboard buttons a,s,d,f,g,h and j. I wrote this code and it works for only a but I couldn't configure other buttons.
Code is:

#include "Keyboard.h"

const int buttonPin = 3;          // input pin for pushbutton
int previousButtonState = HIGH;   // for checking the state of a pushButton
int counter = 0;                  // button push counter

void setup() {
  // make the pushButton pin an input:
  pinMode(buttonPin, INPUT);
  // initialize control over the keyboard:
  Keyboard.begin();
  Keyboard.press('a');
}

void loop() {
  // read the pushbutton:
  int buttonState = digitalRead(buttonPin);
  // if the button state has changed,
  if ((buttonState != previousButtonState)
      // and it's currently pressed:
      && (buttonState == HIGH)) {
    // increment the button counter
    counter++;
    // type out a message
    Keyboard.print("a");
  }
  // save the current button state for comparison next time:
  previousButtonState = buttonState;
}

How can I configure other buttons s,d,f,g,h and j to pin buttons 4,5,6,7,8 and 9.
Thanks for help:)

You could basically duplicate your code and variables to handle each button, or you could do things with an array or even an object-oriented approach.  6 buttons is about at the point where duplication is unsophisticated, but still practical if it best fits your understanding.  Also you might want to get rid of what looks like a dummy/test 'a' in the setup.


text:
Generating and reading a PWM signal at the same time on Arduino Uno R3?
The code below should generate a PWM signal on digital pin 3. But know I want to see if it is even working. I was thinking about a Event triggering method like ISR. But somehow it does not work. I guess a ISR needs to a Input Pin, e.g. it would work, when I would've a PWM signal coming from somewhere.
Is it even possible to generate a PWM signal and read it to see some results on the serial monitor?
edited code:
byte const PWM_PIN = 3;

volatile unsigned long pwm_value = 0;
volatile unsigned long prev_time = 0;

void setup() {
  pinMode(PWM_PIN, OUTPUT);
  Serial.begin(9600);
  attachInterrupt(digitalPinToInterrupt(PWM_PIN), rising, RISING);
}

void loop() {
  digitalWrite(PWM_PIN, HIGH);
  delay(400);
  digitalWrite(PWM_PIN, LOW);
  delay(1600);
}

void rising() {
  attachInterrupt(digitalPinToInterrupt(PWM_PIN), falling, FALLING);
  prev_time = millis();
}

void falling() {
  attachInterrupt(digitalPinToInterrupt(PWM_PIN), rising, RISING);
  pwm_value = millis()-prev_time;
  Serial.println(pwm_value);
}

wire the pin to other pin and read the other pin. what you generate is not PWM. you don't attach any interrupt in setup. use CHANGE interrupt

If a digitalWrite is not working for an output pin, then you should not use that arduino board anymore. You create a extra code that can have bugs to test something very simple, it is therefor more likely that the extra code is wrong. It is allowed to do a digitalRead for an output pin, you can therefor make the pin high, and read if it is really high. But please don't do that. If that fails, then something else is very wrong. When you assign a value to a variable (for example int i = 3 ;), how do you know that does work? Do you want to add extra tests to check if the variables do work?

With your current code the delays are so long, that you  can see the code working by connecting a LED to the output pin. An on time of 400ms is well noticable by eye. Though I wouldn't call this slow signal PWM.

@Juraj Yes right. I tried to do it without Serial.println(); in loop() and I also added attachInterrupt to setup(). I set both delays to 1000 (which should be in ms). But the pwm_value is only 16984, which are micro seconds. ---> 16,9ms

But that makes no sense, the right pwm_value should be 1000000 us right?

And connecting pwm pin to another pin, which is used as interrupted pin doesn't make any difference.

You can use approach from this video: https://www.youtube.com/watch?v=p-kCPR42EtU

You are declaring the variables prev_time and pwm_value as int, which has (on a standard Arduino) 16 bits. Since you use the signed variant, you get a range of values from -32768 to 32767. But micros() is returning an unsigned long, which has 4 bytes (32 bits) and is not signed. With int there are only 32.767 ms (since it represents microseconds here), without letting the variable overflow. Even the full range would give you only about 65 ms. It simply cannot hold a value like 1000000. If you assign this value to an int, it will directly overflow (which - I think - would give you the value modulo 2^16), effectively loosing big parts of the information. You cannot get meaningful results with this in such a high time scale.
When measuring time (with millis() or micros()) you should always be sure to use unsigned long as type to prevent these problems.

Apart from the variable type, why do you use micros() here? You are measuring times in the hundreds of milliseconds, so why not use millis()? This would keep the values lower.

Yes! It works now. I've edited the code above. So you can attach an interrupt to both input and output. Through @leoc7 I probably even found an easier way to create a PWM signal with: https://playground.arduino.cc/code/timer1

If it works now, please consider to accept the answer as correct.

You aren’t generating a correct PWM, because Serial.println introduces a delay. The right way for generating PWM is to use analogWrite function.
You can’t use attachInterrupt function for detecting rising and falling edge of an output pin.
In order to detect the rising and falling edge of a PWM signal, you have to use the timer interrupt of PWM module. For doing this, You have to write/read directly ATmega registers without using Arduino libraries. What version of Arduino are you using?

there is a delay(1200) and you nitpick the Serial println()? 3. what?

I mean Timer Overflow Interrupt

is incorrect. You can.

@leoc7 Arduino 1.8.8

@Gamdschiee Sorry, I meant what model of Arduino

@leoc7 Elegoo Uno R3

@Gamdschiee Take a look to this guide for detecting rising edge using timer 1 overflow interrupt https://playground.arduino.cc/code/timer1


text:
Why does a delay make my stepper stop? And why does the break command raise an error?
I am using a stepper motor for a project that I want it to stop. I tried for loops, while, and an if statement. All of these were placed inside the void loop, because it raised an error.
My code with the if loop:
//This program does about 1 rotation or 4100 steps. The program should be able to stop the stepper motor after it does one rotation.
int Pin1 = 8;
int Pin2 = 9;
int Pin3 = 10;
int Pin4 = 11;
int _step = 0;
int _on = 4100;
int _switches = 0;
boolean direct = false;
void setup() {
  pinMode (Pin1, OUTPUT);
  pinMode (Pin2, OUTPUT);
  pinMode (Pin3, OUTPUT);
  pinMode (Pin4, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  if (_on > 0) {
    switch(_step)
    {
      case 0:
        digitalWrite (Pin1, LOW);
        digitalWrite (Pin2, LOW);
        digitalWrite (Pin3, LOW);
        digitalWrite (Pin4, HIGH);
      break;
      case 1:
        digitalWrite (Pin1, LOW);
        digitalWrite (Pin2, LOW);
        digitalWrite (Pin3, HIGH);
        digitalWrite (Pin4, HIGH);
      break;
      case 2:
        digitalWrite (Pin1, LOW);
        digitalWrite (Pin2, LOW);
        digitalWrite (Pin3, HIGH);
        digitalWrite (Pin4, LOW);
      break;
      case 3:
        digitalWrite (Pin1, LOW);
        digitalWrite (Pin2, HIGH);
        digitalWrite (Pin3, HIGH);
        digitalWrite (Pin4, LOW);
      break;
      case 4:
        digitalWrite (Pin1, LOW);
        digitalWrite (Pin2, HIGH);
        digitalWrite (Pin3, LOW);
        digitalWrite (Pin4, LOW);
      break;
      case 5:
        digitalWrite (Pin1, HIGH);
        digitalWrite (Pin2, HIGH);
        digitalWrite (Pin3, LOW);
        digitalWrite (Pin4, LOW);
      break;
      case 6:
        digitalWrite (Pin1, HIGH);
        digitalWrite (Pin2, LOW);
        digitalWrite (Pin3, LOW);
        digitalWrite (Pin4, LOW);
      break;
      case 7:
        digitalWrite (Pin1, HIGH);
        digitalWrite (Pin2, LOW);
        digitalWrite (Pin3, LOW);
        digitalWrite (Pin4, HIGH);
      break;
      case 8:
        digitalWrite (Pin1, LOW);
        digitalWrite (Pin2, LOW);
        digitalWrite (Pin3, LOW);
        digitalWrite (Pin4, LOW);
      break;
    }

    if(direct == false) {
      _step++;
      _switches++;
      direct = false;
    }else{
      _step--;
      _switches--;
      direct = true;
    }

    Serial.println(_switches);

    if(_step>7) {
      _step=0;
    }

    if(_step<0) {
      _step=7;
    }
    _on--;
    delay(1); // This solves it.
  }
  break; //This raises an error when used with for loop.
}

Can anyone help on why the delay makes it stop? And why the break command raises and error?
Arduino UNO. 5 wire stepper.

I'm not sure if print statements can keep up the speed, but you can try it (print out the relevant variables, so you can see where it is going wrong), for this you can temporarily comment out the digitalWrites. Also a tip, to give your variables a good name (like _on, I would expect it is a boolean).

@michel keijzers. I have fixed it, the delay at the end fixes it for some reason. I don’t know why though.

Ok good to hear :-)

... why the break command raises and error?

Because you are using it wrong! break will end a loop, and is used in the switch...case statements. Read the documentation for break if you need to know more

I have fixed it, the delay at the end fixes it for some reason. I don’t know why though.

You haven't really fixed it if you don't know why. It seems that you are trying to directly control a 5 wire stepper, i assume your pins must drive a transistor or something as the arduino pins themselves will not work.
The reason it works is because the stepper takes time to energize and move, if you don't wait long enough it won't work, your serial.print must be long enough, as the delay(1) should produce a 1ms delay which is too short.
You are driving your stepper wrong, you have the code setup for a half-step control, but you have 9 states, state 8 in not needed.
you are duplicating effort you don't need with both _steps and _switches, they always have the same value.
you can do better on your code as well:
int dir = 1
int c = 0

// in loop
c += dir

if (c > max)
{
  dir *= -1
  c = max
}

if (c < min)
{
  dir *= -1
  c = min
}

With this you don't have to check the direction to modify your variables.

Just for clarity, the stepper doesn't stop because it needs a delay to calculate what to do next? Also, the break should break the main loop void loop(). And, lastly, this is my first time using Arduino and C. I don't know how to work with the code as well as many of you guys.

@12944qwerty void loop() is a function, you return from functions, you break from loops; naming a function loop doesn't make it a loop; its called loop() because the main Arduino library calls loop() in a loop!

@12944qwerty the stepper motor needs a delay to PHYSICALLY move; it takes time for the coils to energize and build up a magnetic field, then the motor will move to the next step.

In simple terms: break() literally breaks out of the immediate loop it is in. Since you were in no loop [void loop() is not your usual loop functions, it's just Arduino-for keep repeating whatever is inside infinitely. You could use a for/while loop in setup() for how many ever times you want it to run and then use break().] delay(time in ms), as the name says just pauses the Arduino like a brainfart for how much ever time you put as the parameter. You could check out this link in the future for information of inbuilt functions and other language-related doubts.


text:
Sim800 sim card requirements
What kind of a sim card is required for sim800 module? I know it must be activated and must be valid. But about 2g, 3g or LTE...What kind of a sim card in overall should I use with this module?

the question is: whether it will work with 4G or not?

What kind of a sim card is required for sim800 module?

The SIM interface complies with the GSM Phase 1 specification and the new GSM Phase 2+ specification for FAST 64 kbps SIM card. Both 1.8V and 3.0V SIM card
are supported. The SIM interface is powered from an internal regulator in the module.
For more details see here and here. And remember "Google is your friend".
Cheers!

so if I were to go to a store to look for a sim card for a project related to sim800, I would ask for a 1.8V or 3.0V sim that complies with GSM phase 1 or 2+ specification right?

oh only 2g sim...and micro sim won't work

Actually I think it works like this; the SIM card gives a set of numbers to identify the unit when connecting to the network. The SIM800 can only connect with GSM (2G) so the SIM card must be for a vendor (service provider) that supports that.

So what kind of a sim should I ask the seller for?

You are still missing some info to be able to answer that. What size is the SIM card holder? You will have to ask for a 2G (GSM) SIM with the right size. Check other restrictions such as security (PIN) etc in the SIM800 documentation. It is all a question of reading.

a doubt: will 3g sim work?

The SIM800 can only connect to a 2G (GSM) radio network. The SIM card is not specifically GSM, 3G etc. It is the radio network service provider that must support GSM. They may call the SIM card 3G but the radio network may be a combination of technologies for provide coverage. You will have to stress that you need 2G (GSM) coverage.

I wanted to know that a regular sim or a micro/nano sim is required for this module:http://www.ebay.in/itm/SIM800-Quad-Band-GSM-Module-with-SMA-Antenna-Better-than-SIM900A-or-SIM900-/301782413058?hash=item4643a22f02:g:8LsAAOSwwbdWMidW

The SIM card holder is under the shield; http://i.ebayimg.com/00/s/MTYwMFgxMzQ4/z/4KYAAOSw5VFWMidx/$_58.JPG Looks like a mini? https://en.wikipedia.org/wiki/Subscriber_identity_module


text:
Problem while writing sketch for GSM module sim800
I wanted to my GSM to recieve SMSs. I have written a sketch for it. But while verifying the sketch an error pops out in this part:
if (sms.available()) {
      sms.remoteNumber(senderNnumber, 20);
      if (senderNumber == "09432167015") {
        c = sms.read();
      if (c == "yes") {
          alarm_police();
          }
        }
      }
The error message:

Arduino: 1.6.5 (Windows 8.1), Board: "Arduino/Genuino Uno"
GuardDog_v2.5.ino: In function 'void loop()':
  GuardDog_v2.5:201: error: 'senderNnumber' was not declared in this scope
  GuardDog_v2.5:204: error: ISO C++ forbids comparison between pointer and >integer [-fpermissive]
  'senderNnumber' was not declared in this scope
This report would have more information with
   "Show verbose output during compilation"
   enabled in File > Preferences.

I have checked the receiving sms example and have written the sketch according to the example.I need help regarding this error and how to fix it

You have a scope problem and you are comparing a pointer to an integer. Show us the rest of your sketch and provide a link to the library u're using

The sketch is a bit too big and contains parts which are not related to GSM. Should I show the complete sketch? BTW the library I used is the default GSM library which is present in the IDE.

You misspelled the variable senderNumber. Correct it. Also you aren't reading the SMS properly or comparing the phone numbers properly. Your code should be like this (using the examples):
#define MAX_MSG 50

char senderNumber[20];
char sms_buf[MAX_MSG];   // a buffer for your sms, max len = 50

if (sms.available()) {    // this part should be in loop()
  sms.remoteNumber(senderNumber, 20);
  if (strcmp(senderNumber, "09432167015") == 0) { // compare numbers
    while (sms.available() == 0);   // wait for a char
    char i = 0;
    while (i < MAX_MSG - 1){    // till max len is reached; 1 byte for null
      c = sms.read();
      if (c == '\0')  // assuming the modem terminates sms with null
        break;
      sms_buf[i++] = c;   // write char to the buffer
      while (sms.available() == 0);   //wait for a char
    }
    sms_buf[i] = 0;   // terminate the string, just in case
    if (strstr(sms_buf, "yes") != NULL)  // look for 'yes' in buffer
      alarm_police();
  }
}

is MAX_MSG an int

It can be a char or int; just edited it

during the upload an error for char sms_buf[MAX_MSG]; pops up: array bound is not an integer constant before ']' token.

Change MAX_MSG to int and try again

I had used int for MAX_MSG it doesn't work for both char and int

Oh, i remember now....use #define MAX_MSG 50

@Reptile1234 Array bounds have to be integer constants. So the previous declaration didnt work (unless u make it 'const int').


text:
Details on OV7670
I am thinking of working on a project based on a camera module OV7670. I am making a security system using an arduino where detected motion (I am also using a PIR sensor) will trigger the camera module. I wanted to get all kinds of information needed to work with the camera module in this kind of project.

I am not expecting a very long answer rearding everything about the module. The most important points and maybe a few references would be enough. It would also be helpful if programming reference for the camera module is also provided.

This post is a link to a blog that describes the pinout and connections, along with some general information. They also have a link to an "ArduCAM" library with an example utilizing your camera model.


text:
Functions of GSM
I am currently working on an arduino project and wanted to use a GSM module. This is my first time working with a GSM module. So I had a few queries.

What can a GSM module sim900a do with arduino programming?
Also can it do the following:

Send sms when motion is detected by a PIR sensor
Send sms to only a particular group of cell phones.
Respond to a particular kind of sms

Send sms when motion is detected by a PIR sensor

Yes, write a function that does this. Basic support functions in libraries will help you send the sms and detect the PIR. You need to provide the logic.

Send sms to only a particular group of cell phones.

If the question is if the GSM module supports group send the answer is no. You will have to write a function that sends the SMS to each number in the group.

Respond to a particular kind of sms

Yes, again but now you have to write a function that parses incoming messages and does some actions (just as any input parse).
The answer to all these questions is no if the function is already available in libraries. The answer is maybe if someone has already done something similar.

None of those things you ask are a function of the SIM900A GSM module.
The SIM900A GSM module is capable of sending and receiving text messages (SMS). What you do with those text messages, and what text messages you send to where is entirely down to your Arduino program.
What you are asking is like "Can this car drive from Manchester to Carlisle?" The car can be driven from place to place, but it's you that does the driving. So you should be asking "I have a car. Am I capable of driving it from Manchester to Carlisle?"
So yes, the SIM900A GSM module is capable of being used to achieve those three things you ask, but the real question is not can the SIM900A do them, but can you program the Arduino to get a SIM900A to do them? And the answer is "Yes, it is perfectly possible if you know how", and we can help you to know how when you start working on the project and come across some stumbling blocks in your programming.


text:
Sensor for very low temperature (liquid nitrogen)
I'm looking for a way to measure temperatures in range of 40 to -200 °C (100 to −320 °F). The usual solution DS18B20 works only down to -55 °C (-67 °F).
Any ideas?
p.s.
Precision of 2 °C would be good enough.

You probably want a K-type thermocouple (the most common type).
They have a range of around -200°C to +1350°C (depending on probe).
Alternatively a Resistive Temperature Device (RTD) can be used, since these have a typical range of around -240°C to 650°C with higher accuracy.
This might be of help to you: http://digital.ni.com/public.nsf/allkb/C50FA55B3B2F85D9862572D00083350E

I found on adafruits this board: Thermocouple Amplifier MAX31855 breakout board (https://www.adafruit.com/products/269) so for fast solution I'll try to built something around this board. In long term PT100 is a better solution.

I did a search on "cryogenic temperature sensors" and found these from Lake Shore Cyrotronics – the price is shocking. It appears that you can use silicon diodes as cryogenic temperature sensors, so you might be able to use less expensive parts if you don't need a ton of accuracy.


text:
How Atmel Studio 7 compile Arduino code?
Atmel stated in their website:

Atmel Studio 7 features seamless one-click import of projects created in the Arduino development environment. Your sketch, including any libraries it references, will be imported into Studio 7 as a C++ project. Once imported, you can leverage the full capabilities of Studio 7 to fine-tune and debug your design. Atmel Studio 7 fully supports the powerful embedded debugger on the Arduino Zero board. For other Arduino boards, shield-adapters that expose debug connectors are available, or switch to one of the many available Xplained-Mini/PRO boards to fully leverage the Atmel HW eco-system. Regardless of what you choose, you will surely make something amazing.

I wonder how they do it? Is it just a plug-in meaning that we still have to install Arduino software? Or do they have their own compiler and debugger?

I'm not sure, but best way to find out is just by trying? It appears you can easily import arduino project. I wonder how much they leave intact, or change to a more C++ like project.

The difference between code for the Arduino IDE and C++ is really just a few conveniences - adding #includes, function prototypes, setting up compile options etc. No reason this couldn't be done without requiring the Arduino software be installed. But, as @Paul suggests, why don't you just try it and see?

I tried and it ask the Arduino IDE path. I wonder why should I install Arduino IDE.

It is almost always the case that a high-level environment like an IDE provides an interface to an existing tool-chain rather than being truly an all-in-one mega-application, which would a maintenance nightmare. Atmel Studio 7 is no exception, and according to Atmel, uses and includes (quite likely by downloading it during the install process) the GCC tool-chain.

Why Atmel Studio asked about Arduino IDE path when I try to import Arduino sketch?

Probably for the Arduino libraries, which are contained within the Arduino IDE executable.

Why Atmel Studio asked about Arduino IDE path when I try to import Arduino sketch?

http://youtu.be/7WnOe00dVu0

Atmel Studio allows for the arduino .ino file to actually be compiled as a c++ project. Doing so allows true debugging, and stepping through all arduino code. It was actually insightful as it walked me through ARDUINO's main() function, which is normally tucked away nicely in a library never to be seen.
The IDE allows for highly useful features such as refactoring, find and replace, syntax highlighting and much more. I found it very useful, and a pleasant upgrade from the arduino IDE.
I often switch back and forth between the Arduino IDE and Atmel Studio, very easy to do.
Installing the Arduino software allows Atmel Studio to locate the libraries when it is installed.
By installing the Vmicro(visual Micro) toolbar, things really come together, and seem very seamless.


text:
Where can I get a high-quality ADC (audio digitizer) for Arduino?
Is there a high-quality (32 bit/96,000 kbps) digitizer for Arduino?
Does anybody know where I can find the best options for this?

32 bit ADCs are unlikely to exist.  Even at 24 bits on a multilayer PCB designed by an experienced professional the lower bits will only have meaning in a statistical sense as an input to certain types of filtering.  You are unlikely to be able to use even 16 bits to full advantage in an arduino project, so there's no point in looking beyond that.

You are going to need a bigger board.
(96000000 samples/second) * (32 bits / sample) ~= 3 Gigabits/second
A poor little Arduino Uno only runs at 20MHz and can process 8 bits bytes at a time, so even if it could somehow read and store a byte every cycle, it would still be orders of magnitude too slow for your purposes.
While I guess is might be possible to build a shield with an ultra high speed ADC and on board memory to directly store the captures samples to, you probably would bother making it since the Arduino would struggle to do anything useful with the captured data even after the fact.
The highest quality audio recording shield for Arduino I've seen is a modified Wav Shield that can record 8-bit mono files at 44,100 samples per second using the waverp library.

think 96000kps was most likely a typo. 96ksps or 96000sps is more likely since the title specifies audio. Still a little too much for an Arduino though. You need a chip with I2S and a CODEC chip.
I am working on a project at the moment interfacing a PIC32 to a CODEC for CD quality audio reproduction. The codec I am using (PCM1774) is DAC only, but you can get CODECs in many combinations of ADC and DAC with different numbers of channels in each.
I2S is very similar to SPI but needs some extra facilities that not all chips can provide. Things like:

High speed flexible base clock at (for example) 256x the sample frequency
Left/Right framing clock derived from base clock
DMA for smooth transfer of data

I don't know what offerings Atmel have, but for PIC32 you need one of the more modern chips, such as the PIC32MX1xx/2xx family, PIC32MX470, or for high end work the 200MHz PIC32MZ chips.
The MX1xx/2xx and MZ chips are available in a Arduino-like system called chipKIT which might suit your needs better than small Atmel chips.
The Arduino Due might also be able to do I2C but I won't be able to help you with that since I have relegated my Due to the bittom of my junk pile.


text:
Arduino Uno - why doesn't memory leak crash the program?
I wrote this test program:
void loop()
{
    digitalWrite(13,1);
    delay(300);
    digitalWrite(13,0);
    delay(300);
    void *a = malloc(10000000000000000000000000000000000000000);
}

Curiously, the LED keeps blinking and so it means the loops continues.
My question is how can it continue when it runs out of heap memory like that?

You do realize that your code never checks to see if malloc() actually succeeded, right?

you are right.. it probably failed on the first call.

10000000000000000000000000000000000000000 doesn't fit in a 16-bit integer. I wouldn't be surprised if the compiler doesn't know what to do with such a large value, and just replaces it with a zero. Try it with more reasonable value.

malloc() by itself generally doesn't crash a program.  It attempts to allocate the requested amount of memory, and if it can it will.  If it can't (there isn't enough memory available) then it won't allocate anything and will just return NULL.
By trying to allocate more memory than you have it will just fail every time and no memory will be allocated - thus you don't actually have a memory leak, so your program doesn't fail.
The main reason for crashing is a phenomenon called stack smashing where the memory area used by malloc() (known as the heap) and the memory area for the stack (used by local variables and for storing the contents of registers during function calls) collide with one another and one corrupts the other.  For instance, if the return address of the current function in the stack is corrupted, when the function finishes it will return to the wrong memory location and who knows what may happen then?  Wrong instructions will be executed for sure.
For instance, try this program out instead:
void setup() {
    Serial.begin(9600);
}

void loop() {
    char *a = (char *)malloc(10);
    if (a != NULL) {
        Serial.println("Allocated 10 bytes");
    } else {
        Serial.println("Allocation failed");
    }
}

If all goes well you should see lots of "Allocated 10 bytes" followed by some "Allocation failed".  Since the memory is now full there is a chance that it may now crash as the stack and heap collide - in which case you would expect to see the "Allocation failed" messages stop.

The allocator has a "heap safety margin" of around 128 bytes so the crash is unlikely in this case.

Allocating memory doesn't really do much to it except for (typically) writing some bookkeeping information into its header - a portion the caller doesn't (isn't supposed to...) see. In particular, that bit of memory doesn't become unavailable for anything (other than further allocation).
Malloc maintains a buffer between the stack pointer location and the heap, from which it will not allocate. This tends to ( <--- note "weasel words") prevent a heap vs. stack collision
If the stack grows down into memory that was already allocated, the stack will over-write the data in some allocated block. It is impossible to say what effect that will have on further program operation without knowing a whole lot more about the program, and quite possibly, about the contents and timing of any data that has yet to be received.
If the heap grows upward into the stack, and program writes into that allocated block, it will be over-writing parts of it's own stack with, again, unpredictable (without a lot more information) results.
A simple test program that merely allocates lots of small blocks will have a good chance of running forever, or at least until the malloc() call returns a NULL pointer when it is out of memory to allocate. At that point, if the test program is checking for the NULL return, there is a good chance the program can print its message and end normally. But if the program blindly writes into the memory malloc() returns, and writes through the eventual NULL pointer, then low-memory will get corrupted. Low memory is typically the location of the interrupt vector table (and the Arduinos' AVR processors are no exception), some interrupt is likely to get vectored to somewhere other than its proper service routine, and abnormal program operation will result; most likely, a crash.

Writing to SRAM at address NULL (0x0000) on AVR actually does something interesting. It does not corrupt interrupt vector table. That is in the program memory (PROGMEM). http://www.avr-tutorials.com/general/avr-memory-map

Right - Harvard bites von Neumann again!  :-) Thanks for the catch.