text:
Python PySerial with Arduino fails byte check
I'm struggling with my first steps with Python and PySerial. I have one Arduino which reads impulses from an electricity power meter, passes the counts over to another Arduino over an RF link and then sends the data over to an Raspberry Pi. The Arduino to Arduino communication works well. However the last step of passing this to the RPi fails.
The MeterValue from the Arduino side is an unsigned Long (32 bits) and therefore split in 4 pieces of 8-bit transmissions plus a frame start and frame end:
[0x01] Frame start
[0xMeterValueByte0]
[0xMeterValueByte1]
[0xMeterValueByte2]
[0xMeterValueByte3]
[0x04] Frame end

This is my Arduino code continuously sent to the RPi in debug purpose :
void loop() {
//static test loop
Serial.write(0x01); //start frame
Serial.write(0x00);
Serial.write(0x00);
Serial.write(0x02);
Serial.write(0x04); //end frame
delay(3000);

}

This is my Python code:
Import serial
ser = serial.Serial('/dev/ttyACM0',9600)
print("Connected to: " + ser.portstr)

inputbuffer=[]
inputbuffer = [0 for i in range(10)]

while True:
    if ser.inWaiting() > 0:
        inputbuffer = ser.read(1)
        print "Byte received"
        print "Inputbuffer[0]: " + hex(ord(inputbuffer[0]))

        j = inputbuffer[0]
        print "j= " + hex(ord(j))

This check of the "j" parameter somehow fails:
        if (j == 0x1): #look for start of frame
            print "Start found\n"
            print "Filling buffer\n"
            while ser.inWaiting() < 5: #hold here until 5 bytes arrived
                pass #proceed here
            inputbuffer +=ser.read(5) #read 5 bytes

            if inputbuffer[5] == 4: #check that the message has frame end
                RXval = inputbuffer[1]
                RXval |= (inputbuffer[2] << 8)
                RXval |= (inputbuffer[3] << 16)
                RXval |= (inputbuffer[4] << 24)
                print "RXval: ", RXval
            else:
                print "RX error, no frame end\n"
        inputbuffer = []

This is the Python output:
Connected to: /dev/ttyACM0
Byte received
Inputbuffer[0]: 0x1
j= 0x1
Byte received
Inputbuffer[0]: 0x0
j= 0x0
Byte received
Inputbuffer[0]: 0x0
j= 0x0
Byte received
Inputbuffer[0]: 0x2
j= 0x2
Byte received
Inputbuffer[0]: 0x4
j= 0x4

And then it repeats. Obviously the Python code doesn't realize j == 1. How should I handle the checking of the received bytes?

I think the problem is that you can't count ;)
Spot the difference:
0: [0x01] Frame start
1: [0xMeterValueByte0]
2: [0xMeterValueByte1]
3: [0xMeterValueByte2]
4: [0xMeterValueByte3]
5: [0x04] Frame end

and:
0: Serial.write(0x01); //start frame
1: Serial.write(0x00);
2: Serial.write(0x00);
3: Serial.write(0x02);
4: Serial.write(0x04); //end frame

Your receiver is looking for a pattern of 6 bytes, but your Arduino sketch is only sending a pattern of 5 bytes.
Your check for the start character is simple enough - you solved it fine a few lines above:
print "j= " + hex(ord(j))

But you forgot to do something similar for the check:
if (j == 0x1):

That should really be:
if (ord(j) == 0x1):

Helpful, but it still doesn't solve the problem with the checking of the first byte, does it?

@Dejvid_no1 Check my edit

Excellent, that did it! So I'm getting a character via the UART and what I really wanted was the Integer Unicode representation of that character which ord() solves. One step at a time...


text:
How much power can the Teensy 3.2 deliver to external components?
Can a teensy 3.2 deliver enough power to properly activate multiple servos by chance?

it can provide system voltage of 3.3V to other devices at up to 100mA

Is there anyway to boost it up to 5v?

I would just go with a 5v power supply.

No.  You should provide your own regulator or supply for the servos specified voltage.
This might be an original design, or an off-the-shelf "battery eliminator" intended for an R/C vehicle of similar needs.
Note that the teensy regulator's maximum input voltage is fairly low, and may be in the range of what more powerful servos expect, ie, you might be able to run the teensy regulator off of the servo supply.
Be sure to consider the possibility of brownouts - multiple active or stalled servos can consume a lot of power, and if your upstream supply is not "stiff" enough this can result in the voltage dropping low enough that control electronics misoperate or reset - granted that is less likely with the teensy than with a 5v MCU using a regulator with a higher voltage dropout.

If you are running servos from the same supply as the Teensy and the supply is not decoupled enough you could also encounter noise related issues that might affect other parts of your build. In any case, use capacitors to stabilize your power inputs if you are dealing with actuators.

Capacitors only cover very temporary demands - a stalled servo is a demand which can easily last longer than any practical capacitor could cover for.

source: Stack Exchange

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

sort: votes


text:
SIM800 or SIM900 library for Arduino
I have a SIM 800L module which I am using to send /receive SMS calls.
I just wanted to know whether there is any library suitable for the SIM800 for arduino. I don't need GPRS functionality . I see mostly the arduino shield library but not sure whether it works with the SIM800 module bought from aliexpress.
Can someone help me in get me a library which can be used for the SIM800 .I have tried a lot but not getting a simple library for the same.
Actual Issue :
I am able to make it work with the AT commands using the Serial3 in the arduino MEGA. But when i started integrating with the existing project of ESP8266 and DS3231 somehow the Serial3 read() is not working properly. I tested with Serial3.readString()/ Serial3.read() and all. The CNMI for the SIM800 is 2,3,0,0 which is to direct the incoming message to the Terminal.
If my project is having a simple loop with only Serial3.read, then all messages contents are read properly. If I include the other Serial2 readings which is for the ESP8266, then I am not able to read the full messages from Serial3.I have tried with timer to read serial from the Serial3 for 3-5 secs but now way it is working.

Most likely, the Serial3 buffer is being overrun because you are not reading fast enough. That is why when you use a simple loop, everything works and you get the whole message; very little time passes between reads. The simplest solution to this is to increase the size of the Serial buffer to, maybe, 256 bytes. Search for HardwareSerial.h in your Arduino installation and look for the #defined variable SERIAL_RX_BUFFER_SIZE in the file near the top. Change its value to 256 and save. This should provide enough buffer space to store the entire SMS until you read it.
Alternatively you could change your CNMI settings to push only SMS notifications, which are a lot smaller in size, to the Arduino. Then you can parse the notifications, extract the SMS index and then request the SMS from the SIM800 using the index whenever you wish, making sure to read quickly (you will need to craft a while loop to do this efficiently, with timeouts and all).

Thanks a lot @brianrho . I have tried increasing the serial buffer as you mentioned. It works. But it has an impact on the dynamic memory for the program. Previously  in MEGA it was using only 25% for my entire program but now it has risen to 39% if i change both Rx/Tx buffers to 256. I don't think i need the Tx buffer to be increased. Even if I increase the Rx to 128 it works. Can this be further reduced to 96 ?? and keep the Tx as 64 . will that cause any other issues .. I have tried setting the CNMI to sim memory and used index to read that but facing the same issue.

I once again tried with the CNMI index logic and it works fine with the default buffer setting !!!:)

@user3689864 Great...but you'll have to use trial and error to know what RX buffer size is good enough for you. Keep in mind that the maximum length of an sms is 140 and the SIM can only store a max of 15 sms (in my experience) before it stops saving them. Receiving only notifications is a good way to handle a lot of SMS traffic since it would take about 25 notifications for a 256-byte Serial buffer to get full, and it also allows you to use the default buffer size, like you've discovered. There's no need to change the TX buffer size from its default value.

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


text:
How to setup Uno + xbee shield 1.1 + wee wifi chip?
I am an absolute beginner with electronics and Arduino.
I have this hardware:

arduino uno
xbee shield 1.1
wee wifi chip

I've tried to make them work (to connect my Uno to the Internet) but I can't find the right tutorial.
Are there good resources I should look at, or do you know how set this up?

As far as the Wi-Fi and Uno is concerned, it's not too difficult. You should download its library for Arduino, which is available on Github and then try its example named Wifi Client.
In this example, change your SSID and password, and run serial terminal. It will show you that your Arduino is connected to Wi-Fi and it will also display your IP Address.
Now enter this IP address in your browser and it's like you are pinging your Wi-Fi shield.  Soon it will display your analog values. Just make sure your computer and your Wi-Fi chip are connected to the same Wi-Fi connections.

Thank you for your help. I try to make it work but I am such a noob that I would need a step by step tutorial.

I'd suggest taking this in small hunks. If you haven't done it already, your first step should be to get your development environment together. Use it to create and upload a simple test. The Blink sketch is a common place to start. There are excellent tutorials at the Adafruit site, the have a whole series for getting started with the Arduino.
After you've gotten far enough with the basics to start feeling confident. Try searching for a tutorial for your project. You can often find them by searching on Google – try something like "arduino xbee shield tutorial" – look for descriptions that sound like what you want to do and try reading them. Another good place to look for tutorials is on sites that sell the hardware you're interested in using. For example Adafruit has this tutorial on getting started with the Xbee.
As you work through the tutorials, come back with more questions. As you get more experience it will be easier to ask specific questions and those are easier to answer :-)


text:
Declare for loop as an array of variables
My goal is to store the variable in the for loop as an array rather than as a single 'ultrasoundValue'. Can some one help me structure the code?
I have this code:
int ultraSoundSignalPins[] = {5,7};
int tx = 4;
char *pingString[] = {"Ping1 ","Ping2 "}; // just something to print to             indicate direction

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

void loop()
{

 unsigned long ultrasoundValue;
 for(int i=0; i < 2; i++)
 {
   ultrasoundValue = ping(i);
   Serial.print(pingString[i]);
   Serial.print(ultrasoundValue);
   Serial.print("cm, ");
   delay(500);

 }
}

