text:
Is it safe to power an MQ-7 gas sensor with a 9V D.C supply?
I'm looking for a portable power source for an MQ-7 gas sensor. According to my research - it needs 5V D.C power with at least 0.3A of current. I'm not really good with electronics so I need to know if I can use a 9V battery instead which produces 0.5A. Will the cell damage my sensor and if it does may you please recommend me something else.

I don't think a 9V battery can supply 0.5A.

You can, but you will have to reduce the voltage to the 5V the sensor needs, otherwise you will blow up the sensor.
To that end you require a voltage regulator. You can use a linear regulator like the Arduino has on-board, but they are very wasteful of power and will dissipate the excess 4V of electricity as heat.
Better would be to use a switching regulator (commonly and cheaply available on eBay and other sites) to step the voltage down to 5V more efficiently.

Thanks. I was considering a voltage regulator but I'm not sure If that can be shipped to where I live in a week without extra costs. Can I use 4x AAA cells instead?

It requires 5V ±100mV, so 4.9V to 5.1V. 4 AAA alkeline is 4x1.5 = 6V (too high). 4 AAA NiMh is 4x1.2 = 4.8 (too low).  You might get away with 4x NiMh at a pinch, but as they discharge the voltage will drop and it will fail.

Ok, so do  4 AAA NiMh cells provide 0.3A as well?

They can provide considerably more than that. They will last much longer than a 9V PP3 which would be lucky to last an hour.

Thanks, so I can safely use 4 AAA NiMh? I don't mind them not lasting over an hour - I just need to make a demonstration then I order a voltage regulator to create a proper circuit!

Yes, that should work OK.


text:
How do I use SNAP protocol, correctly?
I've reviewed the documentation
I'm still a little lost when it comes to applying the functions. Each of the redundancy check methods take in an unsigned char and return an unsigned char.
Shouldn't there be some sort of boolean return somewhere confirming that the data is accurate?
I've been trying to debug unsigned char* tempData = "snap" to the terminal, writing it directly to the register, according to the doc it should return h17:
  UDR0 = crc8(tempData,sizeof(tempData));

The terminal outputs '?' - as if it cannot be read.

Whereabouts are these functions you are using?

This was the only AVR-GCC example implementation of the protocol: http://www.hth.com/filelibrary/snap/usrcode/GCC01.ZIP

The crc8 function calculates the Cyclic Redundancy Check (8-bit) value for the data you provide. It is then up to you to compare that calculated value with the CRC you have received.
The ? you are seeing in the serial terminal is an unprintable character. It is representing an 8-bit value that doesn't lie within the 32-127 range of normal ASCII characters, or 32-255 of the extended ASCII character set.

Okay! Is this appropriate moving forward?

On the transferring node store the value crc8() returns and call it the 'checksum' , then send it as part of the payload.
On the receiving node call crc8() on incoming tempData and compare it to checksum?

I'm sort of concerned that even if this works my implementation is to simple and I'm missing something. I might try another protocol that has stronger avr examples

The SNAP specification seems very wooly. I'd try something more rigidly defined with proper libraries.  Depending on what you want to achieve my ICSC library might work well for you.

My needs are pretty straight forward, I just need to validate incoming packets. Your library looks solid but I'm not running off Arduino. I think it would be challenging to port.

source: Stack Exchange

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

sort: votes


text:
Extracting a substring from original string
I am trying to extract a substring out of another string, but it doesn't seem to be working. I am new to programming in arduino and c++ in general. Here is my code:
void setup()
{
    Serial.begin(9600);
}

char rfid;

void loop()
{
  while (Serial.available() > 0)
  {
    rfid = Serial.read();
    String cardnum(rfid);
    cardnum.replace("", "");
    cardnum.replace("", "");
    String id = cardnum.substring(0,2);
    Serial.print(id);
  }
}

The first argument in cardnum.replace("", ""); and cardnum.replace("", ""); replaces the start and end bit with nothing, but it somehow doesn't display it correctly here.
Now on to the problem at hand. The output for cardnum is 1F006B471F2C which it should be, but the ouput for id is the same, when i want it to be only the first two characters of cardnum. How would i go about achieving that.
Thanks in advance for any answers you can provide.

First off you're not reading the serial properly. You should read and digest this before you go any further: https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/

The entire while{} loop executes once for each character you read - is that what you intend? I suspect your intent was to read the the whole string and then modify it. If so, perhaps you'd find the Serial.readBytes() function useful.

Thanks for your answers. Yes my intent was to read the whole string. This helps me out a lot.

