text:
Arduino Prototype on Breadboard: "avrdude: stk500_recv(): programmer is not responding"
I have created an arduino prototype using the exact instructions found on this page:
https://www.arduino.cc/en/Main/Standalone
However, when I plug in the micro USB power supply and try to upload a program, here's the error I get:
avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xe0

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xe0

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xe0

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xe0

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xe0

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xe0

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xe0

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xe0

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xe0

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xe0

I have tried the following solutions, to no avail:
1) press the restart button (in a variety of ways and lengths of time)
2) Enable verbose output
3) trying the different board types in the Arduino IDE
4) Checking the COM port
I have no idea what to do I've basically tried everything I could find, on this website and others.
I hope you guys can help! Thanks very much :)

Those instructions do seem to lack one vital bit: the connection between DTR on the USB board, through a 100nF capacitor, to the reset pin of the ATMega328P.

Thank you. So how would I make this connection, given that the reset pin of the ATMega is already connected to a momentary switch?

Just like I said. There's more than one hole in the breadboard...

I will give it a go, thanks. Just to confirm: 100nF = 100 x 10^-9 F?

Yes, but what does that matter? 100nF is 100nF or 0.1uF. No one works in F it is too big.

Either you don't have serial communication, your ATmega is not powered, fused, and clocked correctly, or it does not yet contain a bootloader of compatible configuration.

Remove the pins connected to Tx and Rx while uploading the code , it worrked for me.
also include all the libraries currently used in your program.
Good luck!!

Check for Baudrate, the Arduino Serial Terminal, and serial port terminal should exactly match.
Or either check your Rx and Tx pins for respective voltages
Either there may be problem related to power supply.
It is better you also mention the code


text:
What is the equivalent of this old SPI code using the current SPI library?
I see some old library code that initializes SPI this way:
    SPI.begin();
    SPI.setClockDivider(2);

It does not use beginTransaction/endTransaction blocks, and setClockDivider is now deprecated. The current way to use SPI is to use transaction blocks where you pass the settings in.
What is the equivalent to this code using transaction blocks? Also, since the other settings (max speed, data order, data mode) aren't specified in the above code, there must be defaults. What are these defaults?

The default is:

Mode 0
MSBFIRST

Not sure on the default speed. But:
setClockDivider() sets a speed relative to the system clock. So it's impossible to say what speed that will be since it'll be different on 8MHz boards compared to 16MHz.
setClockDivider(2) would be the same as using F_CPU/2 as a speed.

I have example code here.
The code is:
#if SPI_HAS_TRANSACTION
  SPI.usingInterrupt (0);  // I am using external interrupt 0
  SPI.usingInterrupt (1);  // I am also using external interrupt 1
  SPI.beginTransaction (SPISettings (2000000, MSBFIRST, SPI_MODE0));  // 2 MHz clock
#else
  SPI.setClockDivider(SPI_CLOCK_DIV8);
  SPI.setBitOrder(MSBFIRST);
  SPI.setDataMode(SPI_MODE0);
#endif // SPI_HAS_TRANSACTION

digitalWrite (SS, LOW);        // assert Slave Select
byte foo = SPI.transfer (42);  // do a transfer
digitalWrite (SS, HIGH);       // de-assert Slave Select

#if SPI_HAS_TRANSACTION
  SPI.endTransaction ();   // allow external interrupts to fire now
#endif // SPI_HAS_TRANSACTION

The default setting for SPI is to use the system clock speed divided by four.

source: Stack Exchange

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

sort: votes


text:
Potentiometer with switch wiring question. Not reading correctly
I have a potentiometer with switch, that seems to be working a little wonky (Keep in mind I have tried this with a few different pots and they all behave the same way which leads me to believe I am wiring them wrong).
I can easily hookup the potentiometer and it's three terminals on the side, 1 being ground, 2 being output, 3 being input power. I can monitor it's value on a serial port with Arduino.  However when I try and test the switch, which are two terminals on the bottom of the pot.  I get an on signal when the pot is on, but when it is clicked off I get a random on/off signal.  As in it reads that it is sort of on but never truly reads off.
Right now I am simply giving it 5v from the Arduino to both the switch and the third terminal.  Should I be giving the switch power via a capacitor? Not sure, have not tried that yet but that may smooth out my readings.
Any suggestions?

From your description of switch wiring, it sounds like you have one of the switch leads attached to +5 V and the other switch lead to an input.
As noted in comments and answers to  “Why all unset pins of my Arduino Uno are outputting 2 volts?”, such an input will read high when the switch is closed, and will read randomly when it is open, because an input is a high-impedance device that can accumulate charge:

... input impedance typically can be taken as 100 MΩ for design purposes. ... Each pin has a few pF (5-10?) of capacitance ... which in general is small compared to stray capacitances of attached wiring.
When stray electromagnetic fields charge the pin and stray capacitances, a small voltage develops on the pin. You could connect a 1 to 10 MΩ resistor between the pin and ground, to avoid the [voltage] you are seeing.

The easy fix for the problem is to attach one switch-lead to ground, one to an input pin, and initialize the pin with INPUT_PULLUP pinmode instead of just INPUT.

Perfect, that makes sense, I now remember this small detail when learning Arduino a long time ago

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


text:
Non-blocking MQTT library
Are there any MQTT libraries that do not block while connecting?
I'm currently using PubSubClient, and the connection part contains this code:
https://github.com/knolleary/pubsubclient/blob/master/src/PubSubClient.cpp

        while (!_client->available()) {
            unsigned long t = millis();
            if (t-lastInActivity >= ((int32_t) MQTT_SOCKET_TIMEOUT*1000UL)) {
                _state = MQTT_CONNECTION_TIMEOUT;
                _client->stop();
                return false;
            }
        }

I'd like my main loop to continue, or a callback to be called, while the MQTT connection is established, rather than waiting for ages if the MQTT server is unavailable.
Update:
I wrote a modification to take a callback function, and called it in an else clause added to that if statement, and discovered that the blocking delay is not this while loop. I think it's in the _client->connect at the start of the method.

I had the same question and found an mqtt library that is completely non-blocking.

https://github.com/marvinroger/async-mqtt-client

You need to manually install it and the docs give instructions:

https://github.com/marvinroger/async-mqtt-client/blob/develop/docs/1.-Getting-started.md

It requires one additional library:

for esp8266: https://github.com/me-no-dev/ESPAsyncTCP
for esp32:   https://github.com/me-no-dev/AsyncTCP

I also liked the example's use of the Ticker library as a general tool for non-blocking code.

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


text:
Can the servo pulse width range be changed?
I recently found that standard servos only rotate 90deg total rotation for a pulse width range of 1-2 usec.  To rotate 180deg total rotation they need a .5-2.5 usec pulse range.  The arduino is programmed to only output the 1-2 usec range for 0-180 deg rotation.  Is there a way to make the arduino output the .5-2.5 usec pulse range to get full 180deg rotation?
Thanks

The Servo Attach method has two forms,
servo.attach(pin)
servo.attach(pin, min, max)

In the latter form, you can specify values for the min and max microseconds that servo.write() will use to represent 0° and 180° respectively.
Note, default values are 544 μs and 2400 μs, which is not so different than the range you say you want, so perhaps some other problem is afflicting your setup.
Also, as explained in my answer to question  “Change Servo Speed With RedBearLabs BLE Shield”, you can issue servo.write(value) calls with value in microseconds instead of in degrees, which may allow more precise control.

Thanks for responding to my post.  I thought I read somewhere that the Arduino outputs only the 1000usec to 2000usec pulse range, but I see from testing it that the standard range is as you say it is.  When you go to buy a servo, most that I've found say they only turn 90 deg, but can turn 180 deg. if you supply the greater pulse range of 500 usec to 2500 usec.  Hitec has a "180 deg. rotation" option that costs $10 but I think its not needed, the Arduino already can output the extended pulse range.  Hitec shows that standard RC servo controllers only output the smaller pulse range.


text:
Is this function subject to memory fragmentation?
I'm trying to understand if the following bit of code is subject to memory fragmentation.
Let's say I incrementally build a string within a function and I don't know how large the string should be.
String f() {
    String s = String("");
    s += "a"; // ...
    s += "bc"; // ...
    return s;
}

The String object does dynamic memory allocation internally, but s is on the stack, so once the function returns, the s object presumably deallocates and dynamically allocated memory is freed.
Before this happens, the String object to be returned must be copied from s. Since String objects hold internal data in dynamically allocated buffers, this means that the s internal buffer is allocated, then the return object internal buffer is allocated, then the s internal buffer is deallocated.
The return object internal buffer allocation is sandwiched between the s object alloc and dealloc.
To me, this implies that this will cause memory fragmentation. Am I reading this properly, or is this not the case? If so, does this also imply that functions like Serial.readString are also subject to memory fragmentation?

Pretty much every use of the String object can lead to memory fragmentation. Especially concatenating and copying objects.
I cover it here: https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/
You are much better off never using the String class and instead sticking to basic C strings (char arrays).

Thanks. And what about all the other classes in the Arduino library? A search at the Arduino source code finds a lot of ...allocs. Are Arduino projects subject to heap fragmentation in general?

There is very little allocation done in the core. It's only really String that does it. Libraries, though, are a law unto themselves.

Memory fragmentation is hard to predict, as it depends on how your
different allocation patters interact. This single pattern, per se,
looks safe. By safe I mean that if

your heap is not fragmented when you enter this function, and
you do no dynamic allocation inside the function other than growing the
string,

then the string will be allocated to the top of the heap and grow from
there without moving or making holes. You can check this is the case by
looking at the address of the string's internal buffer, which is given
by the c_str() method. It should not change inside the function:
String f() {
    String s = String("");
    const char * p = s.c_str();
    s += "a"; // ...
    s += "bc"; // ...
    if (p != s.c_str())
        Serial.println(F("Warning: memory fragmentation."));
    return s;
}

Edit: I wrote this small test program to show the behaviour of the
heap when you use string concatenation this way:
extern uintptr_t __brkval;

String f() {
    String s("");
    const char * p = s.c_str();
    Serial.print(F("  f(): string buffer @ 0x"));
    Serial.println((uintptr_t) p, 16);
    for (int i = 0; i < random(8) + 1; i++)
        s += random(2) ? "a": "bc";
    if (p != s.c_str())
        Serial.println(F("Warning: memory fragmentation."));
    Serial.print(F("        top of heap at 0x"));
    Serial.println(__brkval, 16);
    return s;
}

void setup() {
    Serial.begin(9600);
    Serial.print(F("***     heap starts at 0x"));
    Serial.println((uintptr_t) __malloc_heap_start, 16);
}

void loop() {
    Serial.print(F("loop(): top of heap at 0x"));
    Serial.println(__brkval, 16);
    String s = f();
    Serial.print(F("  f() returned "));
    Serial.println(s);
    Serial.print(F("        with buffer at 0x"));
    Serial.println((uintptr_t) s.c_str(), 16);
    delay(1000);
}

The output of the program is:
***     heap starts at 0x1D7
loop(): top of heap at 0x0
  f(): string buffer @ 0x1D9
        top of heap at 0x1DF
  f() returned abcbc
        with buffer at 0x1D9