//Ping function
unsigned long ping(int i)
{
 unsigned long echo;

 pinMode(ultraSoundSignalPins[i], OUTPUT); // Switch signalpin to output
 pinMode(tx, OUTPUT);
 digitalWrite(ultraSoundSignalPins[i], LOW); // Send low pulse
 digitalWrite(tx, LOW);
 delayMicroseconds(2); // Wait for 2 microseconds
 digitalWrite(ultraSoundSignalPins[i], HIGH); // Send high pulse
 digitalWrite(tx, HIGH);
 delayMicroseconds(5); // Wait for 5 microseconds
 digitalWrite(ultraSoundSignalPins[i], LOW); // Holdoff
 pinMode(ultraSoundSignalPins[i], INPUT); // Switch signalpin to input
 digitalWrite(ultraSoundSignalPins[i], HIGH); // Turn on 0pullup resistor
 echo = pulseIn(ultraSoundSignalPins[i], HIGH); //Listen for echo
 return (echo / 29.1); //convert to CM then to inches
}

You don't even have to add any lines, just modify a couple!
unsigned long ultrasoundValue [2]; //creates an array of unsigned longs of size 2

...and inside your for loop:
ultrasoundValue[i] = ping(i);

It appears you are acquiring 2 separate ultrasound values. If you'd like to store multiple sets of these 2 values, you could use a two-dimensional array:
unsigned long ultrasoundValue [10][2]; //an array of 10 pairs of long unsigned values

...and you could modify your for loop to have a pair of nested for loops:
 for (int i = 0; i < 10; i++)
 {
   for (int j = 0; j < 2; j++)
   {
      ultrasoundValue[i][j] = ping(j);
      //do whatever else
   }
 }

Make ultrasoundValue an array and use i as the index to it? Just like you have with all your other arrays?
You obviously know how to use arrays, since you have already been using them throughout your code.


text:
HardwareSerial - check for overflow
The SoftwareSerial library has a built-in Overflow function, but the Serial library does not.  Is there a simple way to check for a data buffer overflow on a hardware serial port?

The current code just ignores incoming data, if the buffer is full. So there is no way to see if the buffer has been "overflown". Though it wouldn't be hard to add this yourself.

@Gerben - yes I'm aware.  That is the question I'm asking: how would you add something to check?

Just add a single boolean variable to the class  (e.g. _rx_overflow). After the lines in the link, add else _rx_overflow=true;. Add the function overflow which returns the value of _rx_overflow and sets it back to false. Pretty much the same way the softwareserial library did it.

The HardwareSerial has actually two levels of RX data overflow. The first may occur if the ISR is locked out a longer period and the UART RX registers are not emptied in time. There is a special status flag for this (UCSR0A USART Control and Status Register A, Bit: DOR0 Data Overrun). The second level is the RX ring-buffer as described above.

A look at HardwareSerial_private.h shows incoming bytes are always read (interrupt-based), regardless of what your code is doing. So we can't set up a hardware interrupt to notify us when the chip's RX register has overflowed, because such an interrupt would depend on overflow flags but these flags never become set because, like I said, bytes are always read. It also shows that while all incoming bytes are read, not all are added to the 64-byte Serial buffer i.e. a byte may be read but if the buffer is full, nothing else happens; it is simply read to clear hardware flags. So the only (direct) way I can think of is to constantly poll Serial.available() in loop() to check if the number of bytes available for reading is equal to 64. If this condition yields TRUE, then you may safely conclude that the Serial buffer is full and about to overflow. This should suffice:
    void loop(){
        //your code
        if (Serial.available() == SERIAL_RX_BUFFER_SIZE){ // Just to be general, 64 bytes in most cases
            //buffer is overrun, do what u will
        }
    }

You could make some changes to HardwareSerial_private.h to get something like the overflow() method of SoftwareSerial. The relevant lines are:
    if (i != _rx_buffer_tail) {
        _rx_buffer[_rx_buffer_head] = c;
        _rx_buffer_head = i;
    }

The snippet above ensures that the current write position is not equal to the tail of the ring buffer (i.e. if we are about to overwrite a character in the buffer), before writing the incoming byte to the buffer. An else block could be added to set some global variable to indicate overflow. This global variable would have to be cleared when Serial.read() is called.


text:
Permanent connections with Arduino Due
The Arduino Uno (for some models) has the ability to dislodge its IC chip. You can mount this on a piece of perfboard and, in essence, have a permanent connection. I will need the beefier Arduino Due, but I do not know how to make permanent connections with this device. Is there any way to form some kind of permanent connection with this board?

Your first sentence is wrong – there is no Arduino that can take its own chips off the board – but perhaps you meant to refer to Arduinos that have the chip in a socket.  Or maybe you are referring to the pin sockets along the edges of the boards.  In any case, you can buy little plastic cases to contain Unos, Dues, etc which may help hold pins into the pin sockets; or less elegantly, can hot-glue your wires in place

The AT91SAM3X8E is only available in QFP and BGA packages. Not in DIP like the UNO.

The chip on the Arduino Mega (ATmega1280) is available in DIP. So that might be an alternative, that's a bit more powerful then the UNO.

@Gerben Having more pins and more memory doesn't really equate to the chip being more powerful. It's still the same wimpy 8-bit core as the '328P. It just means you can be a little lazier with your programming and memory usage.

What it sounds like you want is an Arduino Due footprint prototyping shield.
Arduino make one, although it is out of stock, but it gives you an idea of what you are looking for. There are plenty of other designs out there for purchase of varying degrees of complexity.
You solder the pins in place and mount it on top of your Due just like any shield, and solder your wires and components in where you want them.
An alternative option, of course, is to step away from Arduino and investigate some of the many other chips from other manufacturers out there that are considerably more powerful than the 8-bit ATMegas used on the low-end Arduinos, and yet are still available in a DIP footprint - chips like the PIC32MX1xx/2xx series from Microchip - 28 pin DIP (just like the 328P) yet 50MHz, 32-bit power.  Yes, it will be a bit of a learning curve, but there are helpful options out there that can assist you, like the chipKIT system including the handy DP32 board from Digilent.

Also investigate the Teensy 3 for a much beefier Arduino-compatible system with a small footprint which can be soldered to perfboard etc.

You can disolder the female pin headers from pcb and make permanent connections on the remaining holes.

I think the best thing you can do with this, is that you use temporary wires to connect and test the application and later, when you'll come to part, where you should "make-a-solid", you just solder these wires to the bottom, where pin headers are. I think this is the simplest way to do it.
If you want to do it a bit better, desolder female header pins and solder cables to those holes. It's more electronics-approved that way.
Or the simplest (but not the brighest): Jumper wires can be glued into female header pins, but I strongly unrecommend this option, as same as making a shield for this.
There's another(and most elegant too!) option of making a PCB version of arduino: Add the AtMega, few passive components and proper pads, to solder wires on.


text:
How do I connect multiple pinhole cameras and take photos and video at the press of a button?
I am trying to set up a 4 cameras which can take videos/photos at the press of a button.
Things which I will need:

4 micro cameras(the ones which are very small in size) with good
shutter speed and sensor. The cameras will often travel at 20 to
30mph. So I guess good shutter speed is needed.
2 Push buttons. One will start and stop taking pictures really fast, and the other will do the same for video
Battery which can last atleast taking 5 images/1 min of video recording.
4 Microsd cards and the connectors. Is there anyway I would be able to set up a common adapter to all these cards, so when connected to a computer it will show up as 4 different drives?

So I think I can make the set up using this: http://www.arducam.com/
But can it take images really fast. I couldn't see any information regarding this. It should be able to take like 4 images per second. Also it would be awesome if this set up can somehow support taking videos.
Now another thing I need is a push button which will start taking the photos and stop taking it.
This whole thing should operate from a battery.
Mostly I want to know is the list of products which will work or the specs to look for when choosing the products. Also I would like to know if this is the best way to go for  a project like this. This thing will be more like a toy, so I don't want to use really expensive parts for this. Also I don't want a gopro. I want to make this whole set up myself.
Let me know if you need to know more details about this.

Arduino's are way underpowered for these kinds of applications. Might I suggest something like a Raspberry Pi with Multi Camera Adapter

As it stands, I think this question is too broad to get good answers. At the very least you need to be clear about whether you are planning to use the Arduino as a controller for the cameras or if you're hoping to do the image processing yourself.

I want to connect 4 cameras and control it by using a single button to start and stop image capturing. It needs to take like 4 images per second. I want the arduino board because I would like to enable WiFi functionality and small webserver to access the images. What cameras I should use to capture the images as Arduino board can't process the images. Do you have any suggestions? @Gerben

That will never work on a single arduino uno. Webserver, WiFi, images capture, image storage. Why do you insist on using an arduino?

Now that I think about it, I think I will use Pi instead of arduino. The thing is Pi is bigger and it will need a bigger power source. I thought of using arduino because of these reasons.

Arduinos and Cameras do not mix well at all.  It's all down to the sheer quantity of data involved in pictures.
Take for instance a typical VGA image - 640x480 pixels at 24-bit (3 byte) colour depth.  One single picture requires 640x480x3 = 921600 bytes just to store it.
Add to that the fact that most small cameras include hardware JPEG compression which the Arduino really has no hope of being able to handle, and you just can't do anything with it.
Most camera modules use a system called CSI-3 (Camera Serial Interface version 3) for streaming the raw data from the CCD elements into the target.  That allows for high speed data transfer of the whole frame at a speed that is able to support video.  If you think about video as 25 frames per second, and raw data, that means that the data is being transferred from the CCD elements in total at arouns 22 MiB/s - there is absolutely no way that an Arduino can deal with that kind of data.  So cameras that attach to an Arduino have their own controller chip that compresses the image to JPEG and streams it out through a much slower interface - typically RS232.  All the Arduino can then do is tell the camera "Take a picture for me" at which point an image is captured and compressed, and then the Arduino receives the JPEG data through serial (slowly) and stores it on an SD card (also slowly). It can't do anything else with it.
To crunch those numbers - assume that the compressed VGA image from the camera's processor chip is 100,000 bytes (I took a typical photo, scaled it to 640x480 and saved it with 90% JPEG compression and it was roughly that size).  At 9600 baud you get 960 bytes per second. 100,000 / 960 = 104 seconds.
That is how long it would take to transfer one single image through the Arduino.
If the camera has a higher speed UART, say 115200 baud (11520 Bps), that would then give you 100,000/11,520 = 8.7 seconds.
So no, using an Arduino to control cameras in that way just isn't possible.
Instead you need a system that can talk CSI-3 directly - something with a direct camera connection, such as the Raspberry Pi.  Another alternative is any embedded computer with enough processing power and USB ports to connect cheap USB webcams to.  Again the Raspberry Pi would do - especially the newer version 2 with the quad core processor.

