text:
MG2639 CELL AND GPS LIBRARIES
I'm using a MG2639 Cell Module with the SMS and GPS functionality.
I have a sketch that sends through SMS the location of the arduino UNO.
This is my code:
#include <SoftwareSerial.h> //to communicate with mg2639 cell module.
#include <SFE_MG2639_CellShield.h> //basic librarie of the module.
#include <AltSoftSerial.h>   //to communicate with the GPS module
#include <TinyGPS++.h>    //to acquire the NMEA codes.

TinyGPSPlus gps;

AltSoftSerial ALTS(9, 8);
char celprim[11]="4423337388";
uint8_t GPStatus=0;
long temp=0;

 void configurado()
{
  sms.start(celprim);
  sms.print("Transmitiendo GPS Tracking....");
  sms.send();
  delay (6000);
}

     void GPSTracking()
{
   do
      {
        if (ALTS.available()>0)
          if (gps.encode(ALTS.read()))
      {
        if (gps.date.isValid() && gps.location.isValid() && gps.time.isValid()){
          sms.start(celprim);
          sms.print("Fecha/Hora/Ubicacion: ");
          sms.print(gps.date.day());
          sms.print("-");
          sms.print (gps.date.month());
          sms.print("-");
          sms.print(gps.date.year());
          sms.print(" ");
          if ((gps.time.hour()-5) < 10) sms.print("0");
          sms.print(gps.time.hour()-5);
          sms.print(":");
          if (gps.time.minute() < 10) sms.print("0");
          sms.print(gps.time.minute());
          sms.print(":");
          if (gps.time.second() < 10) sms.print("0");
          sms.print(gps.time.second());
    sms.print("https://www.google.com.mx/maps/dir/19.4161748,-99.1664011/");
          sms.print(gps.location.lat(), 6);
          sms.print(",");
          sms.print(gps.location.lng(), 6);
          sms.print("/@");
          sms.print(gps.location.lat(), 6);
          sms.print(",");
          sms.print(gps.location.lng(), 6);
          sms.print(",19z");
          sms.send();
          GPStatus=1;
        }
    }
      if ((millis()-temp) > 30000 && GPStatus==0)
      {
        GPStatus=1;
        sms.start(celprim);
        sms.print("Imposible ubicar equipo, intente mas tarde...");
        sms.send();
      }
    }while (GPStatus ==0);
}

void setup()
{
  delay (5000);
  int beginStatus = cell.begin();
  if (beginStatus <= 0)
  {
     while(1)
      ;
  }
  delay (10000);
  sms.setMode(SMS_TEXT_MODE);   //Se pone al modulo en modo de recepción y envio de sms
  ALTS.begin(115200); // Or whatever rate the GPS uses
  configurado();
}

void loop()
{
  if (GPStatus==0)
  {
    temp = millis();
    GPSTracking();
  }
}

Is it possible to use only AltSoftSerial to create 2 serial ports and communicate with both cell and GPS in order to reduce program storage and global variables space? If it's possible, what changes should do in the MG2639 library to make it work?
Or what could i do to reduce space.

Is it possible to use only AltSoftSerial to create 2 serial ports and communicate with both cell and GPS in order to reduce program storage and global variables space?