loop(): top of heap at 0x1D7
  f(): string buffer @ 0x1D9
        top of heap at 0x1DF
  f() returned abcbc
        with buffer at 0x1D9
loop(): top of heap at 0x1D7
  f(): string buffer @ 0x1D9
        top of heap at 0x1DC
  f() returned aa
        with buffer at 0x1D9
loop(): top of heap at 0x1D7
  f(): string buffer @ 0x1D9
        top of heap at 0x1E2
  f() returned aabcabca
        with buffer at 0x1D9
[...]

The very first “top of heap at” is bogus because at this point the
malloc library has not been initialized. Besides that, you can see here
that:

the heap is always empty (top = bottom) at the beginning of loop()
the string is always allocated at the same place
the heap size inside f() varies depending on the string's length
the string is not copied when returned to the caller, as the internal
buffer is still at the same address.

However, if the statement String s = f(); is replaced by
String s; s = f();, then the string is copied when returned to the
caller, which doubles the amount of RAM required to handle it. This is
presumably because only the first form allows copy elision
optimization. (This
paragraph was added after reading Nick Gammon's answer, which made me
realize the copy elision issue).
Keep in mind that this works so nicely only because there is nothing
else doing dynamic allocation in this small program. This usage pattern
is safe, but once you start doing dynamic allocation in different parts
of the program, it becomes difficult to ensure that the
allocation/deallocation pattern is still safe vs. memory fragmentation.

The worst line in your example is this:
s += "a"; // ...

Any sort of loop that adds one byte to a String is potentially going to fragment memory. First the String class allocates zero bytes for the string, then when you add a byte, it has to allocate one byte, then when you add another byte it has to deallocate (free) that byte and allocate two bytes, and so on.
The allocator tries to be efficient, so eventually when you get up to three bytes you will, with luck, actually get the memory previously allocated to the one-byte string followed by the two-byte string.
But if other allocations have occurred (eg. another use of String elsewhere in the program) this might not be possible. Eventually you have lots of small gaps of maybe one or two bytes, with other stuff inbetween. Unless they are adjacent they cannot be recombined into a bigger block. This is your "fragmentation".

When you += "a", it does not free the previously allocated space: it calls realloc() to grow the buffer, and realloc() tries to grow it in place.  This works fine, without fragmentation, as long as your buffer is at the top of the heap.

Good point, however if you have multiple String instances, this may not work.
Edgar Bonet is right, however there is certainly the potential, with multiple String instances, for each of them to prevent the others from growing their buffer size neatly. In the example in the question, you will probably find that when f() returns, it returns a copy of the String allocated on the stack, thus we now have 2 x String instances.

While Edgar was writing some test code, so was I. :)
#include <memdebug.h>

String foo;

String f() {
  String s = String("");
  s += "a"; // ...
  s += "bc"; // ...
  return s;
}  // end of f

void showMemoryUsage ()
{
  Serial.println (F("---------------"));
  Serial.print (F("Largest block in freelist: "));
  Serial.println (getLargestBlockInFreeList ());
  Serial.print (F("Largest available memory: "));
  Serial.println (getLargestAvailableMemoryBlock ());
  Serial.print (F("Free memory: "));
  Serial.println (getFreeMemory ());
  Serial.print (F("address of foo data = "));
  Serial.println ((int) foo.c_str ());
} // end of showMemoryUsage

void setup()
{
  Serial.begin (115200);
  Serial.println ();
  showMemoryUsage ();
  Serial.println (F("Calling f() ..."));
  foo = f ();
  showMemoryUsage ();
  Serial.println (F("Calling f() ..."));
  foo = f ();
  showMemoryUsage ();
  Serial.print (F("foo = "));
  Serial.println (foo);
}  // end of setup

void loop ()
{
}  // end of loop

Memory debug library from http://andybrown.me.uk/wk/2011/01/01/debugging-avr-dynamic-memory-allocation/
Output:
---------------
Largest block in freelist: 0
Largest available memory: 1675
Free memory: 1677
address of foo data = 478
Calling f() ...
---------------
Largest block in freelist: 2
Largest available memory: 1669
Free memory: 1675
address of foo data = 482
Calling f() ...
---------------
Largest block in freelist: 2
Largest available memory: 1669
Free memory: 1675
address of foo data = 482
foo = abc

The address of the data in foo has changed from 478 to 482, so my prediction above was right. The function f() made a String, but a second copy was returned, hence we have now "lost" 4 bytes in the heap. Well, not lost, but there is a gap.
Calling f() a second time did not make the fragmentation worse.

BTW, this is unnecessary:
  String s = String("");

Just write:
  String s;

You are invoking a second String just to provide something to copy into the first String. Strings start off empty so this is just wasted time.

Actually, it first allocates one byte (for the NULL at the end of ""), not zero. When you += "a", it does not free the previously allocated space: it calls realloc() to grow the buffer, and realloc() tries to grow it in place. This works fine, without fragmentation, as long as your buffer is at the top of the heap.

See amended answer.

Added example code which tests the fragmentation theory.

Thanks for the test. It made me realize mine worked so well (zero copy) only because I used an idiom that allowed the compiler to do copy elision optimization. I added a note to my own answer. It's nice to learn stuff from comparing and elaborating answers this way. ;-)

I also had to print foo or the compiler thought I had made a useless variable and optimized it away. :)