I really thought of doing this with raspebrry pi, but the thing is I need it to run with batteries and the whole set up should be portable. So if we add Raspberry pi it would need heavy(300gms atleast) batteries right? Is there anyway of doing this without using heavy batteries? I don't care if I use raspebrry pi or arduino to be frank!

If you want to work with video you need a higher powered system. If you work with a higher powered system you require more current. If you require more current you need bigger batteries. It's a fact of life. Using the right batteries is important of course - Li-Poly gives better power density (smaller/lighter batteries with higher power) than alkaline, for instance.

So what if I don't want the video. I would need like 4 images captured per second. Can that be done without a system like raspberry pi or arduino?

It sounds to me like you want to get a bunch of cheap digital cameras and interface the trigger buttons to the Arduino so the Arduino just tells them to take photos. The cameras themselves then do all the work.

If that can be done, yes. I wanted arduino board because then I can access these photos via WiFi or can connect a single cable to access the pictures from all the 4 cameras. So is it doable?

With Arduino you can only control, you cannot get at the data. For that you will need a Pi or something else that can directly interface with the camera or its USB interface. There's no getting away from it, you can't do what you want on an Arduino! At the moment you're trying to use a trowel to do open cast mining. It just won't work.

Yeah, I think its better to use Pi. I can't find any other way of doing it!


text:
GPS library for Proteus
I am working on a project in which I have to connect my Arduino with a GPS module. In this project I need to get longitude, latitude, time and date from the GPS module and need to send these values via USB to a computer.
On this computer, I am going to design software in Microsoft Visual Studio 2010, which will receive this data and display it on a map.
Now, before designing it in hardware, I want to simulate it on Proteus. I have searched in Proteus but there's no GPS module in it, so does anyone know any GPS module library for Proteus?

As far as I can tell, most GPS modules communicate over serial/UART. In this case, you should be able to add some sort of hardcoded serial string to be sent on the serial pins of the arduino, and as long as it is in the correct format, the GPS library should parse it as if it were from a real GPS module.

I have found the solution to my question so I thought to post it here so that others could also get benefit out of it. Here's the link to GPS Library for Proteus - A complete step by step tutorial on How to download GPS Library for Proteus.
From this link you can download the GPS Library which you need to add to the libraries folder of your Proteus software and you will have the GPS module in Proteus and you can design your simulation quite easily. More details are given in this link.

If you will be using the computer to interface, you don't really need Arduino in the middle.
You can hook the GPS module to the computer using a USB-UART bridge like one below:

The usual GPS modules (ebay or other hobby stores) output NMEA sentences over their serial port. Check the datasheet of your GPS module for the baud rate and the RX/TX pins. Connect the RX and TX lines of your GPS to the USB-serial module and you should be able to see NMEA output on a terminal emulator (set to right baud).
Once you see NMEA sentences over a terminal emulator, you can parse those in your application directly (bypassing terminal emulator) instead of using an Arduino.


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

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

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

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

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

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

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

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

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

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

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

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


text:
WARNING: Category '' in library *any library* is not valid. Setting to 'Uncategorized'
I'm using Ubuntu 14.04 with arduino Galileo and the newest arduino IDE from arduino.cc and every time I compile I got this warnings with any library in place of EEPROM, SD, Wire, Wifi and a lot of others.
When I check the boards manager I got the following:
Invalid library found in /home/User/.arduino15/packages/Intel/hardware/i586/1.6.2+1.0/libraries/Wire: /home/User/.arduino15/packages/Intel/hardware/i586/1.6.2+1.0/libraries/Wire
Anyone knows how to solve this?

As sated above you need to "Edit or add library.properties to that folder so that you specify a valid category."
This link has some good info on the structure of the file: https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification
From that link:
library.properties file format
The library.properties file is a key=value properties list. Every field in this file is UTF-8 encoded. The available fields are:
**name** - the name of the library
version - version of the library. Version should be semver compliant. 1.2.0 is correct; 1.2 is accepted; r5, 003, 1.1c are invalid
**author** - name/nickname of the authors and their email addresses (not mandatory) separated by comma ","
**maintainer** - name and email of the maintainer
**sentence** - a sentence explaining the purpose of the library
**paragraph** - a longer description of the library. The value of sentence always will be prepended, so you should start by writing the second sentence here
**category** - if present, one of these: "Display", "Communication", "Signal Input/Output", "Sensors", "Device Control", "Timing", "Data Storage", "Data Processing", "Other"
**url** - the URL of the library project, for a person to visit. Can be a github or similar page as well
architectures - a comma separated list of architectures supported by the library. If the library doesn’t contain architecture specific code use “*” to match all architectures
**dot_a_linkage** - (available from IDE 1.6.0 / arduino-builder 1.0.0-beta13) when set to true, the library will be compiled using a .a (archive) file. First, all source files are compiled into .o files as normal. Then instead of including all .o files in the linker command directly, all .o files are saved into a .a file, which is then included in the linker command.
**includes** - (available from IDE 1.6.10) a comma separated list of files to be added to the sketch as #include <...> lines. This property is used with the "Include library" command in the IDE. If the property is undefined all the headers files (.h) on the root source folder are included.

If you get this error for the FlexIO library installed with Teensyduino, this is because the author has entered a category "Utility" which is not accepted. I changed the category to "Timing" and the error is gone.

Edit or add library.properties to that folder so that you specify a valid category.
Example of library.properties:
name=WebServer
version=1.0
author=Cristian Maglie <c.maglie@example.com>, Pippo Pluto <pippo@example.com>
maintainer=Cristian Maglie <c.maglie@example.com>
sentence=A library that makes coding a Webserver a breeze.
paragraph=Supports HTTP1.1 and you can do GET and POST.
category=Communication
url=http://example.com/
architectures=avr

From: https://www.bountysource.com/issues/29336127-one-wire-library-still-in-v2-3-0-causes-useless-warning

The Arduino library manager still defaults to v2.3.0, which causes the
  IDE to raise the following warning on compile :
WARNING: Category '' in library OneWire is not valid. Setting to
  'Uncategorized'

Solution (In 1.6.12):

Sketch -> Include Library -> Manage Libraries
In the upper-right "Filter Your Search" box enter (without the quotes): "OneWire"
Click the "OneWire by Jim Studt, Tom P..."
Select version 2.3.1 (or newer)
Click "Install"

authors: שם טוב בן גיאת


text:
Can't make Wee serial WiFi work with Arduino Uno
I'm trying to plug a Wee serial WiFi module on my Arduino Uno, through an XBee shield .

I'm simply trying to make work the example from the library.
All I get is
setup begin
FW Version:
to station err
Join AP failure
setup end

The code i'm using :
#include <SoftwareSerial.h>
#include <doxygen.h>
#include <ESP8266.h>

SoftwareSerial mySerial(3, 2); /* RX:D3, TX:D2 */
ESP8266 wifi(mySerial);

#define SSID "yuflowoffice"
#define PASSWORD "cashless"

void setup(void) {
  Serial.begin(9600);
  mySerial.begin(115200);
  Serial.print("setup begin\r\n");

  Serial.print("FW Version: ");
  Serial.println(wifi.getVersion().c_str());

  if (wifi.setOprToStation()) {
    Serial.print("to station ok\r\n");
  } else {
    Serial.print("to station err\r\n");
  }
  delay(1500);

  if (wifi.joinAP(SSID, PASSWORD)) {
    Serial.print("Join AP success\r\n");
    Serial.print("IP: ");
    Serial.println(wifi.getLocalIP().c_str());
  } else {
    Serial.print("Join AP failure\r\n");
  }

  Serial.print("setup end\r\n");
}

void loop(void) {
}

What can I do?

Do any of the examples work? Although I guess none of them will work as the setup() is the same in each, and that is where the problems begin. It seems like no information is being picked up from the Serial port (Tx/Rx), as wifi.getVersion().c_str() results an empty string. Have you taken note of the issues/points listed on the main page, in particular increasing the size of the buffer?

Also, take a look at Need Help with WiFi Connection. As a sanity check, instead of using the XBee shield  and the sketch, try just using the Wee just plugged into an XBee Explorer/Breakout board, and then use a terminal to send it AT commands to see if it responds appropriately. I have recently ordered one of these devices, but it has not yet arrived, so I can't try any tests of my own unfortunately.

A look at https://github.com/itead/ITEADLIB_Arduino_WeeESP8266/blob/master/ESP8266.h shows that when you pass a SoftwareSerial object to the ESP8266 constructor, a default baud rate of 9600 is also passed to it. Also, the library source file shows that, in the constructor, the begin() method of the SoftwareSerial object you passed (myserial) is called with 9600 baud. Thus, this line in your code:
    mySerial.begin(115200);

is a duplicate, albeit one with a different baud rate, thus rendering the constructor's call of mySerial.begin() useless, since your call comes after the constructor's. If you are certain that 115200 is the right baud rate for the hardware, then you should get rid of the line above and instead pass the baud rate to the constructor like this:
    ESP8266 wifi(mySerial, 115200);

Replace 115200 with any baud rate you discover to be the right one for the AT commands. You also need to uncomment the line in ESP8266.h in your library:
    //#define ESP8266_USE_SOFTWARE_SERIAL

and then save, since you are using SoftwareSerial to communicate with the module.

Thank you for your reply. I tried your code, with every baud rate available, nothing changed for now.

Just to be clear, you got rid of the mySerial.begin() in your code, tried baud rates like i recommended, and uncommented the #define in ESP8266.h and saved it? And your pin connections are like this:               ESP8266_TX->Arduino pin 3
ESP8266_RX->Arduino pin 2
ESP8266_CH_PD->3.3V
ESP8266_VCC->3.3V
ESP8266_GND->GND....you should also get rid of the #include <doxygen.h>