Let's dissect your program a moment and see why it's not doing what you want:
while (Serial.available() > 0)
{

So while there are characters available to read in the serial buffer
  rfid = Serial.read();

read one character into the rfid variable.
  String cardnum(rfid);

Convert that character into a string.
  cardnum.replace("", "");

Replace nothing ("") with nothing ("")
  cardnum.replace("", "");

Do the same again,
  String id = cardnum.substring(0,2);

Take the first two characters of the string that contains the single character that you have read.
  Serial.print(id);

Print it.
So basically you have read one character, made it into a string, done nothing to it, copied it to another string, then printed it.
Instead of this method, which does nothing useful, you should read the whole ID into a string (I'd use a C string [i.e., char array] rather than an Arduino String object) then perform operations on that string once you have read the whole ID code.
There's many methods of doing that, but how you do it is heavily influenced by exactly how the data is presented to you. Does it have a terminating CR or LF to indicate the end of the string? If not you will have to use some form of timeout to determine when the string has been completer.

Thanks for your answer. cardnum.replace("", ""); replaces the bit that signals the start and the end of the id with nothing. It looks like there is nothing because Stackexchange can't display the symbol. When i print cardnum it displays 1F006B471F2C. So it should have read more than one character i assume.

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


text:
Looking for a Mega 2650 drawing or picture that shows the components labeled
I am Looking for a Mega 2650 drawing or picture that shows the components labeled.
I've seen the schematics but didn't find a labeled assembly drawing yet.  Should this exist?
Thanks

Yes, it exists, but not (commonly) as an "image" in the traditional sense.
You need to install Eagle PCB design software and open the PCB file downloadable from the Arduino site from where you can see exactly which component is where.

Hi thanks for responding.  I got Eagle installed and downloaded the files from the arduino website.  Thanks. It would still be nice to have a labeled picture to easily tell what the components are.


text:
Trying to start a timer to change lights when a button is pressed
I am trying to setup a series of lights (traffic lights) that change based on a timer that begins when a button is pressed.  The goal is to use the lights to track how long its been since you pressed the button.
The issue I am running into is trying to use the "TimeAlarms" library.  I am getting an error
'Timer' was not declared in this scope
I think it may be an issue with the version of Arduino I am using (1.6.8) but I am not sure.
Board: Arduino Leonardo
Here the code:
#include <TimeAlarms.h>
#include <Time.h>
#include <TimeLib.h>

int redPin = 2;
int yellowPin = 3;
int greenPin = 4;
int buttonPin = 5;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  while (!Serial) ;
  pinMode(redPin, OUTPUT);
  pinMode(yellowPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(buttonPin, INPUT);
  // set timers in seconds, yellow = 24 hours, red = 48 hours)
  // http://www.pjrc.com/teensy/td_libs_TimeAlarms.html
  Alarm.timerOnce(86400, YellowTimer);
  Alarm.timerOnce(172800, RedTimer);

}

void loop() {
  // put your main code here, to run repeatedly:
  if (digitalRead(buttonPin))
  {
      setLights(LOW, LOW, HIGH)
      void YellowTimer(){
         setLights(LOW, HIGH, LOW)
         }
      void RedTimer(){
         setLights(HIGH, LOW, LOW)
         }
  }
  delay (1000);
  }

void setLights(int red, int yellow, int green)
{
  digitalWrite(redPin, red);
  digitalWrite(yellowPin, yellow);
  digitalWrite(greenPin, green);
}

Any help would be greatly appreciated.

Please use "code sample" button to display the code. It is very hard to read like you pasted now.

thank you Mattia,  I am brand new here and appreciate the formatting help.

@Chris no problem welcome in the community. Also remember that if you want to write something to someone (as you just did in the comment with my name) it's better to mention the name with [at] in order to reach the attention to the particular person (i.e., @Mattia) ;-)

You must first declare your timer functions. I have placed them above so they are visible when you call the timer. Also in the loop() you want probably to call timer.
I have changed the code to reflect what I told above. I do not have ability to test this, so please try. There may be some syntax errors, but I think you can handle it.
#include <TimeAlarms.h>
#include <Time.h>
#include <TimeLib.h>

int redPin = 2;
int yellowPin = 3;
int greenPin = 4;
int buttonPin = 5;

void YellowTimer()
{
    setLights(LOW, HIGH, LOW)
}

void RedTimer()
{
    setLights(HIGH, LOW, LOW)
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  while (!Serial) ;
  pinMode(redPin, OUTPUT);
  pinMode(yellowPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(buttonPin, INPUT);
  // set timers in seconds, yellow = 24 hours, red = 48 hours)
  // http://www.pjrc.com/teensy/td_libs_TimeAlarms.html
  Alarm.timerOnce(86400, YellowTimer);
  Alarm.timerOnce(172800, RedTimer);

}

void loop() {
  // put your main code here, to run repeatedly:
  if (digitalRead(buttonPin))
  {
      setLights(LOW, LOW, HIGH)
      Alarm.timerOnce(86400, YellowTimer);
      Alarm.timerOnce(172800, RedTimer);
  }
  delay (1000);
  }

void setLights(int red, int yellow, int green)
{
  digitalWrite(redPin, red);
  digitalWrite(yellowPin, yellow);
  digitalWrite(greenPin, green);
}


text:
Why does the arduino respond so slow to serial input
I have this really simple sketch where I blink a led light.
If I send another value threw the serial monitor then first there is always a brief second where the light doesn't blink anymore. Why is that, and how can I get rid of that?
int the_delay = 300;

void setup() {
  Serial.begin(115200);
  pinMode(12, OUTPUT);
}

void loop() {
  digitalWrite(12, HIGH);
  delay(the_delay);
  digitalWrite(12, LOW);
  delay(the_delay);
}

void serialEvent() {

  if (Serial.available()) {
    the_delay = Serial.parseInt();
    Serial.println(the_delay);
  }
}

In case it helps, eventually I would like to send values with 60fps.

It's because you're using Serial.parseInt().  It uses a timeout to find the end of the data on the serial port, and while it's waiting for that timeout it can do nothing else.
You would be better off manually reading the serial data a character at a time to build up an input string (C-string, not Arduino String) with a proper line terminator (line-feed, \n) and then convert that into an integer with atoi().

Try typing a non-digit character after the delay value; even Enter should work if your terminal is configured to send any kind of end-of-line. Serial.parseInt() waits the full timeout (default: 1000 ms) after each digit, for the next one. A non-digit will end the input value immediately.

See How to process incoming serial data without blocking. An interim solution is to get the Serial Monitor to send a newline automatically when you press Send.
Here is example code that processes input without blocking:
// Example of processing incoming serial data without blocking.

// how much serial data we expect before a newline
const unsigned int MAX_INPUT = 50;

void setup ()
  {
  Serial.begin (115200);
  } // end of setup

// here to process incoming serial data after a terminator received
void process_data (const char * data)
  {
  // for now just display it
  // (but you could compare it to some value, convert to an integer, etc.)
  Serial.println (data);
  }  // end of process_data

void processIncomingByte (const byte inByte)
  {
  static char input_line [MAX_INPUT];
  static unsigned int input_pos = 0;

  switch (inByte)
    {

    case '\n':   // end of text
      input_line [input_pos] = 0;  // terminating null byte

      // terminator reached! process input_line here ...
      process_data (input_line);

      // reset buffer for next time
      input_pos = 0;
      break;

    case '\r':   // discard carriage return
      break;

    default:
      // keep adding if not full ... allow for terminating null byte
      if (input_pos < (MAX_INPUT - 1))
        input_line [input_pos++] = inByte;
      break;

    }  // end of switch

  } // end of processIncomingByte

void loop()
  {
  // if serial data available, process it
  while (Serial.available () > 0)
    processIncomingByte (Serial.read ());

  // do other stuff here like testing digital input (button presses) ...

  }  // end of loop

Edit as follows:
Serial.begin(115200);
Serial.setTimeout(10); //Maximum time in ms that it should wait for data
The default delay is 1000ms.
The code above sets it to 10ms.
Play around with the Timeout value and check for faults.
https://www.arduino.cc/reference/en/language/functions/communication/serial/settimeout/

This is good so far as it goes. But, it seems mostly a repeat of an existing answer.

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


text:
Arduino Nano - Upload verification error
I'm new to Arduino; and I'm trying to upload a simple sketch to a new Arduino Nano
I tried a few sketches (blink / helloworld / empty one); and changing the USB PORT.
Windows find the correct serial port (but it's a CH340 USB-Serial; I think that's some Chinese clone).
I tried a few USB ports.
When I upload the sketch, it seems to upload. But a verification error appears:
avrdude: verifying ...
avrdude: verification error, first mismatch at byte 0x00ea
         0x8c != 0x8d
avrdude: verification error; content mismatch

This is the command line
D:\Arduino\hardware\tools\avr/bin/avrdude -CD:\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM6 -b57600 -D -Uflash:w:C:\Users\corti\AppData\Local\Temp\build462236accad2415310c5b24cce7ccca0.tmp/Blink.ino.hex:i

This is the full verbose log of the flashing:
avrdude: Version 6.0.1, compiled on Apr 15 2015 at 19:59:58
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "D:\Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM6
         Using Programmer              : arduino
         Overriding Baud Rate          : 57600
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : Arduino
         Description     : Arduino
         Hardware Version: 2
         Firmware Version: 1.16
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e950f
avrdude: reading input file "C:\Users\corti\AppData\Local\Temp\build462236accad2415310c5b24cce7ccca0.tmp/Blink.ino.hex"
avrdude: writing flash (1066 bytes):

Writing | ################################################## | 100% 0.32s

avrdude: 1066 bytes of flash written
avrdude: verifying flash memory against C:\Users\corti\AppData\Local\Temp\build462236accad2415310c5b24cce7ccca0.tmp/Blink.ino.hex:
avrdude: load data flash data from input file C:\Users\corti\AppData\Local\Temp\build462236accad2415310c5b24cce7ccca0.tmp/Blink.ino.hex:
avrdude: input file C:\Users\corti\AppData\Local\Temp\build462236accad2415310c5b24cce7ccca0.tmp/Blink.ino.hex contains 1066 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 0.24s

avrdude: verifying ...
avrdude: verification error, first mismatch at byte 0x00ea
         0x8c != 0x8d
avrdude: verification error; content mismatch

Run through some of the suggestions here and see what happens.

(but it's a CH340 USB-Serial; I think that's some chinese clone) Good luck with that then. Those CH340s aren't the most reliable chips around.

Have you tried just uploading blink through the IDE?

Yes, I tried any kind of sketch. I also tried to reflash the bootloader (and went just fine).  When I write something with serial monitor, leds blinks /but no answer/

Have you installed drivers for CH340?

@Lipsyor with no drivers you can't even get to that point

I have seen this once before when one of my mates was having troubles programming a ATMega328P on a custom board. It turned out to be his physical serial port. We later confirmed it with a scope - indeed the first packet wasn't what it was meant to be sending. So we switched to a USB-to-Serial dongle that I had and the problem was resolved.
In your case, I highly suspect that it is the CH340 to blame here.
Try programming the Adruino with the AVRISPmkII or another USB-to-TTL converter.
Edit: Alternatively you could program your microcontroller using a genuine Arduino Uno board (such as a friends) and then place it back onto your board.


text:
a mega 2650 power supply mystery
Something happened to my mega2650 as I was experimenting the other day.  It no longer turned on when powering from the 2.1mm jack or from Vin, regardless of the voltage applied.  A plastic bubble had formed on the 5V regulator, I assumed I had shorted something and fried it.  If I applied 5V to the 5V pin everything worked fine.  It also works fine when powered from USB.  So I replaced the 5V regulator with a NCP1117 version.  But I have the same situation.  If I apply voltage directly to the 5V regulator input pin I get 5V on the output pin and everything is fine.  I tested up to 12V and it is dead on at 5V.  I also checked the PNP switching transistor, and found it was working correctly.  As far as I can tell, the only thing remaining is that the trace is severed somewhere between just after the Vin pin and the 5V regulator, maybe the regulator input is not soldered well to the trace?  But this was one of the better solder joints I made, so I thought.  Any other ideas as to the root cause?
Thanks

How about D1? The M7 diode. Try testing before and after that with power applied to the power jack.

I wonder if I should do a forensic nuking of my Mega2560? Connect it to a nice meaty PSU and short the 5V, see exactly what does happen besides the Magic Smoke™ escaping from the 1117...

@NickGammon I know of one very popular board designed by an associate of mine that uses a 500mA diode on both the USB and main power inputs leading to the Vin of an 800mA 3.3V regulator.  Short out the 3.3V power and the diode feeding the power at the time literally blows itself clean off the board.

What I did was power the mega by 12v to Vin.  But, I also powered a LED constant current boost driver from the same 12v terminals.  I had the usb plugged in for programming.  When I switched off the 12v battery, then the usb was now powering the mega and the boost driver via Vin header pin instead of receiving power from it.  There was 5v reverse voltage across the 5v reg.

You obviously have some form of DMM or volt meter at your disposal, since you know the voltages around the regulator.
Some places you should, therefore, probe for voltages, and what voltages you should expect.  With the barrel jack connected and powered up, and assuming a 12V supply, you should expect:

At the rear of the socket: 12V
At the socket side of the M7 diode: 12V
At the header side of the M7 diode: 11.4V
At the right-hand (VIN) pin of the regulator: 11.4V
On the tab of the regulator: 5V

If you find any of those are wrong then the component that comes before it may well be faulty.

Ok, I checked and found these:  11.14 at battery;  11.14V at Vin header pin;  11.14V at D1 +; 11.14V at D1 - ;  0V at 5V header pin;  0V at 3.3V header pin;  0V at IC1 (5V reg) at all 3 pins; 0V at IC5B (comparator) at all 6 pins; 0V at T2 (5V switch) at a 3 pins; 0V at IC6 (3.3V regulator) at all 5 pins.  If I look close it appears the 3.3V reg also has some visible heat damage but slight.  So in this case it seems to me a power supply smoothing capacitor is at fault.

I got EagleCAD - wow that is extremely helpful.  The trace between the PC1 smoothing cap and the 5V reg. must be open because the cap terminal is at Vin, probably a bad solder job on the 5V reg.  Thanks.

Well the answer is ... I fried the rest of the board when I was trying to troubleshoot it further :(  I think 12V went to the 328p, it got hot.  Oh well, thanks everyone!


text:
Forensic security of Arduino (SRAM)
Pardon the double post, but I'm not getting much traction with this question over at arduino.cc so I'm looking for answers here now.
Original post: http://forum.arduino.cc/index.php?topic=391698.0

I get the idea of uploading a "stop" sketch for the purpose of
  overriding a previously uploaded program in Flash memory space.
Then of course we have EEPROM for "long-term" storage.
However, let's say an Arduino: Read user input as secret key and store
  in memory (SRAM) Performed a signing operation with secret key
  Subsequently powered off
We know that computers introduce a wide range of complications to
  security because data can still be recovered, even after being erased
  or overwritten in some cases, variables stored in memory float around
  (unless pinned for decryption in SecureString contexts, etc.), etc.
To establish context for the following questions, let's [overly]
  simplify the attack vector in saying this would be a scenario where an
  Arduino used in a security application is physically disconnected,
  stolen, and then powered on sometime later.
Question 1: Obviously we're not talking about storing keys on disk
  necessarily (i.e. EEPROM). How likely (or difficult) would it be to
  analyze SRAM with the intent to recover keys that may have been
  previously stored in memory?
Question 2: Similarly, let's say sensitive information was in fact
  stored in EEPROM.  Does the same hold true of data previously stored
  in EEPROM that has since been overwritten with new (i.e. zero) data?

Any help would be greatly appreciated. Thanks!

As the others already said, if it is in RAM as soon as you power it off your key is gone. If you want to be really safe, overwrite the key as soon as you stop using it. If you store it in EEPROM, theoretically it is recoverable, but practically it isn't (it would require the "attacker" to tear apart the uC case, estract the silicon die, know where are the eeprom cells and read it with costy  equipment. But before doing this, probably they already guessed your password (or brute-forced it)

RAM can be retained for a while under certain circumstances. Read e.g. this article http://wp.josh.com/2014/03/03/the-mystery-of-the-zombie-ram/

Mystery of the zombie RAM, nice. I just read about this recently in an electronics book that LEDs not only give off light, but can produce a tiny current if light is shown onto it, "enough to sustain RAM indefinitely." So don't forget to bring a flashlight along with your liquid nitrogen (RE: Nick Gammon) :)

RAM memory looses its contents when it's powered off. However, this
natural erasure process is not instantaneous: it can take several
seconds, or even minutes. It has been demonstrated that cooling down a
memory chip can extend its data retention time to hours, which enables
a type of attack known as cold boot
attack.
This type of attack has been studied mostly on DRAM computer modules.
The Arduino memory, however, is based on SRAM, which is physically very
different from DRAM (a transistor feedback loop vs. a capacitor). There
seems to be very little research on cold boot attacks against SRAM. I
found nonetheless a technical report from the computer laboratory of the
University of Cambridge: Low temperature data remanence in static
RAM, by Sergei
Skorobogatov. Quoting from the conclusion:

Contrary to the established wisdom, there are several chips that
  retain data for dangerous periods of time at temperatures above −20°C.
  The temperature at which 80% of the data are retained for one minute
  varies widely between devices. Some require cooling to at least −50°C,
  while others retain data for this period at room temperature.
  Retention times can be significantly reduced by shorting VCC to ground
  rather than by leaving it floating.

From this perspective I would say that, although the attack seems non
obvious, your secret key is not completely safe even in SRAM. Since the
data retention time varies widely between devices, it could be worth
testing on your Arduino. If possible, I would suggest you overwrite the
key after the signing operation.

Update: I did a quick test on my Arduino Uno, at room temperature,
by just unplugging and plugging back the board. Here is my test code:
// This memory buffer will not be zeroed at startup by the C runtime.
uint8_t __attribute__((section(".noinit"))) buffer[1024];

void setup()
{
    Serial.begin(9600);
    Serial.println(F("Program started."));
}

void loop()
{
    switch (Serial.read()) {
        case 'i':  // Initialize the buffer with pseudo-random bits.
            srand(42);
            for (size_t i = 0; i < sizeof buffer; i++)
                buffer[i] = rand();
            Serial.println(F("Buffer initialized."));
            break;
        case 'f':  // Report number of flipped bits.
            int count = 0;
            srand(42);
            for (size_t i = 0; i < sizeof buffer; i++) {
                uint8_t mask = buffer[i] ^ rand();
                while (mask) {
                    count += mask & 1;
                    mask >>= 1;
                }
            }
            Serial.print(F("Flipped bits: "));
            Serial.print(count);
            Serial.print(F(" / "));
            Serial.println(8 * sizeof buffer);
    }
}

And this is the output, with my comments on the right:
Program started.            ← fresh boot
Buffer initialized.         ← pressed 'i'
Program started.            ← pressed the reset button
Flipped bits: 0 / 8192      ← pressed 'f'
Program started.            ← unplugged and plugged back
Flipped bits: 4166 / 8192   ← pressed 'f'

It appears the RAM is preserved across a warm reboot (pressing the reset
button), but it is completely lost after a power cycle: half the bits
flipped is a total loss of information. I tried to do this as fast as I
could, which is slightly less than one second. It would seem the SRAM in
the ATmega chips decays pretty fast, at least at room temperature.

Update 2: I found an enlightening story about an unpowered AVR
keeping data in RAM for more than 10 minutes, but only on mornings:
The mystery of the Zombie
RAM.

Sounds good, but if I was going to burst into a room with liquid nitrogen to cool down the chip, I would arrive a minute earlier, and make sure that the chip wasn't powered down in the first place.

+1 for conducting your own separate tests to validate existing research :)

Uploading a new sketch using the IDE does "page erases" which means that a small sketch will not completely replace a larger one. However using a ICSP programmer starts with a complete flash erase, so that would be more secure. Or you could probably (and it would be better to) upload a new sketch containing mostly random data (eg. a large array in PROGMEM).
Rewriting EEPROM should be pretty secure, especially if you replace the EEPROM with random data, and preferably do it a number of times.
As for SRAM, I would be surprised if you could recover much after a power-off. If the attacker manages to keep the power on that would be different. If possible, write over sensitive data with random bytes as soon as you don't need it any more.
If the data has to stay in RAM, I could envisage a scenario where if I got access to the processor (still powered on) I would upload a small sketch which would simply dump RAM to (say) the serial port a byte at a time, to avoid needing much RAM to do the dumping.
I think the AVR processors at least would be comparatively safe. After all they don't have disks, virtual memory, or fancy remapping of sectors like a USB stick might.

Read user input as secret key and store in memory (SRAM) Performed a signing operation with secret key. Subsequently powered off.

Sounds pretty safe once you specify "powered off".

https://xkcd.com/538/

“I would upload a small sketch which would simply dump RAM to (say) the serial port a byte at a time, to avoid needing much RAM to do the dumping.” I bet you would write the program in such a way that it uses zero RAM.

Yes, quite possibly. :) It might depend on how much money changed hands. :P

+1 for covering EEPROM details and pointing out complete flash erase as added safety measure. Thanks!


text:
SMS Receiving problem - Arduino Uno and SIM900A GSM Module
My intention is to control an LED according to the content of the SMS received. For example, if the SMS is "ON", turn on the LED and if it is "OFF", turn it off. I referred many sites and got the below code.
The digital pins 9 and 10 are used instead of Rx and Tx to avoid the code uploading problem.
(I have kept the different versions of AT commands commented in the code because I'm not sure which one is correct. With the current one, I'm able to get some kind of output which I've mentioned after the code.)
#include <SoftwareSerial.h>
SoftwareSerial mySerial(9, 10);

char msg;
void setup()
{
  Serial.begin(9600);
  mySerial.begin(9600);   // Setting the baud rate of GSM Module
  delay(1000);
  //mySerial.print("AT+CMGF=1r"); // set SMS mode to text
  mySerial.print("AT+CMGF=1\r");  // set SMS mode to text

  delay(100);
  //mySerial.println("AT+CNMI=2,2,0,0,0"); // AT Command to receive a live SMS
  //mySerial.print("AT+CNMI=2,2,0,0,0r");

  mySerial.print("AT+CNMI=1,2,0,0,0\r"); // AT Command to receive a live SMS
  delay(100);
  Serial.println("Ready");
}

void loop()
{
  if (mySerial.available()>0)
  {
    msg=mySerial.read();
    Serial.print(msg);
  }
}

This is the output I'm getting..
Ready
AT+CMGF=1
AT+CNMI=1,2,0,0,0

OK

+CMTI: "SM",31

+CMTI: "SM",32

+CMTI: "SM",33

+CMTI: "SM",34

The issue is, I'm not able to retrieve the message content. What I'm getting is
"+CMTI: "SM",31"
"+CMTI: "SM",32"
and the number keeps on incrementing. (33, 34 and so on).
I do understand that I have to parse the message to get the exact content, but here I'm not getting the content at all. What exactly should I do to get the SMS content? Could anybody help me to solve this?
One more thing, the GSM module I'm using is a SIM900A type (from elementzonline.com). It's not a shield type, so I've made connections using wires; the Rx, Tx connections and the ground one.
(Sorry for the bad explanation, I'm a complete noob in Arduino, a hobbyist.)
Thanks in advance.

You should download the SIM900 command set (Google away) and read it. According to your CNMI settings, sms notifications are pushed to the Arduino not the sms content, thus the +CMTI data you're receiving. SM tells you the sms is stored on the SIM and the number that follows tells you the index of the sms in the SIM memory. With that index, you use the command AT+CMGR=<index> to get the sms content (as well as the sender number and timestamp) from the modem.
So basically, you must parse the CMTI notification, get the number at the end, and use that number to retrieve the SMS content from the modem with the CMGR command. You could also change your CNMI settings to (2,2,0,0,0) i think, if you want the content of the messages to be sent by the modem, and not the notifications alone.
In either case, the SoftwareSerial Receive buffer will most likely overflow when receiving the sms content from the modem; because you cant read() fast enough. This will make the message appear truncated. You have to increase the size of the SoftwareSerial RX buffer to prevent this. Here's a link to an answer where this is explained. Good luck.

Thank you so much for the answer ! I modified the code as in the link. I just tried mySerial.println("AT+CMGR=35"); and I'm getting the content of the SMS. The output is like OK AT+CMGR=35 +CMGR: "REC READ","+919******7","","16/04/06,18:38:49+22" Hello. In this, "Hello" is the actual content. But now, the issue is, the output is getting displayed infinitely.

@AparnaShajiPeter well, thats probably because you placed it in loop(). Place it in setup() if u want it to print the message only once. Structure your code to do what u want

one more update, now I'm not getting the notifications. i.e., if I run the same first program, I'm not getting the +CMTI messages.  checked the connections, everything is perfect. I'm getting ring as well.Not sure what's happening. :(

@AparnaShajiPeter you are using your original code right? And you havent changed the CNMI settings from (2,2,0,0,0)? And you have sent new messages while the modem is connected? Also, theres no CMGR command present?

first, run the AT+CNMI command to get the index of the message, and then using that index, run the AT+CMGR command. This is the idea, right?

Yeah, same exact code which I posted in the question here. (with CNMI 1,2,0,0,0). While the modem is connected. And, CMGR is not there, because I just tried printing the index, the first program.

@AparnaShajiPeter No. AT+CNMI sets the notification mode of the modem. Using a setting of (1,0,0,0,0) will make the modem forward messages to the terminal directly as they are received WITHOUT notifications. Whereas (2,2,0,0,0) will make the modem forward only the notifications and then you have to use CMGR to get the sms content. The CMTI notifications are unsolicited; u dont ask for them, u simply wait till data is available over serial, and then you parse and obtain the index

@AparnaShajiPeter i suspect your sim memory is full. Maximum is about 15 msgs. Try this command to delete everything: AT+CMGD=ALL or AT+CMGD="ALL"...cant remember which is correct. Place it in setup() on its own and print the results. Then try your original code and send another sms.

I too suspected the same and deleted all messages using AT+CMGDA="DEL ALL"and tried running it again, but it didn't make any change.

@AparnaShajiPeter thats the wrong command. Try the command i gave u...also print the results so u can know if it succeeded

Let us continue this discussion in chat.

Instead of using At commands use the GSM library of Arduino it easier to understand and implement.
the code to recieve SMS
    #include <GSM.h>

    // PIN Number for the SIM
    #define PINNUMBER "" //sim pin incase the sim is kept locked

    // initialize the library instances
    GSM gsmAccess;
    GSM_SMS sms;

    // Array to hold the number a SMS is retreived from
    char senderNumber[20];

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

      Serial.println("SMS Messages Receiver");

      // connection state
      boolean notConnected = true;

      // Start GSM connection
      while (notConnected) {
        if (gsmAccess.begin(PINNUMBER) == GSM_READY) {
          notConnected = false;
        } else {
          Serial.println("Not connected");
          delay(1000);
        }
      }

      Serial.println("GSM initialized");
      Serial.println("Waiting for messages");
    }

    void loop() {
      char c;

      // If there are any SMSs available()
      if (sms.available()) {
        Serial.println("Message received from:");

        // Get remote number
        sms.remoteNumber(senderNumber, 20);
        Serial.println(senderNumber);

        // An example of message disposal
        // Any messages starting with # should be discarded
        if (sms.peek() == '#') {
          Serial.println("Discarded SMS");
          sms.flush();
        }

        // Read message bytes and print them
        while (c = sms.read()) {
          Serial.print(c);
        }

        Serial.println("\nEND OF MESSAGE");

        // Delete message from modem memory
        sms.flush();
        Serial.println("MESSAGE DELETED");
      }

      delay(1000);

    }

GSM library is used with Arduino GSM Shield, right? Here, I'm using another SIM900A GSM module, not the shield..

use cnmi 2,2,0,0,0 to get the SMS contents
use cnmi 1,2,0,0,0, to get only the notification with CMTI+.... if you want to read the cont then u need to parse and check wht number u get in SM and then read that numbered msg using CMGR

Can you please spell this out in English and show an example?


text:
Arduino with Bluetooth
HI I am a newbie and need some suggestions
Is there a possibility to do this?? I am trying to send MIDI data through a button using Arduino and bluetooth module HM10. Can someone help me write the loop part or am going the right way.
#include <MIDI.h>
#include <SoftwareSerial.h>
SoftwareSerial mySerial (2, 3);
char c = ' ';
int pushButton7 = 7;
int buttonState7 = 0;
int note7 = 0;
void setup() {
  MIDI.begin(4);
  // 115200 hairless MIDI
  Serial.begin(9600);
  mySerial.begin(9600);
  pinMode(pushButton7, INPUT);
}

  void loop() {

   int buttonState7 = digitalRead(pushButton7);

 // Button 7

  // when button pressed:
  if (buttonState7 == HIGH) {
    // if note not playing
    if (note7 == 0) {
      // play note (note number, velocity, channel)
      // more info: http://arduinomidilib.sourceforge.net/a00001.html
      // MIDI notes chart http://www.phys.unsw.edu.au/jw/notes.html
      // 55 = G3, 127 = trigger note with max volume
      MIDI.sendNoteOn(55,127,1);
      // note is playing
      note7 = 1;
    }
  // when button released
  } else {
    // if note playing
    if (note7 == 1) {
      // if playing - stop
      MIDI.sendNoteOff(55,0,1);
    }
    // if button released note is off
    note7 = 0;
  }

  delay(1);

  }


text:
Diagnosing crashed Arduino Uno
I have an Arduino Uno connected to a motor controller over I2C. The Arduino accepts commands from a Raspberry Pi via the USB serial line.
I'm trying to diagnose a problem where the Arduino will become completely unresponsive. It's programmed to respond to a "ping" request every N seconds, and for some reason I can't identify, it seems to crash and no longer respond to any commands. However, the motor controller continues powering the motors.
Everything is powered from a 12V Li-Po battery, but everything is located behind 5V regulators. When this problem happens, the battery is fully charged and the motors aren't sourcing much current, and neither the motor controller or Raspberry Pi are effected, so I've ruled out a brownout.
My theory is there's some subtle programming error in my Arduino code that's causing an "exception", but I don't know how to identify it. I've tried adding special code to allow me to trigger one of these, by indexing an array outside of its limits or calling a null function pointer, but the Arduino stubbornly refuses to crash when I try to explicitly make it.
How do I diagnose an Arduino becoming unresponsive?

and for some reason I can't identify, it seems to crash and no longer respond to any commands. - how long does this take? Minutes? Seconds? Hours?

Assuming you don't have access to a debugger, the most common way is to add debug logging. The ususal algorithm to solve those problems is more or less like this:
do {
    add_logs_in_suspicious_places();
    wait_until_it_crashes();
    analyze_logs();
} while( ! i_know_why_it_crashes() );

If you cannot add any debug logging because of a flawed system design (lack of I/O, etc) you've commited a captial engineering crime and this is your punishment. :)

There is an excellent post by Nick Gammon that covers a wide array of possible problems. Look into this, as might be useful.

If you have spare pins, add debugging LEDs. For example, toggle one at the start of loop, another at the start of another function, and so on. When the Arduino "crashes" the state of the LEDs should provide a hint as to where in the code it is.

but the Arduino stubbornly refuses to crash when I try to explicitly make it.

Typically you are indexing outside an array or using uninitialized memory. Your debugging code has moved the problem around enough to stop it happening (or appearing to happen).
If you amend your question and post your code we might spot something.


text:
2WD robot - logic error
I am making a basic 2WD robot using Arduino Uno with motor shield.
I am getting no compile errors - but something in my logic flow is not working as expected.
Expected Operation:

Ping sensor does distance check.
If distance is less than 5cm.
Turn both Channel A & B motors half-speed for 1 second.
Stop motors.
Take new distance reading ping, start again.

What however is happening, is that channel A works as expected, but channel B motor keeps running??
Where is my code / logic mistake?
Later date I will add to else statement to turn one wheel to change direction.
/*
 HC-SR04 Ping distance sensor:
 VCC to arduino 5v
 GND to arduino GND
 Echo to Arduino pin 7
 Trig to Arduino pin 8
 */

#define echoPin 7 // Echo Pin
#define trigPin 8 // Trigger Pin
#define LEDPin 13 // Onboard LED

int maximumRange = 1000; // Maximum range needed
int minimumRange = 1; // Minimum range needed
long duration, distance; // Duration used to calculate distance

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

Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(LEDPin, OUTPUT); // Use LED indicator (if required)

  pinMode(12, OUTPUT); /* Motor Channel A RIGHT SIDE*/
  pinMode(9, OUTPUT); /* Motor Channel A */

  pinMode(13, OUTPUT); /* Motor Channel B LEFT SIDE */
  pinMode(8, OUTPUT);

  }

void loop() {

  /* Distance check begins */

  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);

  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);

  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH);

 //Calculate the distance (in cm) based on the speed of sound.
 distance = duration/58.2;

 /* End distance check */

 if (distance >= 5){
 /* Distance great enough to provide room to move */
  Serial.println("Move!");

  digitalWrite(LEDPin, HIGH); /* LED show movement */

  digitalWrite(12, LOW); /*move channel A motor half-speed */
  digitalWrite(9, LOW);
  analogWrite(3, 123);

  digitalWrite(13, HIGH); /*move channel B motor half-speed */
  digitalWrite(8, LOW);
  analogWrite(11, 123);

  delay(1000);

  digitalWrite(9, HIGH);
  digitalWrite(8, HIGH);
 }

 else {
 /* Send the distance to the computer using Serial protocol, and
 turn LED OFF to indicate successful reading. */
 Serial.println(distance);
 digitalWrite(LEDPin, LOW);
 }

 //Delay 50ms before next reading.
 delay(500);

}