text:
Why does DHT-library (and others) only allow one object instance?
I came across the problem to handle two DHT22 devices.
I use the Adafruit DHT Sensor library.
Since my Arduino sketch works as a "relay" for Serial commands on a host, I tried to wire up and dynamically instantiate DHT22. With no luck.
I checked the source and found, that the DHT object only gets constructed before setup() as a constant in the examples, because the library is written that way.
I did a quick hack, which works, but seems ugly to me:
DHT.cpp
DHT::DHT(uint8_t pin, uint8_t type, uint8_t count) {
-  _pin = pin;
-  _type = type;
-  #ifdef __AVR
-    _bit = digitalPinToBitMask(pin);
-    _port = digitalPinToPort(pin);
-  #endif
+  //_pin = pin;
+  //_type = type;
+  //#ifdef __AVR
+  //  _bit = digitalPinToBitMask(pin);
+  //  _port = digitalPinToPort(pin);
+  //#endif

...

-void DHT::begin(void) {
+void DHT::begin(uint8_t pin, uint8_t type, uint8_t count) {
+  _pin = pin;
+  _type = type;
+  #ifdef __AVR
+    _bit = digitalPinToBitMask(pin);
+    _port = digitalPinToPort(pin);
+  #endif

DHT.h*
-   void begin(void);
+   void begin(uint8_t pin, uint8_t type, uint8_t count=6);

Basically, I moved a few lines from the constructor to the begin() method. The whole thing works. I can even rewire & change the data-pin dynamically while the Arduino runs.
Here are my questions:

Is the hacked away behavior a bug or feature?
Would my solution be good enough for a pull request to Adafruit? I would clean it up beforehand.

I would contact the owners of the Github repository and point them to your "hack" and get the thumbs up first. At least, you would be notifying them about the issue. Either they don't know about it, or are working on a fix

Upvote for editing my post. Nice diff feature btw.

There is nothing wrong with the library. It does not allow just one object instance.
What is wrong is your way of using it.
It, and many other libraries, specify the pin numbers and other (under normal usage) static data in the constructor. You want to have two objects then create two objects.
But it seems you want to change that static data. So you need to construct differently.  Instead of statically declaring your objects you need to be dynamic. Use new and delete.
DHT *myDHT = NULL;

myDHT = new DHT(4,5);
// do something
// change pins
delete myDHT;
myDHT = new DHT(6,7);

Cool, I missed that, since I'm not familar with the underlying concepts of C, but your answer is what I was looking for. This is why I wrote, that my solution seems ugly to me. I keep the repo on github, to keep this post understandable.

The onky caveat with it is that excessive use on boards with very low memory could lead to heap fragmentation and stability issues. Shouldn't happen as long as you new immediately after deleteing.

On second thought. Wouldn't it save mem on the arduino, if only one Object exists? I think this was the origin of the hack. Changing an objects attribute value should be much cheaper, than instanciating an object and destroying it again.

No memory difference. Just where in memory it resides. Maybe a minor difference in processing at the time of instantiation, but minimal.

Changing the pins sounds like a reasonable requirement, and you shouldn't have to delete/new to achieve it.
I would leave the library alone (for backwards compatibility) except to add a changePins function which you may choose whether or not to call, to assign new pins to the class structure. (Effectively it would be your rewritten begin function with a different name).


text:
How to add SD card to store data
I'm new to Arduino and I was wondering how to add an SD card to Arduino so it can store more code and also store files such as text files.
Is there such a shield, and if so, any suggestions?

Have you asked Google? It knows about ALL the shields. But yes, there are shields. There are lots and lots and lots and lots of shields, breakout boards, dead-bug tutorials, you name it.

There are 2 things you need to know: SD-card library & https://luckyresistor.files.wordpress.com/2014/10/sd-card2.png

I'm voting to close this question as off-topic because it's more a general question...

On top of that already said, you cannot use the SD card to store code, only data

Take a look at this:
Sparkfun OpenLog

Here's a good tutorial:
https://learn.adafruit.com/adafruit-micro-sd-breakout-board-card-tutorial/intro
This is from adafruit and is for the micro sd card.

authors: Дмитрий Шатаев


text:
Arduino join multiple strings and numbers and then seperate them
OK, I'm working on a remote controlled robot. Both the robot and the remote use Arduino with a Bluetooth shield. The Bluetooth is working and I need to send something similar to this over Bluetooth:
X:1026,Y:1026,Button:1
There may be more buttons added and X,Y can be between 1026 and 0. How can I build that string from:
xPosition = 1026;
 yPosition = 1026;
 buttonState = 0;
I also need to be able to separate that string back into variables on the 2nd Arduino.
EDIT: I have seen other questions similar to this but they involved Serial. I am using Bluetooth.
EDIT AGAIN: I am sending the data over Bluetooth with the BlueToothSerial.print command from the SoftwareSerial.h library. (BlueToothSerial is SoftwareSerial BlueToothSerial(RxD,TxD);)

Have a look at the Serial.parseint function and format your output and input so the come in correct order.

You do realise, don't you, that the fact that you're using Bluetooth is a complete red-herring? It is just being used as a bridge between two serial ports. What you read pertaining to Serial is the same as your bluetooth.

Indeed, serial-interfaced Bluetooth is just serial... with one catch for the unwary.  Because the bluetooth portion will be packetized, data may arrive at the far end in bursts, potentially with gaps between them at arbitrary points, such as the middle of a word rather than in any logical place. Well written receiving software won't care about that, as it should read across delays until finding a known end-of-message condition such as a newline character. But badly written software that makes invalid assumptions (such as assuming that a full message will be received at once) could be confused.

To make the string you can:
char outstring[30];
sprintf(outstring, "X:%d,Y:%d,Button:%d", xPosition, yPosition, buttonState);

Be sure to make the outstring big enough to store it all.
That is, of course, if you actually need to have the whole thing in one string all the time.  You haven't said how you are sending it (yes, I know, bluetooth, but there is bluetooth and there is bluetooth, and there are different ways of it working.)
Splitting a string like that can be done with strtok() then looking for the location of the colon in each returned token. Or, depending on how the string data actually arrives, could be parsed on a character-by-character basis, which would be better. Again, because you haven't told us how the data is actually being transferred it's impossible to elaborate on that.

I edited the post with how I am sending the data. I can send it separately and receive it as one string, but I don't know how too separate the string into multiple variables.

@Starwarsfan2099 Majenko hinted on using strtok() which is a C++ function and is well documented:  http://www.cplusplus.com/reference/cstring/strtok/ you might also use the Arduino indexOf function to find the comma's "," in your text string, see this tutorial: https://www.arduino.cc/en/Tutorial/StringIndexOf


text:
How to read long value sent by Arduino in C
I have a quick question regarding this code below in Arduino:
Serial.print("0");
Serial.print(5);
Serial.print("0");
Serial.print(1);
Serial.print("0");
Serial.print(5);
Serial.print("0");
Serial.print(1);
Serial.print("0");
Serial.println(5);

In C code, currently I'm receiving the message using this method below:
int serialport_read_until(int fd, char* buf, char until, int buf_max, int timeout)
{
    char b[1];  // read expects an array, so we give it a 1-byte array
    int i=0;
    do {
        int n = read(fd, b, 1);  // read a char at a time
        if( n==-1) return -1;    // couldn't read
        if( n==0 ) {
            usleep( 1 * 1000 );  // wait 1 msec try again
            timeout--;
            if( timeout==0 ) return -2;
            continue;
        }
        buf[i] = b[0];
        i++;
    } while( b[0] != until && i+1 < buf_max && timeout>0 );

    buf[i] = 0;  // null terminate the string
    return 0;
}

In C i defined:
char message[13];
uint32_t num;
char until = '\n';

serialport_read_until(fd, message, newLine, sizeof message, 20000);
// the 20000 is timeout in millisec
// this method stores the data in serial buffer into message array

printf("message is %d\n", num);

I am expecting a raw value of 0501050105 first.
Then I convert this raw string into 501050105 using:
sscanf(message, "%d", &num);

Currently it works fine, but I strongly believe it is not the correct way to do it (or rather not the optimized way to do it).
In addition, when i use serialport_read_until() method above, even though i specify the char until as '\n', the method terminates after reading '\r' (leaving the \n in the serial buffer), and the '\n' is only captured in the next method call.
Q1: Am i reading the \r\n wrongly from the println (I saw in Arduino documentation that println prints \r\n)? What resulted in C 'cutting off' the message when it detected a \r from Arduino even though I specifically set to kill it only when \n is received?
Q2: Instead of printing a string to me and converting it back to integer in C, is there a way for Arduino to send me a long value directly instead? eg 501050105 or 51515. how should I rewrite the serial print or method? And how do i capture that integer correctly in C? If i'm not wrong if a raw integer is print out from Arduino, it converts it into ASCII code. I'm still very new to C and Arduino and hope some guidelines to be given so I can improve on the current coding.
Thank you very much.

What's the number you are sending? 501050105? or 51515?

@NickGammon currently we are sending 501050105 but we are thinking of reducing it to 51515 in future. Both will still be long in Arduino

What I am trying to ask is: What is the "actual" number you are sending? For example, could it be: 5,1,5,1,5? Are the zeroes part of the number or a delimiter?

@NickGammon yes we are trying to send 5,1,5,1,5 efficiently from arduino to C!! Not sure if theres any other efficient ways to do it. We currently reserve 2 digits for the 5 different variables, so i split them up with x%100 followed by x/100 and repeat 4 more times

The commas sounds much more sensible to me. What if you want to send a zero?

@NickGammon We will never ever send a zero (minimum value is 1). if we were to use comma, whats the efficient way to extract it out? strtoul, sscanf or others?

If you are always sending one digit, then the simplest is your suggestion of just packing them all together. Then just index into the received array, eg. message[0], message[1] and so on. And to convert back to a number, just subtract '0' from it.

@NickGammon ok thanks i will try out later and let you know!

char b[1];  // read expects an array, so we give it a 1-byte array

No, it expects a pointer to a destination to store the data. You don't need a 1-entry array - you can simplify your code with:
char b;
...
int n = read(fd, &b, 1);  // read a char at a time
...
buf[i] = b;
... etc ...

Currently it works fine, but I strongly believe it is not the correct way to do it (or rather not the optimized way to do it).

C has the function strtoul() which is far more efficient that sscanf.
uint32_t val = strtoul(buf, NULL, 10);

The 10 is the base to convert from, so you could convert hexadecimal (base 16), octal (base 8), etc using it.

Q1: Am i reading the \r\n wrongly from the println (I saw in Arduino documentation that println prints \r\n)? What resulted in C 'cutting off' the message when it detected a \r from Arduino even though I specifically set to kill it only when \n is received?

You're defining the variable until to contain \n, yet passing the variable newLine to your function. Maybe that has something to do with it?

Q2: Instead of printing a string to me and converting it back to integer in C, is there a way for Arduino to send me a long value directly instead? eg 501050105 or 51515. how should I rewrite the serial print or method? And how do i capture that integer correctly in C? If i'm not wrong if a raw integer is print out from Arduino, it converts it into ASCII code. I'm still very new to C and Arduino and hope some guidelines to be given so I can improve on the current coding.

You can send a 32-bit value using just 4 bytes. However it's not reliable without implementing a whole protocol around those 4 bytes which, for just 4 bytes, is a bit of a waste. Simplest just to stick to ASCII encoding your data.

Thanks for the feedback! That was a typo! It's char newLine = '\n'; Not sure why it still cuts at \r. Could it possibly be because of something like this? https://github.com/todbot/arduino-serial/issues/9 Could I be missing something like this? options.c_iflag &= ~ICRNL; // Don't Map CR to NL


text:
Debugging arduino shield for varying voltage
I'm using this motor shield for arduino from adafruit. It says it can drive 4 DC motors with it. However, two terminals M3 & M4 (as marked in the image) seem to be supplying lesser voltage.

To avoid this becoming an XY problem, some more details:
The entire setup consists of an arduino, shield, raspberry Pi 3 & the motors being  powered with a 2200 mAh 12v supply. The raspberry pi is powered from the 5v supply of this shield.
Now the problem as mentioned is that even though M1 & M2 get the 12v, M3 & M4 don't. When I measured they give varying degree of voltage (3v - 6v). I tried disconnecting & connecting various combinations, with & without motors connected, pi removed, etc. All are giving same result. When I supplied 5v as external power, these pins in question dropped to 2v-3v.
As per this documentation, there seems to be a difference in M3, M4 in that they run at 1KHZ, to save power. But my knowledge to make of this info seems to be limited. Can anyone point me to the right direction here?
The complete setup.

L293D & L298 type bipolar drivers have absurdly high internal losses and should basically be considered to be obsolete by at least a decade and unsuited to low voltage applications.  You will have much better results with an FET bridge.  If you want to try to use the bipolar bridge in the meantime supply it with 2v or so more than you want the connected motors to see.  Of course the bridge and your supply must be rated for the expected current!

Also, a voltmeter measurement of a PWM type output is only going to be truly meaningful when the PWM is set to 0 or 100%.  An analog meter might average something in between to a degree, but a digital one (and even more so if it is a budget model as pictured) could have sampling effects leading to misleading readings.


text:
LEDs instruction code does not loop
I am using Neopixel Library and a Trinket Pro 5V Microcontroller to chase first three LEDs on a strip and then burst the last 2 (could be modified based on the number of LEDs).
The LEDs chase only once. See the code below. I am not sure why, even though the logic is inside the loop function, it only executes once. Any suggestions?
#include <Adafruit_NeoPixel.h>
#include "WS2812_Definitions.h"
#ifdef __AVR__
  #include <avr/power.h>
#endif

// Which pin on the Arduino is connected to the NeoPixels?
// On a Trinket or Gemma we suggest changing this to 1
#define PIN            6

// How many NeoPixels are attached to the Arduino? How many Neopixels do you want to chase (starting from the first in address 0. How many do you want to burst at the end?
#define NUMPIXELS      5
#define NUMPIXELSCHASE 3
#define NUMPIXELSBURST 2

// When we setup the NeoPixel library, we tell it how many pixels, and which pin to use to send signals.
// Note that for older NeoPixel strips you might need to change the third parameter--see the strandtest
// example for more information on possible values.
Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);

void setup() {
  // This is for Trinket 5V 16MHz, you can remove these three lines if you are not using a Trinket
#if defined (__AVR_ATtiny85__)
  if (F_CPU == 16000000) clock_prescale_set(clock_div_1);
#endif
  // End of trinket special code

  pixels.begin(); // This initializes the NeoPixel library.
  clearLEDs();
  pixels.show();
}

void loop() {

  // For a set of NeoPixels the first NeoPixel is 0, second is 1, all the way up to the count of pixels minus one.
  for(int i=0;i<NUMPIXELSCHASE;i++){

   pixels.setPixelColor(i, INDIGO);
   pixels.show(); // This sends the updated pixel color to the hardware.
   delay (200);
  }

  for(int i=NUMPIXELS-NUMPIXELSBURST;i<NUMPIXELS;i++){

   pixels.setPixelColor(i, AQUA);
   pixels.show(); // This sends the updated pixel color to the hardware.
   delay(0);
  }
}

// Sets all LEDs to off, but DOES NOT update the display;
// call leds.show() to actually turn them off after this.
void clearLEDs()
{
  for (int i=0; i<NUMPIXELS; i++)
  {
    pixels.setPixelColor(i, 0);
  }
}

Thank you.

Your 1st pixel should go indigo & stay there, & the other 2 very briefly show Aqua before going back to Indigo. Try a longer delay than 0 at the end, and then clear them down for the next loop.

I agree. Those NeoPixels update quickly. A delay(0) doesn't seem very sensible.


text:
Possible to determine at runtime whether a pointer is declared PROGMEM?
Is it possible to determine at runtime whether a pointer points to PROGMEM'ed values or regular values? This would give some flexibility when writing code that handles both.

Not really, if you are asking whether you can determine (simply from its value) whether 0x100 is in RAM or PROGMEM. Both are possible candidates for a memory location.
The F() macro works around this by changing the type of a variable at compile-time, so that the compiler can select a suitable method of printing. For example:
Serial.println ("Hello, world");
Serial.println (F("Hello, world"));

In this case the appropriate println function is chosen at compile-time by the compiler, based on the type (one would be a const char *, the other a __FlashStringHelper type).
You are best off designing a way (similar to the F() macro) where you can make the decision at compile time.

Is it possible to determine at runtime whether a pointer points to PROGMEM'ed values or regular values? This would give some flexibility when writing code that handles both.

The AVR MCUs are Harvard Architectures. Data and program memory spaces are separated. There are also several data memory spaces, e.g. SRAM, EEPROM, PROGMEM. Each of these have there own address space, and special instructions are used to access them.
In software anything is possible :) so it is possible to unify the address spaces and use a run-time mechanism to do the respective read and write. A simple method is to use the most significant bits to determine the address space. For instance,
SRAM 0x0000..0x7fff
EEPROM 0x8000..0x8fff
PROGMEM 0x9000..0xffff

SRAM pointers are as usual, EEPROM pointers have an extra 0x8000, and PROGMEM pointers an extra 0x9000.
The next step is to write a simple mapping function from the unified address space to the separate memory address spaces. This can be wrapped into a C+++ smart pointer and/or a simple C++ class hierarchy.
An example of this technique can be found in 1) Forth Virtual Machine for Arduino, https://github.com/mikaelpatel/Arduino-FVM (see https://github.com/mikaelpatel/Arduino-FVM/blob/master/src/FVM.cpp#L85), 2) RPN Postscript/Forth Command Shell for Arduino, https://github.com/mikaelpatel/Arduino-Shell (see https://github.com/mikaelpatel/Arduino-Shell/blob/master/Shell.h#L1059).
Cheers!
PS: An interesting detail with the AVR architecture is that the registers 0..31, and the io-registers, are mapped to the SRAM address space.

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