The question is a little vague.
AltSoftSerial only works on pins 8 & 9, so I thought you were asking if you could connect both the cell and the GPS to pins 8 & 9 (using jumper pads on the back of the board), and use one AltSoftSerial instance to talk to both devices.  If it were possible, this would save RAM (just one instance) and program space (you wouldn't need two link in another software serial class, like SoftwareSerial).  However, this is not possible.  Serial connections are always point-to-point.  Although two "things" can listen to one RX line, the TX line cannot be shared by two devices.
If you were asking if you can have two instances of AltSoftSerial on two separate pairs of pins (e.g., 2/3 and 8/9), the answer is again "No", because... AltSoftSerial only works on pins 8 & 9.  Also, the SparkFun library only uses SoftwareSerial to talk to the cell.

what could i do to reduce space.

Use NeoGPS instead, and use the F macro around double-quoted strings that you print:
    sms.print( F("Imposible ubicar equipo, intente mas tarde...") );

That will save several hundred bytes of RAM.
Also, you may be sending multiple SMS's per second.  It depends on what sentences the GPS emits.  As it is, your sketch will send one SMS per sentence (i.e., one for each encode).  Even if you don't use NeoGPS, look at the example program NMEAloc.ino et al for the correct program structure.  The Troubleshooting section also contains some tips.

Huh? It sounds like the original poster already knows that serial connections are point-to-point. Also, he's using the MG2639 Cellular Shield, which connects the "cell module" to Arduino pins 2 and 3; and the "GPS module" to pins 8 and 9, so I don't know why you brought up "shared by 2 devices".

@DavidCary, do you think he means two instances of AltSoftSerial?  I thought he meant one instance shared by two devices.  This board has jumper pads on the back that allow you to connect the devices to other pins.  And because they default to being on two separate ports (2/3 and 8/9), I thought he wanted to wire them both to 8/9, the only port that AltSoftSerial supports.  I'll clarify.

Ok, didn't know AltSoftSerial can only be used at 8/9 pins. What I intend with this project is send an SMS to the MG2639 asking its location, so only in that moment it will acquire a valid GPS fix and reply it with a SMS. So i dont need to be listening the GPS port all the time.       My first sketch was using the hardware serial (0/1 pins) but i didnt get a valid fix, thats why i end up using AltSoft. Meanwhile i'll try to use NeoGPS but i'm not very skilled so it looks a little complex

Yes, NeoGPS is definitely more complex under-the-hood, but I've recently simplified the examples and improved the docs.  BTW, using pins 0/1 for the GPS would be the most efficient and reliable, but I'm not sure what steps need to be taken on the UNO.  The UNO's USB-to-Serial converter is also attached to 0/1.  Three things (UNO, converter & GPS) cannot share pins 0/1.  There might be a way keep the converter from interfering with UNO-GPS comms: disconnect the USB cable? Scratch out a trace?  Regardless, AltSoftSerial is a good alternative, and that's why they connected the GPS to 8/9.

@slash-dev, yes, I think he means two instances of AltSoftSerial or two instances of SoftwareSerial, kind of like how "How to utilize multiple software serial in libraries in Arduino?" uses several instances of SoftwareSerial for the Arduino to communicate to three other devices.

@slash-dev, Meanshile F macro is working great, in the basic sketch it reduced it from 66% of dynamic memory to 57%. I took it to my final program and from 92% reduce it to 69%, leaving behind the instability problems. Next step the NeoGPS library. Thanks for your help.


text:
Arduino Uno - ESP 8266: sending AT commands via Code
I bought a ESP 8266 & I am able to send AT commands and receive response via serial monitor when I upload a empty sketch. I changed the baud rate from 115200 to 9600 by using AT+CIOBAUD=9600 and am able to run AT commands at 9600 baud rate.
Empty Sketch:
void setup()
{

}
void loop()
{

}

Here is how my circuit looks:

Problem
The problem is when I create a custom sketch to run AT commands it doesn't work. Here is how my sketch looks:
#include <SoftwareSerial.h>
SoftwareSerial esp8266(0,1); //RX,TX

void setup()
{

  Serial.begin(9600);
  esp8266.begin(9600);

  Serial.println("Run AT Command");

   esp8266.print("AT\r\n");

}

void loop(){
   String response = "";
   while(esp8266.available())     {
        char c = esp8266.read();
        response+=c;
        Serial.print(c);
      }

      if(response != ""){
        Serial.println(response);
      }

}

ESP8266 is receiving 3.3V but I have read TX and RX sends 5V, and they also need to be 3.3V. Don't know if thats what is causing it, but I am able to run AT commands on empty sketch, so this is a bit weird.

UPDATE:

My sketch is:
#include <SoftwareSerial.h>
SoftwareSerial esp8266(2, 3); //RX,TX

void setup()
{

  Serial.begin(9600);
  esp8266.begin(9600);

  esp8266.print("AT\r\n");

}

void loop() {
  String response = "";
  while (esp8266.available())     {
    char c = esp8266.read();
    response += c;
  }

    if (response != "") {
      Serial.println("Response: " + response);
    }

}

Serial Monitor shows this:
Response: A
Response: T

OK
Response:

OUTPUT when I run AT+CIFSR command:
Response: A
Response: T+CIFSR

Response:
+CIFSR:APIP
Response: ,"192.168.4.1
Response: "
+CIFSR:APMA
Response: C,"5e:cf:7f:80
Response: :f7:74"

OK

Question now is: How do I store the string being returned from the esp8266. I thought my response string was suppose to store the "OK" but that did not happen.

Why are you using software serial?

Because most of the examples I saw used them

Ok, makes sense. I usually use a Mega with Serial and Serial 2. According to your frizting diagram, it looks like you have RX and TX reversed.

I did try to change TX to RX and RX to TX, in arduino but when I do that, I dont get response from AT commands, on the serial monitor

If you are using an Uno like in the image, use different pins for Software Serial like 2,3. Connect pin 2 to the ESP TX and pin 3 to the ESP RX. In your code, try SoftwareSerial(2,3);

Actually It worked, Thanks. I got a ok response. But it seems my "response string" is not actually the string being returned from the ESP8266. I have updated my main question. Please check it out

You are over-driving the ESP's receive pin by connecting to a 5v transmitter. While this isn't likely to be the source of your issue, it will damage the ESP. (The ESP's transmit side is OK because the Arduino receiver will still see a HIGH at 3.3v.) You should put a voltage divider on its receive pin:   Ardu Tx ----- 1KOhm ---- ESP Rx ----- 2KOhm ----- GND

I get your point, could you show with a frtizing diagram, It will be much easier for me.

Of course you cannot use the same pins for both hardware and software serial, but that part seems to have been solved in comments.

Question now is: How do I store the string being returned from the esp8266. I thought my response string was suppose to store the "OK" but that did not happen.

 while (esp8266.available())     {
    char c = esp8266.read();
    response += c;
 }

This will only read as long as characters are available, but the ATmega is able to run this loop much more quickly than characters are received, so unless the entire message was previously transferred it will likely only get a character or two before the receive buffer is found (temporarily) empty and it terminates.
You should instead read until a terminating condition is found, such as a newline character.  For safety you might also put in a "give up and try again" timeout, but make it long.
Some would try to solve this problem by inserting short delays before trying to read, but that is unwise - depending on delays creates unreliability as the necessary delay can easily change due to conditions that may on the surface seem to have little relevance, for example the esp866 might respond more slowly if it is seeing a lot of broadcast traffic on a network, or if the firmware version changes.

There is another technique that you can use, instead of hanging around waiting for more characters from the ESP8266. Your code starts:
void loop() {
    String response = "";
    while (esp8266.available())     {
        char c = esp8266.read();
        response += c;
    } // while

This has the effect of creating a new String every time loop() is entered, and you accumulate the data from the ESP8266 in that - but it's lost if you leave loop(). So it may be better to do it differently:
const char EOL = '\n'; // End of line
String response = ""; // Create String once, outside loop()

void loop() {
    char c = '\0'; // Initialise to NUL
    while (esp8266.available() && c!=EOL) { // Wait for End of Line
        c = esp8266.read();
        response += c;
    } // while
    if (c==EOL) {
        Serial.print("Response: "); // Don't use '+' if you can help it!!!
        Serial.println(response);
        // Do other processing
        response = ""; // Clear response for next string
    } // if

This has three effects:

It keeps an incomplete response between calls to loop().
It only processes response once the end-of-line is read.
It keeps loop() running nicely (important on other Arduino), rather than hanging around

Just check if this answer helps.
Here is the thing, For AT commands from serial monitor, RX or arduino should be connected to RX of ESP and TX of arduino to TX of ESP. That is the reason you are able to enter AT commands with your circuit when empty program is uploaded.
Now for arduino to communicate with ESP using program, you have to connect RX of arduino to TX of ESP and TX of Arduino to RX of ESP. In your case if using software serial 2 & 3, then pin2 to TX of Esp and pin3 to RX of ESP.
To read "OK" from ESP, try below code:
if(esp8266.find("OK"))

Also you may try this code to read:
esp8266.find("pin="); //this acts like a pointer.
int value = esp8266.read(); //returns ASCII Code. this will read value which comes after pin=

Refer : https://www.arduino.cc/en/Serial/read

source: Stack Exchange

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

sort: votes


text:
Hooking up the Arduino to a car's 12v
I am planning an uno based tachometer for my truck, which doesn't have a tachometer. With nothing in place for me to get a reliable signal, I started looking at other sources to read the rpm from the engine.
It seems to me that an engine should affect the power every time a cylinder fires --the power should spike in some way. So in theory I should be able to hook up to the 12v cigar lighter, count the spikes, and calculate the rpm. It would only need to be accurate within 500 rpm or so.
This is a two part question.

How would I hook up the arduino to the 12v system? As in, what should I do to protect the io of the arduino?
How would I gather the test data to see if this is possible? Is there a way to hook the arduino up to the truck via the 12v and my computer via usb and send data back that I can record or monitor?

How would I hook up the arduino to the 12v system? As in, what should I do to protect the io of the arduino?

First you're going to need to do some investigative work. You're going to need to beg, steel, borrow (or use your own if you have one) an oscilloscope. You can then use that to examine the 12V power coming from the cigarette lighter.  Armed with that you can then tell:

If there is any power fluctuation from the engine, and
What form that fluctuation takes.

If there is any fluctuation it will appear as an AC component imposed on top of the 12V DC voltage. Removing the 12V DC offset is simple enough. All you need to do is pass the power through a high pass filter. That's simply a capacitor and a resistor. You need to ensure that the cut-off frequency of the filter is below the lowest frequency you want to measure (idle frequency) yet high enough to cut out the DC component effectively.
Once you have done that you can then clip the waveform using a diode to protect against negative voltage, and a resistor and zenner diode to limit the positive voltage.
For instance, something similar to the following (it's not exact - the source isn't creating spikes, but an offset low duty cycle PWM, which is kind of similar for demonstration purposes):

The first point measured is the 12V signal with big high voltage spikes. Next the power has been high-pass filtered by the RC network and the lower portion of the waveform clipped by the reverse biased diode. Following that the zenner diode clips the upper portion of the waveform to within safe limits for the Arduino. The 100Ω resistor with the zenner is there to limit the current through the zenner.
Don't take any of those values as gospel, since the signal I am filtering there is not your signal. You need to know your signal first before you can work out exactly how it should be filtered, but that gives you the basic idea of how it can be done.

How would I gather the test data to see if this is possible? Is there a way to hook the arduino up to the truck via the 12v and my computer via usb and send data back that I can record or monitor?

Connect the filtered and clipped signal to an interrupt input on the Arduino. Count the pulses within a given time period (1 second, 5 seconds, whatever you choose) and multiply up for number of pulses in a minute. Don't forget to then divide by 4 for a 4-cylinder engine, since I would expect you would see 4 sparks per revolution. How you then gather the data is up to you. It might be simplest to add an SD card shield to your Arduino and record the data onto an SD card. You can then place that card into your computer to process the data at your leisure.
The best way to power your Arduino is, of course, direct from the truck's power. The safest way, because of all those nasty spikes in the power, is to use car USB phone charger adapter. Plug that into the USB of the Arduino and all should be nice and happy.

I was hoping I wouldn't need to acquire an oscilloscope. Is there any way to figure out the filter's values without one, or to build a beefy way to hook up the arduino to 12v without the filters in place to get the numbers?

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


text:
Can I connect a remote control relay to a arduino uno board by disabling the remote control in the relay?
I was making a home automation system by making some of the appliances in the home like fans and lights voice activated. But by mistake I bought a remote controlled relay in place of a normal relay from a shop and return does not seems possible. So I want to know if I will be able to use that remote controlled relay in this project?

You could, let the Arduino control the remote, which activates the relays.

I don't like to work with mains, so I use those outlets and connect a 433MHz transmitter to the arduino to activate the outlets.
You'd have to check the frequency of the unit, and see if anyone have decoded the transmitted data package.
If that doesn't float you're boat, you could open up the unit, and remove/desolder the relay. Add a transistor, and flyback diode and you're done. Just be careful with mains power.

Why use a flyback diode? I assume because it's a mech. relay - I've used these, and had problems one wouldn't expect when switching at ~1 sec intervals for tests. Do you place it between VCC and GND on the relay? (mine were 5V relays which were supposedly isolated from higher currents, but not from the relay 'motor' itself) Did I just answer my own question? Edit: more precisely, the arduino would be reset after the relay went a bit haywire; failing to switch, seitching several other channels.

@user400344 please create a new question instead of hijacking someone else's question.

I would if I could, but it appears I am prevented from posting new questions. I'll just try using a diode from GND to VCC, thanks anyway.


text:
Difference between Arduino IDE giving me headaches
For some time now I've been playing around with the latest version of Arduino IDE and my UNO and ATTiny with simple 433 RF links with the Manchester Library. It all worked fine, but for my next project I want to take the step up and use a better wireless thingy... like the nRF24l01 or the nfm12b.
And then starts the pain. Attiny does not have hardware serial, but people seems to have solved this by implementing software-serial. But then they have to use some other boards for ATTiny, because when I try to run the examples I get error messages that it could not find  and so on. I use the ATTiny boards I found over at google code.
Regarding the RFM12B I got something to compile. If I went back and downloaded Arduino IDE 1.5.0 (no other!) it actually work with the JeeLib - hurray! Why is this, why can't I use the latest version of the Arduino IDE?
Regarding the NRF24 chip this case is unresolved. I have not found the correct combination of boards, IDE and library versions. Could anyone point me in the right direction?
What are the difference between the Arduino IDE's? Why can I get stuff to work on 1.5.0 but not the latest 1.6.x?

To get RF24 working:

Download the latest IDE (not 1.0*)
Use the library manager to download the
latest RF24.
See https://github.com/TMRh20/RF24/issues/236#issuecomment-205354077
about what core to use.
Don't forget to define ATTiny in the sketch
Ex: #define __AVR_ATtiny84__
(84, 44, 24 are the choices)

ATTiny* do not have SPI, that's why it can't find SPI.h (SPI library).

As far as I know, there was an internal dispute in the Arduino company. So now there are two companies selling under the Arduino name.
www.arduino.cc 's latest ide is 1.5.x and that has more features than www.arduino.org 's ide 1.6.x. So make sure you use arduino.cc's version only because they do the major development of the IDE.


text:
Arduino: Sending SD CSV file online at specific time of the day
I intend to perform data logging from sensors and store it on SD card as CSV format. The data is related to weather and I would like to send it at the end of the day/
Any available codes how to deploy the SD files from Arduino to the cloud/online at specific time of the day?
Thank you in advance.

You should use arduino as an ftp client, then stream the csv file to the site in binary mode. You should find examples on the web.

Well for CSV, you might as well do dataFile.print(",");. It will log a comma and thus separating your values with a comma.
For logging your data at the end of the day, you have multiple ways.
1- Use a delay (worst idea EVER! Don't do this!). This will require you putting delay(86400000);. Yes that is indeed a 24h delay!
2- Use the millis() function. This function returns the number of milliseconds since the programmed started running. There is an example code called blinkWithOutDelay(or something like that). This method is somewhat "ok" but after 49 days there is a rollover which makes things complicated. To solve that rollover, see here.
3- Use a RTC. RTC stands for Real Time Clock. It is pretty much a module that keeps actual time even if the power to your project is disconnected. There are many popular models out there such as the DS3231. There are many libraries for it. You can do so that each day, at a specific time, it logs the data to your SD card.
Now to send the data. You have may options for this too.
1- Use an Arduino Ethernet shield. This will connect your Arduino to the Ethernet via an Ethernet cable. From there, you can either log your data to a Google Sheets file or a custom web server. Many tutorials out there for you.
2- Use an ESP8266. With this Wifi module, you can easily host your own web server with it. Note that This makes it somewhat harder for your code then simply using an Ethernet cable but it makes you project wireless. Note that if you do use an ESP8266, you can put the Arduino aside. The ESP has many GPIOs that can be used to do many things, but I'll still suggest keeping the Arduino for sake of simplicity. Again, many tutorials out there.
Note that there are many cloud services out there. A quick Arduino IOT search will bring out many result and interresting projects ideas for you.


text:
Setting the frequency of a timer interrupt
The concept:
Play a sine wave saved as a character array in PROGMEM through an 8-bit DAC connected to the PORTC pins on the Arduino Mega.
This works:
// File just defines an array and a size

#include "sine440.h"

int i = 0;
void setup() {
  DDRC = B11111111;
}

void loop() {
  PORTC = pgm_read_byte(&sine[i++]);
  if(i >= sine_size){
    i = i - sine_size;
  }

  delayMicroseconds(60);
}

The above code produces a sine wave of about 440 Hz, exactly what I wanted. Now, I'd like to move this into an interrupt routine, as follows:
This doesn't work
#include "sine440.h"

int i = 0;
void setup() {
  DDRC = B11111111;
  TCCR5B = (1 << WGM52) | (1 << CS50 );
  OCR5A =  16000000/16000;
  TIMSK5 = (1 << OCIE5A);
}

ISR(TIMER5_COMPA_vect){
  PORTC = pgm_read_byte(&sine[i++]);
  if(i >= sine_size){
    i = i - sine_size;
  }
}

void loop() {

}

The above code produces a sine wave of 1721 Hz. I know that this means it's iterating through the array too fast, but I don't know how to change it. In order for it to produce 440 Hz, it needs to be preforming 16,000 iterations per second, which is what I believe  OCR5A =  16000000/16000; does. But it doesn't appear that changing the value of OCR5A does anything at all. Giving it the max value of 65,535 still produces a 1721 Hz sine wave...
So what am I doing wrong here? How do I change the speed of this timer interrupt?

Try setting TCCR5A = 0 explicitly, maybe arduino has WGM51 or WGM50 set at startup for some reason.

I second BrettAM's comment. The Arduino IDE sets most of all the timers up for PWM, and I had to comment out a section once to use my own ISR with Timer 3 on a 32u4, because no matter where or how I set it, the CTC interrupt never went. The WGM50 and CS51 are set at the start of the Arduino files basically, so that messes with your settings.
You will need go into the Arduino core files. This is $install_path/arduino-1.x.x/hardware/arduino/avr/cores/arduino/, and under that directory you need to find file wiring.c. This file contains all the setup of the timers for PWM and the millis() or micros() functions.
Go to line 342. Located there is this:
#if defined(TCCR5B) && defined(CS51) && defined(WGM50)

  sbi(TCCR5B, CS51);           //set ter 5 prescale factor to 64
  sbi(TCCR5B, CS50);
  sbi(TCCR5A, WGM50);         // put timer 5 in 8-bit phase correct pwm mode

#endif

Here you can place another #if defined() macro around this, resulting in:
#if !defined(doNotSetTimer5)

  #if defined(TCCR5B) && defined(CS51) && defined(WGM50)

    sbi(TCCR5B, CS51);           //set ter 5 prescale factor to 64
    sbi(TCCR5B, CS50);
    sbi(TCCR5A, WGM50);         // put timer 5 in 8-bit phase correct pwm mode

  #endif

#endif

Now when you want to use your custom settings, you will put the following at the top of your .ino file:
#define doNotSetTimer5
#include <wiring.c>

That does not block the Arduino environment from setting up Timer 5 when compiled with other code, but only when you want to use custom settings (changed because of @Gerben's suggestion). When you change these settings you will lose PWM on 3 pins: 44 45 46. But you will be able to make use of setting your own PWM up or a CTC ISR().
This doesn't mess with anything else and is the easiest way to do it.

Wouldn't it be better to use a !defined(...), as to not break existing code? Something like #if !defined(doNotSetTimer5). That way you need to set the flag only if you want the no-standard settings.

@Gerben         that's a good point, I will change it to that rather then. Will be more compatible with stuff. +1

Hey, thanks. I actually found a thread yesterday before seeing BretAm's comment that addressed this issue with a different timer. So i tried it out and it worked. But this did a great job in explaining WHY it was happening.

@Dave          pleasure, maybe just add that link as a comment here or something to have another way too.


text:
HTTPS Client with MKR1000
I am making an IoT device with the MKR1000.
As a part of the process, I would like to set up an HTTPS connection to https://hit.tl8.co/api/ping (this is a website I have made and control).
The problem is that client.connect(url, 443) is returning false. I have tried normal HTTP and the URL works on a browser. I can also access https://www.google.com. The code is a small variation of the example HTTP client.
As such, I believe that the TLS certificate I am using is not accessible by the MKR1000. Running this report shows that it is a RSA 2048 bits (e 65537) with SHA256withRSA certificate.
Is there a way to get the MKR1000 to accept this certificate? Failing that, what changes do I need to make to this certificate for it to work?
Is there a software solution to get this certificate working?

You need to use connectSSL() instead of connect(), and possibly add your certificate to the MKR1000 as described on Hackster.

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


text:
Arduino Nano Update failure - avrdude: stk500_recv(): programmer is not responding
Before I tear all my hair and teeth out, can anyone please help. I have tried googling an answer and have not found anything.
My Setup:

Win7 64bit
Arduino 1.6.9 IDE freshly reinstalled
COM14 port in Arduino IDE checked
Under Device Manager COM14 shows as: "USB Serial Port (COM14)". Not as "Arduino...(COM14)" as some pages have shown
I am not sure if I have a real or copy of the Arduino. As far as I can figure out I have a real one, on the back I have the FT232RL chip
I have bought 2 Arduino Nanos and both show same error
Both Nanos came pre-soldered, (no noob soldering by me)
I have tried uploading sketches on my Win7 platform AND over a Raspberry Pi, both same error

Now perhaps most importantly I previously ordered an Arduino from the same retailer and that one worked. The two I have now dont work.
The problem:

When I try upload I get the same message every time: avrdude: stk500_recv(): programmer is not responding
a. it does this 10 times and then fails
b. Rx and Tx LED's are ON and do NOT blink at all at any point in time
c. Green power LED is always ON, no blinking
d. Pin13 LED blinks consistently
e. I have tried the extreemly annoying reset "trick" before uploading, after uploading, at the same time, during uploading, and nothing works

I am seriously at a loss here. I have had an Arduino Nano work on my pc.
Any help would be greatly appreciated please.

The Arduino.cc developers changed the bootloader on official Arduino Nanos to communicate at a different speed. Try setting Tools → Processor → ATmega328P (Old Bootloader)

This worked for me, thank you!

Sorry for posting this as an answer, I don't have enough rep to write comments yet.
1) Have you tried different USB cables? A dodgy USB cable could power the Nano just fine, giving the impression that it's properly connected, without not actually supporting the data rate required for programming. The fact that something shows up on a USB port on your computer makes this explanation less plausible, though.
2) I notice that there are different versions of the Nano, some with ATmega168 and some with ATmega328. If you have the ATmega328, maybe try selecting "Arduino Uno" in the IDE? If you have the ATmega168, maybe try "Arduino Mini"?

The baudrate for those is 57600. Try checking for an error in your boards.txt .

Do you have experience with this? I've never seen any board using 57600 as a baud rate (not saying it doesn't exist), to me it sounds more like a driver issue. A link to a datasheet or other web reference would go a long way to support your (short) answer

Yes, all my nano clones use it for UPLOAD_RATE . Can't very well give you a datasheet reference, the chinese vendors are not that verbose.

And my 3V minis from RobotDyn will only accept 19200 baud...

... and for the sake of completeness: my uno clones use 115200, and my pro mini 5V clones use 57600 baud.

try a different COM port. I had a corrupted COM3 and it gave the exact same error message that you got

If the Arduino is connected to COM3 then he can't just change to a different COM port.

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


text:
74HC595N shift register with separate power supply
I have wired up a 74HC595N with an Uno, and the standard 8 LEDs and resistors, per the usual youtube "shift register tutorial" and written a sketch that works.  For example, I wrote a routine to walk from values 0 through 255 and light up the LEDs as a hex number.  So my wiring and code are correct.
As an experiment, I tried disconnecting the pin on my breadboard's power rail that goes to the Arduino 5V, and the pin that goes to Arduino ground, and instead plugged in a breakout (if that's the right word) that plugs into the breadboard and provides 5V on the power rail when a 9V battery is plugged into it.  (It's been checked with a multimeter, it's just under 5V.)  The only pins still going to the Arduino are for DS, SHCP and STCP.
Things sort of work, but not really.  It seems clear to me that the shift register keeps getting reset. (All of the LEDs briefly light back up in each iteration as I'm running my hex number display routine.) All of the other wiring remains the same; specifically OE-bar is still connected to ground on the power rail.  But it still seems to reset.
Can someone explain why the shift register keeps resetting?  Also, am I doing anything that might burn up the Arduino and/or shift register?

All ground connections except those which are explicitly isolated must be connected together in order to provide a common voltage reference for the circuit. Any breaks in the ground connection can result in gross misbehavior such as what you are experiencing.

Thanks.  Can you elaborate on what "explicitly isolated" means, or is that too broad of a question?

Also.  Let's say that I wanted to chain shift registers together, to the point that they needed too much current for the Arduino to handle.  Does that mean that this is just a brick-wall limitation of the Arduino?

Optocouplers and the like. No, just provide a more powerful external 5V supply for both the Arduino and the shift registers.


text:
Why do I get "invalid operands of types 'const char*'" error?
I am making an Arduino alarm. This is the error:
exit status 1
invalid operands of types 'const char*' and 'const char [2]' to binary 'operator+'

Here is the code that triggers it:
lcd.print("0"+hours+":"+minutes);

This code is similar, but worked before:
String none="00";
lcd.print(none+":"+none+":"+minutes);

I can post the full code if you need it. How can this be fixed?

Your first code took a String object, then added other strings (note lowercase) to it - which are characters enclosed in quotes. It is legal to add strings to String objects.
Your new code doesn't have any String objects at all - and you're not allowed to add strings to strings (both lowercase).
It will work if you change your new code to:
lcd.print(String("0")+hours+":"+minutes);
That turns the original string "0" into a String object, and then adds more strings to it.


text:
Why does my lcd screen work fine and then display random characters?
It works as expected for a few seconds and then random letters appear on the second row. The wiring and the programming should be correct. I wired it according to an Arduino Starter Kit Book and coded it myself.

Code:
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int hours=23;
int minutes=0;
String none="00";
unsigned long timer;
void setup() {
lcd.begin(16, 2);
lcd.setCursor(6, 0);
lcd.print("Time:");
lcd.setCursor(6, 1);
lcd.print("23:00");
}

void loop() {
timer=millis();
if(timer%600==0){
   minutes++;
  if(minutes==60){
      minutes=0;
      hours++;
      }
   if(hours==24){
      hours=0;
   }
  lcd.clear();
  lcd.setCursor(6, 0);
  lcd.print("Time:");
  lcd.setCursor(6, 1);
  if(minutes<10){
    if(hours<10){
      lcd.print(String("0")+hours+":"+"0"+minutes);
    }
    else{
      lcd.print(hours+String(":")+"0"+minutes);
    }
  }
  else{
    if(hours<10){
       lcd.print(String("0")+hours+":"+minutes);
    }
    else{
       lcd.print(hours+":"+minutes);
    }

  }
  delay(200);
  }
}

I was able to narrow down the problem. I was testing what happens when it hits 24 hours so I set hours to 23 in the beginning and made the time 600 ms. Once it hits 10 seconds, the characters appear. If the hour is a 2 digit number, the issue happens. I made the hours 9, and the issue disappeared. What can I do?

Where is your decoupling?

There was nothing mentioned about capacitors in the book. I did what was illustrated. I followed the schematic exactly. I will post the schematic.

The problem was that I was adding ":" to the printed string on the lcd without making it a String object. That only occurred if I had double digit hours and minutes.
Incorrect way:
lcd.print(hours+":"+minutes);

Correct way:
lcd.print(hours+String(":")+minutes);

You should avoid using String. There is no need to concatenate your parts like that - just print each bit to the LCD separately. Excessive use of String like that will cause heap fragmentation and could lead you into memory problems further down the line.


text:
RC Car Hack Issue
I am trying to hack a cheap RC car as to be able to control it using my Arduino. I took apart the cars remote controller and found the pins that make it go forwards, backwards, left, and right. So I soldered 4 jumper wires to these pins and connected them to the Arduino as follows:
Pin 8 - Left
Pin 9 - Right
Pin 10 - Forwards
Pin 11 - Backwards
I found the remote controller is controlled by a chip called TX-2E, I checked the data sheet online and found that if any of the pins that control the pins motion are ground, the car will move in that corresponding direction. So if the forwards pin is grounded the car is supposed to move forwards.
To test this, I connected each jumper wire to ground on the Arduino individually and found that it worked as described on the datasheet.
Then I decided to create a sketch that makes the car move forwards for 1 second and backwards for 1 second, it worked as expected.
Then I wrote a sketch that makes the wheels turn left for 1 second and then turn right for 1 second. But it didn't work as expected instead the wheel turned left for 1 second, went to neutral for a second.
I wasn't sure what was wrong, but I decided to run a sketch that should move the car forwards for 1 second, move it backwards for 1 second, turn the wheels left for 1 second, and then turn right for 1 second. But all it actually did was just turn left for 1 second every couple of seconds. I removed the jumper wire connected to pin 8 that is supposed to control the wheels turning left, while the sketch was running and everything worked as expected except the turning left part. it moved forwards for 1 second, moved back for a second, waited at neutral for a second, and then turned right for a second.
When I connected back the jumper wire that controls the car moving left everything stops working again. I am not sure whats wrong, I even connected a multimeter to each pin and found they were pulsing between 0V and 5V as expected but for some reason they weren't moving the car, it was only moving left, in this case at least.
Any help to get this working, ideas to why its not working, or any troubleshooting tips would be greatly appreciated.
Below you can find the code for the sketch, that is supposed to move the car      forwards, backwards, left and right.
const int LEFT = 8;
const int RIGHT = 9;
const int FWD = 10;
const int BWD = 11;

void reset () {
  //Sets all pins to HIGH as the car moves when the pins are grounded.
  //And we want the car to start out by not moving.

  digitalWrite(LEFT, HIGH); //For some reason everything works when I remove this
  digitalWrite(RIGHT, HIGH);
  digitalWrite(FWD, HIGH);
  digitalWrite(BWD, HIGH);
}

void setup() {
  // put your setup code here, to run once:

  pinMode(RIGHT, OUTPUT);
  pinMode(FWD, OUTPUT);
  pinMode(BWD, OUTPUT);
  pinMode(LEFT, OUTPUT);
  reset();
}

void Forward(){

  digitalWrite(FWD, LOW);
  delay(1000);
  digitalWrite(FWD,HIGH);
  delay(1000);
}

void Backward(){
  digitalWrite(BWD, LOW);
  delay(1000);
  digitalWrite(BWD, HIGH);
  delay(1000);
}

void Left(){
  digitalWrite(LEFT, LOW);
  delay(1000);
  digitalWrite(LEFT, HIGH);
  delay(1000);
}

void Right(){
  digitalWrite(RIGHT, LOW);
  delay(1000);
  digitalWrite(RIGHT, HIGH);
  delay(1000);
}

void loop() {

  Forward();
  Backward();
  Left();
  Right();

}

Did you connect the arduino ground to the remote's ground?

What is the voltage across the switches when they are not depressed?  Perhaps your Arduino is getting reset periodically rather than running the entire program.  It could be useful to add some serial output to your program which you could capture to monitor its operation, though connecting to both the computer and the RC transmitter could perhaps cause electrical issues.  Perhaps you could add an LED and resistor (anode to 5v, cathode to signal) to your setup and visually monitor it that way?

Without details of the car's circuitry one can't say with certainty what the problem is.  However, from the description given, one thing sticks out:  The TX-2E spec sheet says to ground a control pin to select a motion.  But besides grounding pins at times, you are also taking them high.
Instead, try leaving pins open when not active, and pulled down for active.  Eg, try code like:
void motion(const int pin) {
  pinMode(FWD, OUTPUT);
  digitalWrite(pin, LOW);
  delay(1000);
  pinMode(pin, INPUT);
  delay(1000);
}
void Forward() {
  motion(FWD);
}
void Backward() {
  motion(BWD);
}
void Left() {
  motion(LEFT);
}
void Right() {
  motion(RIGHT);
}

But is there a reason, this works as opposed to applying a high voltage to the pin when not active?
Some extra info:
The pin when not active and not connected to the Arduino is at around 3.5 V. But when I connect the pin to the Arduino and apply a high voltage to it, the voltage across the pin is about 5 V.
Could this somehow have led to my issue? If so, in what way?
And could it have led to more long term issues if I kept applying 5V to a pin that was used to taking about 3.5 V.
The confusing thing is that it worked properly for all movement except for leftward movement.

I don't really know and haven't thought of a circuit that would work precisely that way, but can  imagine there's some matrix or multiplex circuitry that works when certain combinations are used -- eg, forward and left, or forward and right -- and depends on the left or right contact point being open to let signals flow through.


text:
how can i fix the error ? stk500v2_getsync(): timeout communicating with programmer
I bought this Chinese Arduino Mega 2560 16AU.
This was the first time to deal with Arduino boards. When I try to upload a sketch I always get this error:
stk500v2_getsync(): timeout communicating with programmer
I successfully burnt a bootloader to it using an Arduino uno,
but the same error is there.
Finally I discovered the the loop test is not working, and only the LX LED flashes once  when I enter a letter in the serial monitor.

It's our old friend the CH340G again, isn't it?
You've been sold a dud, I'm afraid. The USB chip used there is dead. It happens a lot with those cheap Chinese boards. You should still be able to use the board with an external FTDI adapter by wiring it in to TX->RX, RX->TX and DTR->RESET (via a 100nF capacitor) with power and ground connected of course.
There is also a slim chance that the CH340G may interfere with the TX/RX pins, in which case you may need to remove it. Simply cutting the pins on it with an xacto knife then removing the stumps with a soldering iron and tweezers would do the job.

If You Downloaded the driver it should be fine!
https://github.com/jimaobian/CH34x_Install_V1.3


text:
avrdude: ser_open(): can't set com-state for "\\.\COM2"
I have an unofficial Arduino Uno.
I've tested these:

Testing on USB 2.0 and USB 3.0
Changing Port (COM XX)
Updating drivers for the Unknown device to Arduino Uno (COM XX)
Resetting Arduino Board
Plug/Unplug
1x PC Reboot
Burning bootloader
Changing 'Programmer'
Uninstalling-Reinstalling device
Holding the "Reset" button while I Upload
Testing different examples (Blinking/Voltage Serial Read)
Testing different "Board" in Arduino software (just in case, you never know)
Removing jump wires

Does anyone have any suggestion more than I just tried?

Which version of Windows are you on?

Arduino app is 1.6.9.

I asked which version of Windows you are using, not which version of the Arduino IDE you are using.

Oh man sorry, I was not very careful. Windows 10.

And what USB chip does your unofficial Uno use?

The board is similar to that one : (Same Brand, but for example behind the USB port the component's text says "U12.000\n r4 ON" where \n is new line)
http://www.ebay.com/itm/M-J-Duino-Arduino-Uno-R3-Compatible-CH340-with-USB-and-Serial-Headers-/311393221914
I don't know how to find the USB chip you're asking sorry. Send me instructions if the information I give you are not enough.

It's the chip nearest the USB socket. In that picture it's the black rectangle next to the crystal that says "12.000"

Thanx, I edited my previous comment with a liiitle more information. I suppose now you can post an Answer now that you have information about the USB chip right ? I mean I just want to reward you :D You already made me think about the USB chip, didn't think that clones used a different one.

I don't understand what you are describing. Please take a photograph of your actual board with a closeup of the USB socket area.

The difference I was talking about : http://prntscr.com/bfhnrq
The whole board : http://prntscr.com/bfho23

That's just the crystal. I need to know what it says on the chip. The big black rectangle just above the component you are describing in that picture. The one with lots of pins sticking out of it.

It says : Header is "WCH" and the rest "CH340G \n 202685413" with \n representing a new line.

I thought that looked like one of those... So... Have you installed the CH340G drivers? Or are you trying to use the genuine Arduino Uno drivers?

Thank you kind sir. I really didn't know that they used different USB chips. And that's because ? (If you can answer ... that would be nice :D )
I installed the CH340G drivers and now it works perfectly :D
Also "Answer The Question" so I can give you some credits if you want.

After spending hours struggling with the same problem, @Brew's response solved my problem! Thanks!

The board you have uses the CH340G chip instead of an ATMega16U2 or FTDI FT232R chip.
It requires special drivers, not the ones that come with the IDE.
Why do they use that chip instead of the proper one? Simply because it's dirt cheap. They are the cheapest of the cheapest of the cheapest USB chips around. They frequently die. You might want to save up and invest in a genuine Arduino at some point, because that one may well die out of the blue.

I had the same problem with the cheap nano from Amazon Longrunner. At first, it worked, I could program it. Then, I farted around with my COM port numbers because I was tired of being in the COM14 area.
Since that moment, it stopped working. IDE couldn't find the port COM3. After reading you guys, I also noticed that the device was identified RAMPS which it wasn't before. I updated the driver which didn't work; it told me I was already with latest driver.
So I deleted that driver and reconnected my Nano and lord and behold, the new driver USB-SERIAL CH340 installed and everything was fine. El cheapo still works. I don't care to pay more just for the USB chip which I will use only once. The uP is still up to par.

I had the same problem. I was able to upload a simple Blink example, but not my own program. And I thought there's no problem in my program, since I successfully tested it on other Arduino before. But actually, that was the problem. I had this in my program (for console logs):
void setup() {
  Serial.begin(9600);
}

Then I read that different Arduinos use different baud rates. Originally I tested it on Arduino Mega, but this time I wanted to upload it to "unofficial" Arduino Nano (for which you have to use ATmega328P (Old Bootloader) option when uploading).
Since I didn't need debug logs in my program anymore, I removed these 'Serial' commands completely. Then it got uploaded without problems.
A short article on this topic

so the upload goes to the bootloader, not to your sketch and the baud rate used by the IDE should match the baud rate used by the bootloader. The baud rate set in sketch is irrelevant

Later, I got this error for this board even without 'Serial' commands in my program. So maybe there was something more happening. It took me like 20 attempts to upload it to that board again. (Other board worked without problems). So maybe it wasn't actually related :-\


text:
programming via ISP
A short question:
I wonder weather I can program an AVR chip (ATMega328, ATMega664, ATMega1284, ATTiny etc.) using the Arduino IDE, via ISP, without needing to bootload first.
Does programming via ISP clear the bootload, if installed previously in the chip?

A very similar question was asked on the Arduino forum.

As Ignacio mentioned, using ISP does not require a bootloader, however, it is also very nearly mutually exclusive with retaining one.

Does programming via ISP clear the bootload, if installed previously in the chip?

Indeed, it does.  The ISP interface on the ATmega cannot erase individual pages but only the entire chip.  This is distinct from the SPM instruction used by a bootloader running on the chip itself, which can perform a partial erase.  It is also distinct from the ATxmega, which does apparently offer an ISP page erase capability.
So in order to end up with both a bootloader and sketch on the ATmega, you would need to erase the full chip, and then load both the bootloader and the sketch, either in a unified hex file or by loading one and then the other to distinct already-blank memory regions while using the -D option to tell avrdude not to perform an automatic erase.
I do not believe the the Arduino IDE supports this, rather its menu option to program a sketch via a programmer is intended to set up a chip for operation with a sketch alone and no bootloader.  There does not appear to be any way at GUI-level to configure it to do otherwise.
Someone determined enough could probably craft a customized board configuration that built a functional bootloader into every sketch (or merged or additionally programmed a pre-built one), allowing one shot installation of both an operable sketch and an operable bootloader that could field upgrade it.  However, the Arduino IDE would be a poor choice for production programming...

Chris Stratton is quite right. As I noted under the question, this was also asked on the Arduino forum a day or two ago. The ICSP process can only erase the whole chip. You can't therefore keep the bootloader and replace the code, or even keep the code and replace the bootloader. A unified file is one approach (production Arduinos would be shipped that way). However re-installing the bootloader afterwards, when wanted, is quite simple.


text:
Getting POST data into a char array
I'm using Energia to program TI's CC3200 MCU. Since Energia is based off the Arduino IDE, I'm hoping someone can help me here.
I'm trying to get the CC3200 to act as a Webserver which when successfully starts up serves up a page with two fields for the username and password that the user needs to fill. Now I'm able to see that the two fields are being successfully POST'd (through Serial.write but only when the code to get it into buffer is not present) but I was hoping someone can help me get this content into a character array (called buffer declared before the setup loop begins).
The code in the section //Here is where the POST data is does not seem to be working as I see garbage values in buffer and in the Serial.write. How do I get these POST values into buffer OR even better how do I split the two field values and store them into two separate character arrays?
void loop()
{
  // listen for incoming clients
  WiFiClient client = server.available();

  if (client) {
    //Serial.println("Client connected");
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;

    while (client.connected()) {
      while(client.available()) {
        char c = client.read();
        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
        if (c == '\n' && currentLineIsBlank) {

            // Here is where the POST data is.
            Serial.println("Post data: ");
            int ctr = 0;
            while(client.available())
            {
            Serial.write(client.read());
            buffer[ctr] = client.read();
            ctr++;
        }
        Serial.println("Buffer: ");
        Serial.write(buffer);
        Serial.println();

        //Serial.println("Sending response");
        // send a standard http response header
        client.println("HTTP/1.0 200 OK");
        client.println("Content-Type: text/html");
        client.println("Connection: keep-alive");
        client.println();

        //form added to send data from browser and view received data in serial monitor
        client.println();
        client.println("<!DOCTYPE html>");
        client.println("");
        client.println("");
        client.println(" <FORM action=\"\" method=\"POST\">");
        client.println("
");
        client.println("    Username:");
        client.println("    <INPUT type=\"text\" name=\"uname\">

");
        client.println("    Password:");
        client.println("    <INPUT type=\"text\" name=\"pwd\">

");
        client.println("    <INPUT type=\"submit\" value=\"Submit\">");
        client.println("
");
        client.println(" </FORM>");
        client.println("");
        client.println("");

        client.println();

        client.stop();
        }
        else if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
        }
        else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    //Serial.println("Disconnected");
    Serial.println();
  }
}

What sort of garbage data are you seeing?

In this loop
while(client.available()) {
    Serial.write(client.read());
    buffer[ctr] = client.read();

you're using client.read() twice, so the buffer gets only every second character.
A solution could be:
while(client.available()) {
    int c = client.read();
    Serial.write(c);
    buffer[ctr] = c;

Thanks! This code worked great!
int ctr = 0;
while(client.available())
{
buffer[ctr] = client.read();
ctr++;
}

Any idea why this loop runs twice? I see two outputs of the buffer. Is it once when I enter the URL and hit Enter and the second when I hit Submit?


text:
How can I make push buttons react to being pressed instantly?
I am making an Arduino alarm clock. I am checking for the state of a button. If it is clicked, I increment the button counter. If the counter is divisible by 2, it is mode 0, if not, it is mode 1. I have small delays in the code for each mode to help the lcd clear itself. Those delays are preventing the buttons to reacting to my touch, because there is likely a delay during that time.
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int hours=0;
int minutes=0;
const int modePin=6; //button
int prevModeState=0; //prev state of button
unsigned long timer;
int modeState;//current state
int mode=0;//mode of alarm
int buttonCounter=0;
void setup() {
lcd.begin(16, 2);
lcd.setCursor(6, 0);
lcd.print("Time:");
lcd.setCursor(6, 1);
lcd.print("00:00");
pinMode(modePin, INPUT);
}

void loop() {
modeState=digitalRead(modePin);
if(prevModeState!=modeState){    //this is the part where I check for the state
  if(modeState==HIGH){
    buttonCounter++;
  }
}
prevModeState=modeState;
if(buttonCounter%2==0){
  mode=0;
}
else{
  mode=1;
}

if(mode==0){
  timer=millis();
  if(timer%600==0){
     minutes++;
    if(minutes==60){
        minutes=0;
        hours++;
        }
     if(hours==24){
        hours=0;
     }
    lcd.clear();
    lcd.setCursor(6, 0);
    lcd.print("Time:");
    lcd.setCursor(6, 1);
    writeTime();
    delay(200); //delay
    }
}
else if(mode==1){
  lcd.clear();
  lcd.setCursor(4, 0);
  lcd.print("Set Time:");
  lcd.setCursor(6, 1);
  writeTime();
  delay(500); //delays

}
}

void writeTime(){
if(minutes<10){

      if(hours<10){
        lcd.print(String("0")+hours+":"+"0"+minutes);
      }
      else{
        lcd.print(hours+String(":")+"0"+minutes);
      }
    }
    else{
      if(hours<10){
         lcd.print(String("0")+hours+":"+minutes);
      }
      else{
         lcd.print(hours+String(":")+minutes);//possibly split if problems arise
      }

    }
}

How can I edit my code?

The simple answer is, of course, don't use any delay() calls. There is no need for them in your code.

I cannot remove delays since lcd.clear(); would be done very often and nothing would be visible on the lcd.

So don't clear the LCD. There is no reason to clear the LCD. Just over-print the existing text with new text. Go on, have a go. Just remove the lcd.clear() calls and the delays from your program and see just how smoothly the screen updates.
On an LCD a cell can only hold one character at a time. Printing one thing and then printing something else in the same place replaces the characters that are already there with the new ones. There is rarely any need to use lcd.clear() for normal screen updates - only if you really need to clear the entire screen should you use it. Just updating a bit of text on the screen does not require clearing of the entire screen.
In fact, you don't even need to print Time: or Set Time: every loop - you only need to do that once when you change mode. If you are going to clear the screen that is the time to do it.  So a quick outline:

When button pressed:

Set mode
Clear screen
Print static text (Time: etc)

Every iteration:

Print the mode's dynamic text

You see the heavyweight screen clearing is only done once when you change mode. All the rest of the time it's just updating small portions of the screen. Not only does it look nicer (no flicker) but it's also considerably more efficient and allows your program to do more.

You have a few options, including using interrupts. But I believe the most important thing is: "do not use delay()" and you might not even need to use interrupts...
Have a look on this nice post from Nick Gammon: http://www.gammon.com.au/blink with some tips about non-blocking coding.
Also a very simple "Blink LED" example: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay

I will look into that. Also, I cannot remove delays since lcd.clear(); would be done very often and nothing would be visible on the lcd. Also, the clear takes time - that is why I need the delay.

Sure you can remove the delays. Have a look on the examples from the links and you'll understand how to do non-blocking coding.In your example, instead of using the delay to hold before "clearing" the LCD, you just define "when" in the future you'll be running clearing. You are already familiar with millis() so tou're on the right direction ;)

You don't need to clear the display at all. Just overwrite the existing text with the new text. Clearing an LCD is quite an "expensive" operation and if you don't actually need it then you should avoid it.


text:
How can i receive data from Mega2560 on PC with Visual C#
How can i receive the data from my Arduino Mega 2560 with Visual C# on my PC.
I send a short databyte (2 bytes) and a timestamp (4 bytes) over USB to PC
//initialization

const int RX = 0;
const int TX = 1;

void setup(){

pinMode(RX, INPUT);   //readpin for USB
pinMode(TX, OUTPUT);  //writepin for USB
...

Serial.begin(28800);   //open interface
}

 //loop()

 Serial.print(incomingByte, BIN); //sending databyte

 sendBinary(currentMillis);   //send timestamp

//method for timestamp

void sendBinary(long currnetMillis)
 {
  int temp = currentMillis&0xFFFF;  //16 bit of the low-byte
  sendBinary(temp);
  temp = currentMillis >> 16;       //16 bit of the high-byte
  sendBinary(temp);
 }

I have surched in the internet for an example but i didn´t find a good. So i ask here what ist the best way with Visual Studio C# to receive the incoming data?
An example code will be nice because i´m a beginner and didn´t understand the jargon.
With frindly wishes sniffi

I haven't tried the code below, but it should point you in the right direction.
All you have to do is write a C# program that opens the Serial port that your Arduino is connected to and read and write from there like you would from a file.

Open Visual Studio, create a C# command line project.
Paste this code inside main()
    System.IO.Ports.SerialPort port = new SerialPort("COM1", 9600);
    try
    {
        while (true)
        {
            int readData = port.ReadByte();
            System.Console.WriteLine("Read {0} from the port", readData);
        }
    }
    catch(Exception)  // Press CTRL-C to exit.
    {
    }
    port.Close();

Compile the code and run it.


text:
Thermometer project shows fluctuation due to varying sensor value and voltage
I built this thermometer that reads the sensor value from the temperature sensor and displays it on the LCD display. It basically works fine, but the displayed temperature shows a fluctuation between +/-2 degrees due to varying sensor value and voltage every second.
(This is my very first Arduino project and I am pretty new to electronics.)
The Arduino gets the power via my Mac through USB.
When I check the sensor value and voltage, it slightly differs each second (or whatever delay interval I use in my code). Sensor value is between 123-125 and voltage usually 0.7, but also changes slightly, which causes the temperature calculation to vary around 2 degrees, which for a "thermometer" is quite a lot.
Is there any way to stabilize it? Should I use a capacitor or another resistor?

Code:
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

const float powerSupply = 5.0;
const int sensorPin = A0;
const float baselineTemp = 23;

void setup() {
  Serial.begin(9600);
  lcd.begin(16, 2);
  lcd.print("Temperature:");
}

void loop() {
  int sensorVal = analogRead(sensorPin);
  Serial.print("Sensor Value: ");
  Serial.print(sensorVal);

  float voltage = (sensorVal/1024.0)*powerSupply;
  Serial.print(", Volts: ");
  Serial.print(voltage);

  Serial.print(", degrees C: ");
  float temperature = (voltage - .5)*100;
  Serial.println(temperature);

  // set the cursor to column 0, line 1
  // (note: line 1 is the second row, since counting begins with 0):
  lcd.setCursor(0, 1);
  // print the number of seconds since reset:
  lcd.print(temperature);
  // lcd.print(String(sensorVal) + ", " + String(voltage) + ", " + String(temperature));
  delay(1000);
}

What you need to do is take an averaged reading, this is because the sensor is always fluctuating, noise on the 5V line or the signal line. There are possible hardware solutions.

Adding a capacitor between Vcc and Gnd near the sensor, 0.1µf
Adding a low-pass filter on the signal line of the LM35 to Arduino
heatsink on the LM35(they are very sensitive to movement, giving odd readings)

The capacitor on the Vcc and Gnd will lessen the effects of voltage spikes from the rest of the Arduino's circuitry.
The low-pass filter will help give a more filtered output from the sensor with a better response over time.
                2.2k
LM35>---------/\/\/\-0------<Arduino
                     |
                     |
                     |
                    === 1µF
                     |
                     |
                    GND

The heatsink will allow the LM35 to get a better reading of the general temperature and not the temperature of the breeze from a window.
All three of the above solutions will probably give the best results.
What you could do in software too is to have an averaging algorithm/function in your code and actually take the averaged reading across the whole second that you delay the MCU.
An example of this would be:
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

const float powerSupply = 5.0;
const int sensorPin = A0;
const float baselineTemp = 23;
int sensorVal = 0;

//these are NEW
unsigned long lastTime = 0;     // last time reading taken
unsigned long currTime = 0;     //current time variable intialised
float AverageReading = 0;

float _readingAv = 0;   // static variable for keeping the averaged reading
int _readingsCount = 0;
int _readings = 100;     //the number of readings to take

void setup() {
  Serial.begin(9600);
  //  lcd.begin(16, 2);
  //  lcd.print("Temperature:");
}

void loop() {
  currTime = millis();

  if ((currTime - lastTime) < 1000) {  //checks to see if a second has passed
    sensorVal = analogRead(sensorPin);

    if (_readingsCount < _readings) {
      _readingAv += sensorVal; //add the current value to the last
      _readingsCount++;
    }
    else {
      AverageReading = _readingAv / _readings; //get the average
    }
  }
  else {
    Serial.print("Sensor Value: ");
    Serial.print(sensorVal);

    float voltage = (AverageReading / 1024.0) * powerSupply;
    Serial.print(", Volts: ");
    Serial.print(voltage);

    Serial.print(", degrees C: ");
    float temperature = (voltage - .5) * 100;
    Serial.println(temperature);

    //~ reset the values used by the previous function
    _readingsCount = 0;
    lastTime = currTime;
    _readingAv = 0; //Important to set this back to 0 so not to get odd values

    // set the cursor to column 0, line 1
    // (note: line 1 is the second row, since counting begins with 0):
    lcd.setCursor(0, 1);
   // print the number of seconds since reset:
    lcd.print(temperature);
    // lcd.print(String(sensorVal) + ", " + String(voltage) + ", " + String(temperature));
  }

}

Probably a better version of making filtering code of the LM35.

There are a few things you might try to stabilize your readings.

Add a small ceramic capacitor, say 22pF between the analog signal from the temp sensor (green on your example) and ground;
Perform multiple reading from your analog, let's say 10, discard max. and min. values and calculate the average. Use this instead of a single reading;
User the "internal" voltage as reference. It's normally more stable than using the external 5V. Just bear in mind that you might need to use a voltage divider as the "interval" voltage reference max value is 1.1V (https://www.arduino.cc/en/Reference/AnalogReference);
Reduce the wire sizes and make sure all connections are OK.

Probably just by using technique number "2" listed above you'll get much more stable results and don't need any hardware, just a small looping. Also adding the capacitor would be quite simple.
Hope it helps. Cheers!


text:
Arduino Wireless SD Shield
Is it possible to use the Wireless SD shield without the wireless function, or XBEE Module? I do not need it to be wireless it simply was cheaper than any other I could find, so I was wondering if it was possible to use it just like a normal, non-wireless SD Shield? Thanks!

In general, on a combined "Something plus SD card" shield like this the SD card is a completely separate section to the rest of it. The only real exception is on some audio shields (mp3) where the SD card is directly controlled by the audio CODEC chip.
So yes, you can pick and choose which portions of the shield you actually use in your code. Just by not using the bits you don't want to use.


text:
Which relay should I use to control the power from mains?
I was making a home automation project in which I want to control appliances like a fan and a bulb through voice commands with the help of an arduino uno and a relay but I am confused which relay to use. Please tell me the specifications of a 4 channel relay fit for this project.

Do you want to control a mains powered fan and light? Please let us know. (For educational experiments something battery powered would be much safer.)

@Andy yes I want to control mains powered fan and light but first I will test the circuit with some leds and a dc motor

There are two factors you need to consider when choosing a relay:

Can it power the devices I want it to power without the contacts melting?
Can I control it?

The first one is simple enough. Find out the current requirements for each of the devices and add them together. Make sure that the relay is capable of switching at least that much at the AC voltage of your country's mains supply.  If in doubt go slightly higher.
For the second point you need to consider the interfacing circuitry and what DC power supply you are using in your system. For instance, if you have a 12V power supply for the Arduino you might consider a 12V coil relay and use the 12V power as the switching power. If you are running from 9V then you might consider a 5V relay and use the Arduino's regulated 5V pin as the switching power source. Either way you need a driving circuit. That could be as simple as an NPN transistor, two resistors, and a diode (the circuit can be found throughout the web if you Google "Arduino Relay"), or more complex involving an opto-isolator.
The simplest solution is to find an all-in-one module - a relay with driver circuit all as a single product. There are many of these around directly targeted at the Arduino, and most are the slightly more complex (and thus better) opto-isolator driving circuit. You still have to consider the same two points - switching capacity and coil voltage - but you don't then need to worry about making your own driving circuit for them.

Your 2 factors omit the most important issues - is it safe and do I have the knowledge to work with potentially lethal mains power.

Well, yes there are those factors as well, however Natural Selection is no bad thing...

@Majenko will the power to be supplied to arduino depend on the power requirements of the appliances to be controlled. I guess it would be best if I will be able to control the relay with arduino's 5 V supply.

@Jasmeetsingh No, the power provided to the Arduino has nothing at all to do with the devices being controlled.

@Majenko So if I use 9 V supply for the arduino is there any chance that the board will malfunction or get hot?

@Jasmeetsingh Possible - it depends what you have connected to the Arduino. 9V is within the specifications of the board, so chances are it will be fine, but I am not psychic and don't know what you are thinking of connecting to your Arduino.

In the US there is a set of products - plug-in modules - collectively known as X10, which uses signals sent over the house wiring to control devices elsewhere in the house. If they are available where you are, this is the safest way to control mains-powered devices with an Arduino because the Arduino needs no connection to the house wiring.
The Wireless Transceiver module receive X10 commands over RF and transmit them onto the power wiring. Using this and a small RF transmitter known here as "X10 Firecracker CM17A", your Arduino can be completely isolated from the house wiring, sending its control commands over the air instead. Amazon shows both products on this page; the CM17A (which you use by removing its circuit board from the plastic package), and the RF control module, of which you only need one. The transceiver module can directly control one fan or light; for additional devices you'd use any other, non-RF (read "less expensive") X10 module, which will "hear" whatever the transceiver module sends.
There is an Arduino library already written for X10 communication.


text:
HTTP Requests using Arduino
I use this simple HTTP Post request to post some values on my API from Arduino using Switch. each time I push the switch it send a different values to API.
void switch_led() {
bool SwitchReading = digitalRead(SWITCH);
if (SwitchReading == HIGH) {
Serial.println("Now pressed....");
state = state + 1;
if (state % 2 != 0) {
  digitalWrite(LED, HIGH);
  char data1[] = "{""LDRValue"": 88888888}";
  Serial.println("\nStarting connection to led server...");
  if (client.connect(server, 8040)) {
    Serial.println("connected to post server");
    client.println("POST /api/sensor HTTP/1.1");
    client.println("Host: 192.168.2.116:8040");
    client.println("Content-Type: application/json");
    client.print("Content-Length: ");
    client.println(sizeof(data1));
    client.println();
    client.print(data1);
    Serial.println("1.finish");
  }
  Serial.println("2.finish");
}
else {
  digitalWrite(LED, LOW);
  char data2[] = "{""LDRValue"": 1111111111}";
  Serial.println("\nStarting connection to led server...");
  if (client.connect(server, 8040)) {
    Serial.println("connected to post server");
    client.println("POST /api/sensor HTTP/1.1");
    client.println("Host: 192.168.2.116:8040");
    client.println("Content-Type: application/json");
    client.print("Content-Length: ");
    client.println(sizeof(data2));
    client.println();
    client.print(data2);
    Serial.println("3.finish");
  }
  Serial.println("4.finish");
}
delay(500);
   }
}

It works perfect for the first and second posts in both Arduino and API but at the third post it works fine on Arduino but it takes long time on the API(about 2 minutes to get the post).
The fourth and the fifth posts also works fine but the sixth is same as the third.
Knowing that my API works 100% with Raspberry Pi and it has no errors.
The same thing for PUT and GET.
After Edition:
After I remove the port number from the host line and using strlen(data)instead of sizeof(data), the POST request works but only for first 7th posts. The output of serial monitor on Arduino is like that:
Attempting to connect to WPA SSID: WiFi-Repeater1

WiFi connected
SSID: WiFi-Repeater1
IP Address: 192.168.2.149
signal strength (RSSI):-66 dBm

Starting connection to post server...
connected to post server

Starting connection to post server...
connected to post server

Starting connection to post server...
connected to post server

Starting connection to post server...
connected to post server

Starting connection to post server...
connected to post server

Starting connection to post server...
connected to post server

Starting connection to post server...
connected to post server

Starting connection to post server...

Starting connection to post server...

Starting connection to post server...

Before the Editing, it was always giving me "connected to post server" and It always posts but as I told you before It takes a lot of time at the 3rd 6th 9th 12th ..... Now after the 7th post it will not posts.

Escape the quotes in your strings. Don't include the port number in the HTTP host header. Use strlen() instead of sizeof().

@TisteAndii which quotes to escape ?

@TisteAndii please see the output in the question

I figure out the problem.
To solve the session between Arduino and the server must ended after each Post using  client.stop();
void switch_led() {
      bool SwitchReading = digitalRead(SWITCH);
      if (SwitchReading == HIGH) {
        state = state + 1;
        if (state % 2 != 0) {
          digitalWrite(LED, HIGH);
          char data1[] = "{""LDRValue"": 88888888}";
          Serial.println("\nStarting connection to post server...");
          if (client.connect(server, 8040)) {
            Serial.println("connected to post server");
            client.println("POST /api/sensor HTTP/1.1");
            client.println("Host: 192.168.2.116");
            client.println("Content-Type: application/json");
            client.print("Content-Length: ");
            client.println(strlen(data1));
            client.println();
            client.print(data1);
          }
          client.stop();
        }
        else {
          digitalWrite(LED, LOW);
          char data2[] = "{""LDRValue"": 11111111111}";
          Serial.println("\nStarting connection to post server...");
          if (client.connect(server, 8040)) {
            Serial.println("connected to post server");
            client.println("POST /api/sensor HTTP/1.1");
            client.println("Host: 192.168.2.116");
            client.println("Content-Type: application/json");
            client.print("Content-Length: ");
            client.println(strlen(data2));
            client.println();
            client.print(data2);
          }
          client.stop();
        }
       }

I THINK the problem might be the client.println() statement.  I believe REST messages should be terminated with a \r\n and I think println just does \n.  So if you change it to client.println("\r") it should start working on every message.
Also you might want to consider moving creating the message into a function to reduce the amount of code you have.

It doesn't work.

No it doesn't because it should be client.println(sizeof(data2));  client.println(); client.print(data2); client.println("\r");  I misread that you hadn't added the new line at the end of the message.

It works but the same problem appears. First 2 posts works fine the 3rd needs a lot of time, and then 4th and 5th are ok, 6th same as 3rd.

3rd, 6th, 9th, .......and so on are not working well. But all the other posts works 100%

The pattern that is happening sound like it may be a leak of some sort, or a lack of resources.  You are not leaking memory. Do you need to disconnect or call a function to mark that you have finished? Could it be that the data1 and data2 values need Null terminating and extra space to allow for that?  What does sizeof (data2) actually return, is it right, would strlen(data2) be better? Is your server expecting 8 byte characters or UTF-16, should you message define that?

Please see the output in the question

So it was "Do you need to disconnect or call a function to mark that you have finished?"
Glad it solved. :)

you may wish to do more than just client.stop:
// ensure the client is clean
while (client.connected()) { while (client.available()) client.flush(); }
client.stop();

also; if you are using a WiFi shield; you may want to take a look at a known issue where on a failed connection; the socket isn't released. i simple patch is required to make it work flawlessly:
https://github.com/arduino-libraries/WiFi/issues/5

I've observed that virtually every example of an Arduino web server posted online fails to adhere to the HTTP standard. When a "GET" request is received, the server should parse the "Content-Length: xxx" attribute to get "xxx", then read xxx characters. When sending a web page to a client, the length of the request should be calculated, omitting the HTTP headers (everything before the "html" tag) and the "Content-Length: xxx" attribute should be included in the header, where xxx is the length of the response from "html" tag to "/html" tag, inclusively.
I had the same problem described here, and nothing I did fixed it until I implemented the standard-compliant code described here.

How does this answer the question? The code in the question isn't missing the Content-Length header. If you are commenting on the code in the question as a solution to your problem, then this obviously isn't an answer to the question.

It highlights what the poster is doing right, which the original post didn't draw much attention to. I just spent lots of time figuring this out for myself, and thought highlighting the correct use of Content-Length here might be helpful to others.


text:
how do you capture the top value in a fallen edge in analogs data (flex sensor)
Guys i'm working with a flex sensor and I'm trying to capture a specific value which is the moment before the user lets go of a flexed flex sensor and its represented as the top point of a falling edge as sub picture A in the picture I included. using an array I tried two methods, which can produce a close value at times but at other it will give me wrong values
first I tried the following logic, whenever I detect a value below a certain threshold it indicates that a fallen edge has occurred so get me the value that came right before it as shown in sub picture C but depending on the delay this can be quite unpredictable.
the second method is to store the maximum value of but this returns the peak and it's not always the top of the fallen edge as shown in subpicture B
what do you guys suggest to capture those values?
this is my code so far
bool loaded = false;
int threshold = 760;
int index = 0 ;
int _max=0;
int values[4];
int values_size = 4;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  int data = analogRead(A0);

  if (loaded) {
    values[index] = data;
    if(data>_max){
      _max=data;
      }

    if (data < threshold) {
      loaded = false;
      Serial.flush();
      Serial.print('a');
      Serial.print(',');
      Serial.print(_max);
      Serial.println();
      _max=0;
      delay(300);
    }
    index++;
    index %= values_size;
  }
  else if ( data > threshold && !loaded) {

    loaded = true;
  }

  delay(20);

}

Did you forget the picture?

yeah, sorry about that...it's now up :)

I suggest you consider as “top value of the falling edge” the maximum of
the values you have read during a specified time window before the edge
is detected. This means you have to compute the maximum at the time you
detect the edge. If you instead continuously compute a running maximum,
then you are going to get a global maximum. Amended source:
bool loaded = false;
int threshold = 760;
int index = 0 ;
const int values_size = 4;  // this controls the time window
int values[values_size];

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

void loop() {
  int data = analogRead(A0);

  if (loaded) {
    // Store the reading.
    values[index] = data;
    index = (index + 1) % values_size;

    // Detect falling edge.
    if (data < threshold) {
      loaded = false;

      // Find the max.
      int _max = 0;
      for (int i = 0; i < values_size; i++) {
        if (values[i] > _max) _max = values[i];
        values[i] = 0;  // clear, for next time
      }

      // Report it.
      Serial.flush();
      Serial.print('a');
      Serial.print(',');
      Serial.print(_max);
      Serial.println();
      delay(300);
    }
  }

  // Detect rising edge.
  else if (!loaded && data > threshold) {
    loaded = true;
  }
  delay(20);
}

Notice the line values[i] = 0;. It is intended to avoid the reading of
one falling edge being seen on the next one.

I think this solved my problem, I increased the size of my array to 8 and added index=0 after delay(300) i think you forgot it, and so far the results are as wanted , thank you :)

@Raed: Resetting index doesn't hurt, but it's not really needed: the values array is used as a circular buffer, and when you are in a circle it doesn't matter where you start.


text:
Arduino Mega different SPI Pins
I am working on a project that uses Arduino and Water Level Sensor MS5540C sensor that uses SPI to communicate with Arduino.
When I use Arduino UNO, it was working like a charm using pins 11, 12 and 13, and pin 9 as clock.
Then When I switched to Arduino MEGA, I changed SPI pins to 51, 50 and 52, and I can't get right reads input from the sensor.
Is there any tricks that should be used when switching between Arduino UNO and MEGA ?
Here's the code I use.
Thanks.
#include <SPI.h>
int clock = 9;

void resetsensor() //this function keeps the sketch a little shorter
{
 SPI.setDataMode(SPI_MODE0);
 SPI.transfer(0x15);
 SPI.transfer(0x55);
 SPI.transfer(0x40);
}

void setup() {
 Serial.begin(9600);
 SPI.begin(); //see SPI library details on arduino.cc for details
 SPI.setBitOrder(MSBFIRST);
 SPI.setClockDivider(SPI_CLOCK_DIV32); //divide 16 MHz to communicate on 500 kHz
 pinMode(clock, OUTPUT);
 delay(100);
}

void loop()
{
 TCCR1B = (TCCR1B & 0xF8) | 1 ; //generates the MCKL signal
 analogWrite (clock, 128) ;

 resetsensor();//resets the sensor - caution: afterwards mode = SPI_MODE0!

 //Calibration word 1
 unsigned int word1 = 0;
 unsigned int word11 = 0;
 SPI.transfer(0x1D); //send first byte of command to get calibration word 1
 SPI.transfer(0x50); //send second byte of command to get calibration word 1
 SPI.setDataMode(SPI_MODE1); //change mode in order to listen
 word1 = SPI.transfer(0x00); //send dummy byte to read first byte of word
 word1 = word1 << 8; //shift returned byte
 word11 = SPI.transfer(0x00); //send dummy byte to read second byte of word
 word1 = word1 | word11; //combine first and second byte of word

 resetsensor();//resets the sensor

 //Calibration word 2; see comments on calibration word 1
 unsigned int word2 = 0;
 byte word22 = 0;
 SPI.transfer(0x1D);
 SPI.transfer(0x60);
 SPI.setDataMode(SPI_MODE1);
 word2 = SPI.transfer(0x00);
 word2 = word2 <<8;
 word22 = SPI.transfer(0x00);
 word2 = word2 | word22;

 resetsensor();//resets the sensor

 //Calibration word 3; see comments on calibration word 1
 unsigned int word3 = 0;
 byte word33 = 0;
 SPI.transfer(0x1D);
 SPI.transfer(0x90);
 SPI.setDataMode(SPI_MODE1);
 word3 = SPI.transfer(0x00);
 word3 = word3 <<8;
 word33 = SPI.transfer(0x00);
 word3 = word3 | word33;

 resetsensor();//resets the sensor

 //Calibration word 4; see comments on calibration word 1
 unsigned int word4 = 0;
 byte word44 = 0;
 SPI.transfer(0x1D);
 SPI.transfer(0xA0);
 SPI.setDataMode(SPI_MODE1);
 word4 = SPI.transfer(0x00);
 word4 = word4 <<8;
 word44 = SPI.transfer(0x00);
 word4 = word4 | word44;

 long c1 = word1 >> 1;
 long c2 = ((word3 & 0x3F) << 6) | ((word4 & 0x3F));
 long c3 = (word4 >> 6) ;
 long c4 = (word3 >> 6);
 long c5 = (word2 >> 6) | ((word1 & 0x1) << 10);
 long c6 = word2 & 0x3F;

 resetsensor();//resets the sensor

//Temperature:
 unsigned int tempMSB = 0; //first byte of value
 unsigned int tempLSB = 0; //last byte of value
 unsigned int D2 = 0;
 SPI.transfer(0x0F); //send first byte of command to get temperature value
 SPI.transfer(0x20); //send second byte of command to get temperature value
 delay(35); //wait for conversion end
 SPI.setDataMode(SPI_MODE1); //change mode in order to listen
 tempMSB = SPI.transfer(0x00); //send dummy byte to read first byte of value
 tempMSB = tempMSB << 8; //shift first byte
 tempLSB = SPI.transfer(0x00); //send dummy byte to read second byte of value
 D2 = tempMSB | tempLSB; //combine first and second byte of value

 resetsensor();//resets the sensor

 //Pressure:
 unsigned int presMSB = 0; //first byte of value
 unsigned int presLSB =0; //last byte of value
 unsigned int D1 = 0;
 SPI.transfer(0x0F); //send first byte of command to get pressure value
 SPI.transfer(0x40); //send second byte of command to get pressure value
 delay(35); //wait for conversion end
 SPI.setDataMode(SPI_MODE1); //change mode in order to listen
 presMSB = SPI.transfer(0x00); //send dummy byte to read first byte of value
 presMSB = presMSB << 8; //shift first byte
 presLSB = SPI.transfer(0x00); //send dummy byte to read second byte of value
 D1 = presMSB | presLSB;

 const long UT1 = (c5 * 8) + 20224;
 const long dT =(D2 - UT1);
 const long TEMP = 200 + ((dT * (c6 + 50))/1024);
 const long OFF  = (c2*4) + (((c4 - 512) * dT)/4096);
 const long SENS = c1 + ((c3 * dT)/1024) + 24576;

 long PCOMP = ((((SENS * (D1 - 7168))/16384)- OFF)/32)+250;
 float TEMPREAL = TEMP/10;
 Serial.print("pressure =    ");
 Serial.print(PCOMP);
 Serial.println(" mbar");

 const long dT2 = dT - ((dT >> 7 * dT >> 7) >> 3);
 const float TEMPCOMP = (200 + (dT2*(c6+100) >>11))/10;
 Serial.print("temperature = ");
 Serial.print(TEMPCOMP);
 Serial.println(" °C");
 Serial.println("************************************");

 delay(300);
 }

Transferring Pin 9 to 12 truly works. Thanks.

The problem was basically because some limitations in Arduino MEGA,
You can't use pin 9, instead use pin 12.
It works like a charm.
Thanks.


text:
Using only Rx pin to receive data from HC 05 and attiny85 (Arduino IDE)
I was building a Bluetooth car with attiny85 (Arduino IDE) and HC05 bluetooth module. I need 4 IO pins to control the car. Since attiny have only 5vIO's, I am left with only 1 pin to connect to HC05. I would only be receiving data from HC05. So, I want to use that leftover pin as RxD to receive data.

#include //the software serial library
#define RxD 4

SoftwareSerial blueToothSerial(RxD);

But when I do this It gives the following error

No matching function for call to 'SoftwareSerial::SoftwareSerial(int)'
Though it works fine, when I also define a TxD pin. But I want to use only one pin (RxD). Please help.

This constructor SoftwareSerial(rxPin, txPin, inverse_logic) requires two parameters (regarding the pins), and according to the error message, there is not any constructor with only one parameter. You could try to call it with an invalid pin number (e.g. 99) for TX, so if it checks for valid pins it will just skip the initialization of an invalid pin number.

I suggest you get rid of SoftwareSerial and use instead this Simple
ATtiny USI UART. This is a driver
for a receive-only UART that uses the USI port of the ATtiny85. It is
superior to a software-only UART as it makes good use of the hardware,
leaving more time for the CPU to do more useful things (or sleep and
save battery). Also, unlike SoftwareSerial, it does not need to block
interrupts for long periods, which is a good thing.

The constructor for the SoftwareSerial object expects to be given both a TX and and RX pin (and, optionally, a boolean value representing whether or not it should use inverse logic.) From SoftwareSerial.h, see:
SoftwareSerial(uint8_t receivePin, uint8_t transmitPin, bool inverse_logic = false);

If you want to use the library in the way you've written, you'll need to either modify the existing constructor or write a new one into the library.
As a quick test, I've added the following lines to each of the listed source files:
SoftwareSerial.h
SoftwareSerial(uint8_t receivePin, bool inverse_logic = false);

SoftwareSerial.cpp
SoftwareSerial::SoftwareSerial(uint8_t receivePin, bool inverse_logic /* = false */) :
_rx_delay_centering(0),
_rx_delay_intrabit(0),
_rx_delay_stopbit(0),
_tx_delay(0),
_buffer_overflow(false),
_inverse_logic(inverse_logic)
{
  setRX(receivePin);
}

Now there's a constructor that allows for a single RX pin argument like you've outlined in your initial example. The problem is that this is likely to break anytime the Arduino codebase gets updated and your changes get blown away.
Best practice may dictate writing your own driver to use the serial functionality of your ATTiny without the possibility of accidentally using the TX functions, but if this is a one-off then maybe Bence Kaulics' suggestion of just feeding it a nonsense pin would be the least time-consuming.


text:
Serial clock for SPI
I'm trying to configure my ADC(LM98725) registers through Arduino UNO via SPI but I'm facing a small problem, it would be great if somebody help me out. I have to configure my 16 bit ADC registers which needs 25+ clocks but right now I'm getting 16 SCLK with my 16 bit data output on MOSI pin, there is no SCLK signal without data output. How can I increase the number of SCLK for my ADC?
To write to the serial registers, the timing diagram shown in a diagram. First, SEN is toggled low. The LM98725 assumes control of the SDO pin during the first eight clocks of the command. During this period, data is clocked out of the device at the rising edge of SCLK. At the rising edge of ninth clock,the LM98725 releases control of the SDO pin. At the falling edge of the ninth clock period, the master should assume control of the SDI pin and begin issuing the new command. SDI is clocked into the LM98725 at the rising edge of SCLK. The remaining bits are composed of the "write" command bit (a zero), two device addressbits (00, 01 or 10 for the LM98725), five bit register address to be written, and the eight bit register value to be written.
#include <SPI.h>

int ss=10;
int DATAOUT=11;
int DATAIN=12;
int SCLK=13;

void setup()
{
    SPI.begin();
    pinMode(DATAOUT, OUTPUT);
    pinMode(DATAIN, INPUT);
    pinMode(SCLK, OUTPUT);
    pinMode(ss, OUTPUT);
    digitalWrite(ss, HIGH);
    SPI.beginTransaction(SPISettings(1000000, MSBFIRST, SPI_MODE0));
}

void loop()
{
    digitalWrite(ss, LOW);
    SPI.transfer16(0x02c6);
    digitalWrite(ss, HIGH);
}

Did you try a dummy write? Can you show us your code?

Its a simple code I just want to send 16 bit data to my ADC but I only have 16 SCLK pulses and I need 25 pulses.

You are transferring only 16 bits. You should transfer at least 25, or rather 32 since it must be a multiple of 8.

on the first 8 clocks my ADC sends data on MISO pin and then it starts receiving data from the 10th clock. If I sends 32 bit data the first 9 bits would be dummy and then my 16bits for the register configuration and then again the last 7 bits have to be dummy. That's what you are saying?

No. According to the graph, all the dummy bits (bits marked "x") should be sent before the register configuration.

Yeah but how? As its written in the description that  from the rising edge of ninth clock,the LM98725 releases control of the SDO pin and at the falling edge of the ninth clock period, the master should assume control of the SDI pin and begin issuing the new command. SDI is clocked into the LM98725 at the rising edge of SCLK.

So according to this it will start taking bits from the 10th clock for writing register that's what I understand.


text:
Wired IoT sensor network with PoE?
Objective: Maybe I'm a bad Googler, but I am finding very little on wired Internet of Things sensor networks using Arduino.
Project Goals:

Arduino based sensor nodes that connect to the local network (not out to the internet)
All the benefits of adding adding/removing nodes, moving nodes, adding new routers for more ports.
Black box sensors that don't take any soldering to plug into the network (although they contain soldered components in the black box.
Using a master Raspberry Pi on the network to identify the nodes and read data from them.
Using Power over Ethernet (PoE) to power my sensor nodes.
Don't want to actually connect to the outside internet, just want the convenience of assembling a network with node names and such.

Why not use wireless solutions (e.g. XBee):
Currently, it seems Xbee is the way to go, but I don't want a wireless solution.

I want the reliability of a wired connection.
I don't want to have to worry about batteries

What I'm doing right now:
Currently, I have all my sensors wired to a central Arduino MEGA using 4-conductor security cable (Vcc, GND, and two signal conductors). The MEGA communicates over serial with a Raspberry Pi. This is annoying for the following reasons:

I have to solder/unsolder every time I want to change something.
I have to figure out which digital I/O pins are available on the MEGA and have to write down which signal conductor goes to which pin on the MEGA and means what on the sensor.
There is a finite number of pins.
Each sensor is its own unique project. I want to start standardizing these sensors to clean up the code.

What I have found so far:
I've been looking at XPort sensors; however they are very expensive (i.e. $60 ea.) and don't support PoE. If there is a solution using Arduino and an Ethernet Shield, it brings down the base cost of a sensor by a lot.
Request:
Where can I find out more information about wired Arduino sensors? Are there any prebuilt solutions that already do what I am looking for?

Since you don't want to connect to the internet, you could just use any protocol over those ethernet cables (they are just copper wires). Something like RS485.

I was hoping to be able to use pre-existing equipment to handle some of the work for me (i.e. add new ports by adding routers/switches, having them assign new addresses automatically).

MySensors.org supports RS485, while qualifying as an IoT platform. It might be worthwhile to consider ethernet<->serial gateways.

I think I am using a setup like you wish at my home:

PoE Switch (for example Cisco SG300-28P)
Arduino Ethernet's with PoE Module (https://www.arduino.cc/en/Main/ArduinoBoardEthernet) I bought one for every room ;-)
Use DHCP-Server on raspberry PI
Put your sensors on your Arduino ethernet board
I am also using MQTT as protokoll for example http://pubsubclient.knolleary.net/
Use MQTT broker Mosquitto on raspberry pi

For the case that you want to use your switch also for internet connectivity, define a vlan (search wikipedia) for your arduino sensor network.
Hope that helps.

I'm curious how/where you bought the Arduino PoE modules.  Everywhere I look they're "retired" and unavailable.

Because I am located in Germany, I bought them at:
Watterott.com also Exp-Tech.de has them available (at the moment ;-) It is no problem to solder the PoE Modules yourself into ethernet shields.

Ah, yes I have seen those modules here in the US as well that you can add to the Ethernet shield, it just seemed rather costly ($13 for the module + ~$30 for the shield + the arduino cost itself).  I managed to find a complete PoE shield on ebay for $20 but that was a one time deal and I'd like to build several.  Thanks for the help.

Enviromon.net has PoE sensors that are plug and play with their base units. The base unit is then connected to your internal network.
If your a bit more experienced (which it seems you are) their base units can also be integrated into other systems like network monitoring apps, and SCADA programs.
You could most likely configure the base unit to slave to your raspberry pi, and bonus, no soldering. All their sensors are PoE. Although unfortunately they are not for the Arduino.
But you mentioned if anyone knew if there was a prebuilt solution.
Heres a link to their sensors you might be interested in http://www.enviromon.net/environmental-monitoring-sensors/

Please note if you want to promote your own product/blog you must disclose your affiliation in the answer, otherwise your answer may be flagged as spam. Please read How to not be a spammer

If you are not affiliated with the site, I recommend you mention it to prevent this.