You might add the pins for the motors to your #define statements. This way you could've easily spotted them having the same pin number.
Some other points that might improve your code are:
1.Try increasing the baudrate Serial.begin(115200) in both the code and your terminal (should make it a little quicker). 2. echoPin 7 // Echo Pinis just a too obvious comment. Try to use comments for a purpose. like//This pin receives the echo pulse 3. maximumRangeshould be anunsigned int` it makes no sense to have negative ranges (and you can have a higher max range with unsigned).

I believe that your error is in that you declare LEDpin as pin 13 and then your motor B as pin 13 as well, that to me would result in errors when you write to the led in the else statement at the end of your code. I would recommend that you clean this up, don't use pins for different things. Try this first.
Your logic is ok in terms of functionality.
Also why is there inconsistency at this part on your code:
digitalWrite(12, LOW); /*move channel A motor half-speed */
  digitalWrite(9, LOW);
  analogWrite(3, 123);

  digitalWrite(13, HIGH); /*move channel B motor half-speed */
 digitalWrite(8, LOW);
  analogWrite(11, 123);

Why do you say pin 12 must beLOW and 13 HIGH when moving forward? Is this the way your un-mentioned circuit setup works, if possible could you add this info?

Thanks - think I missed the LED 13 bit. Reason for the inconsistency is that I motors are wired differently (ie by mistake), so to move fwd one needs a HIGH and other needs LOW to maintain direction.