text:
GPS North? South? East? West?
I'm using the Adafruit SIM808 breakout board to text a GPS link to Google Maps when pinged. My program is mostly working, but the GPS data that I get has no "N, S, E, W" indicators. In addition, I know that the longitude where I live is negative but it's coming out as positive. This is the output that I get:

This is the code that triggers that output:
int8_t stat;
// check GPS fix
stat = fona.GPSstatus();
if (stat < 0)  {
  Serial.println(F("Failed to query"));
}
if (stat == 0) {
  Serial.println(F("GPS off"));
}
if (stat == 1) {
  Serial.println(F("No fix"));
}
if (stat == 2) {
  Serial.println(F("2D fix"));
}
if (stat == 3) {
  Serial.println(F("3D fix"));
}

// check for GPS location
char gpsdata[120];
fona.getGPS(0, gpsdata, 120);
Serial.println(gpsdata);

I'm already reading about how to fix the GPS data so that it can be used by Google Maps, but I don't know what to do about the issue of not having the directional information/sign.
Here is the full code, just for reference:
#include "Adafruit_FONA.h"
#include <SoftwareSerial.h>

#define FONA_RX 2
#define FONA_TX 3
#define FONA_RST 4
#define FONA_KEY 7
#define FONA_PS 8

// this is a large buffer for replies
char replybuffer[255];

SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX);
SoftwareSerial *fonaSerial = &fonaSS;
Adafruit_FONA fona = Adafruit_FONA(FONA_RST);
uint8_t readline(char *buff, uint8_t maxbuff, uint16_t timeout = 0);

void setup() {
  Serial.begin(115200);
  pinMode(FONA_KEY, OUTPUT);
  pinMode(FONA_PS, INPUT);
  analogReference(INTERNAL);
  delay(2000);

  TurnOffFona();

  Serial.println(F("FONA SMS caller ID test"));
  Serial.println(F("Initializing....(May take 3 seconds)"));
  delay(1000);

  TurnOnFona();

  fonaSerial->begin(4800);
  if (! fona.begin(*fonaSerial)) {
    Serial.println(F("Couldn't find FONA"));
    while (1);
  }
  Serial.println(F("FONA is OK"));

  // Print SIM card IMEI number.
  char imei[15] = {0}; // MUST use a 16 character buffer for IMEI!
  uint8_t imeiLen = fona.getIMEI(imei);
  if (imeiLen > 0) {
    Serial.print("SIM card IMEI: "); Serial.println(imei);
  }

  // turn GPS on
  if (!fona.enableGPS(true)) {
    Serial.println(F("GPS failed to turn on"));
  }

  Serial.println("FONA Ready");
}

char fonaInBuffer[64]; //for notifications from the FONA

void loop() {
  char* bufPtr = fonaInBuffer; //handy buffer pointer

  if (fona.available()) {
    //any data available from the FONA?
    int slot = 0; //this will be the slot number of the SMS
    int charCount = 0;
    //Read the notification into fonaInBuffer
    do  {
      *bufPtr = fona.read();
      Serial.write(*bufPtr);
      delay(1);
    } while ((*bufPtr++ != '\n') && (fona.available()) && (++charCount < (sizeof(fonaInBuffer) - 1)));

    //Add a terminal NULL to the notification string
    *bufPtr = 0;

    //Scan the notification string for an SMS received notification.
    //  If it's an SMS message, we'll get the slot number in 'slot'
    if (1 == sscanf(fonaInBuffer, "+CMTI: \"SM\",%d", &slot)) {
      Serial.print("slot: "); Serial.println(slot);
      char callerIDbuffer[32];  //we'll store the SMS sender number in here

      // Retrieve SMS sender address/phone number.
      if (! fona.getSMSSender(slot, callerIDbuffer, 31)) {
        Serial.println("Didn't find SMS message in slot!");
      }
      Serial.print(F("FROM: ")); Serial.println(callerIDbuffer);

      int8_t stat;
      // check GPS fix
      stat = fona.GPSstatus();
      if (stat < 0)  {
        Serial.println(F("Failed to query"));
      }
      if (stat == 0) {
        Serial.println(F("GPS off"));
      }
      if (stat == 1) {
        Serial.println(F("No fix"));
      }
      if (stat == 2) {
        Serial.println(F("2D fix"));
      }
      if (stat == 3) {
        Serial.println(F("3D fix"));
      }

      // check for GPS location
      char gpsdata[120];
      fona.getGPS(0, gpsdata, 120);
      Serial.println(gpsdata);
      String gpsString;

      gpsString = (String) gpsdata; //re-cast chr array as string.
      Serial.println(gpsString);
      int commaIndex = gpsString.indexOf(',');
      int secondCommaIndex = gpsString.indexOf(',', commaIndex + 1);
      int thirdCommaIndex = gpsString.indexOf(',', secondCommaIndex + 1);
      int fourthCommaIndex = gpsString.indexOf(',', thirdCommaIndex + 1);

      String firstValue = gpsString.substring(0, commaIndex);
      String rawLat = gpsString.substring(commaIndex + 1, secondCommaIndex);
      String rawLon = gpsString.substring(secondCommaIndex + 1, thirdCommaIndex);
      String rawAlt = gpsString.substring(thirdCommaIndex + 1, fourthCommaIndex);

      int decimalIndex = rawLat.indexOf('.');
      String lat1 = rawLat.substring(0, decimalIndex);
      String lat2 = rawLat.substring(decimalIndex + 1, rawLat.length());
      Serial.println(lat1);
      Serial.println(lat2);
      rawLat = lat1.substring(0, 2) + "." + lat1.substring(3, lat1.length()) + lat2;
      Serial.println(rawLat);

      int decimal2Index = rawLon.indexOf('.');
      String lon1 = rawLon.substring(0, decimal2Index);
      String lon2 = rawLon.substring(decimal2Index + 1, rawLon.length());
      Serial.println(lon1);
      Serial.println(lon2);
      rawLon = lon1.substring(0, 2) + "." + lon1.substring(3, lon1.length()) + lon2;
      Serial.println(rawLon);

      char txtmsgArray[80];
      String txmsg = "https://www.google.com/maps/@" + rawLat + "," +  rawLon + ",15z";
      txmsg.toCharArray(txtmsgArray, 80);
      Serial.println(txtmsgArray);

      Serial.println("Sending reponse...");
      if (!fona.sendSMS(callerIDbuffer, txtmsgArray)) {
        Serial.println(F("Failed"));
      } else {
        Serial.println(F("Sent!"));
      }
      delay(3000);
      // delete the original msg after it is processed
      //   otherwise, we will fill up all the slots
      //   and then we won't be able to receive SMS anymore
      if (fona.deleteSMS(slot)) {
        Serial.println(F("OK!"));
      } else {
        Serial.println(F("Couldn't delete"));
      }
    }
  }
}

void TurnOnFona() {
  Serial.println("Turning on Fona: ");
  while (digitalRead(FONA_PS) == LOW) {
    digitalWrite(FONA_KEY, LOW);
  }
  digitalWrite(FONA_KEY, HIGH);
  delay(4000);
}

void TurnOffFona() {
  Serial.println("Turning off Fona ");
  while (digitalRead(FONA_PS) == HIGH) {
    digitalWrite(FONA_KEY, LOW);
  }
  digitalWrite(FONA_KEY, HIGH);
  delay(4000);
}

Using AT+CGPSINF=1 should give you NMEA formatted data. That may be of more use to you.

Send the command:
AT+CGPSOUT=1
That should enable the output of the standard NMEA $GPGGA string which includes all the position information you should need in a format that either you can parse or use one of the many existing libraries to parse. It's not clear from the documentation if this will be a one time output or a 1 Hz output.
There are other NMEA messages available if you need them, see https://cdn-shop.adafruit.com/datasheets/SIM808_GPS_Application_Note_V1.00.pdf for details.

GPS is a positioning system: it doesn't do direction.  If your software has serial information coming in,  it can take the difference in readings and generate that data but GPS doesn't do it for you.
Some devices may add it to the standard,  but that's a per-device feature. .

Op is asking for the hemisphere not the direction

No he wasn't, that's "in addition"


text:
What happens if I try to draw power from the VIN port while under USB power on an Uno?
I would like to have a shield permanently attached that use the VIN (not 5v) for it's power - the problem comes in when I want to program the arduino (via the USB port), do I need to also have the barrel connector plugged in, or can I just expect the shield to not work (no, it won't be damaged from not getting enough/any power), but have the arduino itself be fine - or am I somehow damaging the power regulator by attempting to use it in reverse?

You do run the risk of damaging the 5V regulator, yes.
Power will attempt to flow from the 5V rail (USB port) through the voltage regulator (backwards) and into the shield to power it.
As your shield doesn't mind being under-powered from 5V while you're programming the Arduino you can add a diode between 5V (anode) and Vin (cathode). This will bypass the regulator when the voltage of the 5V rail is higher than the Vin rail, and your shield will be supplied with about 4.3V (slightly higher for a schottky diode).

So that would reduce the reverse voltage across the regulator to around .7v if I did it like this I think that would work, thanks

@user2813274 Yep, that's right.


text:
How to merge two arduino sketches, one for relay's and one for Servo motor?
Recently I uploaded individual codes for relay's and Servo motor seperately, it all worked fine. But when I combined these two codes and dumped in to the loop there is a delay in functioning of the relay's but the Servo motor is working fine.
I have to control these devices through Bluetooth HC-05 module.
Could you please help me with the code?
/*
simple LED test
*/
#include <Servo.h>
char val;         // variable to receive data from the serial port
int ledpin = 2; // LED connected to pin 2 (on-board LED)
Servo myservo;
int pos = 0;    // variable to store the servo position
int motor = 0;

void setup()
{
  pinMode(ledpin = 2, OUTPUT); // pin 2 (on-board LED) as OUTPUT
  pinMode(ledpin = 3, OUTPUT); // pin 3 (on-board LED) as OUTPUT
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  Serial.print("Arduino control Servo Motor Connected OK");
  Serial.print('\n');
  Serial.begin(9600);       // start serial communication at 115200bps
  digitalWrite(ledpin = 2 ,HIGH);
  digitalWrite(ledpin = 3 ,HIGH);

}