I also recommend you connect the module directly to the Arduino with jumpers; only the pins indicated above should be connected at all, because other pins may be at a level that affect the module's working (e.g. the FW pin, which switches the module between firmware upload mode and normal mode). Also ensure that the slide switch on the module is set to 'work'. You're powering it using the Arduino 3.3V pin, which can't supply > 50mA, whereas the module can use up to 215mA. Try a different power source, maybe Arduino 5V pin connected to the module through LM1117T to bring it down to 3.3V.

Level-shifting the SoftwareSerial TX from 5V to 3.3V, using a voltage divider circuit, may also be needed, since its unclear if the module is 5V-tolerant.

Thank you brianrho. Actually, it was indeed the voltage that blew it up : I think the arduinoxbee shield doesn't make the right wiring for wee serial wifi. So i wired by myself :
3V3 on first pin
D3 on second pin
D2 on third pin
GND to last pin
and all worked fine. on 9600 bauds, i have to precise.


text:
Logging to multiple destinations (serial & SD card)
I am building a rover using an Arduino Mega and an Arduino Uno. The Mega has a sensor shield that has an SD card slot. The intent is for the rover to be autonomous, and I currently send logging info to the serial port (to log actions like boot, diagnostics, etc.)
Is there a simple way to redirect this output to BOTH the serial and the SD card? I would be happy with just a single file with lines added for each entry.
My complication here is to prevent using Serial.println as well as SD.println as two separate commands. Is there any other way around this?

Create something like a log function that does call both Serial.println and SD.println

Do you want to eliminate the two separate println() calls to keep the code concise or is there another issue that you're concerned with?

Do you have internet connection? I'd rather log to a server than to a SD-card, for faster access of the log and for less wearing out the SD-card.

The simplest thing you can do is to create a simple function that performs both tasks for you.  However, there are certain caveats that you should look out for.  The most basic function would be:
void log(const char *msg) {
    Serial.println(msg);
    myFile.println(msg);
}

However that is not the best way of doing it since that requires all your messages to be in RAM.  So you should really use the __FlashStringHelper type as well as an overload function so you can use the F() macro to save RAM:
void log(const char *msg) {
    Serial.println(msg);
    myFile.println(msg);
}

void log(const __FlashStringHelper *msg) {
    Serial.println(msg);
    myFile.println(msg);
}

And that will pick the right version of log depending on what you pass.  But what if you want to pass some variables, like numbers?  Overloading can help again here.  Another pair of functions now that take two parameters instead of one:
void log(const char *msg) {
    Serial.println(msg);
    myFile.println(msg);
}

void log(const __FlashStringHelper *msg) {
    Serial.println(msg);
    myFile.println(msg);
}

void log(const char *msg, int v) {
    Serial.print(msg);
    Serial.print(" ");
    Serial.println(v);
    myFile.print(msg);
    myFile.print(" ");
    myFile.println(v);
}

void log(const __FlashStringHelper *msg, int v) {
    Serial.print(msg);
    Serial.print(" ");
    Serial.println(v);
    myFile.print(msg);
    myFile.print(" ");
    myFile.println(v);
}