@SvenHansen   thanks for clarifying, try setting all things related to the motors to an "off" setting so when setting the brake pins also set the pwm pins to 0

Indeed, I can still remember one of those controllers that uses 1-pin for CW or CCW rotation. Obviously one has to rotate CW and the other CCW to go forward (since the motors are 180 degree turned).
@SvenHansen you should accept RSM's answer, to let the system (and others) know this question is answered succesfully.

@SvenHansen    glad its working ;)


text:
Altering SoftwareSerial to transmit more than 1 byte at a time
I am trying to create a stable communication channel without any mis-synchronization. In the SoftwareSerial library, the write function transmits one byte at a time. The mis-synchronization occurs when the receiver misjudges which bit is the start bit. Why is this a problem? Because the internal delay between the start bit and the first message bit is different from the internal delay between each message bit.
One of the really good suggestions I have heard is to use Manchester encoding on the Arduino. While I am testing out this option, I also wanted advice on altering the software serial library in the following way. If I modify the write function to transmit 128 bytes instead of 1, then this can avoid the problem I explained above, I assume.
Here is how I have altered the write function of SoftwareSerial. I haven't thought of any issues with this approach, but does anyone else see any problems?
Here is the whole altered function. (I changed the parameter, and added 2 new loops - one to invert all the bytes if(inv) and another loop outside the loop that transmits each bit of a byte. I have attached the original function, further below.
size_t SoftwareSerial::write(byte* b)
{
  if (_tx_delay == 0) {
    setWriteError();
    return 0;
  }

// By declaring these as local variables, the compiler will put them
// in registers _before_ disabling interrupts and entering the
// critical timing sections below, which makes it a lot easier to
// verify the cycle timings
volatile uint8_t *reg = _transmitPortRegister;
uint8_t reg_mask = _transmitBitMask;
uint8_t inv_mask = ~_transmitBitMask;
uint8_t oldSREG = SREG;
bool inv = _inverse_logic;
uint16_t delay = _tx_delay;

//Doubtful of this loop ------------------
for(int i = 0; i < 128; i++)
{
  if (inv)
    b[i] = ~(b[i]);
}

cli();  // turn off interrupts for a clean txmit

// Write the start bit
if (inv)
  *reg |= reg_mask;
else
  *reg &= inv_mask;

tunedDelay(delay);
for(int j = 0; j < 128; j++)
{
  // Write each of the 8 bits
  for (long i = 8; i > 0; --i)
  {
    if (b[j] & 1) // choose bit
      *reg |= reg_mask; // send 1
    else
      *reg &= inv_mask; // send 0

    tunedDelay(delay);
    b[j] >>= 1;
  }
}
// restore pin to natural state
if (inv)
  *reg &= inv_mask;
else
  *reg |= reg_mask;

SREG = oldSREG; // turn interrupts back on
tunedDelay(_tx_delay);

return 1;
}

Here is the original function.
size_t SoftwareSerial::write(uint8_t b)
{
if (_tx_delay == 0) {
  setWriteError();
  return 0;
}

// By declaring these as local variables, the compiler will put them
// in registers _before_ disabling interrupts and entering the
// critical timing sections below, which makes it a lot easier to
// verify the cycle timings
volatile uint8_t *reg = _transmitPortRegister;
uint8_t reg_mask = _transmitBitMask;
uint8_t inv_mask = ~_transmitBitMask;
uint8_t oldSREG = SREG;
bool inv = _inverse_logic;
uint16_t delay = _tx_delay;

if (inv)
  b = ~b;

cli();  // turn off interrupts for a clean txmit

// Write the start bit
if (inv)
  *reg |= reg_mask;
else
  *reg &= inv_mask;

tunedDelay(delay);

// Write each of the 8 bits
for (uint8_t i = 8; i > 0; --i)
{
  if (b & 1) // choose bit
    *reg |= reg_mask; // send 1
  else
    *reg &= inv_mask; // send 0

  tunedDelay(delay);
  b >>= 1;
}

// restore pin to natural state
if (inv)
  *reg &= inv_mask;
else
  *reg |= reg_mask;

SREG = oldSREG; // turn interrupts back on
tunedDelay(_tx_delay);

return 1;
}

The serial buffer can only hold 64 bytes at a time, but I am using the following code, courtesy of Nick Gammon to read the data from serial buffer without blocking. So it shouldn't be a problem on the receiving end either, I hope.

You've asked this before - in what way is this question different to your previous one? As I point out in your other question, by trying to send 1024 bits rather than 8 bits, you are substantially reducing the margin for error, if the difference between the sender and receiver clock is at all significant.

The mis-synchronization occurs when the receiver misjudges which bit is the start bit. - that would happen. You would need to allow a really big gap (greater than 1024 bits) to stop this happening. This gap would wipe out any savings by not just sending 8 bits at a time as is normal. I don't see what this technique achieves.

Basically your code has changed the size of the RS-232 packet from 10 bits to 1026 bits. There is nothing "wrong" with that, but it doesn't really solve the problem of a missed start bit - if anything it makes it worse since instead of losing 8 bits you lose 1024 bits.
Synchronisation is best done separately to the transmission of packets, and for that you need your packet to be nice and short.
A packet consists of 10 bits - the first is a LOW and the last is a HIGH; everything else in between is data.  The trick is to provide a forced idle period before sending of at least the amount of time it takes to transfer one packet.  That way if the receiver is mistakenly in a receive loop for whatever reason the 10 (or more) bits worth of HIGH will effectively cause the receiver to finish whatever it is doing and get ready to receive your real byte.
If you have a hugely long packet (1024 + 2 bits) flushing the receiver before transmitting will take a very long time - rather than just one byte's worth of time it will be your entire packet's transmit time.
On top of that you then have the problem of byte order and data integrity checking.  Just sending two bytes (or 128 bytes) is not reliable. You need to wrap those bytes in a protocol including a start-of-packet indicator (0x55 0xAA is common, as is the special ASCII character 0x01: SOH), packet or payload length, and checksums.  Options for things like sequence numbers, acknowledgements, packet retransmission, etc can also be built in to increase the reliability of the protocol.
Rather than trying to reinvent the wheel by changing the underlying data layer transmission you should learn the OSI 7 layer model and implement your protocol at a higher level than the data layer.

Just a quick clarification, isn't the start bit a one, which is a high?

The start bit is always a zero. See http://www.gammon.com.au/forum/?id=10894. The "idle state" is continuous 1 bits.

Coincidentally, you should learn the OSI 7 layer model is what I recommended, too.

So far you have asked a lot of questions about your project which uses SoftwareSerial to send a lot of bits:

How to transmit more than 1 byte continually?
Basic Serial Transmission Protocol
Synchronization and Implementing hamming code on Software Serial
Encoding clock signal into linear block codes
How to fix baud rate when hardware capacity has a low limit?
Unable to tell if error is from receiving or transmitting end
Read function in Software Serial

And now we have another one (this question).
I think you are flogging a dead horse with this. For one thing, what are you trying to achieve, that can't be achieved by just sending the bytes "normally" as 8-bit bytes? The only thing I can think of is a slight speed increase. By trying to make a 1024-bit packet, you are saving some start and stop bits in the middle, that's all.
In some of your other questions you mention 9600 baud, so let's run with that. At 9600 baud one bit is 1/9600 of a second, that is 104.17 µs.
To transmit 1024 bits "normally" you would need 128 bytes, each of which needs a start and stop bit, so the total is 128 * 10 * 104.17 µs = 133.338 ms.
To use your system you need 1024 bits plus one start and stop bit, so that is 1026 * 104.17 µs = 106.878 ms.
So far you have only saved 26.46 ms.
You could save a lot more by simply doubling the baud rate. Or quadrupling it. However SoftwareSerial is less reliable at higher baud rates. Why not use HardwareSerial?
Your next problem is that SoftwareSerial turns interrupts off during reception of one byte, so that it gets the timing right. For an 8-bit byte this means they are off for 10 * 104.17 µs = 1.0417 ms. That's about the limit for turning interrupts off if you want the internal timer to work, the one which gives you millis and micros. If you turn them off for 128 times as long, you can say "goodbye" to knowing how much time has elapsed.
As I mentioned in a comment, too, since serial comms relies on external clocks (that is, both ends have to get the clocking right) you can only afford around a ±2% error in the receiving clock to ensure that we are sampling at the correct place (see the datasheet) for an 8-bit byte. The error tolerance will drop to 1/128th of that if you try to send 128 bytes in a single stream. The crystal/resonator in the Arduino just won't be that good.
Finally, to avoid false detection of the start bit (which you have asked about elsewhere) you need a much longer gap between packets, to ensure that we get the correct start bit. Effectively you need a one-byte length (ie. the incoming data is continually HIGH) for 8-bit bytes. For 1024-bit packets you will need to introduce a gap of 1024 * 104.17 µs = 106.670 ms between packets. This required gap totally wipes out any saving by not sending those extra start and stop bits.


text:
How can I reduce the size of my sketch?
Looks like I'm overshooting the storage of my Adafruit Trinket:
Sketch uses 5,600 bytes (105%) of program storage space. Maximum is 5,310 bytes.
Global variables use 109 bytes of dynamic memory.

Any tips for reducing the footprint of my code?
#include <Adafruit_NeoPixel.h>
#include <Wire.h>
#include <RTClib.h>

#define LEDPIN 1
#define TONE 4
#define BTNPIN 3

RTC_DS1307 rtc;
Adafruit_NeoPixel strip = Adafruit_NeoPixel(4, LEDPIN, NEO_RGB);

long fadeTime = 1 * 10000L; // X minutes
int colorStops = 256;
int delaySpeed = fadeTime / colorStops;
int notes[] = {262,294,330,349};
int timeHour = 14;
int timeMinute = 43;
uint32_t alarmLength = 5 * 60000L; // 5 minutes

void setup() {
  rtc.begin();
  if(!rtc.isrunning()) {
    rtc.adjust(DateTime(__DATE__, __TIME__));
  }

  pinMode(TONE,OUTPUT);
  pinMode(BTNPIN, INPUT);
  digitalWrite(BTNPIN, HIGH);

  strip.begin();
  strip.show();
}

void loop() {
  DateTime now = rtc.now();

  if (now.hour() == timeHour && now.minute() == timeMinute && now.second() == 0){
    // Fade in light
    for(int i = 1; i<colorStops; i++){
      if (kill() == true){ break; }

      for(int np = 0;np<strip.numPixels(); np++){
        strip.setPixelColor(np, strip.Color(i,i,0));
      }
      strip.show();
      delay(delaySpeed);
    }

    // Play tone after light fully bright
    for( uint32_t tStart = millis();  (millis()-tStart) < alarmLength; ){
      if (kill() == true){ break; }

      for(int np = 0;np<strip.numPixels(); np++){
        strip.setPixelColor(np, strip.Color(random(100,255),random(100,255),random(100,255)));
      }
      strip.show();

      beep(TONE, notes[random(0,3)], 50);
      delay(100);
    }

    for(int np = 0;np<strip.numPixels(); np++){
      strip.setPixelColor(np, strip.Color(0,0,0));
    }
    strip.show();
  }
}

void beep (unsigned char speakerPin, int frequencyInHertz, long timeInMilliseconds)
{   // http://web.media.mit.edu/~leah/LilyPad/07_sound_code.html
  int x;
  long delayAmount = (long)(1000000/frequencyInHertz);
  long loopTime = (long)((timeInMilliseconds*1000)/(delayAmount*2));
  for (x=0;x<loopTime;x++)
  {
    digitalWrite(speakerPin,HIGH);
    delayMicroseconds(delayAmount);
    digitalWrite(speakerPin,LOW);
    delayMicroseconds(delayAmount);
  }
}

bool kill() {
  if (! digitalRead(BTNPIN)) {
    for(int np = 0;np<strip.numPixels(); np++){
      strip.setPixelColor(np, strip.Color(0,0,0));
    }
    strip.show();
    return true;
  }
  else {
    return false;
  }
}

One suggestion would be to change any int variables that you know won't be outside the range of [-127, 127] to a byte variable. byte data type is of size 1 byte, int is 4 bytes. This similar concept can be used for the other variables also.

Have you tried different compiler optimization levels?

@JonathanSmit: The range of a byte is [0, 255], not [-127, 127], as it is typedefed to be an uint8_t. And int is 2 bytes, not 4.

Ops, sorry about that, totally crossed my mind. I forgot byte is unsigned. Also, aren't ints 4 bytes on most 32 bit and 64 bit compilers? http://stackoverflow.com/questions/11438794/is-the-size-of-c-int-2-bytes-or-4-bytes

@JonathanSmit: “Also, aren't ints 4 bytes on most 32 bit and 64 bit compilers?” Yes, they are, but the ATtiny85 inside the Trinket is an 8 bit chip.

I find getting rid of the arduino digitalRead/Write() and pinMode can save space. As a quick test I save 6% of space on a program by removing one digitalRead and pinMode. Gives you an idea.

I'm wondering if there's a more compact way to execute the intent behind the beep function. Ultimately trying to just make the piezo generate a set of rapid beeping noises (this thing is for an alarm).

I'm wondering if there's a more compact way to execute the intent behind the beep function - I wrote a small library to do that, however for the Atmega328. You should be able to adapt it. http://www.gammon.com.au/forum/?id=11504&reply=11#reply11

The AdaFruit Trinket just doesn't have a lot of memory - 8kb, of which 3kb is used by the bootloader.
The order I look for things to reduce the footprint of an Arduino program are:

data (e.g. large strings)
libraries
your code (especially doing the same things several times, which might be combined into loops or functions).

In this case, you don't have much data. Most of your resulting program size is in the libraries you use.
It seems like you use the clock solely to detect the year - that seems like a lot of overhead just to figure out what year it is. It then does nothing for subsequent years (or prior years), if I read your code correctly. Maybe you would consider dropping this code? Then you can skip the entire RTC library. At least try it to see how much you save. I suspect that the RTC library will use another library to do the underlying work.
You use the <Wire.h> library, but don't reference it in your code. It should be optimized out (unless used elsewhere), but there's no reason to have it there.
You may also save a little space by replacing initialized variables which don't change to constants. Storing 25 in a variable takes 1 byte, plus 2 bytes every time you reference it; 25 in a constant gets optimized away, and will take up 1 byte every time you reference it.
As mentioned in the comments, you can also save a few bytes by specifying the size of your int's, especially initialized ones.
Another option would be to use a larger chip - the AtMega328p used in (for example) the Arduino has 32kb of flash - 6 times the (available) size.
You can also save some bytes by removing the clause  if(!rtc.isrunning()) {, once you have set it up once.
Additional: I have had some success reducing footprints by reimplementing a subset of a library. Usually, libraries are very well implemented, but if your needs are substantially different/simpler than what the library was designed for, or you are willing to forgo parts of it (e.g. error checking), then SOMETIMES this can help. WARNING! There is a HIGH price to pay (coding, debugging, loss of error checking, undetected bugs etc), and it may not save you anything in the end.
You can also (sometimes) move data (e.g. large strings) to eeprom. The Trinket has 512 bytes of eeprom. You may need one sketch to load the data into eeprom, to run before loading your main sketch. eeprom has it's own overhead, so may not be worthwhile for 512 bytes, it is slower (which probably won't matter for this), and you have a limited number of writes.
Another few bytes may be saved by doing all the maths for the tone frequency/time beforehand, and sacrificing something. For example, you beep for 50ms. If, instead of passing the frequency (between 262 and 349 hertz) and instead pre-calculate the delayAmount (for 262 hz, this would be 1,000,000/262 = 3817ms); your looptime for this is ((timeInMilliseconds1000)/(delayAmount2)) = (501000)/(38172) = 6.55 cycles. 7 cycles is probably "close enough" for all the tones you want to produce. So you can hardcode 7 cycles (using a constant of 7 for looptime), and get rid of that formula to calculate looptime.
In a similar way, if you don't care too much about the exact frequency (which varies between 3817ms and 2865ms depending on your random number), you might specify the delayamount as 2865+random(0,3)*238 (make sure you store at least the random number, you don't want it to change during the loop!).
You now have:
#define random_beep_length 7
void random_beep (unsigned char speakerPin)
{   // http://web.media.mit.edu/~leah/LilyPad/07_sound_code.html
    // Heavily modified!
  int x;
  unsigned char pitch = 2865+random(0,3)*238;
  for (x=0;x<random_beep_length;x++)
  {
    digitalWrite(speakerPin,HIGH);
    delayMicroseconds(delayAmount);
    digitalWrite(speakerPin,LOW);
    delayMicroseconds(delayAmount);
  }
}