void loop()
{

      if( Serial.read() == 'a' )    // if 'a' was received led 2 is switched off
  {
    digitalWrite(ledpin = 2, HIGH);    // turn Off pin 2

  }

  if( Serial.read() == 'A' )               // if 'A' was received led 2 on
  {
    digitalWrite(ledpin = 2, LOW);  // turn ON pin 2

  }

  if( Serial.read() == 'b' )        // if 'b' was received led 3 is switched off
  {
    digitalWrite(ledpin = 3, HIGH);    // turn Off pin 3

  }

  if( Serial.read() == 'B' )               // if 'B' was received led 3 on
  {
    digitalWrite(ledpin = 3, LOW);  // turn ON pin 3

  }

  if (Serial.read() == '\n')
    {

   motor = Serial.parseInt();
    pos = Serial.parseInt();
      myservo.write(pos);
      delay(15);
      Serial.print("Data Response : ");
      Serial.print(motor, DEC);
      Serial.print(pos, DEC);

    }

    }

A couple of things stand out in your code.

Whenever you perform a digital write you assign a value to ledpin:
digitalWrite(ledpin = 3, LOW);

This is not necessary as you do not do anything with the ledpin variable. Instead, just have the digital I/O pin number:
digitalWrite(3, LOW);

Or simply have 2 variables, one for pin 2 and another for pin 3. Eg.
redledpin = 2;
greenledpin = 3;

This also applies to the pinMode function calls in the setup function.
Each one of your  if( Serial.read() == xx) statements will read a serial character off of the serial buffer. Instead store the read character in a local variable:
readChar = Serial.read()
if( readchar == 'a')
...
if( readchar == 'A')
...
if( readchar == 'b')
...
if( readchar == 'B')
...

I would encase all of the code inside loop() with:
if ( Serial.available() )
{
    ...
}

The delay function is blocking and this will cause issues. I suggest deleting the delay altogether.
Due to the fact that you are sending commands to turn digital outputs on and off as well as sending an integer for motor and another for pos, I suggest that you define a packet structure and make your code follow that (with the necessary error handling). As the code currently stands you will miss information, depending on what character it sees first on the serial buffer.
I suggest something like:
A, B, 142, 090

Starting the packet off with a know character is a good idea. So is having a timeout period - in case only a portion of your packet is received.

This will assign the value of 3 to ledpin and because the operation was successful it will evaluate to true. No it won't. It will evaluate to 3.

Which works because true is any value different from 0. If you try to write ledpin = 0 that will evaluate as false


text:
A library for manipulate Intel Hex data?
For a project i need to extract some data from an external eeprom and then store it somewhere. Suddenly after some manipulations (not necessarly with Arduino board) i need to put them in an external eeprom.
What I would do is to convert the extracted data from the EEPROM in Intel Hex data and vice versa.
To do this I wanted to know if there is already a library for that purpose "ready to use" made for Arduino boards.
thanks

Why does it have to be in Intel Hex format? You could write out the EEPROM to the serial port one byte to a line, or something. Something like this:
#include <EEPROM.h>

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

  for (int addr = 0x0000; addr < 0x0010; addr++)
    {
    Serial.print ("Address = ");
    Serial.print (addr, HEX);
    Serial.print (", value = ");
    Serial.println (EEPROM.read(addr), HEX);
    }

}  // end of setup

void loop ()
{
}  // end of loop

I'm not personally aware of a library that happens to write out/read in, Intel Hex format from/to the EEPROM.

I have code that uploads and downloads files to the Arduino. Inside that is code to read/write Intel hex format. However it isn't a library.
Inside File_Utils.ino are some comments that show the format:
/*
Line format:

  :nnaaaatt(data)ss

  Where:
  :      = a colon

  (All of below in hex format)

  nn     = length of data part
  aaaa   = address (eg. where to write data)
  tt     = transaction type
           00 = data
           01 = end of file
           02 = extended segment address (changes high-order byte of the address)
           03 = start segment address *
           04 = linear address *
           05 = start linear address *
  (data) = variable length data
  ss     = sumcheck

            * We don't use these

*/

In that file is code to write Intel Hex format (reading from Flash, not EEPROM):
void readFlashContents ()
  {
  if (!haveSDcard)
    {
    Serial.println (F("*** No SD card detected."));
    return;
    }

  progressBarCount = 0;
  pagesize = currentSignature.pageSize;
  pagemask = ~(pagesize - 1);
  oldPage = NO_PAGE;
  byte lastMSBwritten = 0;

  while (true)
    {

    Serial.println ();
    Serial.println (F("Choose file to save as: "));

    getline (name, sizeof name);
    int len = strlen (name);

    if (len < 5 || strcmp (&name [len - 4], ".HEX") != 0)
      {
      Serial.println (F("File name must end in .HEX"));
      return;
      }

    // if file doesn't exist, proceed
    if (!sd.vwd()->exists (name))
      break;

    Serial.print (F("File "));
    Serial.print (name);
    Serial.println (F(" exists. Overwrite? Type 'YES' to confirm ..."));

    if (getYesNo ())
      break;

    }  // end of checking if file exists

  // ensure back in programming mode
  if (!startProgramming ())
    return;

  SdFile myFile;

  // open the file for writing
  if (!myFile.open(name, O_WRITE | O_CREAT | O_TRUNC))
    {
    Serial.print (F("Could not open file "));
    Serial.print (name);
    Serial.println (F(" for writing."));
    return;
    }

  byte memBuf [16];
  bool allFF;
  unsigned int i;
  char linebuf [50];
  byte sumCheck;

  Serial.println (F("Copying flash memory to SD card (disk) ..."));

  for (unsigned long address = 0; address < currentSignature.flashSize; address += sizeof memBuf)
    {

    unsigned long thisPage = address & pagemask;
    // page changed? show progress
    if (thisPage != oldPage && oldPage != NO_PAGE)
      showProgress ();
    // now this is the current page
    oldPage = thisPage;

    // don't write lines that are all 0xFF
    allFF = true;

    for (i = 0; i < sizeof memBuf; i++)
      {
      memBuf [i] = readFlash (address + i);
      if (memBuf [i] != 0xFF)
        allFF = false;
      }  // end of reading 16 bytes
    if (allFF)
      continue;

    byte MSB = address >> 16;
    if (MSB != lastMSBwritten)
      {
      sumCheck = 2 + 2 + (MSB << 4);
      sumCheck = ~sumCheck + 1;
      // hexExtendedSegmentAddressRecord (02)
      sprintf (linebuf, ":02000002%02X00%02X\r\n", MSB << 4, sumCheck);
      myFile.print (linebuf);
      lastMSBwritten = MSB;
      }  // end if different MSB

    sumCheck = 16 + lowByte (address) + highByte (address);
    sprintf (linebuf, ":10%04X00", (unsigned int) address & 0xFFFF);
    for (i = 0; i < sizeof memBuf; i++)
      {
      sprintf (&linebuf [(i * 2) + 9] , "%02X",  memBuf [i]);
      sumCheck += memBuf [i];
      }  // end of reading 16 bytes

    // 2's complement
    sumCheck = ~sumCheck + 1;
    // append sumcheck
    sprintf (&linebuf [(sizeof memBuf * 2) + 9] , "%02X\r\n",  sumCheck);

    myFile.clearWriteError ();
    myFile.print (linebuf);
    if (myFile.getWriteError ())
       {
       Serial.println ();  // finish off progress bar
       Serial.println (F("Error writing file."));
       myFile.close ();
       return;
       }   // end of an error

    }  // end of reading flash

  Serial.println ();  // finish off progress bar
  myFile.print (":00000001FF\r\n");    // end of file record
  myFile.close ();
  // ensure written to disk
  sd.vwd()->sync ();
  Serial.print (F("File "));
  Serial.print (name);
  Serial.println (F(" saved."));
  }  // end of readFlashContents

That should give you some tips about how to write out the file. Look in my code to see the reading code as well. However as I said, you don't necessarily have to use that format if you just want to manipulate the data yourself.

But the Intel Hex isn't made for that purpose?

Hex is Hex. Intel Hex is a file format for storing data (in ASCII-HEX) to be loaded to specific addresses. It's a very plain ASCII format and easy to read, write (by humans) and to code for. There really isn't much more to do than skip past an address value and start reading byte data. What might a library to do for you?

Nick's answer assumes you just want to read/process/write the data from one place to another.  If that's the case, there's no need to store the data into an Intel Hex Data formatted file – just keep it in a flat array, or a file that's formatted conveniently rather than in a form that requires parsing.
Of course, if you actually need the formatted file for some reason – such as an intermediate program only working with Hex files – you could edit the question and say so.
Note,  Python Software Foundation's IntelHex page provides a

Python library to read, write, create from scratch and manipulate data from HEX (also known as Intel HEX) file format.

To use it, you would write a Python program that (on your host computer) reads serial-port data with values to be stored, and uses the IntelHex library to write a Hex file.  After the intermediate program fiddles with the Hex file, another Python program on your host computer uses IntelHex to read the modified Hex file and writes it to EEPROM or to serial for an Arduino to write it to an EEPROM.

avrdude himself is very good at providing/inferring the various formats. We are ourselves manipulating output - EEPROMs, for example - in an external editor.
Of course, avrdude is neither external nor a library, but...


text:
Convert library from using bitbanging to hardware SPI
I'm using a MCP3008 8ch 10bit ADC to expand the Analog Inputs for the project I'm working on. The only library I can find for it is here the library is ported from Adafruit's Raspberry Pi library here. From what I can tell the library uses bitbanging as opposed to hardware SPI in order to communicate. I would like to use hardware SPI, but don't have the skills to write a library to communicate with it myself. Are there any resources for how to write a library like that, or anything I can read about on how to convert a library from bitbanging to hardware SPI?

What Arduino is this for?

It's for a PCB I designed based on the Atmega 1284 with hardware support added to the IDE with MightyCore found here: https://github.com/MCUdude/MightyCore

Typically, the library has a "sendByte" function in which it sends through "software spi" you would only have to re-write that.

The library uses some weird form of SPI. As it sends only 5 bits, and then reads 12 bits. SPI is normally a multiple of 8 bits.

Turns out my google-fu needs work. I found this that works great using hardware SPI! Thanks everyone!

The standard AVR library has SPI handling. See, for example: http://www.gammon.com.au/spi
You don't have to write a library if you don't want, just communicate directly using SPI.
The datasheet for the MCP3008 has some tips for using an 8-bit SPI system to communicate with the device. In particular this chart:

You can see from that, that you will need 3 x SPI.transfer. I don't have one here to test with, but the code would look like this:
digitalWrite (SS, LOW);  // select device
int result;
SPI.transfer (0x01);  // start bit
result = SPI.transfer (0b10000000);  // single, ch0
result = (result & 0b11) << 8;  // move to high-order byte
result |= SPI.transfer (0);   // lower order byte
digitalWrite (SS, HIGH);  // deselect