So now you have 4 functions called log, and they can be used in these different ways:
log("This is a message"); // Could be a char * variable
log(F("This is a message"));
log("The temperature is:", temp);
log(F("The temperature is:", temp);

And of course you can keep expanding and expanding the parameters in different ways for different combinations of parameters.  Just be warned that for some combinations of parameters the compiler won't be able to work out which is the right function to call (for instance if you have one that takes a long and one that takes a byte in the same place and you just pass a numeric literal), so you have to think carefully about how you arrange your parameters.


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


text:
Basic usage of Nick Gammon's Regexp library
I am using the following code modified from the examples. I get the count of matches but the actual value is not displayed
#include <Regexp.h>

void setup() {
    Serial.begin(115200);
    MatchState ms;
    char buf [100];
    char buf2 [100] = "The quick brown fox jumps over the lazy wolf";
    ms.Target (buf2);
    unsigned int count = ms.MatchCount ("[aeiou]");

    Serial.print ("Found ");
    Serial.print (count);
    Serial.println (" matches.");
    for (int j = 0; j < count; j++)
    {
          Serial.print ("Capture number: ");
          Serial.println (j, DEC);
          Serial.print ("Text: '");
          Serial.print (ms.GetCapture (buf, j));
          Serial.println ("'");
    }
}
void loop(){}

Could you add the output you are getting, to your question?

You haven't defined any capture groups in your regexp.
The regexp [aeiou] will match any of those characters, but it won't capture them.  To capture you need to define a capture group which is a sequence of tokens surrounded by parenthesis.  For instance:
([aeiou])

In your test phrase "The quick brown fox jumps over the lazy wolf" that should match 11 times and capture each match, resulting in captures of e u i o o u o e e a o.
The reason why matching and capturing are two completely different things is so you can do things like [aeiou]([aeiou]) which would capture the second vowel in a two vowel sequence. In your example it would match the ui of quick and capture just the i.


text:
Can external interrupts be OR'd together on the '328 (Uno)?
I'm thinking about how to handle a rotary encoder. I'm planning on using interrupts and would like to use both the 'A' and 'B' phase transitions to generate interrupts. I'm wondering if there is any reason why the signals couldn't be OR'd together to generate the interrupt so that I wouldn't need to consume both external interrupts for the encoder.

You still need to read both signals regardless, so you only end up using an extra pin.

I know I'd still need to use two pins to read the state of the encoder, but I was hoping to use one interrupt pin and one non-interrupt pin and still be able to get full resolution from the encoder.

All ATmega328P pins support pin change interrupts.

Yes, but my understanding is that the "internal" interrupt latency and/or software overhead is much higher than it is for the "external" interrupts – so I was hoping to find a way to use a single external interrupt. I have't actually measure the difference yet, so I don't know how big a hit it would be to use the internal interrupts for this application. But the question is also generally interesting if the technique could be used in other situations as well.

Regarding the notion that “"internal" interrupt latency and/or software overhead is much higher than it is for the "external" interrupts”, it certainly is true that PCI (pin-change interrupts) libraries PinChangeInt.h (deprecated) and EnableInterrupt.h have high software overhead.  By keeping track of former values, for each pin those libraries support separate callback routines for Rising, Falling, Change, High, and Low.  PCIs are grouped in sets of eight pins per interrupt vector, leading to 40 different cases of callback routines when a PCI fires.  That is, when a PCI occurs, the libraries quickly find out which set of pins changed – because that's what the hardware supports – but then they go through all eight pins on the vector one by one checking if it changed, and how it changed, then calling the callback associated with the particular pin and its particular state.
For reading pins of a rotary encoder, say a KY-040, the overhead described above can cause loss of 10%–20% of rotary counts.  If you are concerned about not losing counts, write your own ISR()-level interrupt service routine.  The example below illustrates a routine using ISR(); this example is from my answer to previous question #18221, with some comments added here and there.  See that answer for discussion of the timing data that is this program's output.  (For rotary encoder quadrature-counting, see discussion below).
/*  rcTiming.ino -- JW, 30 November 2015 --
 * Uses pin-change interrupts on A0-A4 to time RC pulses
 *
 * Ref: https://arduino.stackexchange.com/questions/18183/read-rc-receiver-channels-using-interrupt-instead-of-pulsein
 *
 */
#include <Streaming.h>
static   byte rcOld;        // Prev. states of inputs
volatile unsigned long rcRises[4]; // times of prev. rising edges
volatile unsigned long rcTimes[4]; // recent pulse lengths
volatile unsigned int  rcChange=0; // Change-counter

// Be sure to call setup_rcTiming() from setup()
void setup_rcTiming() {
  rcOld = 0;
  // Note, if using an encoder without pullups on it,
  // change INPUT in next 2 lines to INPUT_PULLUP
  pinMode(A0, INPUT);  // pin 14, A0, PC0, for pin-change interrupt
  pinMode(A1, INPUT);  // pin 15, A1, PC1, for pin-change interrupt
  pinMode(A2, INPUT);
  pinMode(A3, INPUT);
  PCMSK1 |= 0x0F;       // Four-bit mask for four channels
  PCIFR  |= 0x02;       // clear pin-change interrupts if any
  PCICR  |= 0x02;       // enable pin-change interrupts
}
// Define the service routine for PCI vector 1
ISR(PCINT1_vect) {
  byte rcNew = PINC & 15;   // Get low 4 bits, A0-A3
  byte changes = rcNew^rcOld;   // Notice changed bits
  byte channel = 0;
  unsigned long now = micros(); // micros() is ok in int routine
  while (changes) {
    if ((changes & 1)) {  // Did current channel change?
      if ((rcNew & (1<<channel))) { // Check rising edge
        rcRises[channel] = now;     // Is rising edge
      } else {              // Is falling edge
        rcTimes[channel] = now-rcRises[channel];
      }
    }
    changes >>= 1;      // shift out the done bit
    ++channel;
    ++rcChange;
  }
  rcOld = rcNew;        // Save new state
}

void setup() {
  Serial.begin(115200);
  Serial.println("Starting RC Timing Test");
  setup_rcTiming();
}

void loop() {
  unsigned long rcT[4]; // copy of recent pulse lengths
  unsigned int rcN;
  if (rcChange) {

    // Data is subject to races if interrupted, so off interrupts
    cli();          // Disable interrupts
    rcN = rcChange;
    rcChange = 0;       // Zero the change counter
    rcT[0] = rcTimes[0];
    rcT[1] = rcTimes[1];
    rcT[2] = rcTimes[2];
    rcT[3] = rcTimes[3];
    sei();          // reenable interrupts

    Serial << "t=" << millis() << " " << rcT[0] << " " << rcT[1]
       << " " << rcT[2] << " " << rcT[3] << " " << rcN << endl;
  }
  sei();            // reenable interrupts
}

Note, for the above you may need to download and install Streaming.h via Streaming5.zip from arduiniana.org.
Rotary encoder quadrature-counting
The program above tracks and reports pulse-length times, instead of decoding the quadrature signals the rotary encoder provides.  The program below reports rotary encoder counts, but does so using INT0 and INT1 instead of PCIs.  You will want to combine relevant portions of the two routines together – ie, use the interrupt setup and handling framework from above, with the body of the service routine from below.  [Note, this program is from my answer to previous question #16420.  The encoder decoding code within it is faster and shorter than other decoding code I've looked at, and is fast enough to support two encoders rotating simultaneously while losing few counts.]
/*  roto_jw4.ino -- JW, 29 September 2015 --
 *  A 4-state state-machine implementation of rotary
 *  encoding for KY-040 rotary knobs.  The state-machine picture at
 *  https://e2e.ti.com/support/microcontrollers/hercules/f/312/t/318762
 *  in a Feb 4, 2014 7:40 PM post by Anthony Seely shows counts
 *  increasing on transitions 10 -> 11 -> 01 -> 00 -> 10 and
 *  decreasing on transitions the other way.  Transitions between 00
 *  and 11 or 10 and 01 are invalid.  This code detects valid
 *  transitions by (abOld xor abNew) equaling 1 or 2.  It detects
 *  up-count events by the tri-bit value ABA' (where A' is the new
 *  reading on pin A) being equal to 1, 2, 5, or 6 (a bit mask of
 *  0x66), and down-count events by ABA' being equal to 0, 3, 4, or 7
 *  (a bit mask of 0x99).
 *
 *  On a KY-040 unit I tested, there are 30 detent positions per turn.
 *  With this unit the code generates 60 counts per turn, which can be
 *  seen individually as one turns the rotor slowly.  Odd counts
 *  appear between detents, even counts at detents.
 *
 *  Set quadrature-signal pin numbers, via PinA and PinB constants.
 *  Set IPINMODE to INPUT_PULLUP if there are no external pull-ups
 *  on encoder AB pins, else set IPINMODE to INPUT
 */
enum { PinA=2, PinB=3, IPINMODE=INPUT };

static  byte abOld;     // Initialize state
volatile int count;     // current rotary count
         int old_count;     // old rotary count

void setup() {
  pinMode(PinA, IPINMODE);
  pinMode(PinB, IPINMODE);
  attachInterrupt(0, pinChangeISR, CHANGE); // Set up pin-change interrupts
  attachInterrupt(1, pinChangeISR, CHANGE);
  abOld = count = old_count = 0;
  Serial.begin(115200);
  Serial.println("Starting Rotary Encoder Test");
}

// On interrupt, read input pins, compute new state, and adjust count
void pinChangeISR() {
  enum { upMask = 0x66, downMask = 0x99 };
  byte abNew = (digitalRead(PinA) << 1) | digitalRead(PinB);
  byte criterion = abNew^abOld;
  if (criterion==1 || criterion==2) {
    if (upMask & (1 << (2*abOld + abNew/2)))
      count++;
    else count--;       // upMask = ~downMask
  }
  abOld = abNew;        // Save new state
}

void loop() {
  if (old_count != count) {
    Serial.print(millis());
    Serial.print("  ");
    Serial.println(count);
    old_count = count;
  }
}

Using other pins for PCIs
If you wish to monitor two rotary encoder lines using pin change interrupts on pins other than A0 and A1, you may need to replace vector PCINT1_vect with some other vector, and will need to replace the pins mask with a different one.  The following program can be used to display a table of PCI vectors, masks, etc.  (As noted in my question Why PJ0 and PJ1 are not reporting as PCINT pins, pins PJ0 and PJ1 on an ATmega-2560 board will not report correctly.)
/*  pinsList -- JW, 4 October 2015 --
 *
 *  Displays a list of Arduino pin numbers for current kind of Arduino
 *  board, along with port codes, pin-change-interrupt numbers, and
 *  pin-change-interrupt vector numbers.
 *
 *  Here are two examples of output lines for pin 11, the first for an
 *  Uno, the second for a Mega:
 *
 *        11   PB3   0x04   PWM   PCINT3  PCINT0_vect
 *        11   PB5   0x20   PWM   PCINT5  PCINT0_vect
 */
//-----------------------------------------------------------
// Given a value with 1 bit set, return bit #.  Else return 9.
byte getBitfromBV (byte m) {
  byte b=0, v=1;
  while (v) {
    if (m==v)
      return b;
    ++b; v <<= 1;
  }
  return 9;
}
//-----------------------------------------------------------
void processPinNumber(byte pin) {
  char buffi[128];      // We create text-to-write in buffi
  byte nbuff=0;         // #chars used in buffi
  byte nPCICR;          // 0, 1, or 2 for mask-register #
  byte bitInByte;       // 0 to 7 for bit in I/O mask
  byte pinPort;         // pin's port #, in range 1 to 12
  byte PCInum;          // PCINT# if pin is a PCI pin
  char *portLet = "?ABCDEFGHIJKL";

  if (pin >= NUM_DIGITAL_PINS) return;

  pinPort = digitalPinToPort(pin); // Get port #, in range 1 to 12
  bitInByte = getBitfromBV(digitalPinToBitMask(pin));

  nbuff = snprintf(buffi, sizeof(buffi), "  %2d   P%c%d  0x%02x",
           pin, portLet[pinPort], bitInByte, 1<<bitInByte);

  // Indicate if it's a PWM pin
  if (digitalPinHasPWM(pin)) {
    nbuff += snprintf(buffi+nbuff, sizeof(buffi)-nbuff, "  PWM");
  } else {
    nbuff += snprintf(buffi+nbuff, sizeof(buffi)-nbuff, "     ");
  }

  // If it's a PCINT pin, show its PCINT number and 0, 1, 2 for its vector #
  if (digitalPinToPCICR(pin)) {      // Is it a PCint pin?
    nPCICR = digitalPinToPCICRbit(pin); // 0, 1, 2 for pin's PCICR bit#
    PCInum = nPCICR*8 + bitInByte;
    nbuff += snprintf(buffi+nbuff, sizeof(buffi)-nbuff,
             "  PCINT%d  PCINT%d_vect",  PCInum,  nPCICR);
  }
  Serial.println(buffi);
}
void setup() {
  delay(50);
  Serial.begin(115200);
  delay(50);
  while (!Serial) ;             // wait for serial stream to connect
  Serial.println("\nPin#  Port  Mask  PWM   PCINT");
  for (byte p=0; p<NUM_DIGITAL_PINS; ++p)
    processPinNumber(p);
  Serial.end();
}

void loop() {
}

ISR-framework-generating Sketch
The program below generates frameworks for specified PCI pins and prints them to Serial.  See usage comments within the program.  This provides an easy way to create the basic outline of an ISR to handle PCIs.
/*  pinFunctions -- JW, 1 October 2015 --
 *
 *  Displays direct pin-access and pin-change-interrupt setup code,
 *  for inclusion in a sketch, for specified pin numbers.  The
 *  displayed code can be pasted into a sketch where execution speed
 *  matters.
 *
 *  When called with a call like `genCode ("affix", "9,11");`, genCode
 *  will produce a set of procedures: ISR routines for pins that
 *  support pin-change interrupts; get and put routines to read from
 *  or store to registers; and a setup routine.  The generated get,
 *  put, and setup routines will have names formed by suffixing the
 *  affix to get, put, and setup, respectively.  For example, if the
 *  affix is ML47 the names of generated routines will include
 *  getML47, putML47, and setupML47.
 *
 *  Generated get() and put() code is of the following forms (in which
 *  u, v are port-letters; values mu, mv, ni are numerical constants;
 *  and w is a parameter value) if all the pins, n1, ... nk in the
 *  pins-list are in port u, under mask mu:
 *
 *             return PINu & 0xmu; // Get pins n1, ... nk
 *             PORTu = PINu & ~mu | w & mu;
 *
 * For example, with Uno pins 3, 4, 6, get() and put() bodies are:
 *
 *             return PIND & 0x58;
 *             PORTD = PIND & 0xa7 | w & 0x58;
 *
 *  The following forms arise if the pins are in ports u and v; and so
 *  forth if more than two ports are involved.
 *
 *             return PINu & masku | PINv & mv; // Get pins n1, ... nk
 *             PORTu = w & 0xmu;   // Put pins <u pins>
 *             PORTv = w & 0xmv;   // Put pins <v pins>
 *
 *  genCode() does not require that all pins belong to the same port.
 *  It will produce usually-desired results if bit positions don't
 *  interfere, otherwise may not.  For example: An Arduino Uno
 *  pins-list "2,10" corresponds to port pins PD2 and PB2.  Both are
 *  in bit position 2, so get's result will be the OR of the PB2 and
 *  PD2 values, while put will store the same bit value to both pins.
 *
 *  To use the pasted code: A statement like `w = getAFFIX();` will
 *  read a set of pins and store the value in w.  A statement like
 *  `putAFFIX(w);` will write w to a set of pins.  Also, add a line
 *  like the following in setup():
 *
 *       setupAFFIX(ioMode, enablePCI);
 *
 *  In the `setupAFFIX(ioMode, enablePCI);` call, substitute an
 *  appropriate affix in place of AFFIX; substitute one of INPUT,
 *  OUTPUT, or INPUT_PULLUP in place of ioMode; and substitute 1 or 0
 *  for enablePCI, to enable or not enable pin-change-interrupt setup.
 *
 *  If you want to save room and don't plan to use pin-change
 *  interrupts, instead of merely not enabling PCI setup, you can
 *  remove the ISR routines and the `if (enablePCI) {...}` section
 *  from the pasted code.
 *
 *  Each generated ISR routines contains one line, of form
 *
 *        byte datum = PINu & mu; // Read pins <list>
 *
 *  The idea is that you will paste the generated ISR into your
 *  sketch, then populate it with appropriate interrupt processing
 *  code.  Note 1: datum contains data from one port, a port which
 *  belongs to the interrupt vector.  If you need data from other
 *  ports as well, then paste appropriate lines from the get() routine
 *  into the ISR.  Note 2: This version of pinFunctions does not
 *  announce pins that don't belong to PCI vectors, if any.
 *  (Processor pins with functions like PCINT0 ... PCINT23 belong to
 *  PCI vectors.)  You can compare the masks used in get() to those
 *  used in the ISR's to detect this.  If the masks differ, some pins
 *  aren't PCI pins.  Note 3: If multiple ports' pins belong to one
 *  vector (eg Ard#0 or PE0 for PCINT8 and Ard#15 or PJ0 for PCINT9,
 *  both on vector PCINT1_vect), a code-generation error of form "Pin
 *  x's port #y isn't #z" will appear and you will need to paste in
 *  appropriate lines from get() or otherwise manually prepare correct
 *  code.
 */

char buffi[128];        // We create text-to-write in buffi
char buffn[32];         // also in buffn
byte nbuff=0;           // #chars used in buffn
char *c;            // c points into pinsList
byte pin;           // pin number
byte nPCICR;            // 0, 1, or 2 for mask-register #
byte vecmask;           // OR of 1<<nPCICR values
byte intmask[3];        // OR of int. enable masks
byte maskBitPC;         // 0 to 7 for bit in PCI mask
byte maskBitIO;         // 0 to 7 for bit in I/O mask
byte pinPort;           // pin's port #, in range 1 to 12
byte PCInum;            // PCINT# if pin is a PCI pin

// Given a value with 1 bit set, return bit #.  Else return 9.
byte getBitfromBV (byte m) {
  byte b=0, v=1;
  while (v) {
    if (m==v)
      return b;
    ++b; v <<= 1;
  }
  return 9;
}

// Get next pin number from pinsList, and its associated reg numbers
byte getPinNumber() {
  byte cc=*c;
  if (!cc)
    return 0;
  pin=0;
  for (; '0' <= cc && '9' >= cc; cc=*++c) {
    pin = 10*pin + cc - '0';
  }
  pinPort = maskBitIO = PCInum = nPCICR = maskBitPC = 0;
  if (pin < NUM_DIGITAL_PINS) {
    pinPort = digitalPinToPort(pin); // Get port #, in range 1 to 12
    maskBitIO = digitalPinToBitMask(pin);
    if (digitalPinToPCICR(pin)) {        // Is it a PCint pin?
      nPCICR  = digitalPinToPCICRbit(pin); // 0, 1, 2 for p's PCICR bit#
      maskBitPC = digitalPinToPCMSKbit(pin);
      PCInum =  nPCICR*8+ getBitfromBV(maskBitIO);
    }
  }
  if (!cc)         // At end of string? If so,
    --c;           // allow for caller incrementing c
  return 1;
}

void genCode (char *affix, char *pinsList) {
  char *portLet = "?ABCDEFGHIJKL?";
  enum { portMax=12 };
  byte readmask;        // Input-bits mask
  byte port;            // Port #

  snprintf(buffi, sizeof(buffi), "\n// %s : pins %s", affix, pinsList);
  Serial.println(buffi);

  //==================================================================
  // Generate  "byte get<affix>() { // Get pins <list>"
  //              return PINu & mu | PINv & mv | ...
  //            }"
  nbuff = snprintf(buffi, sizeof(buffi), "byte get%s () { // Get pins", affix);
  for (port=1; port<=portMax; ++port) {
    for (readmask=0, c = pinsList; getPinNumber(); ++c) {
      if (pinPort==port) {
    nbuff += snprintf(buffi+nbuff, sizeof(buffi)-nbuff, "% d,", pin);
    readmask |= maskBitIO;
      }
    }
    if (readmask) buffi[nbuff-1] = ';'; // Replace extra , by ;
  }
  Serial.println(buffi);    // Print first line of get...() function
  nbuff = snprintf(buffi, sizeof(buffi), "  return");
  for (port=1; port<=portMax; ++port) {
    for (readmask=0, c = pinsList; getPinNumber(); ++c) {
      if (pinPort==port) {
    readmask |= maskBitIO;
      }
    }
    if (readmask)
      nbuff += snprintf(buffi+nbuff, sizeof(buffi)-nbuff, " PIN%c & 0x%02x |",
            portLet[port], readmask);
  }
  snprintf(buffi+nbuff-2, sizeof(buffi)-nbuff, ";\n}"); // -2 loses extra " |"
  Serial.println(buffi);  // Print last two lines of get...() function

  //==================================================================
  // Generate  "void put<affix>(byte w) { // Put pins <list>"
  //              PORTu = PINu & ~mu | w & mu;
  //              ...
  //            }"
  nbuff = snprintf(buffi, sizeof(buffi), "void put%s () { // Put pins", affix);
  for (port=1; port<=portMax; ++port) {
    for (readmask=0, c = pinsList; getPinNumber(); ++c) {
      if (pinPort==port) {
    nbuff += snprintf(buffi+nbuff, sizeof(buffi)-nbuff, "% d,", pin);
    readmask |= maskBitIO;
      }
    }
    if (readmask) buffi[nbuff-1] = ';'; // Replace extra , by ;
  }
  Serial.println(buffi);    // Print first line of put...() function
  for (port=1; port<=portMax; ++port) {
    for (readmask=0, c = pinsList; getPinNumber(); ++c) {
      if (pinPort==port) {
    readmask |= maskBitIO;
      }
    }
    if (readmask) {
      snprintf(buffi, sizeof(buffi), "  PORT%c = PIN%c & 0x%02x | w & 0x%02x;",
           portLet[port], portLet[port], (byte)(~readmask), readmask);
      Serial.println(buffi);  // Print a port-setting line of put...() function
    }
  }
  Serial.println("}");  // Print last line of put...() function

  //=================================================================
  // Generate ISR's:  Process 3 possible pin-change interrupt vectors
  vecmask = 0;
  for (byte ivect=0; ivect < 3; ++ivect) {
    byte sinPort=15;        // currently-in-use same port #
    intmask[ivect] = 0;
    byte busyvect=0;              // Assume vector not used
    byte readmask=0;              // Input mask
    // Loop to see if vector is used
    for (c = pinsList; getPinNumber(); ++c) {
      if (nPCICR == ivect) {
    ++busyvect; sinPort = pinPort;  // Bits on same port get read once
    vecmask |= 1<<ivect;
    intmask[ivect] |= 1<<maskBitPC;
      }
    }
    if (busyvect) {     // If vector is busy, create its ISR
      snprintf(buffi, sizeof(buffi), "ISR(PCINT%d_vect) {", ivect);
      Serial.println(buffi);
      nbuff = 0;
      for (c = pinsList; getPinNumber(); ++c) {
        // See if it's a PCint pin, and on the current vector
    if (digitalPinToPCICR(pin) && nPCICR == ivect) {
      intmask[ivect] |= 1<<maskBitPC;
      readmask |= digitalPinToBitMask(pin);
      nbuff += snprintf(buffn+nbuff, sizeof(buffn)-nbuff, " %d,", pin);
      if (pinPort != sinPort) {
        snprintf(buffi, sizeof(buffi), "Pin %d's port #%d isn't #%d",
             pin, pinPort, sinPort);
        Serial.println(buffi);
      }
    }
      }
      snprintf(buffi, sizeof(buffi), "  byte datum = PIN%c & 0x%02x; // Read pins %s\n}",
           portLet[sinPort], readmask, buffn);
      Serial.println(buffi);
    }
  }
  snprintf(buffi, sizeof(buffi), "void setup%s(byte ioMode, byte enablePCI) {", affix);
  Serial.println(buffi);
  for (c = pinsList; getPinNumber(); ++c) {
    nbuff = snprintf(buffi, sizeof(buffi), "  pinMode(%2d, ioMode); // %2d, P%c%d",
         pin, pin, portLet[pinPort], getBitfromBV(maskBitIO));

    if (maskBitPC)
      snprintf(buffi+nbuff, sizeof(buffi)-nbuff, "   PCINT %d", PCInum);
    Serial.println(buffi);
  }
  Serial.println("  if (enablePCI) {");
  for (byte ivect=0; ivect < 3; ++ivect) {
    if (intmask[ivect]) {
      snprintf(buffi, sizeof(buffi), "    PCMSK%d |= 0x%02x;", ivect, intmask[ivect]);
      Serial.println(buffi);
    }
  }

  snprintf(buffi, sizeof(buffi), "    PCIFR  |= 0x%02x; // clear PC interrupts if any",
       vecmask);
  Serial.println(buffi);
  snprintf(buffi, sizeof(buffi), "    PCICR  |= 0x%02x; // enable PC interrupts\n  }\n}",
       vecmask);
  Serial.println(buffi);
}

void setup() {
  Serial.begin(115200);
  while (!Serial) ;             // wait for serial stream to connect
  Serial.println("Starting Code Generation");
  genCode ("A0A1",  "14,15\0"); // A0, A1 on a nano
  genCode ("Pair78",  "7,8");
  genCode ("Trip346",  "3,4,6");
  genCode ("Quad789A", "7,8,9,10");
  genCode ("Hex8toD",  "8,9,10,12,11,13");
  genCode ("LotsSmall", "2,6,7,8,9,10,11,12,13,14,15,19,20,21,22,28,29,30,31,37");
  genCode ("LotsBig",   "31,37,38,37,38,45,46,52,53,54,55,61,62,63,69,70,71,76");
  Serial.println("Ending Code Generation");
  Serial.end();
}

void loop() {
}


text:
How to have precise measurements
I need to display measurements of a sensor which need to be presented on a precise time-scale.
Since the loop function is not quite precise, how can i make sure that i can measure at say for example exactly 1ms?
( I am using an ADXL345 sensor )
Thanks a lot!

The ADXL345 has both a FIFO and data rate setting. This allows sampling to be done with a precise frequency without having to use timers, etc, on the MCU. The MCU/Arduino has to fetch data before the FIFO overflows. The max sampling frequency depends on the communication protocol (I2C or SPI), i.e. how fast the MCU can empty the FIFO.
It is possible to use the ADXL345 in stream mode, collect samples at a fixed rate, and get an interrupt when the FIFO has been filled to a specified level (watermark). The samples can then be read in burst mode.
The samples will be on a "precise time-scale".
There are even more advanced usages of the device with tap, double-tap and free fall detect.
Please see Data Rate setting and FIFO control in datasheet.
Cheers!
PS: Using I2C at 100 KHz will take 1 ms just to address the device. Addressing a register will take another ms and a ms per data byte. Reading the data register (six bytes) will take at least 8 ms. Realistic max sample rate with I2C at 100 KHz is 10-100 Hz. There is also limited amount of memory for buffers.

Microcontrollers have built in peripherals called Timers. They are used for many purposes, including working out when something should be done.
There are plenty of good Timer libraries around for the Arduino, including the popular TimerOne/TimerThree libraries.


text:
MEGA2560 + SIM900A - constantly blinking, not responding
Recently I got new Arduino Mega 2560 and GSM/GPRS module - SIM900A v3.8.2.
I live in Europe, so I flashed European firmware for SIM900 and it was working OK (sending SMS, receive calls, sending http requests with GPRS) on my PC using PuTTY serial port terminal. After few tests, I ran default sketches from MarcoMartines GSMSHIELD library (other libraries weren't working for me) with Arduino Mega 2560 and they were running ok. After that I decided to make my own sketch. Here you go:

#include "SIM900.h"
#include "inetGSM.h"
#include "sms.h"
#include "call.h"

char NumberCalling[20];
char CorrectNumber[20] = {"5", "0", rest of my number here..... };

void InstantSendSms()
{
  Serial.print(F("SMS: Preparing a text message to be sent to: "));
  Serial.println(CorrectNumber);

  char Message[155];
  sprintf(Message, "Hello from Arduino :)");

  Serial.print(F("Message to be sent : "));
  Serial.println(Message);
  sms.SendSMS(CorrectNumber, Message);
  delay(50);
  Serial.println(F("SMS: Message has been sent."));
}

void InstantSendHttp()
{

  char Address[155];
  sprintf(Address, "test.php?text=test-message");
    Serial.println(F("GPRS: Opening a new Internet connection..."));

    if (inet.attachGPRS("internet", "", ""))
      Serial.println(F("GPRS: Attached!"));
    else
      Serial.println(F("GPRS: NOT attached! Error."));
    delay(1000);

    //Read IP address.
    gsm.SimpleWriteln("AT+CIFSR");
    delay(5000);
    //Read until serial buffer is empty.
    gsm.WhileSimpleRead();

    Serial.print(F("GET request : "));
    Serial.println(Address);

    char ReturnedMsg[50];
    int NumberRetMsg;
    NumberRetMsg = inet.httpGET("myserver.com", 80, Address, ReturnedMsg, 50);
    //Print the results.
    Serial.println(F("GPRS: Number of data received:"));
    Serial.println(NumberRetMsg);
    Serial.println(F("GPRS: Data received:"));
    Serial.println(ReturnedMsg);

    inet.dettachGPRS();

    Serial.println(F("GPRS: Query has been sent."));

  delay(2000);  // time to finish
}

void setup()
{
  Serial.begin(9600); // Serial connection via USB for debugging purposes
  Serial.println(F("*** Device is starting... ***"));
  delay(50);
  Serial.println(F("* Setting up the GSM Module... *"));
  // connection state
  boolean Connected = false;
  // establish network connection...
  while (!Connected)
  {
    if (gsm.begin(9600))
    {
      Serial.println(F("** GSM : GSM connection established. Ready. **"));
      Connected = true;
    }
    else
    {
      Serial.println(F("** GSM : Failed to connect to the GSM network. **"));
    }
  }
  delay(50);
  Serial.println(F("*** Setup complete! All systems are ON ***"));
}

void loop()
{
  Serial.println(F("GSM: Checking voice call status..."));
  switch(call.CallStatusWithAuth(NumberCalling, 0, 0))
  {
    case CALL_INCOM_VOICE_AUTH: // Yes! Someone is calling us
      Serial.print(F("GSM: Receiving call... Caller ID: "));
      Serial.println(NumberCalling);
      if(strcmp(NumberCalling, CorrectNumber) == 0)
      {
        Serial.println(F("GSM: Number IS matching whitelist!"));
        delay(1800);  // Wait 1,8 seconds before hang up
        call.HangUp(); // Hang up on me
        InstantSendSms();
        InstantSendHttp();
      }
      else
      {
        Serial.println(F("GSM: Caller is unknown."));
        call.HangUp();
      }
      break;
    case CALL_NONE:
      Serial.println(F("GSM: No one is callin us right now."));
      break;
    default:
      Serial.println(F("GSM: Talking or not responding..."));
      break;
  }
  delay(10);
}

At first, I used 9600 baud for GSM in the sketch. It successfully sent an SMS, but no luck with GPRS - in the Serial Monitor I got always the error message:

GPRS: NOT attached! Error.

I read on the Internet that the baud rate is very important here. Somewhere on this forum I got the information that I should change baud rates in HWSerial.cpp and GSM.cpp in the library files to 4800 baud.
Well, I tried different bauds in my sketch. Finally I got this working with this configuration: in my sketch - 19200 baud, in library - 4800 baud. I run Arduino, SMS was sent ok, GPRS said "GPRS: Attached!" but no data came to my website. Then suddenly SIM900 module stopped working it is weirdly blinking. Power LED is brightening and darkening, and never goes off, and Status LED is quickly blinking. You can see that on the video, SIM900A Mini v3.8.2 - Weird blinking | Module not responding.
I connected it directly to my PC, PuTTy was receiving crazy input from the SIM900, as you can see below:

I thought that maybe the firmware had broken and I flashed again new firmware. It went smoothly and ok, but then again, module is acting in a strange way, the same as before.
What can I do to get it working normally?

UPDATE:
Hello. Today I tried again to work with my module. I communicated with sim900 using http://m2msupport.net/m2msupport/module-tester/ , things are getting better, SIM900 is responding to AT commands. Module still doesn't work as it is supposed to - PowerLed is ON, StatusLed is indicating connecting to the network. It seems to be connected for about a second and then SIM900 is self-resetting and doing that over and over. How to fix that?
I don't think here power supply is guilty - it's 5V 2A.

There are pieces missing from your code I think. Please post the full code.

Well, I am designing a system which has GSM connection and GPS receiver and few more feautures. I started with GSM module and I got stuck with it, so I haven't wrote any more code. For now it's all I have.

What baudrate SIM900 is specified to work at? (The current output you get on your PC seems like you are using the wrong baudrate)

Also, you should not use if GSM.begin, use while(!GSM.begin).

SIM900 is supposed to work at 19200 but many people reccomned lower bauds. Thanks for the tip. I'll absolutely do that, now I'm facing SIM900 problem, with the arduino code I'll deal later :)

The sim problem is most likely caused by your arduino code. I suggest the first thing you'd do is to try out examples proven to work. Also reset your SIM900 to factory defaults.

Hi :) I'm not using Arduino right now, just simple USB-FTDI connected to the PC as serial device. I'm only using AT commands, no arduino code. SIM900 is resetted. It acts weird even when it's not connected to anything but power supply.

SIM900 resetting: check the power supply! It does draw quite a lot of current in spikes, so you need a decent switching mode regulator, or you can give a try with LiPo batteries. 5V2A does not tell too much, the power can still fail under a load spike. Scope the power! Put a 2200uF electrolit capacitor to your power if nothing helps. I suggest to test the whole connection setup on you PC with a terminal emulator first.

I am not familiar to your inet library, but inet.attachGPRS("internet", "", "") looks fishy to me (setting up the APN is very important step - are you sure that "internet" is the name of the APN from your mobile operator? Also check how the DNS servers are configured, as you seem to use a host name to connect to your server.

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


text:
Why is 1020 steps used for crossfading colors on an RGB LED?
I'm looking into how to smoothly crossfade between colors on an RGB LED with the Arduino and I've found this piece of code for doing it:
https://www.arduino.cc/en/Tutorial/ColorCrossfader
I understand all parts of the code except for one thing.
The values for red, green and blue are changed incrementally through 1020 steps, because 255*4 = 1020.
But WHY 4? There are 3 colors, and 255 * 3 = 765. So why not 765 steps?

255 ^ 3 would be nearer the mark, and that's a lot more than 765. Or 1020...

@Brian, that would be the number of steps to go through every possible colour combination. That wasn't the program intent. (Paraphrasing:) You define a series of RGB colours - #CC0000, #30DD00, etc. - and get the system to smoothly transition between them. The 1020 steps is intended to give quarter bit resolution on the step interval. Details in my answer.

I'm looking a non=blocking cross fader because while it is cycling through the colours slowly the processor is still able to receive serial communications.
So far the non-blocking ones are not smooth enough.

Extract from code:
int wait = 10;      // 10ms internal crossFade delay; increase for slower fades

for (int i = 0; i <= 1020; i++) {
  redVal = calculateVal(stepR, redVal, i);
  grnVal = calculateVal(stepG, grnVal, i);
  bluVal = calculateVal(stepB, bluVal, i);

  analogWrite(redPin, redVal);   // Write current values to LED pins
  analogWrite(grnPin, grnVal);
  analogWrite(bluPin, bluVal);

  delay(wait); // Pause for 'wait' milliseconds before resuming the loop

  if (DEBUG) { // If we want serial output, print it at the
    if (i == 0 or i % loopCount == 0) { // beginning, and every loopCount times
    }
    DEBUG += 1;
  }
}

The 1020 in the loop determines the time taken to make the crossfade from the current colour to the next - not the total cycle as you seem to think. In the main loop we have
crossFade(red);
crossFade(green);
crossFade(blue);
crossFade(yellow);

And each of these crossfades will take 1024 * wait ms to complete. 'wait' is set to 10 ms so I would expect it to take 10.24 s to complete a fade from one colour to the next.
[Edit]
I think the large number (1020) is just to give a fine resolution in the steps calculation which is all done with integers. (What struck me as odd is that it doesn't use 256 * 4 = 1024.) The larger we make this number the finer the step resolution becomes. With coarse steps the ramp will complete too early.
Let's say we had 255 steps and we wish to go from 134 to 0.
step = 255 / (endValue - prevValue)
step = 255 / (134 - 0 ) = 1.9 which will be rounded down to 1.

This means that the crossfade will be complete in 134 steps instead of 255. i.e., it will finish 47% early.
If we use 1020 steps and we wish to go from 134 to 0.
step = 1020 / (endValue - prevValue)
step = 1020 / (134 - 0 ) = 7.6 which will be rounded down to 7.

This means that the crossfade will be complete in 938 steps instead of 1020. i.e., it will finish 8% early.

But why is this written in the comments?
There seems to be some meaning behind it:
`* In the real program, the color percentages are converted to

0-255 values, and there are 1020 steps (255*4).`

See the update.

The 1020 is indeed a granularity mistake. First he/she/they/them/it/x say(s) 0 to 255, to then conclude that's 255 levels. Undermines my trust in the efficiency of the remaining maths to be honest, as the total average effective fade error will be lower with the correct 1024 steps for quarter-bit granularity in integer maths. Though the better way is fixed point or integer-remainder maths of course, but "them" often finds that scary?

I'd say it's fine for the application. I don't know that we'd notice the steps given that they're 1/255 of the full brightness. The Arduino code is intended for a learning audience and in this instance I think simplicity and readability wins over accuracy.

"What struck me as odd is that it doesn't use 256 * 4 = 1024" Hee hee. This is classically known as a fence-post error. When you start at (let's say) a value of 00, it only takes 255 steps to get to the maximum value of 256.

@Asmyldof - It's entirely possible that 0 is not considered a level - it is just "off". Not the clearest of thinking, if so, but not all that unusual.

@WhatRoughBeast For steps, yes 255 to go from 0 to maximum, but if you use oversampling ( *4 ) as an argument for the loop, you're increasing granularity. Making a 64/255th bit granularity in the maths in stead of 1/4th bit increases the statistical chance for glitch errors, as bitlevels don't coincide with round maths more than 4 times per 255 steps. Whether you consider 0, 55, 255, or everything below 128 as off.

For my transition between colors I used arrays during the setup to collect the main transitions (bigger jumps between RGB values) then during the loop I used a series of analogWrite() commands essentially splitting the jumps by a 16th, for example starting at 255, 0, 0 the next array value was 223, 0, 0 in the loop it went from 255, 0, 0 to 253, 0, 0 to 251, 0, 0 finally landing the last loop value of 225, 0, 0 before starting the loop over at the next array value of 223, 0, 0. It's important to realize what colors transition into others and what the corresponding RGB values are of that transition.
Tomorrow I'll post my code, it's a bit messy as it was more proof of concept that starting with a distinct plan.


text:
AVR - How to know that there is collision between stack and heap or the memory has filled?
I am using the dynamic memory in AVR microcontroller, so How to know that there is collision between stack and heap or if the memory has been filled?

I am using the dynamic memory in AVR microcontroller, so How to know that there is collision between stack and heap or if the memory has been filled?

The first thing that happens is that malloc() will return NULL saying that memory could not be allocated. The AVR heap implementation has a few safety measures. One is to check that there is a minimum margin (__malloc_margin) between end of the heap and the top of the stack. This can be adjusted by the application.

Typically the minimum margin should be able to hold the largest stack usage (typically deepest function call tree with the largest local variables usage) plus largest ISR stack usage.
If the stack runs into the heap the memory block/s at the end of the heap is/are corrupted. What happens depends on the type of data structure.
Not checking NULL return from malloc() gives some interesting errors on the AVR as the processors registers are memory mapped. NULL points to R0.

A good rule of thumb when using malloc() in small scale embedded systems is 1) avoid it, 2) allocate memory with malloc() during the setup(). All other dynamic memory need be allocated temporary on stack and only for the processing.

“allocate memory with malloc() during the setup()”. If you know from the very beginning how much memory you need, there is no point in using malloc() instead of static buffers. As to what usages of malloc() are safe, see my answer to a related question.

@EdgarBonet I seem to have missed one of the requirements; software with dynamic configuration, e.g. EEPROM variables that say number of elements, etc. The actual size of the dynamic data structure is not known at compile time or is allowed to change. In other cases, I fully agree with your objection. If the size is known avoid malloc().

In simple terms: if the stack and heap have collided then the program will most likely crash, and any countermeasures you may have in place are now null and void.
However, you can find out the current amount of free memory quite easily by looking at where the top of the heap is and creating a local variable on the stack and getting its address - subtract one from the other and you get the free memory size.
That's exactly what the MemoryFree Library does for you.

What happens if the program crashes? Will the AVR reset the program?

Anything at all can happen. No one can predict what might happen.  The watchdog exists as a method to try and recover from such scenarios.


text:
What is the proper way to turn an Arduino UNO into an ISP?
I have a bricked Arduino Uno and I want to try to flash the bootloader. I'm trying to figure out how to do it. On this tutorial from SparkFun you can see this diagram:

They also show this table of the pinout

That seems simple enough but it's totally different than the official tutorial, "Circuit (targeting Arduino Uno, Duemilanove, or Diecimila)"

Which also says

An Arduino board serving as an ISP to program the ATmega on another Arduino board. On the Arduino Uno, you'll need to connect a 10 uF capacitor between reset and ground (after uploading the ArduinoISP sketch). Note that you need access to the reset pin on the target board, which isn't available on NG or older boards.

So do I need a 10 uF capacitor between reset and ground? How do I put a 10 uF capacitor in between reset and ground when, in this configuration, reset is connected to PIN 10? Why are there two configurations? What's the upsides and downsides to either of them?

The wiring is actually identical. It just uses the ISP header (2x3 pins) on the target board, instead of the pins 5v, GND, RST, 11, 12, 13. Just like the table you added says.
The downside to using the ISP header, is you need a male to female wire for connecting. Upside is you can easily take of these 6 pins, and connect it to a different arduino to be programmed.
I always needed to add a capacitor between RESET and GND. The exact value isn't that critical.
The reset pin is the one to the left of 3v3.

You're missing the question: RESET isn't connected to GND, it's connected to Pin10? Do you mean you needed to add a capacitor between RESET and Pin10?

A capacitor between the ISP Arduino's RESET and GND stops the auto-reset happening when the serial port is opened. That's the ISP's reset, NOT the target's reset which is wired direct to pin 10.

Not on the target arduino, but the programming arduino's reset.

Ah.. I see here is the guide for the capacitor on ground-reset

You're missing the question: RESET isn't connected to GND - on both diagrams pin 10 on the programming board is connected to RESET on the target board. The wiring is identical, as Gerben said.

Take a look at my circuit for a minimal "Arduino":

The top image in the question uses the ICSP header, which you can see from the schematic "mirrors" pins on the processor. That is:

SCK is D13
MISO is D12
MOSI is D11
Reset on the target goes to D10 on the programming board
Vcc and Gnd are connected

Trace out the wires to the ICSP header and you will see.

So do I need a 10 uF capacitor between reset and ground?

No you do not.

I have a bricked Arduino Uno and I want to try to flash the bootloader.

See my page about programming a bootloader.

Why are there two configurations?

Just different ways of connecting the same thing to the same thing.

What's the upsides and downsides to either of them?

No difference.

I will debate you one one small point, on the last question about the upsides/downsides, there are two small differences. the lesser is that using the side rails is easier for temporary setups, and the ISCP is easier for reusable setups. the other is that on different models of boards the spi pins may not be in the same place (mega is a case in point) so using the ISCP is more portable.

OK, yes there may be physical differences like that. If you make up an ICSP cable, then the ICSP header is somewhat easier to use.

authors: مریم ترکاشوند


text:
What's the difference between ICSP vs ISP?
I'm not sure if these terms are interchangeable or not. What's the difference between ICSP and ISP? Is it simply the reset? I've shown two configurations in this question I just asked. Are they both ICSP?

From what I've heard, ISP is the term used by Atmel. ICSP is the term used by PIC.

The difference between ISP and ICSP is a hyphen.
ISP stands for In-circuit Serial Programming, and ICSP stands for In Circuit Serial Programming.
Any arrangement that allows you to program a microcontroller while it is in a circuit using a serial protocol can be called ISP or ICSP.

Well, they may the same but, according to Wikipedia, ISP stands for In-system programming

{sarcasm}And of course Wikipedia is always right....!{/sarcasm}  At the end of the day they both refer to the same concept using different wording. Semantics are completely irrelevant when they are just an acronym that refers to a concept, the concept being programming a chip while it is in a circuit using a serial protocol.

I have also seen sometimes «in situ programming». It's the magic of acronyms, they can tell anything you want

According to the Atmega32U4 datasheet:

The device is manufactured using ATMEL’s high-density nonvolatile memory technology. The On-chip ISP Flash allows the program memory to be reprogrammed in-system through an SPI serial interface, by a conventional nonvolatile memory programmer, or by an On-chip Boot program running on the AVR core.

I can't find the word "ICSP" in the datasheet. The quoted paragraph doesn't really explain the acronym. It could be an anagram of SPI. ;)

It seems clear to me that "in system" and "in circuit" are referring to the same thing. The program is serial rather than parallel as it uses SPI (Serial Peripheral Interface).

I've shown two configurations in this question I just asked. Are they both ICSP?

Not really two configurations, because the ICSP header on the board is directly connected to the pins you showed in the other configuration. You may as well talk about using different ground pins as a "different configuration".


text:
Does Arduino.cc silkscreen the pin headers? What explains the differences here?
I have two Arduino's. One from .org, and one from .cc. The arduino.org one has really nice silk screening on the header pins. The arduino.cc one does not. In addition there are some visible component differences. One has a 504S (not sure what this chip is), one has a 504L. The button on the .org one is a bit more tactile. The headers on the top (not the ICSP) headers are missing on the .org one. And, the four points that look like they're for soldering or testing are absent. I can try to get a high-res picture of the two up.
I bought the .org one in a beginner kit online from Amazon (from the official seller). And, the .cc I bought from their website directly.
The .org one seems like it's made from higher-end components, and actually having the headers at the top makes it seem more polished. Is there any through guide to what these differences are or a changelog from one hardware revision to another?

This doesn't make a lot of sense - until fairly recently, arduino.cc's boards were supplied by the folks now calling themselves arduino.org and the pictures on arduino.cc all show very nice silk screen designation of the pin headers.  What exact deficiency are you questioning?  Are you sure these boards were obtained from the sources you think they were?

This is a new Arduino.cc board, presumably not made by the arduino.org folks. It lacks silk screens on the pins, actually lacks a whole set of of header pins, and has some different components. Some either minor imperfections too. The caps are crooked and don't line up like the Arduino.org one.

Is there any through guide to what these differences are or a changelog from one hardware revision to another? - I strongly doubt it.

No, there is nothing that documents the differences as in a changelog, purely because this is not an iterative change.
The two boards are designed and manufactured by two different (competing) companies in two different countries (USA and Italy) using different component suppliers.
Just because they both say Arduino UNO doesn't make them both the same board - not these days anyway, since the founders of Arduino got really childish and started throwing their faeces at each other like monkeys in the zoo.