Thanks for the tips! I forgot to update my code from when I was doing some debugging. I actually need the RTC to detect the current hour and minute (which is now reflected in my post).

I think it is a great idea to set the clock once - in a separate sketch - and then omit the part that checks if the clock is running. If that doesn't help, modify the clock library (or make a copy) to omit the parts that set the time.

“you might specify the delayamount as 2865+random(0,3)*238”. Or, better yet, 2945+random(0,4)*256. This saves 8 bytes at the cost of a small inaccuracy in the frequencies. Or, an equivalent but less readable form: 2945+(random()&3)*256 (saves 18 bytes).

@EdgarBonet, then why not (11+random()&3)*256, saving another byte? :)

The sum of these tips did the trick. I'm at 97% now. :)

You probably mean beep((11+(random()&3))*256);. When I compile it, it takes 28 bytes of flash, v.s. 20 bytes for beep(2945+(random()&3)*256);. For some reason, gcc -Os computes your sum  as a 32 bit number. This can be fixed with beep((11+((uint8_t)random()&3))*256);, which looks ugly but compiles to only 16 bytes! :-)

An option not already mentioned, but may be worth mentioning, would be to remove the bootloader and program the chip directly with a hardware programmer (or another Arduino). That will increase the available sketch memory from 5kiB to the full 8kiB on the chip.