Untested, but this should be roughly it.


text:
Expected Initializer?
I keep getting the error "Expected initializer" at different points in my code whenever I try to verify it. Currently, the error exists before "void setup." How can I fix this error and not allow it to happen in the future?
int ledPins[] = {9, 8, 7, 6};
int index;
int currentLED

void setup();
  {
  pinMode(Led1Pin, OUTPUT);
  pinMode(Led2Pin, OUTPUT);
  pinMode(Led3Pin, OUTPUT);
  pinMode(Led4Pin, OUTPUT);
  pinMode(Led5Pin, OUTPUT);
  pinMode(ButtonPin, INPUT);

  Serial.begin(9600);

  //Start a new game.

 for(index = 0; index <= 4; index++)
  {
    pinMode(ledPins[index],OUTPUT);
    // ledPins[index] is replaced by the value in the array.
    // For example, ledPins[0] is 2
  }
}

void loop()
{

  oneAfterAnotherNoLoop();  // Light up all the LEDs in turn

}

void oneAfterAnotherNoLoop()
{
  int delayTime = 200; // time (milliseconds) to pause between LEDs
                   // make this smaller for faster switching
  // turn all the LEDs on:
  int Index;

for (Index = 0; Index <=3; Index++) {
  digitalWrite(ledPins[Index], HIGH);
  delay(delayTime);
  digitalWrite(ledPins[Index], LOW);
}
for (Index = 3; Index >= 0; Index--) {
    digitalWrite(ledPins[Index], HIGH);
  delay(delayTime);
  digitalWrite(ledPins[Index], LOW);
}
}

void loop();
{
    // Check if the button is pressed at the right moment

   if (digitalRead(10) == 0)
   {
    if (currentLED == 8)
    {
      // Blink the orrect (green) LED
      digitalWrite(8, HIGH);
      delay(200);
      digitalWrite(14, LOW);
      delay(200);
      digitalWrite(8, HIGH);
      delay(200);
      digitalWrite(14, LOW);
    }
    }
  }

For starters, int currentLED is not a valid C++ declaration: you're missing a semicolon. On the other hand, void setup();{} has an extra semicolon which should be removed.

int currentLED

You are missing a semicolon there.

void setup();

There should not be a semicolon here.

Do some tutorials on the C or C++ language. They will help you.


text:
Getting RTK-precision GPS with arduino devices like NavSpark?
In trying to learn how to create a reasonably precise 3d model of my (very hilly) property, I stumbled across a product called Navspark, which appears to be a $22 arduino-compatible development board, with an RTK-capable (and RTKlib-compatible) GPS chip.
The idea with RTK is that a reference-position base-station transmits its positional error to a mobile unit, giving the mobile unit cm-level precision relative to the position of the base station. The error calculation is computationally intensive, but apparently within the capabilities of a Pi.
Is it actually possible to build an RTK-capable mobile/base pair using low-priced equipment like this?  Can you link a howto or project example?

The $22 Nacsparc ( http://navspark.mybigcommerce.com/navspark-arduino-compatible-development-board-with-gps/ ) doesn't appear to do RTK compatible GPS info.  For that you need the $80 NS-RAW : http://navspark.mybigcommerce.com/ns-raw-carrier-phase-raw-measurement-output-gps-receiver/

How about the http://www.navspark.com.tw/tutorial-4 tutorial?  It seems to indicate you need a couple of the more capable $80 NS-RAW units with carrier-phase info rather than the less capable $22 NAV-SPARC plain GPS units.
The RTK system doesn't transmit only its positional error, (which it knows from external information) but also communicates the phase information for the particular channels, and then the RTK software re-calculates the positions of both using common sets of satellites and the phase info.  With the same framework, it knows the relative positions accurately, and with assumptions about the location of the base station, it can correct mobile station
This isn't an arduino problem, unless you are asking about porting RTKlib to something arduino.

It appears that NavSpark uses the same Venus 822A microcontroller as the NS-RAW, and some random blog article I read seemed to be saying that it was therefore capable of RTK.  Somehow missed their tutorial links, thanks.


text:
Arduino Pro Mini and Electronic Speed Controller (ESC)
I want to send servo signal to ESC and Servo with my 3.3V Arduino Pro Mini.
Can the ESC/Servo read 3.3V signal from Arduino Pro Mini? Or do I need to make some level shifter to make 5V signal?

The ESC should have no problem with 3v3 signal.

i have 1 more stupid question.. if i use pro mini 5V, is it ok if i power it with regulated 5V to the RAW pin?

If you put 5V on the RAW pin you will loose voltage over the voltageregulator thats on the Nano, might be as low as 1V or more, depending on the regulator and current draw. If you have 5v regulated use the 5v pin.

Signal can be send easily from Arduino Pro mini to ESC, Simply either use .write() or .Microseconds() function.


text:
Integrating 2 push buttons to toggle the LED ON and OFF
Hey guys need your help in verifying out this program about toggling the LED ON and OFF using 2 push buttons.What i actually want is to let my LED stay ON when i press and even leave the push button-1 , and on pressing and leaving the push button-2 i want the led to turn off and no matter how many times i press the push button-1 i want it to turn ON the LED and the push button-2 should only turn off the LED.but with my program i am only able to see the LED to be at HIGH state,It is not shifting to LOW state on clicking push button-2.
This is my sketch :-
    /* LED CONTROLLED WITH 2 PUSH BUTTON PROJECT
       BY ARSH BANSAL

 CIRCUIT :-
 i) LEDPIN CONNECTED PIN 13.
 ii) PUSHBUTTON1 CONNECTED TO PIN 8.
 iii) PUSHBUTTON2 CONNECTED TO PIN 7.
 iv) BOTH THE PUSH BUTTONS CONNECTED PARALLELY, EACH WITH A 1K PULLUP RESISTOR AND BOTH THE PUSH BUTTONS CONNECTED TO 5V SUPPLY.
   */

 int ledpin = 13;
 int pushbutton1 = 8;
 int pushbutton2 = 7;
 boolean lastbuttonstate1 = LOW;
 boolean lastbuttonstate2 = LOW;

 void setup()
 {
   pinMode(ledpin,OUTPUT);
   pinMode(pushbutton1,INPUT);
   pinMode(pushbutton2,INPUT);
 }

 void loop()
 {
   if ( digitalRead(pushbutton1)== HIGH && digitalRead(pushbutton2) == LOW && lastbuttonstate1 == LOW )
    { digitalWrite (ledpin,HIGH) ;}

   else ( digitalRead(pushbutton1) == LOW && digitalRead(pushbutton2)== LOW && lastbuttonstate1 == HIGH)
    ; { digitalWrite (ledpin,HIGH) ; }

    if ( digitalRead(pushbutton1)== LOW && digitalRead(pushbutton2) == HIGH  && lastbuttonstate2 == LOW)
    { digitalWrite (ledpin,LOW) ;}

   else ( digitalRead(pushbutton1) == LOW && digitalRead(pushbutton2)== LOW  && lastbuttonstate2 == HIGH)
    ; { digitalWrite (ledpin,LOW) ; }
    }

You are better off, in this case, remembering the state of the LED not the state of the buttons:

If the LED is OFF and BUTTON1 is PRESSED then turn the LED on.
If the LED is ON and BUTTON2 is PRESSED then turn the LED off.

For example:
void loop() {
    static bool ledState = false; // LED is off by default
    if ((digitalRead(pushbutton1) == LOW) && !ledState) { // 1 pressed & led is off
        digitalWrite(ledpin, HIGH);
        ledState = true;
    }
    if ((digitalRead(pushbutton2) == LOW) && ledState) { // 2 pressed & led is on
        digitalWrite(ledpin, LOW);
        ledState = false;
    }
}

I just understood my mistake i should have used if statement after else to check the respective conditions well thanks for your efforts.


text:
How to flush the input serial buffer in Arduino?
I am communicating with the esp8266 WiFi module using Arduino. The module returns GET requests from other clients. They will be of the form
GET /101011 HTTP/1.1\r\nHost...

I wish to extract only the 101011 from the received serial data and discard the rest. I came up with this small chunk of code to test it by sending data from my laptop.
This is the code:
String s;

void setup() {

  Serial.begin(9600);
}

void loop() {

  if(Serial.available())
  {
    Serial.println("Inside");
    Serial.find("/");
    s = Serial.readStringUntil(' ');
    Serial.println(s);
    // Discard the rest of the data . Snippet from Jeremy Blum's Blog

    while(Serial.available()>0) Serial.read();

  }

}

Jeremy's Blog
But when I run this using the input GET /101011 HTTP/1.1\r\n the output produced is
Inside
101011
Inside
1.1\r\n

Why is Serial.available() returning true even after reading everything? How to discard the rest of data from the serial input buffer?

How do you know you have read everything? Serial data is still arriving from the ESP8266 while you are clearing the buffer - and you are clearing it much faster than the data is arriving.  Remember: serial data arrives s...l...o...w...l...y...

Read this:~ https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/

@Majenko Thank you. Read your blog. Will try to implement it in my design.

One possible approach is to read and discard everything for a fixed time, like a second. For example:
unsigned long now = millis ();
while (millis () - now < 1000)
  Serial.read ();  // read and discard any input

I'm not a big fan of trying to "flush the input buffer". How do you know if a second is long enough? Or maybe it is too long? You are better off reading to some known delimiter.


text:
How to approach an complex Arduino Uno project (Serial, SPI, Ethernet) in pure C, without libraries?
I have a college assignment where I need to get serial output, the Ethernet shield and SPI communication with other boards to work. We are not allowed to use any existing libraries, though we can use them as strong inspiration, as long as we are able to explain every line we have in our final code.
Since there appears to be a lack of C resource I spent lots of time trying to reverse engineer the CPP libraries but I am hopelessly overwhelmed by anything beyond getting a pure C blinky to run.
Do you have any idea how I should approach this? Are there C resources about the Ethernet shield and Arduino SPI?

You may have the most luck by ignoring the "arduino" and shield aspect aspect and looking for resources for the ATmega, and for whichever Ethernet IC/module is being used by that shield.

Just take a look at the source code. But I have to say that your assignments sounds like a ridiculous amount for work.

Are you allowed to use the built-in Arduino.h functions like digitalWrite()?

For serial and spi read the documentation for the atmega328p for whatever ethernet chip in use, it's datasheet. Might be alot to read but should give you a clue how it's supposed to work.

Since there appears to be a lack of C resource I spent lots of time trying to reverse engineer the CPP libraries - you aren't allowed to use C++?

C++ is fairly controversial in small embedded systems, so it should not be the least bit surprising if an academic assignment mandates traditional C, especially in a setting where the goal seems to be really understanding how things work in detail.

Are you allowed to use the avr-libc? If so, the doc on stdio.h has a simple example on setting up stdout in order to printf() to the serial port. It's really basic, and lacks the ring buffer, but it can get you started.

As Hans Neve wrote, you should really refer to the docs.
This is how it works in real life, when you want to write a driver for a new piece of HW.
You have to at least understand the block diagram, programming models and register sets of the device you want to control.
Then read whatever existing code you might find. In the practical case you have the driver for the version N-1 of the HW. Or maybe for something close enough.
As generic programming advice goes:

avoid any dynamic memory allocation, you will thank yourself later on, when you do not have to debug unexplained memory issues
if you want to write a driver, consider making it reentrant, should the same code be shared across multiple IP blocks
if you want to use OOP, avoid anything that requires runtime lookup. The compiler should have enough information to resolve everything statically.

WRT debugging: both device drivers might suffer from interference if you try to use the serial port. Consider using some ICD tools, like the AVR Dragon. Alternatively, you might find that debugging over I2C is less penalizing. But you have to define your debugging messages.

SPI is pretty trivial (see the existing SPI library). Serial is easy enough. As for the Ethernet shield you would need to look at either the existing library or the manufacturer's datasheet. Some Ethernet chips are much easier to work with than others.

If you look at the datasheet for the Atmega328P (as used in the Uno) they have example code (in C) for SPI - along with comments. That should let you knock off the SPI part in an hour.
They also have example code for serial. Add in a ring buffer and you should be able to get serial going in half a day.
After all, the assignment doesn't tell you to not use the datasheet.
Depending on the Ethernet chip, you should be able to dig up (possibly in the chip datasheet) example code for that as well.

You could always use existing libraries (eg. Serial.print) for debugging, and then pull that code out once you are happy your own code works.


text:
Does Proteus simulate external interrupts properly using Arduino? I can't get them to work
I am trying to simulate an interrupt with an Arduino Uno in Proteus. This is the simple test code that I'm using:

void introutine()
{
  digitalWrite(13,HIGH);
}

void setup()
{
  pinMode(13,OUTPUT);
  attachInterrupt(2,introutine,LOW);
}

void loop()
{
}

Here's the circuit in Proteus:

When I hit the button, the LED is supposed to turn on. Well, nothing happens. I have read something about Proteus being bad at simulating interrupts, but I'm not sure about it because Timer1 interrupts did work well. Basically, the problem lies within EXTERNAL interrupts only. I hope you people can help me.
Thank you.

NOTE: the node between R5 and the button says IO13 because I forgot to undo that. Suppose it says IO2, and still it will not work.

Why do you have mode LOW in attachInterrupt instead of RISING?  Also, instead of putting some kind of correction about IO13 vs IO2 in a comment, please edit that info into the question.  Also, the phrasing  “Suppose it says IO2, and still it will not work” asks us to imagine it doesn't work when you correct the pin number.  Rather than asking us to imagine that's the case, why not go ahead and test it and then edit the question to say what the effect of the change was?


text:
Soldering headers screwed up Trinket?
Last week I purchased a couple of Trinkets from Adafruit (5v micro-USB). The first thing I did was solder the headers to one of them. I did the whole setup process w/ the Arduino IDE and didn't have any issues, until I actually tried uploading the "Blink" example.
When I plug in the Trinket, I get the pulsing red light, but when I try to upload during that, I get:
avrdude: error: usbtiny_send: Input/output error (expected 64, got -5)
avrdude: verification error, first mismatch at byte 0x0004
         0x1d != 0x36
avrdude: verification error; content mismatch

avrdude: error: usbtiny_transmit: Input/output error

Then, if I press the reset button, I can't get it to "pulse" again. The red light just dimly turns on and stays constant.
I tested the other Trinket I ordered (that has not been soldered yet) and it works perfectly fine.
So, did I somehow screw up something when soldering the headers? Or do I have a faulty Trinket?
For reference, here's the trinket in question...

Is that yours? Or a stock photo from Adafruit? The soldering looks very neat.

This may help: https://learn.adafruit.com/introducing-trinket/repairing-bootloader

@NickGammon Yes, it's mine. Was my first thing to solder...ever. So wasn't sure if I somehow botched it and just didn't know. Will give the bootloader repair a try.

What kind of soldering iron do you have? How hot did you solder it and was it properly grounded?

There are what appear to be burn or melt marks on the 5 pin component labeled QTSO and on the diode near the USB pin. That could be a sign of damage due to soldering, reverse polarity, or excessive current draw through the voltage regulator (a short circuit).
Based on the fact that the light stays on solid when the reset button is pressed,  it sounds like it could also a different issue. First, turn on verbose output in the arduino IDE and post the full output when you try to upload.
Next, try disconnecting everything except the USB cable while uploading the program. If that does not fix it, it is most likely that the bootloader is corrupted. This has happened to me on multiple occasions for no apparent reason and it is pretty easy to fix.
If repairing the bootloader does not fix this, it is most likely that one or both of the components mentioned above are damaged.

The 5 pin component is the 5V regulator that provides power to the microcontroller if you're using a battery. The diode is there to just to make sure that the Vout of the 5V regulator isn't visible on pin 1 of the USB. I can say with almost 100% certainty that the components are fine. The fact that the LED is on but is dim makes me believe that the PB1 pin of the ATTINY is floating which suggests it's either ESD damage to the chip or some sort of corruption to the bootloader

On this side it doesn't seem like there's a solder bridge, although it's possible there is one on the other side if you were heavy handed on the solder.
Since you did the verification with the other unit this can't be a software or usb cable issue.
So indeed it's coming from the trinket itself. I think your best bet is to desolder the pins and check the upload again. If it's failling, try flashing a new bootloader. And if it's still not working then I guess either it was faulty from the start or you did damaged a component during the soldering.

Trying to desolder the pins is only likely to make things worse.  In theory it can be done, probably by heating them one by one with an iron and pulling each out of the board and plastic keeper individually with pliers, but it's unlikely to improve the state of the board.  Carefully sliding the plastic keeper down so the bottom of the pins could be examined makes as much sense - a little hot air (but short of soldering temperature) can help with that.  Checking for shorts electrically is probably the most sensible.


text:
Burn normal bootloader onto Atmega328P configured to use internal 8MHz clock
I have an Atmega328P that I have previously burned with a bootloader configured to use the 8MHz internal clock as described here. I would like to now burn the normal Duemilanove bootloader configured to use an external 16MHz clock onto the chip. However, when I try following the normal procedure, it says "Invalid device signature". I can still upload programs to the chip and they will run, but I would like it to use the 16MHz external clock. How do I do this?

I have a sketch that will upload the Optiboot bootloader - that will work perfectly well on the Duemilanove.
The latest version will be available on GitHub.
This particular sketch is in the "Atmega_Board_Programmer" subdirectory.
You need to run this sketch on another Arduino (like a Uno) and connect it up like this:

As it turns out, I had the chip in backwards. It surprisingly still works.

No wonder you got invalid device signature! :)