This is a good idea, however bear in mind you'll need to put the bootloader back if you ever want to use it the way it was originally designed.

Is there some sort of how-to anywhere about doing this? I have an Uno I presume I could do that with.

As already mentioned by AMADANON Inc. in his answer, you should qualify
as const all the constant variables at the beginning of the program.
This is probably the biggest space saver.
You can gain something like 100 bytes by using direct port
access instead of
pinMode/digitalRead/digitalWrite. In the case of the ATtiny85, you only
have port B, and the Arduino pin numbers are the same as the Atmel bit
numbers. So you would for example use PINB & _BV(BTNPIN) instead of
digitalRead(BTNPIN).
There are a few optimization opportunities in beep():

pass only one parameter, as speakerPin and timeInMilliseconds are
constants in your program
have this parameter be delayAmount instead of frequencyInHertz,
and store these delays, instead of the frequencies, in the notes[]
constant array
do not compute the number of iterations (the misnamed loopTime)
beforehand, instead compute the elapsed time and loop until you reach
the required time

Here is my version of beep() with these optimizations:
void beep(int delayAmount)
{
  for (uint16_t t = 0; t < BEEP_TIME*1000/2; t += delayAmount)
  {
    PORTB |= _BV(TONE);  // digitalWrite(TONE,HIGH);
    delayMicroseconds(delayAmount);
    PORTB &= ~_BV(TONE);  // digitalWrite(TONE,LOW);
    delayMicroseconds(delayAmount);
  }
}

Notice that the loop variable is actually half the elapsed time. This
saves a few bytes. Making the number of iterations constant, as proposed
by AMADANON Inc., also saves a few bytes (6 bytes in my test).
You should also remove all the calls to strip.Color(): replace every
instance of strip.setPixelColor(np, strip.Color(r, g, b)) by
strip.setPixelColor(np, r, g, b).
With all these optimizations combined, I am quite confident you will
gain more than the 290 bytes you need to fit your program in the
Trinket.

"constant variables"? lol! I know what you mean :)


text:
Sending GPS data between two Arduinos using Easy Transfer
I'm trying to get GPS data transmitted from one Arduino UNO to a second unit to eventually be displayed on an LCD and stored in an SD card.  I am using Xbees S2C's on Xbee Shield's to do this.  The GPS information is coming from an Adafruit ultimate GPS breakout.
First I wanted so send two NMEA sentences as strings, but have since found that the EasyTransfer library does not like that.  I was getting information but it was just random characters, sort of.  The pattern was repeated, so it was consistent.
After doing some searching I thought the best way to do it was to convert my strings to character arrays and send those.  I managed to successfully convert them to character arrays, but I can't seem to get them over to the other Arduino.  I do get the FIX int as well as the Length int that I sent over just to make sure it is working.  Any ideas on what I am doing wrong?
Sender code:

#include <EasyTransfer.h>
#include <Adafruit_GPS.h>
#include <SoftwareSerial.h>

SoftwareSerial mySerial(3, 2); //Initialize SoftwareSerial, and tell it you will be connecting through pins 2 and 3
Adafruit_GPS GPS(&mySerial); //Create GPS object

String NMEA1;  //We will use this variable to hold our first NMEA sentence
String NMEA2;  //We will use this variable to hold our second NMEA sentence
char c;       //Used to read the characters spewing from the GPS module
int fix = 0;
long GPStime = 0;
int val = 0;

EasyTransfer ET;

//Declare Data Structure for the EasyTransfer Library
//Note: Data Structure must be same on TX and RX...

struct DATA_STRUCTURE{
 int fixed;
 int length1;
 int length2;
 char* nmea1;
 char* nmea2;
};

DATA_STRUCTURE myData;

void setup()
{
  //Initalizing EasyTransfer Serial Ports
  Serial.begin(115200);
  ET.begin(details(myData), &Serial);
  GPS.begin(9600);       //Turn GPS on at baud rate of 9600
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);
  //Serial.println("Two GPS Sentences From GPS");
  GPS.sendCommand("$PGCMD,33,0*6D"); // Turn Off GPS Antenna Update
  GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA); //Tell GPS we want only $GPRMC and $GPGGA NMEA sentences
  GPS.sendCommand(PMTK_SET_NMEA_UPDATE_10HZ);   // 10 Hz update rate
  delay(1000);  //Pause
}

void loop()
{
  readGPS();  //This is a function we define below which reads two NMEA sentences from GPS
  //Sending Data
  ET.sendData();
}

void readGPS()    //This function will read and remember two NMEA sentences from GPS
{
  clearGPS();    //Serial port probably has old or corrupt data, so begin by clearing it all out
  while(!GPS.newNMEAreceived())   //Keep reading characters in this loop until a good NMEA sentence is received
  {
    c=GPS.read(); //read a character from the GPS
  }
  GPS.parse(GPS.lastNMEA());  //Once you get a good NMEA, parse it
  NMEA1=GPS.lastNMEA();      //Once parsed, save NMEA sentence into NMEA1
  while(!GPS.newNMEAreceived()) //Go out and get the second NMEA sentence, should be different type than the first one read above.
  {
    c=GPS.read();
  }
  GPS.parse(GPS.lastNMEA());
  NMEA2=GPS.lastNMEA();

  fix = GPS.fix;
  if (fix == 1)
  {
    //Serial.print("FIXED");
    digitalWrite(13, HIGH);
    //Serial.print(NMEA1);
    myData.fixed = 1;
    int str_len1 = NMEA1.length();
    char char_array1[str_len1];
    NMEA1.toCharArray(char_array1, str_len1);
    myData.length1 = str_len1;

    //Serial.print(char_array1);
    //Serial.println("");
    //Serial.println("");
    myData.nmea1 = char_array1;

  }
  else
  {
    //Serial.println("No fix");
    digitalWrite(13, LOW);
    myData.fixed = 0;

  }
}

void clearGPS() //Since between GPS reads, we still have data streaming in, we need to clear the old data by reading a few sentences, and discarding these
{
  while(!GPS.newNMEAreceived())
  {
    c=GPS.read();
  }
  GPS.parse(GPS.lastNMEA());
  while(!GPS.newNMEAreceived())
  {
    c=GPS.read();
  }
  GPS.parse(GPS.lastNMEA());
}

Receiver Code:
#include <EasyTransfer.h>
#include "Wire.h"
#include "Adafruit_LiquidCrystal.h"

EasyTransfer ET;

Adafruit_LiquidCrystal lcd(0);

//Declare Data Structure for the EasyTransfer Library
//Note: Data Structure must be same on TX and RX...

struct DATA_STRUCTURE{
 int fixed;
 int length1;
 int length2;
 char* nmea1;
 char* nmea2;
 //int pause;
};

DATA_STRUCTURE myData;

char* NMEA1[100] = {0};

void setup()
{
 //Initalizing EasyTransfer Serial Ports
 Serial.begin(115200);
 ET.begin(details(myData), &Serial);

 lcd.begin(20, 4);
 lcd.clear();
 lcd.setBacklight(HIGH);

 pinMode(13, OUTPUT);
 digitalWrite(13, LOW);

}

void loop()
{
  //check and see if a data packet has come in.
  if(ET.receiveData()){
    //this is how you access the variables. [name of the group].[variable name]
    int FIX = myData.fixed;
    int LENGTH1 = myData.length1;
    char* NMEA1 = myData.nmea1;
    Serial.println(FIX);
    Serial.println(LENGTH1);
    Serial.print(NMEA1);
    Serial.println("");
    if (myData.fixed == 1)
    {
      digitalWrite(13, HIGH);
      lcd.setCursor(10, 3);
      lcd.print(" GPS Fixed");
    }
    else
    {
      digitalWrite(13, LOW);
      lcd.setCursor(10, 3);
      lcd.print("No GPS Fix");
    }
  }

  delay(1000);
}

Any help would be appreciated.
Thanks!
K-Bert

Possible duplicate of Casting a struct member between uint8_t and char, with regard to serial transfer

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


text:
Sending data from Arduino UNO as a SOAP request
I have a servo motor on one end which can be turned ON and OFF with web service sending SOAP request. In the other end I have my Arduino UNO with ESP8266. Currently, I am able to send HIGH or LOW status from my Arduino to ESP8266.
My query is: After receiving the status "HIGH" from Arduino to ESP8266, I need to POST the status via SOAP request so that my motor would be "turned ON" . After turning ON the motor in the other end I would like to GET a simple SOAP response.
I am not sure if the above explains to you clearly but I am tired of thinking "how to do this".

Are you directly programming the ESP8266 with your own firmware, or are you communicating to it with AT commands?

Thank you for the reply. I follow this tutorial (http://randomnerdtutorials.com/sending-data-from-an-arduino-to-the-esp8266-via-serial/) to send data from my board to ESP. But I am not sending "HI". Instead I am using two buttons, one for sending "HIGH" and other for "LOW".

OK, so you are programming the ESP8266 in Lua and that is where you want to implement your SOAP transmission. I am sorry, but this probably isn't the best place to help you. We can help with the Arduino programming, and with the ESP8266 if you were communicating with it using AT commands, or programming it with the Arduino IDE in C++. Not many people here will be versed enough in Lua to be able to help you.

SOAP, though, is just XML sent over an HTTP connection (although other connections can be used - you can even implement it as XML through email). The important thing is the XML. Since you only have two states - on and off - you can just pre-program the correct XML strings in your code and send them as a POST request to the remote end. How you would do that in Lua though is anyone's guess...

Thank you for the reply. How this can be done using Arduino IDE using AT commands or Arduino IDE in C++.? Is there any good references..? I also have a WSDL file for the other end Servo motor. Is there any use with that..?

@Majenko, Hi could you suggest me with something on how to proceed further.

Install the default AT command set firmware for the ESP8266 and you should be able to use this library on the Arduino: https://github.com/itead/ITEADLIB_Arduino_WeeESP8266

Support of SOAP occupies a lot of memory, it is better to use JSON-RPC ;)


text:
RF 433 Module with VirtualWire: transmit and receive using the same Arduino board
I was wondering if it was possible to work, in the same Arduino board, both Transmitter and Receiver RF 433 MHz modules. Is it feasible?
Here is the schematics I tried:
1) a pushbutton toggles a state value (0 or 1) and triggers the RF transmitter to send it as a message to the receiver module
2) the RF receiver, whenever reading the message, turns on or off a LED according to the corresponding value (0 or 1)

Here is the source code I wrote:
#include <VirtualWire.h>

#define BTN_PIN A0    // pushbutton que aciona a transmissao
#define LED_PIN 13    // LED aceso ao receber o sinal
#define TX_PIN   4    // ligado ao pino DATA do transmissor RF
#define RX_PIN   7    // ligado ao pino DATA do receptor RF

#define SPEED  5000   // velocidade de comunicacao (bits por segundo)

int estado = 0;

void setup() {
  pinMode(BTN_PIN, INPUT);
  pinMode(LED_PIN, OUTPUT);

  vw_set_tx_pin(TX_PIN);  // transmissor
  vw_set_rx_pin(RX_PIN);  // receptor
  vw_setup(SPEED);
  vw_rx_start();

  Serial.begin(9600);
}

void loop() {
  int pressionado = !digitalRead(BTN_PIN);
  char msg[4];

  if (pressionado) {
    estado = !estado;
    itoa(estado, msg, 10);

    vw_send((uint8_t *) msg, strlen(msg));
    vw_wait_tx();

    Serial.print("Mensagem enviada: [");
    Serial.print(msg);
    Serial.println("]");

    delay(500);
  }

  uint8_t buf[VW_MAX_MESSAGE_LEN];
  uint8_t buflen = VW_MAX_MESSAGE_LEN;
  int recebido = 0;

  memset(msg, 0, 4);
  if (vw_get_message(buf, &buflen)) {

    for (int i = 0; i < buflen; i++)
      msg[i] = char(buf[i]);
    msg[buflen] = '\0';

    Serial.print("Mensagem recebida: [");
    Serial.print(msg);
    Serial.println("]");

    recebido = atoi(msg);

    Serial.print("recebido = ");
    Serial.println(recebido);

    digitalWrite(LED_PIN, recebido);
  }
}

When I run it, according to Serial Monitor it sends the message. The problem is no message comes to the RF receiver.
Does anyone have an idea of what could be wrong?

Just to get some background; have you already tried this particular set of modules with 2 Arduinos? I only ask because I noticed that there was no antenna wire on either module, and my experience with these modules is that without even a basic antenna, they will not receive

As said in the comment you definitely need an antenna on both modules.
It is also possible that you are not supplying enough power to the 433 Mhz modules. The Arduino is not capable of outputting much current and RF transmitters generally have large current spikes.
So I would recommend that you use a seperate power supply to power the modules (do not forget to keep common ground between the Arduino and the Transmitter.)
I have also heard that it is preferred to not maintain common ground between the transmitter and the receiver. So if all else fails then use two separate power supplies.

The antennas - this is definitely true, I just tested out a couple of modules and they weren't working at all... added some antennas and with some wiggling around and moving them closer together, was able to get a signal.

These lines in the ISR in VirtualWire.cpp
    if (vw_rx_enabled && !vw_tx_enabled)
        vw_rx_sample = vw_digitalRead_rx() ^ vw_rx_inverted;

and
    if (vw_rx_enabled && !vw_tx_enabled)
        vw_pll();

mean that the receive path code is just not executed while the transmitter is enabled.
It kind of seems from the comment as that might not have been true at some point in the past, though I'm not seeing a version history for an "official" version to check.
You could try to modify the code to implement both, but it is worth noting that VirtualWire has been deprecated in favor of the more versatile RadioHead, so you might want to evaluate that and perhaps make modifications there instead.


text:
Wire.h not found newliquidcrystal
The arduino IDE can't seem to find the wire.h file when i'm using the new liquid crystal library. Does anyone know how to solve this? here is the code i'm using and the error message:
/*-----( Import needed libraries )-----*/
#include <Wire.h>  // Comes with Arduino IDE
#include <LiquidCrystal_I2C.h>

/*-----( Declare Constants )-----*/ /*-----( Declare objects )-----*/ // set the LCD address to 0x27 for a 16 chars 2 line display // A FEW use address 0x3F // Set the pins on the I2C chip used for LCD connections: //                    addr, en,rw,rs,d4,d5,d6,d7,bl,blpol LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C address

/*-----( Declare Variables )-----*/ //NONE

void setup()   /*----( SETUP: RUNS ONCE )----*/ {   Serial.begin(9600);  // Used to type in characters

  lcd.begin(16,2);   // initialize the lcd for 16 chars 2 lines, turn on backlight

// ------- Quick 3 blinks of backlight  -------------   for(int i = 0; i< 3; i++)   {
    lcd.backlight();
    delay(250);
    lcd.noBacklight();
    delay(250);   }   lcd.backlight(); // finish with backlight on

//-------- Write characters on the display ------------------ // NOTE: Cursor Position: (CHAR, LINE) start at 0     lcd.setCursor(0,0); //Start at character 4 on line 0   lcd.print("Hello, world!");   delay(1000);   lcd.setCursor(0,1);   lcd.print("HI!YourDuino.com");   delay(8000);

// Wait and then tell user they can start the Serial Monitor and type in characters to // Display. (Set Serial Monitor option to "No Line Ending")   lcd.clear();   lcd.setCursor(0,0); //Start at character 0 on line 0   lcd.print("Use Serial Mon");   lcd.setCursor(0,1);   lcd.print("Type to display");

}/*--(end setup )---*/

void loop()   /*----( LOOP: RUNS CONSTANTLY )----*/ {   {
    // when characters arrive over the serial port...
    if (Serial.available()) {
      // wait a bit for the entire message to arrive
      delay(100);
      // clear the screen
      lcd.clear();
      // read all the available characters
      while (Serial.available() > 0) {
        // display each character to the LCD
        lcd.write(Serial.read());
      }
    }   }

}/* --(end main loop )-- */

Here is the compiler output

Arduino: 1.6.7 (Windows 10), Board: "Arduino Nano, ATmega328"
C:\Users\martin\Documents\Arduino\libraries\LiquidCrystal\I2CIO.cpp:35:26:
  fatal error: ../Wire/Wire.h: No such file or directory
#include <../Wire/Wire.h>
                      ^

compilation terminated.
exit status 1 Error compiling.
This report would have more information with   "Show verbose output
  during compilation"   enabled in File > Preferences.

I’m close this question because this Q&A pair is obsolete.

The liquid crystal library has to be installed in the same folder as the wire library:
libraries/Wire/Wire.h (etc)
libraries/LiquidCrystal/LiquidCrystal_I2C.h (etc)

There is a hard-coded path in the liquid crystal library pointing to the wire library that is relative to where the liquid crystal library is, which is done to get around the problem that the Arduino library doesn't recurse libraries. It's not actually needed since including the Wire library in the IDE is enough to tell it where to find it for the liquid crystal library, so I don't really know why they did it that way.

Thanks! i copied the whole Wire folder from C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries and put it in the documents/arduino/libraries folder and it worked!
Is there any cons with solving it this way?

An upgrade to the IDE or Arduino core could leave your two copies of the wire library out of step. Just so long as you keep your copy up to date it should be fine.


text:
Using a SPI based ADC (ADE7912) with Arduino
I'm trying to use Analog Devices' isolated ADC ADE7912 to build a native product for voltage and current sensing, using an Arduino as a microcontroller. The IC communicates with the Arduino using SPI (and SCK frequencies of 8,4,2 and 1 MHz), and I have followed the datasheet and written down some basic code using SPI-transactions and all, which seems to be giving correct results when I apply a positive voltage to the inputs of the ADC. I have two problems here:

When I try to display the SCLK, MISO and MOSI signals on an oscilloscope, the clock seems to have trouble maintaining its value (it becomes erratic and hence the SPI communication also misses some values etc.) Why is this happening?
When I apply a negative voltage to the ADC inputs, the IC does not really show any response to that even though it clearly supports negative voltage inputs to the ADC, as mentioned in the datasheet. This might be an IC related problem, but I am not sure.

Also, is there anyone who has built a library for this IC? Would be greatly obliged if they could share it.

As for the first question, what happens when you don't connect the oscilloscope? Cause sometimes (unlikely in this case, but who knows) the capacitance you add by connecting a probe changes the behavior. As for the second question, probably you'll need to post the schematic too

Please post screenshots of what you see on the oscilloscope -- that makes problems like this much easier to debug.

The Arduino drives the SCLK pin of the ADE7912, right?
I often find it much easier to debug problems if I can (at least temporarily) use a slower clock. The ADE7912 datasheet says it works at 250 kHz SCLK; can you program the Arduino to use that speed? (It is normal for the SCLK to run at the programmed frequency for 8 or 16 cycles, and then pause for long times; that kind of "erratic SCLK" is perfectly normal).