text:
Why does enabling TIMSK1 mess up serial?
I am intending to write a code where a user will send lines through serial to affect timer interrupts. I am noticing a problem with serial where as soon as I enable the timer interrupts, the serial communication becomes garbled. More specifically, as soon as I enable the timer interrupts and I open the serial monitor, the monitor gets flooded with garbage. I haven't written too much code and this is already happening. Am I making a silly mistake? I am using an Arduino Mega 2560. My code is below:
void setup() {
  Serial.begin(9600);
  Serial.println("Hello World!");
  timer_setup();
}

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

void timer_setup() {
  // waveform generation = 0100 = CTC
  TCCR1B &= ~(1 << WGM13);
  TCCR1B |=  (1 << WGM12);
  TCCR1A &= ~(1 << WGM11);
  TCCR1A &= ~(1 << WGM10);
  // output mode = 00 (disconnected)
  TCCR1A &= ~(3 << COM1A0);
  TCCR1A &= ~(3 << COM1B0);
  // Set the timer pre-scaler
  TCCR1B = (TCCR1B & ~(0x07 << CS10)) | (2 << CS10);
  OCR1A = 0x4000;
  TCNT1 = 0;
  // Enable timer interrupt mask 1
  TIMSK1 |= (1<<OCIE1A);
}

If I comment out the TIMSK1 |= (1<<OCIE1A) line, serial doesn't mess up.

You've enabled interrupts for Timer 1 Compare A interrupt. Where is the interrupt handler?
For example:
ISR(TIMER1_COMPA_vect)
{
  // whatever
}  // end of TIMER1_COMPA_vect

Without that, the processor is just restarting. No wonder serial output is messed up.

Thanks, Nick. I hadn't added it yet because I wasn't testing interrupts yet, just setting it up. I didn't know it would do that if I didn't include the handler.

You can't "set up" interrupts without a handler and expect things to work. Once you enable the flag, you are promising something will handle them. The compiler generates a default handler that jumps to the start of the program (same place Reset goes).


text:
How to generate true random numbers over Arduino Uno without any external hardware?
Using a 'random' function in sketch gives same pattern of numbers every-time. But, I need to generate different numbers such that any number to repeat itself should have a very less probability.

If you just want random data (but not true random data, only random pseudo-random data) follow Edgar Bonet solution. Read this article and, of course, the wikipedia page to better understand this. However, unless your application is very particular, you won't need true randomness, because pseudo-random numbers are fine for almost every application

Related: https://arduino.stackexchange.com/questions/50671/getting-a-truly-random-number-in-arduino

The standard (but not very good) solution is to seed the random number generator from an analogRead() on an unconnected pin. For better options, see this answer to a related question.

This, however, is not a "true random numbers generator", it's a randomly seeded pseudo-random generator. This, however, is what I think the OP was requestiong, so +1