I have not written a full library, but I have recently been using the ADE7913 (same as ADE7912 but with an extra voltage channel) with an Arduino MEGA.
The basic sketch located here talks to the ADE7913 over SPI, and then prints the results of the measurement registers over serial (so you can see them using a serial monitor).
I have not yet done much measurement testing, so can't comment on the negative voltage issue you have seen, but the sketch sets up the ADE7913 to use the V2WV register for monitoring temperature, and converts the result into degrees C, so you should be able to tell if its working properly.
In terms of the issues you have been having with the SPI comms, I can offer the following suggestions based on my troubleshooting experience (I also had glitchy comms initially):

I'm pretty new to SPI, but my interpretation of the data-sheet is that the ADE791X chips use SPI_MODE3 (i.e. SCLK is normally high, and samples are read on the trailing clock edge). I have found SPI_MODE1 also works, but unless others can correct me would suggest using 3.
I found having physically long jumper wires (my prototyping is still on a bread-board) caused issues. I have read elsewhere that at frequencies in the ones of MHz, distances less than tens of meters shouldn't be an issue; but I shortened / tidied my wiring and it seemed to help.
I would run everything at lowest possible speeds to troubleshoot, i.e. set the ADC sampling rate to 1kHz (set CONFIG bits 5:4 to 11), and set the SCLK at 250kHz.
In the attached sketch, I am reading the register values based on an interrupt from the CLKOUT\!DREADY pin. You have to be careful that this reading routine takes less than one ADC sampling time to read all the registers. There is a good explanation of this timing constraint in Figure 8 of this application note. The attached sketch also reports some timing information over serial to help with this.

Hope that helps,

Khalid.

Just to update the note above, I have now tested over a range of positive and negative voltages (from +250mV to -250mV at the V1P pin) and confirmed excellent linearity over this range (within 1% is as good as I can say with the test equipment I have).


text:
Rc switch library transmit using protocol 5
I'm trying to transmit using mode 5 with the rc switch library, but my reciever tells me that the data is using protocol 2. I'm using the RecieveDemo_simple example as a sniffer for 433 MHz and I'm recieving data with protocol 5 from a wireless electric plug that I want to replicate.
I am able to send the data, but it is using the wrong protocol most of the time.
Here's some output from the reciever:
Received 15766156 / 24bit Protocol: 2
Received 15766156 / 24bit Protocol: 5
Received 15885740 / 24bit Protocol: 2
Received 15885740 / 24bit Protocol: 2
Received 15766156 / 24bit Protocol: 2
Received 15766156 / 24bit Protocol: 2
Received 15766156 / 24bit Protocol: 5
Received 15885740 / 24bit Protocol: 2
Received 15885740 / 24bit Protocol: 2
Received 15885740 / 24bit Protocol: 5

The code:
/*
  Example for different sending methods

  https://github.com/sui77/rc-switch/

*/

#include <RCSwitch.h>

RCSwitch mySwitch = RCSwitch();

void setup() {

  Serial.begin(9600);

  // Transmitter is connected to Arduino Pin #10
  mySwitch.enableTransmit(10);

  // Optional set pulse length.
  // mySwitch.setPulseLength(320);

  // Optional set protocol (default is 1, will work for most outlets)
  mySwitch.setProtocol(5);

  // Optional set number of transmission repetitions.
  // mySwitch.setRepeatTransmit(15);

}

void loop() {

  /* Same switch as above, but using decimal code */
  mySwitch.send(15885740, 24);
  delay(1000);
  mySwitch.send(15766156, 24);
  delay(1000);

}

I would expect your sending protocol 5 just fine.
But because protocol 2 and 5 are very similar, your receiver gets confused about which protocol it sees when there's noise or other interference.
This is the definition of the two protocols from the code:
{ 650, {  1, 10 }, {  1,  2 }, {  2,  1 }, false },    // protocol 2
{ 500, {  6, 14 }, {  1,  2 }, {  2,  1 }, false },    // protocol 5

Note the last three parts are the same, which are the pulses for 0, 1, and whether or not the high/lows are inverted.
The first part is also very similar, which is the pulse length. It's so similar that the difference probably falls within the margin for error the receiver software uses.
Only the second parts differs a bit more, which is the sync bit, it's a short high pulse followed by a longer low pulse. It's easy to mistake the one for the other though when there's noise and such.


text:
Upload sketch via Bluetooth using HC-06 module
I'm dealing with an application in which I need to upload sketches remotely to an arduino UNO board. I successufully managed to upload sketches using an HC-06 bluetooth adapter. The only problem is that I am forced to manually press the reset button once the bluetooth link is established. Is there a way to automatically reset the arduino, in a software or hardware way,  so that it will be able to accept and install the incoming and sketch?
Would it be enough to activate a digital pin connected to the reset at the right timing prior the upload process starts?

Use a BJT/FET.
For a NPN, connect RST to COLLECTOR, a digital pin in series with a 220 ohm (or whatever’s appropriate) resistor to BASE, and EMITTER to GND.
Just bring the digital pin HIGH to reset your arduino.

Here's a instructable on how to reset the arduino with software
Instructables link


text:
HM-10 and Arduino Due
I am trying to communicate between HM-10 module (without any breadboard or soldering) and experience problem with reading data from serial.
Here is the code:

#define TO_HEX(i) (i <= 9 ? '0' + i : 'A' - 10 + i)

void afterSetup() {
  Serial3.write("AT+NAME?");
  delay(500);
}

void setup() {
  // initialize both serial ports:
  Serial.begin(9600);

  /*Serial3.begin(115200);  // The Bluetooth Mate defaults to 115200bps
  delay(100);  // Short delay, wait for the Mate to send back CMD
  Serial3.println("U,9600,N");  // Temporarily Change the baudrate to 9600, no parity
  // 115200 can be too fast at times for NewSoftSerial to relay the data reliably*/
  Serial3.begin(9600);  // Start bluetooth serial at 9600

  Serial.write("\n\n\n==== START ====\n");

  afterSetup();
}

unsigned char mode = 2;

void wr(HardwareSerial*, int);

void wr(HardwareSerial *target, int bt, unsigned char mode) {
    //target->write(TO_HEX(((bt & 0xF000) >> 12 )));
    //target->write(TO_HEX(((bt & 0x0F00) >> 8 )));
    if(mode > 0) {
      target->write("\t\t\t\t");
    }
    target->write(TO_HEX(((bt & 0x00F0) >> 4 )));
    target->write(TO_HEX((bt & 0x000F)));
    target->write(" (");
    target->write(bt);
    target->write(")\n");
    return;
}

void loop() {

  // read from port 1, send to port 0:
  if (Serial3.available()) {
    int inByte = Serial3.read();

    if(mode != 1) {
      mode = 1;
    }

    wr(&Serial, inByte, 1);
  }

  // read from port 0, send to port 1:
  if (Serial.available()) {
    int inByte = Serial.read();
    Serial3.print((char)inByte);

    if(mode != 0) {
      mode = 0;
    }

    wr(&Serial, inByte, 0);
  }
}

Wiring is simple:
HM-10    | due
-------------------
RX       | TX3
TX       | RX3
VCC      | 3V3
GND      | GND

Basically, I am able to get data from serial, but it corrupted.
Here is an example:

Command: AT+NAME?
Expected: HMSoft
Response:
        28 (()
        25 (%)
        2A (*)
        35 (5)
        15 ()
        FE (�)

And another, simpler:

Command:  AT
Expected: OK
Response: F5

What am I doing wrong?

Why are you printing from Serial3 before calling begin() on it?


text:
Proximity sensor without proximity sensor; is my hand magic, my competency crap, or my arduino fried?
here is a very simple circuit, with a LED between pin 2 and ground, and a loose wire in pin 8.

Here is the sketch that was intended for use with a small 4-contact switch like these in every arduino starter kit :
int yellowCIn = 8;
int yellowCOut = 2;

void setup() {
  pinMode(yellowCIn, INPUT);
  pinMode(yellowCOut, OUTPUT);
}

void loop() {
  if (digitalRead(yellowCIn) == HIGH) {
  digitalWrite(yellowCOut, HIGH);
  }
  else {
    digitalWrite(yellowCOut, LOW);
  }
}

However, simply moving my hand near the loose white wire is enough to light the LED, moving it away to put it off. As I am writing this, with the arduino connected by usb, rather than on the blue battery visible in the picture, I notice moving my hands away from the keyboard lights the led, moving them close to the keyboard powers it off...
So back to my title : are my hands magic, my electronics competency crap (well, it is, for sure) enough that I never heard of such a tremendous static electricity effect (and never fried one of the many computers I built from parts), or does this board have dire problems?
Thanks for your attention :)

Nothing's broken; you have discovered  the nature of a floating pin.  Unfortunately, that means that strange things happen...
A very small charge from your hand is triggering the logic because the state of the pin (high or low) is not set.  To fix this, you need to add a pull-up or pull-down resistor (or activate the internal input-pullup resistor).
You can read about how to accomplish this here.

Sorry for the dunce questions, hopefully I get to the level of not being a dunce soon enough to not get SE to hate me. Thanks :)

It was NOT a dunce question by the way - it's the difference between building a computer from ready-made parts (motherboards and slot-in cards), and the far more complex business of building those parts yourself.

@pouzzler I had the exact same problem when I first started using buttons :D. You're not at all alone; that's what this site is for

Try configuring your input pin as INPUT_PULLUP instead. This connects an internal pullup resistor to stop the input value from drifting around.
I would only use the "INPUT" mode on its own if I have that pin wired to something on the board and the levels won't be erratic.
Your hands are magic - they pick up interference from various sources and the high impedance input of the chip pick this up...
(There's a bit more on the modes here: Arduino DigitalPins page)


text:
Print the response from GSM shield
I have a GSM shield connected with my Intel Galileo board.
I intend to connect the board with serial communication at a baud rate of 115200 instead of the GSM library. I want to print the results of "at" commands in my serial window, how should I do it?

Send the commands, read the responses, print the responses. What's so tricky about that?

well can u kindly give the syntax for printing those responses ?? plzz

https://www.arduino.cc/en/Reference/Serial

I have only worked with the SIMCOM series of GSM modules like the SIM900 and the SIM808. Here is a sample of the kind of code you should be looking at using.
It will send one "AT" to the GSM module and then it will spit out the result in the serial monitor.
void setup()
{
  Serial.begin(115200);
  int bytesSent = Serial.write(“AT\r\n”); //send "AT" and send the end of line characters to signify end of the command
 }

 void loop()
{
   if (Serial.available() > 0) {
            // read the incoming byte:
            incomingByte = Serial.read();
    }
}

This seems a bit confused and probably unworkable - the Serial Monitor and the GSM module are both serial-interfaced devices (or at least appear to be so in the Arduino world), but you only use a single serial interface and seem to somehow imagine that it is independently connected to both of them.

I copied the normal serial command and left in the echo by mistake. Thanks for pointing that out.

Now it produces no output and so does not achieve the goal of the question.  The question requires two serial ports.