Allocate 4 bytes in EEPROM to save a seed value.
Use the EEPROM library (#include ). Use EEPROM.put() and EEPROM.get() functions to write and read the seed value to EEPROM.
In setup(): Read the seed_value from EEPROM, increment it and write it back to EEPROM. Then call randomSeed(seed_value).
Now, after every run of setup(), random() will create a whole new random sequence. If you need a new sequence within your sketch, you can repeat the process, and don't forget to write the new seed to EEPROM for next time.
Note that I didn't bother with initialising the EEPROM value the first time we run. It'll probably be zero when you start a new Arduino board, but the only thing that matters is that you increment it each run. Incrementing by 1 will do the trick, but any increment value will probably do.

I notice that the title said "true random", but the question asked for something different. My suggestion solves the request, but it's not a "true random" generator, of course.

The EEPROM usually has a initial value of 255 on a fresh Atmel AVR chip.

Oh? I thought I remembered finding zeros up there, but it doesn't matter in this case. Thanks.


text:
QuadCopter PID using MPU6050
I am using Arduino Uno, with PID library and Jeff Rowberg library for MPU6050 i.e I2Cdev.h, MPU6050_6Axis_MotionApps20.h.
There is one PID for each axis i.e Pitch and Roll, I am getting output that wobbles and is unstable. I don't know whether my code is wrong or something else.
Errors which I feel are:

I am using Esc.write(), I know Microseconds should be used but it feels very light, even it doesn't wobble.
Kalman Filter not used, but I am getting the pitch, roll, yaw.
PID library (By Brett Beauregard) not suitable for Quadcopter.
else if (mpuIntStatus & 0x02) // wait for correc available data length, should be a VERY short wait
         while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();
This statement in loop making loop slow, it's written in its comment and maybe it making pid compute upset

Please look at code.
#ifdef OUTPUT_READABLE_YAWPITCHROLL
        // display Euler angles in degrees
        mpu.dmpGetQuaternion(&q, fifoBuffer);
        mpu.dmpGetGravity(&gravity, &q);
        mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
        yaw = ypr[0] * 180/M_PI;
        pitch = ypr[1] * 180/M_PI;
        roll = ypr[2] * 180/M_PI;

        Input = pitch;
        RInput = roll;
        myPID.SetTunings(Kp,Ki,Kd);
        myPIDR.SetTunings(RKp,RKi,RKd);

        //Sample Time is 10 for both PID.

             myPID.Compute();
              myPIDR.Compute();

        if(armed == 1) {
          int m1 = throttle.toInt() + Output;
          int m2 = throttle.toInt() + ROutput;
          int m3 = throttle.toInt() - Output;
          int m4 = throttle.toInt() - ROutput;

 int angle1 = map(m1, 0, 100, 0, 180);
 ESC1.write(angle1); //FRONT PITCH+
 int angle2 = map(m2, 0, 100, 0, 180);
 ESC2.write(angle2); //LEFT ROLL+
 int angle3 = map(m3, 0, 100, 0, 180);
 ESC3.write(angle3); //BACK PITCH-
 int angle4 = map(m4, 0, 100, 0, 180);
 ESC4.write(angle4); //RIGHT ROLL-
        }
    #endif

Kp = 0.25, Ki = 0.04, Kd = 0.05 |
RKp = 0.25, RKi = 0.04, RKd = 0.05
From testing: if I shake my Quadcopter fast by hand it behaves like PID is activated and works as wanted, but suddenly after a couple of seconds again feel loose, may be PID compute become upset

Quadcopters usually use 2-PID loops per axis, a rate loop and an angle loop.
Your quadcopter needs to be very aggressive about its rate of rotation but relatively relaxed about how quickly it returns its angle to the center so it doesn't overshoot. With a single PID it will either be too slow to correct or overshoot and oscillate with no "usable" range of tunings in-between, because in order for its outputs to be strong enough to control the quad it will necessarily be too aggressive to smoothly align with the center position. There is a lot of math that explains why this cannot be achieved with a single loop more rigorously if you care to look into it.
So try setting it up with a PitchAngle PID whose output is the setpoint of a PitchRate PID loop whose output goes to the motors, and similarly with the Roll.
That is only one possible problem though, there is a huge number of things that could be wrong. Are your pitch and roll measurements angles to the horizon or euler angles? how fast is your loop running? Are oscillations induced by the motors causing your accelerometer reading/attitude filter combo to be unusable? Are the PID parameters correct? Is the accelerometer's bias calibrated? Is the gyro drift calibrated? Are all you ESC's calibrated the same way?


text:
XBee unstable sensor data transmission
I am using two XBee Series 2 modules (Zigbee), an Arduino Uno, and a HC-SR04 Ultrasonic sensor to send distance readings from the coordinator XBee on the Arduino to the XBee connected to my computer. I configured the ArduinoXBee as "Zigbee coordinator AT" and the ComputerXBee as "Zigbee end device AT" with the following networking settings:
Coordinator:
PanID: 1234
DH: 0
DL: FFFF
End Device:
PanID: 1234
DH: 0
DL: 0 (so it can only talk to the coordinator)
The problem I am facing is that when I open the End Device terminal on X-CTU, the distance readings I get are accurate yet very unstable. Like it receives the correct readings but the transmission is unsynchronized as it sometimes receives 5 numbers in one transmission and lags for 10 seconds then receives the next bunch and lags for another 10 seconds and so on...
The arduino code is:
#include <SoftwareSerial.h>
const int trigPin = 13;
const int echoPin = 9;

SoftwareSerial xbee(10, 11); // RX, TX

void setup()  {
   xbee.begin( 9600 );
   pinMode(trigPin, OUTPUT);
   pinMode(echoPin, INPUT);
}
void loop()  {
long duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;
  xbee.println( distance );
  delay(500);
}

Can anyone help me?

Probably the end device is set into sleep mode. Check the Sleep Mode(SM) and the sleep period(SP) because what I can see is the XBee gives readings for every 10 seconds.


text:
Barebones 328p, 2xAA vs 3xAA, which will last longer?
So im just running a 328p at 8mhz with the internal oscillator. Datasheet says 1.8 to 5.5v is voltage range.
Will 3xAA in series (~4.5v) last longer than 2xAA in series (~3v), assuming all batteries have the same capacity, theoretically each option should have the same mAh but does the difference in voltage affect things ?

Yes, running at a higher voltage will consume more current.  In the datasheet you have this nice graph:

I have highlighted the two voltages at 8MHz for you. At 4.5V you would typically be using about 4.7mA.  At 3V you would be using around 2.8mA.  That's not taking into account anything else in your circuit of course - just the ATMega itself.

thank you for pointing this out, yes its just the atmega im talking about.

Majenko's answer is correct, however he (or both of you) are assuming that the processor clock is running. When it runs, a processor cycle at a higher voltage will use more current. However when in power-down sleep mode the clock stops, and consumption is much lower. If you don't need the watchdog timer (for example, a switch closure activates the processor) then the difference will be negligible. Indeed, the current consumption is around 100 nA.

If you need the watchdog to periodically wake you, then the difference will be about 2 µA (that's a lot less than 2.8 mA).

These are quoted at room temperature - around 25°C.

I would be concerned about 2 x AA batteries. Their nominal voltage might be 3V, but their actual voltage (say, if they are NiMh batteries) might be closer to 2.4V, and that is the minimal amount for running at 8 MHz.
With 3 x AA batteries you are much more safely in range for the voltage requirements, particularly if you have some peripherals that might drain power, and thus lower the voltage.

Other discussions about low-power considerations at http://www.gammon.com.au/power.


text:
Problem updating Arduino WiFi Shield's Firmware
I'm using Arduino Uno R3 and the official Arduino WiFi Shield R3. I'm trying to update the Shield's firmware to 1.1.0 through this guide.
Everything goes fine until Step 9. When I execute the code in Step 10, I get an error (see attachment) as:
AtLibUsbDfu: 3EB 2FF8 no device present
FAIL Could not open USB device.
ISP done.

EDIT: I re-installed the firmware on my shield and now the problem's gone.

I cant comment because of reputation... You've already upgraded the firmware. Just when you try upgrading again your wifi device is rebooting itself because of upgrading before.

Many of the online instructions do not work. This one does - http://arduinotronics.blogspot.com/2015/06/upgrading-arduino-wifi-shield-firmware.html


text:
Library for DIY Keyboard
I'm planning on making my own Bluetooth mechanical keyboard using the Adafruit Feather 32u4 Bluetooth LE. Something that I haven't really figured out is the programming side of things. I was wondering if there is an easy to use library for this.
I know of the KeyPad library but I'm not sure how to handle modifier keys like Shift and CTRL with it. Any idea can help!
Edit: Like said before the project I'm working on is a Bluetooth mechanical keyboard. So this means there will be 85 (at least for my design) switches in a matrix.
In an ideal world the library I'm looking for can do the following: I specify the keys and their position in a matrix and what the modifier keys are. It can generate the appropriate ASCII character when the matching key(s) are pressed and return it or something, so that I can send it over Bluetooth in another piece of code.
In a less ideal world I use the KeyPad library but I don't really know how to take care of modifier keys like shift when doing that.
Have a nice day!

What exactly the library should do? Your whole project?

@ThomasS. My project is a Bluetooth Mechanical Keyboard. I'm sorry for the fuzzy explanation, I updated the question. I hope its a bit better!

What is the problem of accessing a matrix, checking for keys (pressed and typed) and converting to the appropriate character/byte sequence? I don't see how a library would help here much because of the massive configuration. The only tiny problem you need to solve is that pressing multiple keys should be allowed by the circuit (e.g. using diodes in the rows or columns or, if you want to be perfect, for each key).

That's how I'm going to do it now. I just remembered coming a cross a library for making an USB keyboard that handled everything by itself. I thought I would need to handle lower- and uppercase letters in the code but it turns out you don't need to do that, you send a MODIFIERKEY_SHIFT command.

I do not have experience with the Bluetooth version of it, but at least with "normal" Arduinos, I found out that only the UNO could produce the correct sequences to enter BIOS configuration mode. This is due to the fact that the BIOS has very specific expectations. The UNO employs a secondary AVR chip to emulate the USB keyboard and it happens to be compliant with the BIOS expectations. Other Arduinos (nano, due, etc.) that rely on a sw library are not compliant. So you might want to check if you can enter BIOS config mode, before ditching other keyboards.

@IgorStoppa I'm currently using a Mac so I don't even have a BIOS to enter haha :) a very useful tip for other people though!

If you want to make it work anywhere near the what a keyboard does, you'll certainly want to make it a bluetooth HID keyboard. Also, you'll probably not want to multiplex the keys in a way that you can't handel specific patterns: www.microsoft.com/appliedsciences/antighostingexplained.mspx

For shift (making an a into an A), simply program in some ands. Pseudo-code:
if shift AND a:
    return A
elif shift AND b:
    return B

and so on and so forth.

Nope. Look at the ASCII table, you can use shift to decrease the ASCII value with 22, so you don't have to program it for every single combo

https://github.com/tmk/tmk_keyboard is what you want.
Search in Adafruit's site for how to incorporate Bluefruit.


text:
How to interrupt a Timer to Change position along a Colour Cycle
I want to have a loop of 4 colours which runs constantly (i.e. red -> green -> blue -> white) each of the colours having their own LED and pin on the Arduino board. There is a 7 second delay between switching the colour and this cycle should run continuously. When I press a button, I want the cycle to immediately switch back to green and continue the cycle (i.e. -> blue -> white -> red) again.
How should I go about this? Can you have a listener for a button press going at the same time as a delay? How do you interrupt the timer and change the active LED?

You could start with the attachInterrupt example sketch and work from there. Here is a possible solution:
enum { GREEN = 0, BLUE = 1, WHITE = 2, RED = 3};
const int buttonPin = 2;
const int ledPin[] = { 4, 5, 6, 7 };
volatile bool reset = false;
int state = GREEN;

void setup() {
  pinMode(buttonPin, INPUT_PULLUP);
  for (int i = 0; i < 4; i++) pinMode(ledPin[i], OUTPUT);
  attachInterrupt(digitalPinToInterrupt(buttonPin), doResetState, FALLING);
}

void loop() {
   digitalWrite(ledPin[state], HIGH);
   delay(7000);
   digitalWrite(ledPin[state], LOW);
   if (state == RED || reset) {
     state = GREEN;
     reset = false;
   }
   else {
     state = state + 1;
   }
}

void doResetState () {
    reset = true;
}

This will not immediately cycle back to GREEN when pressing the button but you can fix that by modifying the doResetState().
Cheers!

The SimpleTimer library would be ideal for this. One timer callback function, the present contents of the loop() function, would advance the lighting state, called by a 7 second timer. Another, your present doResetState() with the modification noted by @MikaelPatel, would read (and debounce) the button on, say, a 100ms timer. The main loop would be reduced to Timer.run();