text:
How do I connect Arduino to a Bluegiga112?
I am a new user of Arduino (I have a Arduino Due) and also I am a new user of BLE112 (Bluegiga module 112)
My teacher told me to make the BLE112 advertisable and furthermore he told me to look for information about UART@115K. (The Ble112 he gave me came with wires already soldered to the selected pins: I'm assuming I only need to use those.)
PIN NUMBER [PIN NAME] for BLE112

    2         AVDD                    (Supply voltage 2-3.6V)
    3         AVDD                    (Supply voltage 2-3.6V)
    4        [P2_2]  DC- Debug clock  (DIGITAL I/O)
    5        [P2_1]  DD- Debug data   (DIGITAL I/O)
    9        VDD_USB                  (Supply voltage 2-3.6V)
    20        DVDD                    (Supply voltage 2-3.6V)
    23       [P0_5]  RXD(Rx)          (DIGITAL I/O)
    24       [P0_4]  TXD(TX)          (DIGITAL I/O)
    25       [P0_3]  RTS              (DIGITAL I/O)
    26       [P0_2]  CTS              (DIGITAL I/O)
    29        RESET
    30         GND

I put:
BLE pins [2,3,9,20]    to     3.3v pin of Arduino
BLE pin  [30]          to     GND pin of Arduino

Then I found a picture (attached at the bottom of this post) that describes that I should put CTS of BLE on RTS of Arduino and vice versa. Where is the CTS on an Arduino board? I think I have to program one of the Digital pins.
I tried some other connections. I put:
BLE pin 26(CTS)   to    Arduino random digital pin 32, and
BLE pin 25(RTS)         Arduino random digital pin 34.

BLE pin 24(TX)          Arduino RX pin 0
BLE pin 23(RX)          Arduino TX pin 1

I didn't connect DC(Debug clock), DD(Debug data) and Reset on the BLE112.
So then I found some more info on the web that if I use USART than I should use a wake up pin which is by the default P0_0(??) more about that in this PDF. (Search wake_up)
Now I should mention sleep mode Ble112 (there are three kinds of it) and I believe that the one I am after is MODE 3 (that means that it consumes the minimum (power) of them all)
I found some example named UART@115K

UART@115k
  This example configures the BLE112 or BLE113 Bluetooth Smart module to expose the BGAPI protocol over UART interface with the following settings: 115200 bps, 8n1 and hardware flow control enabled. The power mode 3 is enabled in this example and the wake-up pin is configured to P0_0 pin (P0_0 button on DKBLE112
  and DKBLE113). When the power mode 3 is enabled the device will not be able to receive commands or data over UART unless the wake-up pin is asserted.
The example uses UART in the pin configuration channel 1 and alternate 1, which is the configuration used in the DKBLE112 and DKBLE113 development kits.
  If you try this example with DKBLE112 or DKBLE113 make sure the UART interface is enabled and the device is NOT powered with a CR2032 battery as it’s not able to power up the level shifter or UART to USB converter.
This is also the factory default configuration for BLE112 and BLE113 Bluetooth Smart Modules.

Source: https://bluegiga.zendesk.com/entries/22412436

The PDF link seems broken... it gives me this error: Sivua ei löytynyt! which translate into Page not found. Good think I know Finnish! (Just kidding: Google Translate)

First off all I am a new user of this forum so I make a mistake.. the reason i culd not answer sonner was that i got sick...
Here is that PDF https://dl.dropboxusercontent.com/u/65932667/Bluetooth_Smart_Configuration_Guide_v33.pdf

And some more abut BLE112 (if you want more literature you need to registrate on their website (it's for free)
Links:
Ble112 Datasheet https://dl.dropboxusercontent.com/u/65932667/BLE112_Datasheet.pdf
Ble112 Modul https://dl.dropboxusercontent.com/u/65932667/BLE112_Module.pdf

@FirsTime No problem. Three things that I should tell you: 1.) <br /> doesn't work in comments (like this here), 2.) Next time edit the link in. I changed it for you 3.) Some people might be offended if you call it a forum. It doesn't really matter, but since this site is a different setup, it's generally called a "Q&A Site." Just a minor detail... :) I'll look at the PDFs and see if I can find anything out.

The most popular way to establish communication between an Arduino (I've used a Duemilanove) and a BLE module (I've used BLE113 that's on a DKBLE113) is through UART.
UART is a two wire interface (don't forget the common GND) with one RX and one TX.
You can use the SoftwareSerial library to define your communication object on the Arduino.
In contrast, the BLE113 uses four. The additional two are RTS and CTS (Request To Send and Clear To Send).
However, you can configure the UART in two ways using hardware.xml:

Go to the <usart > tag and set flow = "false". This "disengages" the RTS and CTS allowing a traditional two wire interface.
Had you set flow = "true", you need to connect the RTS and CTS as well, which I had a big problem with, though the two are both digital.

Further, in hardware.xml, you need to disable sleep mode by including <sleep enable="false" /> within the <hardware> tag. This will solve all your problems.
If you intend to use sleep mode, you need to skip the previous step and instead govern the module's mode through the P0_0 pin. Moreover, there are additional definitions to be included in hardware.xml, which are documented by BG. These work nicely for the BLE112 too.
In my exercise, I'd established communication at 9600 baud. It worked the same way when I increased it to 115200 baud (this is a plus in the BLE113).

Software serial would be important for an ATmega328 based Arduino with only one hardware serial port already used for loading.  The Arduino Due of the question appears to have multiple hardware ports.

Well I found another way how to make it work, you just need to put CTS from BLE on GND, and RTS open "in the air" and that's it!
You can see these on this link: https://bluegiga.zendesk.com/entries/23143152--REFERENCE-Using-or-bypassing-flow-control-with-UART-communication

I would connect TX and RX to one of the 3 extra serial ports on the Due. Pins 0 and 1 are used for the USB-Serial communication

To communicate with the Arduino, it is only necessary to connect the RX and TX pins between the module and the Arduino.
Source: http://www.mkroll.mobi/?page_id=386


text:
Arduino Pro Mini (3.3V version) input voltage range / tolerance
I have a few Arduino Pro Mini clones (cheap Chinese stuff) and would like to power them with 12V power supply (same as fan voltage). According to the Arduino Pro Mini spec the RAW pin can take 3.35-12V (3.3V model). In practice this means a 12V PSU cannot be used as they are almost always over 12V with low load. I read that the voltage regulator in this board is capable up to 16V input. I tried plugging in a cheap 12V power adapter that read 15.1V with no load but a component on the arduino clone board actually exploded instantly. The board seems to work still when powered from usb programmer. Component that burned out is just above VCC, RST and GND pins.
Why did this happen? What did I just damage and most importantly what is a safe voltage level to use? I already have a few 12V switching power supplies it would be a shame if I could not use them.
Solution:
In the end it seems to have been a faulty arduino clone, faulty or poor quality power adapter or the fact that I powered the power supply before plugging it to the board's RAW input pin. The cheap 12V switching power supplies work just fine even though my multimeter registers a voltage spike as high as 30V during power up.

There doesn't seem to be any Pro Micro board on the official site. I can only find it on Sparkfun. Could you verify which board do you have?

My mistake, it's actually Pro Mini (corrected now).

The genuine Pro Mini's use a MIC5205 regulator which should accept up to 16V at it's input normally, with an absolute maximum of 20V. It's unlikely that the regulator would be damaged by 15.1V.
However, the component you have indicated that has blown is a capacitor. SMD capacitors are available in different voltage ratings, typically 4V, 6.3V, 10V, 16V, 25V, 35V and 50V (and above, but let's ignore them for this). It's rare to see any intermediate values.
SMD capacitors are very intolerant of being used at a higher voltage than specified. This is especially true of electrolytic and tantalum capacitors. The blown capacitor on the genuine Pro Mini's is polarised (the grey band not he package and the schematic indicates this), so we can infer it is either electrolytic or tantalum. A 10µF SMD electrolytic is unlikely to be in this package, so it is almost certainly a tantalum.
Sparkfun sell 10µF tantalums, and they are rated at 16V. It's quite likely these are the same ones used on the Pro Mini. 15.1V is very close to 16V - in fact, if this is a poorly smoothed power supply, the meter might show 15.1V but the peaks could well be 16V or even 20V. It is recommended that you de-rate the voltage ratings on tantalums by 50% at least.
It's really important to realise that most low-cost DC power supplies are not regulated and produce a very bumpy output voltage with no regulation:

Tantalums also have no tolerance for reverse voltage, so if you did apply reverse voltage, it would pop.
So it is quite likely that you over-volted the cap and blew it. You could replace them with higher rated capacitors - I would go for 35V ones if you want to supply 15.1V. Desoldering and desoldering a single capacitor is relatively easy as long as the pads haven't been damaged. Realistically, you could use a normal leaded 10uF electrolytic between RAW and GND instead of the SMD one.
EDIT: However, looking at the data sheet for the regulator, it shouldn't really matter if that 10uF is there or not:

A 1μF capacitor should be placed from IN to GND if there is more than
  10 inches of wire between the input and the ac filter capacitor or if
  a battery is used as the input.

Some regulators absolutely require an input capacitor, with others it is just advisable. This looks like it is just advisable. So if it isn't working on external power now, you may have blown the regulator as well.
Even if the clone board uses a different SMD regulator, their characteristics are all very similar. As stated, some do need a capacitor on the input to work, so replacing it might fix it.
There is a further consideration that dropping from 15.1V to 3.3V on a SMD regulator is not a great idea. You will need to burn off a lot of power.
The MC5205 can dissipate 455mW with a minimal PCB footprint (which the Pro Mini has) with a 25°C ambient:

So, we know the maximum power we can dissipate, and we know the voltage drop - we can then calculate the current:
P = (Vin - Vout) * I
0.455 / (15.1 - 3.3) = I
I = 38.5mA
This isn't very much at all. You might want to consider regulating off the board, and probably with a switching regulator rather than linear regulator.
I also note your PS:

the ground of the 12V PSU is shared with Arduino ground pin, not sure
  if this might be the cause.

If they weren't shared, there would be no way that this could work. They need to be shared otherwise the Vcc from the power supply is not referenced to anything and may as well not be there.

Fantastically detailed answer! The psu I used could well have higher peak voltage. Could a switching supply have this problem too? The damaged capacitor has "a104C" written on it and "3A052" below that. Not sure what that means. The pads seem fine as I only contacted the RAW pin for less than half a sec. I will attempt to solder a normal 35V capacitor when my soldering iron arrives. I assume larger cap is ok?

A blown tantalum would likely result in more damage than just a blown capacitor (like, say, a scorched PCB).

I only see damage to the capacitor, no marks on the PCB at all. Top of cap has a hole and some exposed metal inside also some black burn mark on the side but that's all. I only touched the contacts for a very short time so maybe that's why.

I've definitely taken out tantalums and the damage has been limited to the cap and minor scorching.

@Cybergibbons I had the power adapter plugged in before connecting the arduino, does that rule out that the startup voltage was the cause? I have switching supplies but not sure if they are prone to higher voltages than rated or not..?

Always remove power before connecting anything. Most small unregulated PSUs slowly ramp up rather than spike. Switch mode PSUs can spike when turned on.

Also, for the replacement, try to stick to ~10µF, certainly no smaller than 1µF, no bigger than 20µF

@Cybergibbons indeed the dc adapter I used does ramp up to 15.1V in 1-2 seconds. Will see how switching psu behaves when I get my soldering iron. Would I notice a start up spike on the multimeter? Don't want to damage another arduino, how would you test/make sure it will not be damaged before trying with another psu? I'd rather not use voltage dividers or other components if I don't have to.

The component that exploded during your test is a capacitor.
According to the position on the board you mentioned, it is one of the 2 electrolytic capacitors used on both sides of the 3.3V regulator (I would say that's probably the upstream capcitor).
There are a few reasons why a capacitor may explode:

apply an inverted voltage to it (polarized capacitors only)
apply a voltage above its rating
apply a current above its rating

Your situation is probably the 2nd one: too high voltage applied.
According to Sparkfun original schematics, this capacitor must be polarized with 10uF capacity. Unfortunately the schematics do not mention the maximum voltage.
According to the specification for the original board, the maximum voltage for this cap should be at least 12V, but there is no guarantee that it is anthing above than 12V. Hence, you have to consider 12V is the maximum voltage applicable to your board (on the RAW pin).
In addition, you have mentioned you are using a cheap chinese clone, it is perfectly possible (although not expected, as it would make the board operate differently than the original specs) that this one uses a lower voltage cap (eg 10V) which would be a bit cheaper.
If you do want to reuse your 12V PSU, you will have to ensure that its output voltage never exceeds 12V, for this you are left with a few options:

use a voltage divider made of 2 resistors: you must first know the max voltage output of your PSU and then calculate resistance values to get 12V based on that max voltage. That's easy but it can waste a lot of energy
use a 12V Zener diode outside your PSU
use a 12V voltage regulator circuit after your PSU: that one is the safest, but also the most expensive solution

Edit:
Of course, if you have already done it and are equipped for it, you can find replacements for the capacitor that has exploded and buy a higher-voltage one, then replace it on your boards; that will reauire good soldering/desoldering equipement usable for surface-mounted components.

Or replace the low-voltage parts with higher-rated ones.

Yes of course but that involves SMC desoldering which is not something everyone can do.

@Ignacio-Vazquez-Abrams I have edited my answer to include your suggestion, thanks.

I do have a few capacitors, just waiting for my hakko soldering iron to rrive as my el cheapo broke... Can I use any non smd capacitor with voltage rating of let's say 35V?

Higher voltage caps is OK, as long as capacitance is the same as the original. You can go and remove the SMD cap (only one is needed to be replaced) and solder a "normal" cap instead, but beware of shorts as leads are much bigger!

Any idea what the capacitance of this cap is? I cant seems to find any info on it based on what's written on it. a104C 3A052.

According to the board schematic it is 10uF

For the replacement you can solder it onto the pins on the board rather than the pads.

Although this thread is old, people has to be aware that some clone boards uses 4B2X regulator and they support maximum 10v (https://epstik.com/p744820729-xc6204b332mr-4b2x-stabilizator.html , https://www.mcucity.com/product/3240/xc6204b332mr-g-3-3v-4b2x-4b2y-positive-voltage-regulator). Theses clones are extremely common on ebay and another marketplaces.

source: Stack Exchange

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

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

sort: votes


text:
connection issues with 3 arduinos any suggestions?
I have 3 arduinos that I want to program on, all of them with their own cable and I have tried to connect them to my laptop on several different usb ports, my usb ports work with mouses so that's unlikely to be the problem. However I just cannot connect to them they just don't appear under /dev/ttyACM* and the arduino IDE cannot find them either. I'm running ubuntu 14.04 any suggestions for finding out what is likely to be wrong with my system or the arduinos?
For some odd reason they now all appear to be seen as /dev/ttyACM* but they now all give me a
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00

error
Anybody have any idea how to fix? The arduino's do not have any wires in them except usb (nothing in reset or any other pin), I'm on ubuntu so the drivers shouldn't be an issue? And pin 13 flashes when I reset the arduino.

Are these Arduino clones?

One is an official arduino one is a funduno and one is a "uno" (no other marking)

Take a look at this video - Check and see if they are bricked https://www.youtube.com/watch?v=RZH_qGautqM

I'm working from ubuntu 14.04 not from windows so I don't think that tutorial will work

Do you have access to a Windows Machine?

Yes but that requires some extra wait

Its a quick check to see if the FTDI to 232 is bricked. I am not sure if this is your issue, but it was for me. My MAC couldnt read my cloned arduinos.

Absolutely no need to waste time with windows (you would learn less there anyway) Look in dmesg when connecting and compare lsusb output with and without them connected.  Note that many chips will show up as /dev/ttyUSBn not ttyACMn.  In theory you could be missing drivers or lack a udev rule for permissions, but ubuntu should be set up right by default.

it's been a while but a long time later I found that the cable I was using was broken. A different cable worked.

That has happened to me a lot.  Broken cable, charge-only cable, ...

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


text:
Reading analog value while generating PWM signal
I'm trying to generate dim two LED strips simultaneously by generating two PWM signals based on potentionmeter value. The pot sets how bright each of the LED strips will be. To drive this I'm using Arduino Pro Micro equipped with Atmel 32u4 chip.

I'm using following code:
int sensorValue = 0;
int outputValue = 0;

void setup() {
}

void loop() {
  sensorValue = analogRead(A0);

  outputValue = map(sensorValue, 0, 1023, 0, 255);
  analogWrite(5, outputValue);
  analogWrite(6, 255 - outputValue);

  delay(2);
}

The problem is, the analogRead never returns 1023 when the pot is fully open. The value is always around 980. This itself would not be a big deal.
The main issue is that the analogRead is incredibly noisy. The value returned for the maximum position is in range of [940-1020].
When I don't use the analogWrite to generate PWM, the problem goes away an the input is crystal clear in range [0-1023] as expected.
I have tried to turn off the PWM before reading the value in, but this generates flicker, as the LEDs are temporarily off.
Is there any HW or SW solution to this? I don't mind writing some assembly if required.

It sounds like fluctuations in the power caused by the switching of the LEDs.  Add some large capacitors across the power near the LEDs.

Have you checked your power source? If it is a switching source you might want to add some capacitors to cancel out the ripple. I suggest you use a scope. If you don't have a scope just connect your voltage source to A1 and analogread(A1).

Try adding some delay, say sample the pot just 10 or 20 times a second, vs the ~500 times a second that your code would do now. That gives the PWM outputs a chance to perform vs being constantly given new values to use.

@Majenko it was an issue with the power source. It's an USB led strip, so I was powering it through Arduino, which was a bad idea as it turns out.

It was an issue with the power source. It's an USB led strip, so I was powering it through Arduino, which was a bad idea as it turns out.
When I have added external power source to the circuit everything started working correctly.

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


text:
Arduino - Progamming issue
my first post here.
Anyway I'm working on a Simon Says game.
I have a weird bug with the function that reads button input.
This is the code:
int deBounce(int count){
  int pressed=-1;
  int laastButtons[3]; // save the previous deBounce read.
  for(int x; x<4; x++)
  {
    laastButtons[x] = lastButtons[x];
    lastButtons[x] = !digitalRead(button[x]);
    if(lastButtons[x] == true)
    {
      delay(50);
      lastButtons[x] = !digitalRead(button[x]);
      if(lastButtons[x] == 1){ pressed = x;}
      nt("Pressed!, Button ID: ");nt(x); nt(" pressed:  ");nt(pressed); nt(" state "); ntln(lastButtons[x]);
    }
  }
  if((lastButtons[0] + lastButtons[1] + lastButtons[2] + lastButtons[3]) > 1)
  {
    ntln("ERROR: dont press more than one button at a time. ");
  }
  if( ((lastButtons[0] + lastButtons[1] + lastButtons[2] + lastButtons[3]) == 1 ) && !laastButtons[pressed] && (pressed != -1) ) {
    pressButtons[count] = pressed;
    nt("Pressed!, ID: ");nt(count); nt(" Button ID ");ntln(pressed);
    return count++;
  }else return count;
}

This is what I recieve in the Serial Monitor if I press one of the buttons.

Pressed!, Button ID: 3 pressed: -1 state 1

How is that possible? Note the lines where that line is printed and the line above it.
Seems like that if should run, but the line pressed = x; doesn't function.
Note that, nt and ntln are just a short for Serial.print.
I have this weird bug and sometimes it seems like the chip is glitching!
Another question is- I tried attaching interrupt and it didn't worked,
Is it possible that my board is not compatiable with them? (It's not original).
Thanks.
EDIT:
After Majenko helped me figure it out,
The thing that created the bug was that I expected a x==0, but I didn't define it in the for loop.
Before:
for(int x; x<4; x++)

After:
for(int x=0; x<4; x++)

Thanks again Majenko!

int laastButtons[3]; // save the previous deBounce read.
for(int x; x<4; x++)
{
   laastButtons[x] = lastButtons[x];

Well, there's a common bug right away.  An array with three slices, numbered 0, 1 and 2, and you're accessing them with a loop that counts from 0 to 3.
Spot the error.
Also, in the for loop, what number does it start counting from?
And now for your "bug".  This block of code:
if(lastButtons[x] == true)
{
  delay(50);
  lastButtons[x] = !digitalRead(button[x]);
  if(lastButtons[x] == 1){ pressed = x;}
  nt("Pressed!, Button ID: ");nt(x); nt(" pressed:  ");nt(pressed); nt(" state "); ntln(lastButtons[x]);
}

I think you have it slightly wrong.  Let's convert it into plain english:

If button is pressed:

Delay 50 ms
Read button again
If button is pressed:

Set pressed to the button number

Print the button message

Note the indenting, which highlights what gets executed for what IF statement.  The print is going to happen regardless of the setting of the pressed variable.
I think the structure you wanted is:

If button is pressed:

Delay 50 ms
Read button again
If button is pressed:

Set pressed to the button number
Print the button message

In that layout the second If is controlling both the setting of the pressed variable as well as whether or not to print the Pressed! message.
if(lastButtons[x] == 1){ pressed = x;}

That line is saying "If last buttons X is 1, then set pressed to X. That is all it is doing. Nothing more, nothing less.


text:
How do I split an incoming string?
I am sending a list of servo positions via the serial connection to the arduino in the following format
1:90&2:80&3:180

Which would be parsed as:
servoId : Position & servoId : Position & servoId : Position
How would I split these values up, and convert them to an integer?

i have slave(arduino uno) send string via serial 30;12.4;1
and 1 master (esp8266) recive string
i want in master have seperated data like
30
12.4
1
and save it in micro sd card

Contrarily to other answers, I'd rather stay away from String for the following reasons:

dynamic memory usage (that may quickly lead to heap fragmentation and memory exhaustion)
quite slow due to construction/destruction/assignment operators

In an embedded environment like Arduino (even for a Mega that has more SRAM), I'd rather use standard C functions:

strchr(): search for a character in a C string (i.e. char *)
strtok(): splits a C string into substrings, based on a separator character
atoi(): converts a C string to an int

That would lead to the following code sample:
// Calculate based on max input size expected for one command
#define INPUT_SIZE 30
...

// Get next command from Serial (add 1 for final 0)
char input[INPUT_SIZE + 1];
byte size = Serial.readBytes(input, INPUT_SIZE);
// Add the final 0 to end the C string
input[size] = 0;

// Read each command pair
char* command = strtok(input, "&");
while (command != 0)
{
    // Split the command in two values
    char* separator = strchr(command, ':');
    if (separator != 0)
    {
        // Actually split the string in 2: replace ':' with 0
        *separator = 0;
        int servoId = atoi(command);
        ++separator;
        int position = atoi(separator);

        // Do something with servoId and position
    }
    // Find the next command in input string
    command = strtok(0, "&");
}

The advantage here is that no dynamic memory allocation takes place; you can even declare input as a local variable inside a function that would read the commands and execute them; once the function is returned the size occupied by input (in the stack) is recovered.

Hadn't thought of the memory issue.  this is great.

Excellent. My answer was very "arduino" based and using typical arduino SDK functions which a novel user could be more used to, but this answer is what should be done for "production" systems. In general, try to escape from dynamic memory allocation in embedded systems.

This function can be used to separate a string into pieces based on what the separating character is.
String xval = getValue(myString, ':', 0);
String yval = getValue(myString, ':', 1);

Serial.println("Y:" + yval);
Serial.print("X:" + xval);

Convert String to int
int xvalue = xval.toInt();
int yvalue = yval.toInt();

This Chunk of code takes a string and separates it based on a given character and     returns
The item between the separating character
String getValue(String data, char separator, int index)
{
    int found = 0;
    int strIndex[] = { 0, -1 };
    int maxIndex = data.length() - 1;

    for (int i = 0; i <= maxIndex && found <= index; i++) {
        if (data.charAt(i) == separator || i == maxIndex) {
            found++;
            strIndex[0] = strIndex[1] + 1;
            strIndex[1] = (i == maxIndex) ? i+1 : i;
        }
    }
    return found > index ? data.substring(strIndex[0], strIndex[1]) : "";
}

You could do something like the following, but please take into account several things:
If you use readStringUntil(), it will wait until it receives the character or timeouts. Thus, with your current string, the last position will last a little longer, as it has to wait. You can add a trailing & to avoid this timout. You can easily check this behavior in your monitor, try to send the string with and without the extra & and you will see such timeout delay.
You actually do not need the servo index, you can just send your string of positions, and get the servo index by the value position in the string, something like: 90&80&180&.
If you use the servo index, maybe you want to check it (convert to int, and then match the loop index i) to ensure that nothing went wrong with your message.
You have to check that the returning string from readStringUntil is not empty. If the function timeouts, you didn't receive enough data, and thus any attempt to extract your int values will produce strange results.
void setup() {
  Serial.begin(9600);
}

void loop() {
  for (int i=1; i<=3; i++) {
    String servo = Serial.readStringUntil(':');
    if (servo != "") {
      // here you could check the servo number
      String pos = Serial.readStringUntil('&');
      int int_pos=pos.toInt();

      Serial.println("Pos");
      Serial.println(int_pos);
    }
  }
}

This seems like a very good solution thank you.  The example clears it up perfectly

What if we had an undefined number of servo inputs?  in my example there was 3.  But what if sometimes it was more, or less.  Can you offer any suggestion for handling such a scenario

Sure: There are two possibilities. 1. Send first the number of servos: 3:val1&val2&val3&, read such number prior to starting the loop. 2. Use a different terminator to indicate you have no more servos, loop until you find it: val1&val2&val3&#, for example.

Glad this solution helped you, @ValrikRobot, could you please validate the answer if it was useful?

or you can just remove the for, and so the code will just work any time you send a command.

You can use Stream.readStringUntil(terminator) passing a different terminator for each part.
On each part you then call String.toInt

Simplest solution is to use sscanf().
  int id1, id2, id3;
  int pos1, pos2, pos3;
  char* buf = "1:90&2:80&3:180";
  int n = sscanf(buf, "%d:%d&%d:%d&%d:%d", &id1, &pos1, &id2, &pos2, &id3, &pos3);
  Serial.print(F("n="));
  Serial.println(n);
  Serial.print(F("id1="));
  Serial.print(id1);
  Serial.print(F(", pos1="));
  Serial.println(pos1);
  Serial.print(F("id2="));
  Serial.print(id2);
  Serial.print(F(", pos2="));
  Serial.println(pos2);
  Serial.print(F("id3="));
  Serial.print(id3);
  Serial.print(F(", pos3="));
  Serial.println(pos3);

This give the following output:
n=6
id1=1, pos1=90
id2=2, pos2=80
id3=3, pos3=180

Cheers!

It is not working for serial.read()... any idea why? I get the following error: invalid conversion from 'int' to 'char*' [-fpermissive]

String getValue(String data, char separator, int index)
{
    int maxIndex = data.length() - 1;
    int j = 0;
    String chunkVal = "";

    for (int i = 0; i <= maxIndex && j <= index; i++)
    {
        chunkVal.concat(data[i]);

        if (data[i] == separator)
        {
            j++;

            if (j > index)
            {
                chunkVal.trim();
                return chunkVal;
            }

            chunkVal = "";
        }
        else if ((i == maxIndex) && (j < index)) {
            chunkVal = "";
            return chunkVal;
        }
    }
}

That's was good. That's was perfect!!!

See example at:
https://github.com/BenTommyE/Arduino_getStringPartByNr
// splitting a string and return the part nr index split by separator
String getStringPartByNr(String data, char separator, int index) {
    int stringData = 0;        //variable to count data part nr
    String dataPart = "";      //variable to hole the return text

    for(int i = 0; i<data.length()-1; i++) {    //Walk through the text one letter at a time
        if(data[i]==separator) {
            //Count the number of times separator character appears in the text
            stringData++;
        } else if(stringData==index) {
            //get the text when separator is the rignt one
            dataPart.concat(data[i]);
        } else if(stringData>index) {
            //return text and stop if the next separator appears - to save CPU-time
            return dataPart;
            break;
        }
    }
    //return text if this is the last part
    return dataPart;
}

jfpoilpret provided great answer for parsing serial command on Arduino. However Attiny85 doesn't have bidirectional serial - SoftwareSerial has to be used. This is how you port same code for Attiny85
#include <SoftwareSerial.h>

// Calculate based on max input size expected for one command
#define INPUT_SIZE 30

// Initialize SoftwareSerial
SoftwareSerial mySerial(3, 4); // RX=PB3, TX=PB4

// Parameter for receiving Serial command (add 1 for final 0)
char input[INPUT_SIZE + 1];

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

void loop() {
  // We need this counter to simulate Serial.readBytes which SoftwareSerial lacks
  int key = 0;

  // Start receiving command from Serial
  while (mySerial.available()) {
    delay(3);  // Delay to allow buffer to fill, code gets unstable on Attiny85 without this for some reason
    // Don't read more characters than defined
    if (key < INPUT_SIZE && mySerial.available()) {
      input[key] = mySerial.read();
      key += 1;
    }
  }

  if (key > 0) {
    // Add the final 0 to end the C string
    input[key] = 0;

    // Read each command pair
    char* command = strtok(input, "&");
    while (command != 0)
    {
      // Split the command in two values
      char* separator = strchr(command, ':');
      if (separator != 0)
      {
        // Actually split the string in 2: replace ':' with 0
        *separator = 0;
        int servoId = atoi(command);
        ++separator;
        int position = atoi(separator);
      }
      // Find the next command in input string
      command = strtok(0, "&");
    }
  }
}

Attiny85 schematics for pin numbers

Sketch compiles into:
Sketch uses 2244 bytes (27%) of program storage space. Maximum is 8192 bytes.
Global variables use 161 bytes (31%) of dynamic memory, leaving 351 bytes for local variables. Maximum is 512 bytes.

So there is plenty of space and memory for the rest of code

How to read from serial on an ATtiny85 isn't really part of the question.

Sorry for diverging from question, but community and resources available for Attiny is way smaller than for Arduino. People like me looking for answers use Arduino keyword and sometimes get into very tricky situations as implementing Arduino code onto Attiny is not always trivial. Had to convert original code to work on Attiny, tested it working and decided to share it

This site is in Q&A format. Answers should answer the question. Yours just adds something that's unrelated to it.

Here is Arduino method to split a String as answer to the question "How to split a string in substring?" declared as a duplicate of the present question.
The objective of the solution is to parse a series of GPS positions logged into a SD card file. Instead of having a String received from Serial, the String is read from file.
The function is StringSplit() parse a String sLine = "1.12345,4.56789,hello" to 3 Strings sParams[0]="1.12345", sParams[1]="4.56789" & sParams[2]="hello".

String sInput: the input lines to be parsed,
char cDelim: the delimiter character between parameters,
String sParams[]: the output array of parameters,
int iMaxParams: the maximum number of parameters,
Output int: the number of parsed parameters,

The function is based on String::indexOf() and String::substring() :
int StringSplit(String sInput, char cDelim, String sParams[], int iMaxParams)
{
    int iParamCount = 0;
    int iPosDelim, iPosStart = 0;

    do {
        // Searching the delimiter using indexOf()
        iPosDelim = sInput.indexOf(cDelim,iPosStart);
        if (iPosDelim > (iPosStart+1)) {
            // Adding a new parameter using substring()
            sParams[iParamCount] = sInput.substring(iPosStart,iPosDelim-1);
            iParamCount++;
            // Checking the number of parameters
            if (iParamCount >= iMaxParams) {
                return (iParamCount);
            }
            iPosStart = iPosDelim + 1;
        }
    } while (iPosDelim >= 0);
    if (iParamCount < iMaxParams) {
        // Adding the last parameter as the end of the line
        sParams[iParamCount] = sInput.substring(iPosStart);
        iParamCount++;
    }

    return (iParamCount);
}

And the usage is really simple:
String sParams[3];
int iCount, i;
String sLine;

// reading the line from file
sLine = readLine();
// parse only if exists
if (sLine.length() > 0) {
    // parse the line
    iCount = StringSplit(sLine,',',sParams,3);
    // print the extracted paramters
    for(i=0;i<iCount;i++) {
        Serial.print(sParams[i]);
    }
    Serial.println("");
}

char str[] = "1:90&2:80&3:180";     // test sample serial input from servo
int servoId;
int position;

char* p = str;
while (sscanf(p, "%d:%d", &servoId, &position) == 2)
{
    // process servoId, position here
    //
    while (*p && *p++ != '&');   // to next id/pos pair
}

It's not an answer to your question but it may be useful for someone. If your string has a specific prefix, then you can use simply startsWith and substring. E.g.
void loop ()
  if(Serial.available()){
    command = Serial.readStringUntil('\n');
    Serial.println("Received command: " + command);
    if(command.startsWith("height")) {
      Serial.println(command.substring(7));
    }
  }
}

And then send height 10 what will extract 10.

void setup() {
Serial.begin(9600);
char str[] ="1:90&2:80";
char * pch;
pch = strtok(str,"&");
printf ("%s\n",pch);

pch = strtok(NULL,"&"); //pch=next value
printf ("%s\n",pch);
}
void loop(){}


text:
How to create a serial communication connection between Cubieboard running Android and Arduino
I am connecting my Arduino to my Cubieboard that is running Android.
I tested this originally with my android tablet and USB cable. This worked successfully for the most part using the firmata kit but I don't want to use firmata.
I want a basic function library written in Java for use with Unity (eg Library Tutorial Video) to connect to the Arduino via the USB serial port connection much like a connection with my Windows computer.
I'd like basic command functions like:

Connect / Open
Write
Read
Flush
Close

I was thinking maybe of using this library here but I am unsure how to go about this. I know similar discussion have already taken place on the forum claiming it may not be possible, but it is very clear that it is. It has been done many times. All I need to do is send strings with serial after finding the Arduino's COM port and reading from the serial.

is your Cubieboard using adroid? what does "java eclipse" means? java is a language, eclipse is an ide, i think you have a bit of confusion.
Many times they say it not possible as many phone does NOT have an USB HOST, but only USB SLAVE. Cubie should have a master.
Java's library used by arduino ide are RXTX(old) and JSSC(use that)

Of course yes.  I did get it a little confused.  I need to access the serial port connected to arduino.  Could you give a bit of information on the JSSC?

Ive been looking at the documentation at https://code.google.com/p/java-simple-serial-connector/wiki/jSSC_examples and im not seeing any android support, am i being a little naive?

JSSC does not support Andorid. i was thinking you was running Linux on the cubie.. Then the library you linked is the way to go

Using the library you linked should be a simple case of downloading the library's jar file from https://github.com/mik3y/usb-serial-for-android/releases and adding it as a reference/library/dependency (I forget what eclipse calls them) in your eclipse project.
Then of course providing you connect with the right baud rates and so on it should work.

Totally insane thought here but.....
Have you tried writing a chrome App to talk to your Arduino?
I did it on the Mac - had chrome monitoring things happening on the network and sending Serial Commands to the Arduino over USB.
You can find samples in the Chrome samples / docs
https://developer.chrome.com/apps/serial

Do you know if this will run on the poster's embedded board, under their current operating system, and have access to the serial devices?


text:
Set up an Arduino Cellular Shield SM5100B
I'm trying to set up an Arduino Cellular Shield SM5100B to send SMS.
My setup is:

Arduino UNO R2
SM5100B
"Movistar" SIM Card (Chile)

I've uploaded a code similar to the one described here, but when communication is supposed to star it cannot find a network. I suspect the problem is I haven't setup correctly the GSM band. But when I issue the command (AT+SBAND=7, same as in the US), it doesn't respond. How can I check in what band I'm on? And change the band?

How are you issuing the command to it? Do you have a new line after the command? Maybe it needs CR+LF. You can tweak those options in your serial terminal program.

/*
 Band Management

 This sketch, for the Arduino GSM shield, checks the band
 currently configured in the modem and allows you to change
 it.

 Please check http://www.worldtimezone.com/gsm.html
 Usual configurations:
 Europe, Africa, Middle East: E-GSM(900)+DCS(1800)
 USA, Canada, South America: GSM(850)+PCS(1900)
 Mexico: PCS(1900)
 Brazil: GSM(850)+E-GSM(900)+DCS(1800)+PCS(1900)

 Circuit:
 * GSM shield

 created 12 June 2012
 by Javier Zorzano, Scott Fitzgerald

 This example is in the public domain.
 */
 // libraries
 #include <GSM.h>

 // initialize the library instance
 GSMBand band;

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

   // Beginning the band manager restarts the modem
   Serial.println("Restarting modem...");
   band.begin();
   Serial.println("Modem restarted.");

 };

 void loop()
 {
   // Get current band
   String bandName = band.getBand(); // Get and print band name
   Serial.print("Current band:");
   Serial.println(bandName);
   Serial.println("Want to change the band you’re on?");
   String newBandName;
   newBandName = askUser();
   // Tell the user what we are about to do…
   Serial.print("\nConfiguring band ");
   Serial.println(newBandName);
   // Change the band
   boolean operationSuccess;
   operationSuccess = band.setBand(newBandName);
   // Tell the user if the operation was OK
   if(operationSuccess)
   {
     Serial.println("Success");
   }
   else
   {
     Serial.println("Error while changing band");
   }

   if(operationSuccess)
   {
     while(true);
   }
 }

 // This function offers the user different options
 // through the Serial interface
 // The user selects one
 String askUser()
 {
   String newBand;
   Serial.println("Select band:");
   // Print the different options
   Serial.println("1 : E-GSM(900)");
   Serial.println("2 : DCS(1800)");
   Serial.println("3 : PCS(1900)");
   Serial.println("4 : E-GSM(900)+DCS(1800) ex: Europe");
   Serial.println("5 : GSM(850)+PCS(1900) Ex: USA, South Am.");
   Serial.println("6 : GSM(850)+E-GSM(900)+DCS(1800)+PCS(1900)");

   // Empty the incoming buffer
   while(Serial.available())
   Serial.read();

   // Wait for an answer, just look at the first character
   while(!Serial.available());
   char c= Serial.read();
   if(c=='1')
     newBand=GSM_MODE_EGSM;
   else if(c=='2')
     newBand=GSM_MODE_DCS;
   else if(c=='3')
     newBand=GSM_MODE_PCS;
   else if(c=='4')
     newBand=GSM_MODE_EGSM_DCS;
   else if(c=='5')
     newBand=GSM_MODE_GSM850_PCS;
   else if(c=='6')
     newBand=GSM_MODE_GSM850_EGSM_DCS_PCS;
   else
     newBand="GSM_MODE_UNDEFINED";
   return newBand;
 }


text:
Modbus Protocol Compile Error
I have Code for Mod bus Library as below. I have Gone through lots of forum. How to assign device ID, slave address, length using below library function:
#include <SimpleModbusSlave.h>
#define  LED 9
enum
{

  ADC_VAL,
  PWM_VAL,
  HOLDING_REGS_SIZE // leave this one
};

unsigned int holdingRegs[HOLDING_REGS_SIZE];
void setup()
{
  modbus_configure(&Serial, 9600, SERIAL_8N2, 1, 2, HOLDING_REGS_SIZE, holdingRegs);
  pinMode(LED, OUTPUT);
}

void loop()
{
  modbus_update();
  holdingRegs[ADC_VAL] = analogRead(A0); // update data to be read by the master to adjust the PWM
  analogWrite(LED, holdingRegs[PWM_VAL]>>2); // constrain adc value from the arduino master to 255
}

I am getting Error has.
SimpleModbusSlaveArduino.cpp: In function 'void setup()':
SimpleModbusSlaveArduino:79: error: 'SERIAL_8N2' was not declared in this scope

I have  made changes in the lib as in forum. but I found no value read by my software.
Master sending below request on read mode. But not receiving anything.
12:31:02.953: Com8, Baud Rate: 9600, Data Bits: 8 Bits, Parity: None, Stop Bits: 1 Stop Bit
12:31:02.953: Echoback: On, RTS Control: On, Transmit Delay: 5 ms, Response Delay: 1000 ms
12:31:02.953: Read Holding Register(s), Repeat Loop
12:31:02.953: Device Address: 01h, Register: 0000h
12:31:02.953: |-> Read Register: 0000h
12:31:02.968: -> [01h] [0Dh] [00h] [00h] [00h] [01h] [CBh] [EDh]

CHANGES MADE IN AS IN FORUM MENTIONED

Are you using the Uno or the Mega? Someone mentioned the Due, is that what you're using? You have both tags, but that doesn't make much sense IMO.

Not sure where you got the library from, but if it's from this github repo, you're using it wrong.
The function prototype for modbus_configure is:
void modbus_configure(long baud, byte _slaveID, byte _TxEnablePin, unsigned int _holdingRegsSize, unsigned char _lowLatency);

The example file shows how to use it correctly
modbus_configure(115200, 1, 2, TOTAL_REGS_SIZE);

I tried already it is not working. i have pasted Error for your library

All those errors are, again, with using the library. Read the error carefully and look at the appropriate part of your code. Other than re-stating the error, I can't help you unless you show code.

In your first example the error is that SERIAL_8N2 is not declared. maybe you are using an old Arduino IDE? try latest 1.0.x or 1.5.x
in the second case TOTAL_REGS_SIZE is a pointer to int, while the function expect a char. Without code is hard to tell what is wrong and how, but in your first code it should be
modbus_configure(115200, 1, 2, HOLDING_REGS_SIZE);

also because you are not passing a reference to the array, you have to pass a pointer pointing the current element in the update function
modbus_update(holdingRegs[i]);
i++

As u said downaded v 1.5 now. But error is same error

seems like you are using an arduino DUE, witch is not explicitly supported by the lib.


text:
Button reading not going off
I made a circuit which in my intentions would allow me to toggle a LED dimming loop.
Problem is that once I push the button the first time pushing it a second time doesn't toggle the LED loop off.
Here is the code:
const int LED = 9; // the pin for the LED
const int BUTTON = 7;

int val = LOW;

int old_val = LOW;
int state = 0;
int i = 0;

void setup()
{
  pinMode(LED, OUTPUT);
  pinMode(BUTTON, INPUT);

}

void loop()
{
  val = digitalRead(BUTTON);

  if ((val == HIGH) && (old_val==LOW))
  {
    state = 1 - state;
    delay(10);
  }

  old_val = val;

  if (state == 1)
  {
    for (i = 0; i < 255; i++)  // loop from 0 to 254 (fade in)
    {
      analogWrite(LED, i); // set the LED brightness
      delay(10);           // Wait 10ms because analogWrite
      // is instantaneous and we would
      // not see any change
    }

    for (i = 255; i > 0; i--) // loop from 255 to 1 (fade out)
    {
      analogWrite(LED, i); // set the LED brightness
      delay(10);           // Wait 10ms
    }
  } else
  {
    analogWrite(LED, 0);
  }

  if ((val == LOW) && (old_val == HIGH))
  {
    delay(10);
  }
}

Here is the circuit scheme:

I would be interested both in learning what the problem is AND learning any mental methods I can apply to debug in such situations.

Is the 10kohm resistor really connected to A5, A4, A3, A2, A1, A0, VIN, and GND?

No, only to GND1. It is a problem with the rendering in 123d circuits.

Then you should consider fixing your wiring diagram.

There! I fixed it.

While the led is fading in and out (which takes 5 seconds), the state of the button is never checked. So you'd need to have the button released for at least 5 seconds (so old_val becomes LOW), and then pressed exactly we the led is faded out (again, 5 seconds later). So try keeping the button pressed for at least 5 seconds. PS you probably want to rewrite your code, so the button is more 'responsive'.

You are right @Gerben! Thank you for the explanation. Any hints on how to make it more responsive?

While the led is fading in and out (which takes 5 seconds), the state of the button is never checked. So you'd need to have the button released for at least 5 seconds (so old_val becomes LOW), and then pressed exactly we the led is faded out (again, 5 seconds later). So try keeping the button pressed for at least 5 seconds.
You probably want to rewrite your code, so the button is more 'responsive'. Below I added an example of how to do this.
const int LED = 9; // the pin for the LED
const int BUTTON = 7;

int val = LOW;
int old_val = LOW;

bool fadeLed = false;
int brightness = 0;//current pwm value
int direction = 1;// 1 is brightness is increasing, -1 if brightness is decreasing

void setup()
{
  pinMode(LED, OUTPUT);
  pinMode(BUTTON, INPUT);
}

void loop()
{

  /* check the button */
  val = digitalRead(BUTTON);
  if ((val == HIGH) && (old_val==LOW))
  {
    // button pressed ( called only once per press )
    fadeLed = !fadeLed;// invert boolean
  }
  old_val = val;

  /* update the leds brightness */
  if( fadeLed )
  {
    // fade led in and out
    if( brightness==0 )
      direction = 1;//change direction is minimum value reached
    if( brightness==255 )
      direction = -1;//change direction is maximum value reached
    brightness += direction;// increase/decrease brightness
  }
  else
  {
    // fadeLed is disabled, so only decrease brightness till it reaches zero
    if( brightness>0 )
      brightness--;
  }

  analogWrite(LED, brightness); // set the LED brightness
  delay(10);           // Wait 10ms because analogWrite
                       // is instantaneous and we would
                       // not see any change

}

Any questions about the code; just let me know.


text:
Powering fans and arduino pro mini from single 12v supply
So, I have a 5V Arduino Pro Mini, which is running the logic behind a multi-DHT22 sensor array, and using that input to control a 12v 24mm fan (12v, 0.16 A).
This is currently a working board on an Arduino Nano with two separate power supplies (1 to USB, 1 to fan). I want to simplify it and make a more permanent installation.
What I'm keen to do is something like the following:
Wall Wart (12v, 500mA) ------------------------> Relay -> Fan
                \ (1) -> Arduino Pro Mini @5V -> /

In order to power the Arduino efficiently at 5V, and avoid drawing power all the time (i.e. when the Arduino is asleep), is the best way to apply a Linear (or Switching) Regulator with minimal burn when idle at (1) in the diagram, and power the Pro via its VCC line, or is it better to just run via the internal regulators and RAW?
Will this actually just generate a high burn whenever the arduino is on to convert the 12v-5v? What is the most power efficient approach here?

Can you see what's the part number of the regulator on the Mini? You can then loop up the Quiescent current (sometimes called bias current) of that part. But my guess is it's negligible. Also note that the arduino is only using around 5mA, so that is only 60mW of power. Even if the quiescent current of the regulator is 5mA, you only use 0.12W. If you want to safe power, it think you could better use a mosfet instead of a relay to switch the fan (as relays use quite a bit of power to keep energized). This also means you can PWM the fan, so you can have basic speed control.

If you want to minimize power usage, the best thing would be to start with devices that use more power! :D
It's time for math! I'm going to use the generic L7805CV 5V, 1A linear regulator. Poking in the datasheet, we find that the quiescent (standby) current is max of 6 mA. I'm assuming this power drawn is 12V, not 5V.
Since a linear regulator is basically a variable resistor, we can figure out that the efficiency is:
Vout / Vin

...thus, our efficiency in this application is...
5V / 12V = 0.416666667% efficiency

... Read more here.
So, we can use the inverse of the efficiency function (Vout / Vin → Vin / Vout) to establish the amount of power it'll use. Final equation:
Power Used (W) = (12V / 5V) * Current Draw + (0.006A * 12V)

...which simplifies to:
Power Used (W) = 2.4 * Current Draw + 0.072 W

So, all we need to find is the power consumption of the Arduino. This forum post states the power consumption of different sleep modes:

SLEEP_MODE_IDLE: 15 mA
SLEEP_MODE_ADC: 6.5 mA
SLEEP_MODE_PWR_SAVE: 1.62 mA
SLEEP_MODE_EXT_STANDBY: 1.62 mA
SLEEP_MODE_STANDBY : 0.84 mA
SLEEP_MODE_PWR_DOWN : 0.36 mA

Let's give the Arduino a generous 15mA to sleep:
Power Used (W) = 2.4 * 0.025 + 0.072 W = 0.132 W

So, 132 milliwatts, idle. A bit further, we can calculate that, if your wall wart has an efficiency of 10%, it will actually draw 1.32 W from your wall socket. Using a general cost per killawatt hour ($0.125), we can calculate that it will cost you about $1.45 a year for that Arduino to be ran in sleep mode 24/7 (given that we used the maximums for everything).
It's pretty cheap, so I wouldn't worry about that power. A good switching regulator will cost more than to run it for a few years with a linear regulator. I'd use the onboard one.
If you still want to optimize things, the wall wart or the fan should be looked at first. Consider getting a switching wall wart instead; this will give you a higher return on your investment since both the fan and the logic use this.


text:
Flashing ATmega8U2 using another Arduino
I have an Anduino Uno R1 and the ATmega8U2 on. It does not respond correctly. How can I use another Arduino Uno R3 in order to reinstall the correct firmware? What I want to avoid it to solder the resistor because I am not very good with the soldering iron.
As fas as I understand there are some pins close to the AREF pin that can be used in order to attach a programmer. Also how can I temporally attach them without the need of a soldering iron? On the R1 the pins are just some exposed metal. How can I connect to them?
Also, if I load into the other Arduino the programmer, then how can I load the firmware using GNU/Linux into the ATmega8U2?

Those pads are actually plated through-holes. But the are filled with solder during manufacturing. You can suck the solder out with a solder sucker. Then solder in some headers. It helps to first add some leaded solder to the “pads”. That way the unleaded solder that’s already there will mix with the leaded, and will lower it’s melting point. The other option is to use the DFU method of updating the firmware (which I think you were talking about in you question).

Even if I solder the header then how I will load the firmware on GNU/Linux?

I think there is a guide on the Arduino website for this. Can’t really check at this moment.

it does not respond correctly - in what way? It is extremely unlikely that the Atmega8u2 has become corrupted.

You can suck the solder out with a solder sucker. - you can also solder wires to them. However the OP said that he is not very good with a soldering iron.

I am kinda in a hurry to fix it - the fastest thing would be to find another Uno.

https://www.arduino.cc/en/Hacking/DFUProgramming8U2 . Are you sure it's an R1, as that's quite an old model?

Yes I am sure but I want to use another method instead the ones mentiuoned in the instructions because I want to use external programmer in order to flash the atmega8u2.

There is an official guide. Arduino as ISP and Arduino Bootloaders
But you need to add the 2x3 ISP pin header since some of the signals isn't available on D0-D13 or any other pins.

None of the signals on the '8U2 are available on Female headers except power & Gnd. One must connect to the 2x3 ISP header for the '8U2 that is shown below the chip in the picture.


text:
Arduino Debounce Sketch
I want to use 4 Push Buttons and 4 leds in my project. What do I need to change in my sketch for multiple input push buttons and multiple outputs of leds? So my sketch is only for one push button and one led. So tell me how I can solve this problem.
Here is the code:
const int buttonPin =2;    // the number of the pushbutton pin
const int ledPin = 13;      // the number of the LED pin

// Variables will change:
int ledState = HIGH;         // the current state of the output pin
int buttonState;             // the current reading from the input pin
int lastButtonState = LOW;   // the previous reading from the input pin
long lastDebounceTime = 0;  // the last time the output pin was toggled
long debounceDelay = 50;
void setup() {
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, ledState);
}

void loop() {
int reading = digitalRead(buttonPin);
if (reading != lastButtonState) {
// reset the debouncing timer
lastDebounceTime = millis();
}

if ((millis() - lastDebounceTime) > debounceDelay) {
// whatever the reading is at, it's been there for longer
// than the debounce delay, so take it as the actual current state:

// if the button state has changed:
if (reading != buttonState) {
  buttonState = reading;

  // only toggle the LED if the new button state is HIGH
  if (buttonState == HIGH) {
    ledState = !ledState;
  }
  }
  }

  // set the LED:
 digitalWrite(ledPin, ledState);
 lastButtonState = reading;
 }

In many systems, you can simply ignore all inputs for a debounce delay after detecting any one.  Others have more complicated requirements, for (rare) example filtering input noise before accepting an input, or allowing a different button to be pressed simultaneously or without delay.  In that case you can use unique code for each, but could also use an array.

Well you declared only one pushbutton and one led. Now do like push1, push2, push3, push4 and led1, led2, led3, led4, and so on. You can also do that with your buttonStates1... Do not forget to declare them as INPUTs or OUTPUTs. Copy paste will help you with this task.

This does not address the primary question of debouncing.

What do I need to change in my sketch for multiple input push buttons and multiple outputs of leds?

easy:
1) study your code to understand how it debounces one input;
2) isolate those parameters / variables used to debounce that specific input;
3) group those parameters / variables into a struct and pass a pointer to that struct to your code;
4) rewrite your code so that it takes the pointer to that struct and debounces accordingly;
5) use that code on as many inputs as you wish.
that's the general approach you take to coding any task.
hope it helps.

I hope this will work for you.
const int buttonPin1 = 2; // Button 1
const int buttonPin2 = 3; // Button 2
const int buttonPin3 = 4; // Button 3
const int buttonPin4 = 5; // Button 4

const int ledPin1 = 6; // LED 1
const int ledPin2 = 7; // LED 2
const int ledPin3 = 8; // LED 3
const int ledPin4 = 9; // LED 4

int ledState1 = HIGH;
int ledState2 = HIGH;
int ledState3 = HIGH;
int ledState4 = HIGH;

int buttonState1, buttonState2, buttonState3, buttonState4;

int lastButtonState1 = LOW;
int lastButtonState2 = LOW;
int lastButtonState3 = LOW;
int lastButtonState4 = LOW;

long lastDebounceTime1 = 0;
long lastDebounceTime2 = 0;
long lastDebounceTime3 = 0;
long lastDebounceTime4 = 0;

long debounceDelay1 = 50;
long debounceDelay2 = 50;
long debounceDelay3 = 50;
long debounceDelay4 = 50;

void setup()
{
  pinMode(buttonPin1, INPUT);
  pinMode(ledPin1, OUTPUT);
  digitalWrite(ledPin1, ledState1);

  pinMode(buttonPin2, INPUT);
  pinMode(ledPin2, OUTPUT);
  digitalWrite(ledPin2, ledState2);

  pinMode(buttonPin3, INPUT);
  pinMode(ledPin3, OUTPUT);
  digitalWrite(ledPin3, ledState3);

  pinMode(buttonPin4, INPUT);
  pinMode(ledPin4, OUTPUT);
  digitalWrite(ledPin4, ledState4);
}

void loop()
{
  led1Fun();
  led2Fun();
  led3Fun();
  led4Fun();
}

void led1Fun()
{
  int reading1 = digitalRead(buttonPin1);

  if(reading1 != lastButtonState1)
  {
    lastDebounceTime1 = millis();
  }

  if((millis() - lastDebounceTime1) > debounceDelay1)
  {
    if(reading1 != buttonState1)
    {
      buttonState1 = reading1;

      if(buttonState1 == HIGH)
      {
        ledState1 = !ledState1;
      }
    }
  }

  digitalWrite(ledPin1, ledState1);
  lastButtonState1 = reading1;
}

void led2Fun()
{
  int reading2 = digitalRead(buttonPin2);

  if(reading2 != lastButtonState2)
  {
    lastDebounceTime2 = millis();
  }

  if((millis() - lastDebounceTime2) > debounceDelay2)
  {
    if(reading2 != buttonState2)
    {
      buttonState2 = reading2;

      if(buttonState2 == HIGH)
      {
        ledState2 = !ledState2;
      }
    }
  }

  digitalWrite(ledPin2, ledState2);
  lastButtonState2 = reading2;
}

void led3Fun()
{
  int reading3 = digitalRead(buttonPin3);

  if(reading3 != lastButtonState3)
  {
    lastDebounceTime3 = millis();
  }

  if((millis() - lastDebounceTime3) > debounceDelay3)
  {
    if(reading3 != buttonState3)
    {
      buttonState3 = reading3;

      if(buttonState3 == HIGH)
      {
        ledState3 = !ledState3;
      }
    }
  }

  digitalWrite(ledPin3, ledState3);
  lastButtonState3 = reading3;
}

void led4Fun()
{
  int reading4 = digitalRead(buttonPin4);

  if(reading4 != lastButtonState4)
  {
    lastDebounceTime4 = millis();
  }

  if((millis() - lastDebounceTime4) > debounceDelay4)
  {
    if(reading4 != buttonState4)
    {
      buttonState4 = reading4;

      if(buttonState4 == HIGH)
      {
        ledState4 = !ledState4;
      }
    }
  }

  digitalWrite(ledPin4, ledState4);
  lastButtonState4 = reading4;
}

That code would greatly benefit from the use of arrays.


text:
MODbus response for configure data
I am not able to receive data. I am able to send data from master but am not getting any response. This program uploaded successfully. I have below setup to monitor data from Modbus.
I have included code for Modbus protocol below.
Also, can someone suggest me the link to download modbus slave config library without any error along with wiring diagram
11:42:17.000: Device Address: 01h, Register: 000Dh
11:42:17.000: |-> Read Register: 000Dh
11:42:17.015: -> [01h] [0Dh] [00h] [0Dh] [00h] [01h] [08h] [7Ch]

#include <modbus.h>
#include <modbusDevice.h>
#include <modbusRegBank.h>
#include <modbusSlave.h>

/*
This example code shows a quick and dirty way to get an
arduino to talk to a modbus master device with a
device ID of 1 at 9600 baud.
*/

//Setup the brewtrollers register bank
//All of the data accumulated will be stored here
modbusDevice regBank;
//Create the modbus slave protocol handler
modbusSlave slave;

void setup()
{

//Assign the modbus device ID.
  regBank.setId(1);

/*
modbus registers follow the following format
00001-09999  Digital Outputs, A master device can read and write to these registers
10001-19999  Digital Inputs, A master device can only read the values from these registers
30001-39999  Analog Inputs, A master device can only read the values from these registers
40001-49999  Analog Outputs, A master device can read and write to these registers

Analog values are 16 bit unsigned words stored with a range of 0-32767
Digital values are stored as bytes, a zero value is OFF and any nonzer value is ON

It is best to configure registers of like type into contiguous blocks.  this
allows for more efficient register lookup and and reduces the number of messages
required by the master to retrieve the data
*/

//Add Digital Output registers 00001-00016 to the register bank
  regBank.add(1);
  regBank.add(2);
  regBank.add(3);
  regBank.add(4);
  regBank.add(5);
  regBank.add(6);
  regBank.add(7);
  regBank.add(8);
  regBank.add(9);
  regBank.add(10);
  regBank.add(11);
  regBank.add(12);
  regBank.add(13);
  regBank.add(14);
  regBank.add(15);
  regBank.add(16);

//Add Digital Input registers 10001-10008 to the register bank
  regBank.add(10001);
  regBank.add(10002);
  regBank.add(10003);
  regBank.add(10004);
  regBank.add(10005);
  regBank.add(10006);
  regBank.add(10007);
  regBank.add(10008);

//Add Analog Input registers 30001-10010 to the register bank
  regBank.add(30001);
  regBank.add(30002);
  regBank.add(30003);
  regBank.add(30004);
  regBank.add(30005);
  regBank.add(30006);
  regBank.add(30007);
  regBank.add(30008);
  regBank.add(30009);
  regBank.add(30010);

//Add Analog Output registers 40001-40020 to the register bank
  regBank.add(40001);
  regBank.add(40002);
  regBank.add(40003);
  regBank.add(40004);
  regBank.add(40005);
  regBank.add(40006);
  regBank.add(40007);
  regBank.add(40008);
  regBank.add(40009);
  regBank.add(40010);
  regBank.add(40011);
  regBank.add(40012);
  regBank.add(40013);
  regBank.add(40014);
  regBank.add(40015);
  regBank.add(40016);
  regBank.add(40017);
  regBank.add(40018);
  regBank.add(40019);
  regBank.add(40020);

/*
Assign the modbus device object to the protocol handler
This is where the protocol handler will look to read and write
register data.  Currently, a modbus slave protocol handler may
only have one device assigned to it.
*/
  slave._device = &regBank;

// Initialize the serial port for coms at 9600 baud
  slave.setBaud(9600);
}

void loop()
{
//put some data into the registers
  regBank.set(1, 1);
  regBank.set(2, 1);
  regBank.set(3, 0);
  regBank.set(4, 1);
  regBank.set(5, 1);
  regBank.set(6, 0);
  regBank.set(7, 1);
  regBank.set(8, 0);

  regBank.set(10001, 1);
  regBank.set(10002, 1);
  regBank.set(10003, 1);
  regBank.set(10004, 1);
  regBank.set(10005, 0);
  regBank.set(10006, 0);
  regBank.set(10007, 0);
  regBank.set(10008, 0);

  regBank.set(30001,1);
  regBank.set(30002,2);
  regBank.set(30003,3);
  regBank.set(30004,4);
  regBank.set(30005,5);
  regBank.set(30006,6);
  regBank.set(30007,7);
  regBank.set(30008,8);
  regBank.set(30009,9);
  regBank.set(30010,10);

  regBank.set(40001,1);
  regBank.set(40002,2);
  regBank.set(40003,2);
  regBank.set(40004,4);
  regBank.set(40005,5);
  regBank.set(40006,6);
  regBank.set(40007,7);
  regBank.set(40008,8);
  regBank.set(40009,9);
  regBank.set(40010,10);

 while(1)
  {
    //put a random number into registers 1, 10001, 30001 and 40001
    regBank.set(1, (byte) random(0, 2));
    regBank.set(10001, (byte) random(0, 2));
    regBank.set(30001, (word) random(0, 32767));
    regBank.set(40001, (word) random(0, 32767));

     slave.run();
  }
}

Does that mean your other question is resolved? If so, you should mark an accepted answer.

Nope that also not resolved. I am getting issue which being not solved yet. Since code is different and also problem associated with it is different so i posted here

maybe you switched TX and RX?


text:
Response of Modbus Protocol
I have the below code. This code is successfully compiling and uploading, but I am not getting any response from Slave. What do I need to do?

Some time data being received from Slave (I get this error):

My main code:
#define ID  1
/*static float ARDUINO_ANALOG_SCALING = 0.00488758;
static float Ydegree;
static int Sensor_Value;
float Yvoltage;

*/

Modbus slave(ID, 0, 0);
boolean led;
int8_t state = 0;
unsigned long tempus;
// data array for modbus network sharing
uint16_t au16data[9];
float latitude=13.08;

void setup() {
  pinMode(13, OUTPUT);
  slave.begin( 19200 );
  tempus = millis() + 100;
  digitalWrite(13, HIGH );
}

void loop() {

  state = slave.poll( au16data, 9 );
  if (state > 4) {
    tempus = millis() + 50;
    digitalWrite(13, HIGH);
  }
  if (millis() > tempus) digitalWrite(13, LOW );

  au16data[4] = analogRead(0);
  au16data[5] = analogRead(1);

  au16data[6] = slave.getInCnt();
  au16data[7] = slave.getOutCnt();
  au16data[8] = slave.getErrCnt();
}

Modbus code:
#define  MAX_BUFFER  64
typedef struct {
  uint8_t u8id;          /*!< slave address between 1 and 247. 0 means broadcast */
  uint8_t u8fct;         /*!< function code: 1, 2, 3, 4, 5, 6, 15 or 16 */
  uint16_t u16RegAdd;    /*!< address of the first register to access at slave/s */
  uint16_t u16CoilsNo;   /*!< number of coils or registers to access */
  uint16_t *au16reg;     /*!< pointer to memory image in master */
}
modbus_t;

enum {
  RESPONSE_SIZE = 6,
  EXCEPTION_SIZE = 3,
  CHECKSUM_SIZE = 2
};

enum MESSAGE {
  ID = 0,
  FUNC,
  ADD_HI,
  ADD_LO,
  NB_HI,
  NB_LO,
  BYTE_CNT
};

enum MB_FC {
  MB_FC_NONE                     = 0,   /*!< null operator */
  MB_FC_READ_COILS               = 1,   /*!< FCT=1 -> read coils or digital outputs */
  MB_FC_READ_DISCRETE_INPUT      = 2,   /*!< FCT=2 -> read digital inputs */
  MB_FC_READ_REGISTERS           = 3,   /*!< FCT=3 -> read registers or analog outputs */
  MB_FC_READ_INPUT_REGISTER      = 4,   /*!< FCT=4 -> read analog inputs */
  MB_FC_WRITE_COIL               = 5,   /*!< FCT=5 -> write single coil or output */
  MB_FC_WRITE_REGISTER           = 6,   /*!< FCT=6 -> write single register */
  MB_FC_WRITE_MULTIPLE_COILS     = 15,  /*!< FCT=15 -> write multiple coils or outputs */
  MB_FC_WRITE_MULTIPLE_REGISTERS = 16   /*!< FCT=16 -> write multiple registers */
};

enum COM_STATES {
  COM_IDLE                     = 0,
  COM_WAITING                  = 1

};

enum ERR_LIST {
  ERR_NOT_MASTER                = -1,
  ERR_POLLING                   = -2,
  ERR_BUFF_OVERFLOW             = -3,
  ERR_BAD_CRC                   = -4,
  ERR_EXCEPTION                 = -5
};

enum {
  NO_REPLY = 255,           /*!< */
  EXC_FUNC_CODE = 1,        /*!< Function code not available */
  EXC_ADDR_RANGE = 2,       /*!< Address beyond available space for Modbus registers */
  EXC_REGS_QUANT = 3,       /*!< Coils or registers number beyond the available space */
  EXC_EXECUTE = 4           /*!< */
};

const unsigned char fctsupported[] = {
  MB_FC_READ_COILS,
  MB_FC_READ_DISCRETE_INPUT,
  MB_FC_READ_REGISTERS,
  MB_FC_READ_INPUT_REGISTER,
  MB_FC_WRITE_COIL,
  MB_FC_WRITE_REGISTER,
  MB_FC_WRITE_MULTIPLE_COILS,
  MB_FC_WRITE_MULTIPLE_REGISTERS
};

#define T35  5

class Modbus {
private:
  HardwareSerial *port; //!< Pointer to Serial class object
  uint8_t u8id; //!<0=master, 1..247=slave number
  uint8_t u8serno; //!<serial port: 0-Serial, 1..3-Serial1..Serial3
  uint8_t u8txenpin; //!<flow control pin: 0=USB or RS-232 mode, >0=RS-485 mode
  uint8_t u8state;
  uint8_t au8Buffer[MAX_BUFFER];
  uint8_t u8BufferSize;
  uint8_t u8lastRec;
  uint16_t *au16regs;
  uint16_t u16InCnt, u16OutCnt, u16errCnt;
  uint16_t u16timeOut;
  uint32_t u32time, u32timeOut;
  uint8_t u8regsize;

  void init(uint8_t u8id, uint8_t u8serno, uint8_t u8txenpin);
  void sendTxBuffer(); // transmit buffer to serial port
  int8_t getRxBuffer(); // get serial buffer contents
  uint16_t calcCRC(uint8_t u8length); // get CRC from au8Buffer until u8length
  uint8_t validateAnswer();
  uint8_t validateRequest(); // validate master request
  void get_FC1(); // *** only master ***
  void get_FC3(); // *** only master ***
  int8_t process_FC1( uint16_t *regs, uint8_t u8size ); //!< *** only slave ***
  int8_t process_FC3( uint16_t *regs, uint8_t u8size ); //!< *** only slave ***
  int8_t process_FC5( uint16_t *regs, uint8_t u8size ); //!< *** only slave ***
  int8_t process_FC6( uint16_t *regs, uint8_t u8size ); //!< *** only slave ***
  int8_t process_FC15( uint16_t *regs, uint8_t u8size ); //!< *** only slave ***
  int8_t process_FC16( uint16_t *regs, uint8_t u8size ); //!< *** only slave ***
  void buildException( uint8_t u8exception ); // build exception message

public:
  Modbus(); // !< Default Constructor
  Modbus(uint8_t u8id, uint8_t u8serno); // !< Constructor
  Modbus(uint8_t u8id, uint8_t u8serno, uint8_t u8txenpin); // !< Full Constructor
  void begin(long u32speed);
  void begin();
  void setTimeOut( uint16_t u16timeout); //!< write communication watch-dog timer
  uint16_t getTimeOut(); //!< get communication watch-dog timer value
  boolean getTimeOutState(); //!< get communication watch-dog timer state
  int8_t query( modbus_t telegram ); //!< only for master
  int8_t poll(); //!< cyclic poll for master
  int8_t poll( uint16_t *regs, uint8_t u8size ); //!< cyclic poll for slave
  uint16_t getInCnt(); //!< number of incoming messages
  uint16_t getOutCnt(); //!< number of outcoming messages
  uint16_t getErrCnt(); //!< error counter
  uint8_t getID(); //!< get slave ID between 1 and 247
  uint8_t getState();
  uint8_t getLastError(); //!< get last error message
  void setID( uint8_t u8id ); //!< write new ID for the slave
  void end(); //!< finish any communication and release serial communication port
};

Modbus::Modbus() {
  init(0, 0, 0);
}

Modbus::Modbus(uint8_t u8id, uint8_t u8serno) {
  init(u8id, u8serno, 0);
}

Modbus::Modbus(uint8_t u8id, uint8_t u8serno, uint8_t u8txenpin) {
  init(u8id, u8serno, u8txenpin);
}

void Modbus::begin(long u32speed) {

  switch ( u8serno ) {
#if defined(UBRR1H)
  case 1:
    port = &Serial1;
    break;
#endif

#if defined(UBRR2H)
  case 2:
    port = &Serial2;
    break;
#endif

#if defined(UBRR3H)
  case 3:
    port = &Serial3;
    break;
#endif
  case 0:
  default:
    port = &Serial;
    break;
  }

  // port->begin(u32speed, u8config);
  port->begin(u32speed);
  if (u8txenpin > 1) { // pin 0 & pin 1 are reserved for RX/TX
    // return RS485 transceiver to transmit mode
    pinMode(u8txenpin, OUTPUT);
    digitalWrite(u8txenpin, LOW);
  }

  port->flush();
  u8lastRec = u8BufferSize = 0;
  u16InCnt = u16OutCnt = u16errCnt = 0;
}

void Modbus::begin() {
  begin(19200);
}

void Modbus::setID( uint8_t u8id) {
  if (( u8id != 0) && (u8id <= 247)) {
    this->u8id = u8id;
  }
}

uint8_t Modbus::getID() {
  return this->u8id;
}

void Modbus::setTimeOut( uint16_t u16timeOut) {
  this->u16timeOut = u16timeOut;
}

boolean Modbus::getTimeOutState() {
  return (millis() > u32timeOut);
}

uint16_t Modbus::getInCnt() {
  return u16InCnt;
}

uint16_t Modbus::getOutCnt() {
  return u16OutCnt;
}

uint16_t Modbus::getErrCnt() {
  return u16errCnt;
}

uint8_t Modbus::getState() {
  return u8state;
}

int8_t Modbus::query( modbus_t telegram ) {
  uint8_t u8regsno, u8bytesno;
  if (u8id != 0) return -2;
  if (u8state != COM_IDLE) return -1;

  if ((telegram.u8id == 0) || (telegram.u8id > 247)) return -3;

  au16regs = telegram.au16reg;

  // telegram header
  au8Buffer[ ID ]         = telegram.u8id;
  au8Buffer[ FUNC ]       = telegram.u8fct;
  au8Buffer[ ADD_HI ]     = highByte(telegram.u16RegAdd );
  au8Buffer[ ADD_LO ]     = lowByte( telegram.u16RegAdd );

  switch ( telegram.u8fct ) {
  case MB_FC_READ_COILS:
  case MB_FC_READ_DISCRETE_INPUT:
  case MB_FC_READ_REGISTERS:
  case MB_FC_READ_INPUT_REGISTER:
    au8Buffer[ NB_HI ]      = highByte(telegram.u16CoilsNo );
    au8Buffer[ NB_LO ]      = lowByte( telegram.u16CoilsNo );
    u8BufferSize = 6;
    break;
  case MB_FC_WRITE_COIL:
    au8Buffer[ NB_HI ]      = ((au16regs[0] > 0) ? 0xff : 0);
    au8Buffer[ NB_LO ]      = 0;
    u8BufferSize = 6;
    break;
  case MB_FC_WRITE_REGISTER:
    au8Buffer[ NB_HI ]      = highByte(au16regs[0]);
    au8Buffer[ NB_LO ]      = lowByte(au16regs[0]);
    u8BufferSize = 6;
    break;
  case MB_FC_WRITE_MULTIPLE_COILS:
    u8regsno = telegram.u16CoilsNo / 16;
    u8bytesno = u8regsno * 2;
    if ((telegram.u16CoilsNo % 16) != 0) {
      u8bytesno++;
      u8regsno++;
    }

    au8Buffer[ NB_HI ]      = highByte(telegram.u16CoilsNo );
    au8Buffer[ NB_LO ]      = lowByte( telegram.u16CoilsNo );
    au8Buffer[ NB_LO + 1 ]    = u8bytesno;
    u8BufferSize = 7;

    u8regsno = u8bytesno = 0; // now auxiliary registers
    for (uint16_t i = 0; i < telegram.u16CoilsNo; i++) {

    }
    break;

  case MB_FC_WRITE_MULTIPLE_REGISTERS:
    au8Buffer[ NB_HI ]      = highByte(telegram.u16CoilsNo );
    au8Buffer[ NB_LO ]      = lowByte( telegram.u16CoilsNo );
    au8Buffer[ NB_LO + 1 ]    = (uint8_t) ( telegram.u16CoilsNo * 2 );
    u8BufferSize = 7;

    for (uint16_t i = 0; i < telegram.u16CoilsNo; i++) {
      au8Buffer[ u8BufferSize ] = highByte( au16regs[ i ] );
      u8BufferSize++;
      au8Buffer[ u8BufferSize ] = lowByte( au16regs[ i ] );
      u8BufferSize++;
    }
    break;
  }

  sendTxBuffer();
  u8state = COM_WAITING;
  return 0;
}

int8_t Modbus::poll() {
  // check if there is any incoming frame
  uint8_t u8current = port->available();

  if (millis() > u32timeOut) {
    u8state = COM_IDLE;
    u16errCnt++;
    return 0;
  }

  if (u8current == 0) return 0;

  // check T35 after frame end or still no frame end
  if (u8current != u8lastRec) {
    u8lastRec = u8current;
    u32time = millis() + T35;
    return 0;
  }
  if (millis() < u32time) return 0;

  // transfer Serial buffer frame to auBuffer
  u8lastRec = 0;
  int8_t i8state = getRxBuffer();
  if (i8state < 7) {
    u8state = COM_IDLE;
    u16errCnt++;
    return i8state;
  }

  // validate message: id, CRC, FCT, exception
  uint8_t u8exception = validateAnswer();
  if (u8exception != 0) {
    u8state = COM_IDLE;
    return u8exception;
  }

  // process answer
  switch ( au8Buffer[ FUNC ] ) {
  case MB_FC_READ_COILS:
  case MB_FC_READ_DISCRETE_INPUT:
    // call get_FC1 to transfer the incoming message to au16regs buffer
    get_FC1( );
    break;
  case MB_FC_READ_INPUT_REGISTER:
  case MB_FC_READ_REGISTERS :
    // call get_FC3 to transfer the incoming message to au16regs buffer
    get_FC3( );
    break;
  case MB_FC_WRITE_COIL:
  case MB_FC_WRITE_REGISTER :
  case MB_FC_WRITE_MULTIPLE_COILS:
  case MB_FC_WRITE_MULTIPLE_REGISTERS :
    // nothing to do
    break;
  default:
    break;
  }
  u8state = COM_IDLE;
  return u8BufferSize;
}

int8_t Modbus::poll( uint16_t *regs, uint8_t u8size ) {

  au16regs = regs;
  u8regsize = u8size;

  // check if there is any incoming frame
  uint8_t u8current = port->available();
  if (u8current == 0) return 0;

  // check T35 after frame end or still no frame end
  if (u8current != u8lastRec) {
    u8lastRec = u8current;
    u32time = millis() + T35;
    return 0;
  }
  if (millis() < u32time) return 0;

  u8lastRec = 0;
  int8_t i8state = getRxBuffer();
  if (i8state < 7) return i8state;

  // check slave id
  if (au8Buffer[ ID ] != u8id) return 0;

  // validate message: CRC, FCT, address and size
  uint8_t u8exception = validateRequest();
  if (u8exception > 0) {
    if (u8exception != NO_REPLY) {
      buildException( u8exception );
      sendTxBuffer();
    }
    return u8exception;
  }

  u32timeOut = millis() + long(u16timeOut);

  // process message
  switch ( au8Buffer[ FUNC ] ) {
  case MB_FC_READ_COILS:
  case MB_FC_READ_DISCRETE_INPUT:
    return process_FC1( regs, u8size );
    break;
  case MB_FC_READ_INPUT_REGISTER:
  case MB_FC_READ_REGISTERS :
    return process_FC3( regs, u8size );
    break;
  case MB_FC_WRITE_COIL:
    return process_FC5( regs, u8size );
    break;
  case MB_FC_WRITE_REGISTER :
    return process_FC6( regs, u8size );
    break;
  case MB_FC_WRITE_MULTIPLE_COILS:
    return process_FC15( regs, u8size );
    break;
  case MB_FC_WRITE_MULTIPLE_REGISTERS :
    return process_FC16( regs, u8size );
    break;
  default:
    break;
  }
}

/* _____PRIVATE FUNCTIONS_____________________________________________________ */

void Modbus::init(uint8_t u8id, uint8_t u8serno, uint8_t u8txenpin) {
  this->u8id = u8id;
  this->u8serno = (u8serno > 3) ? 0 : u8serno;
  this->u8txenpin = u8txenpin;
  this->u16timeOut = 1000;
}

int8_t Modbus::getRxBuffer() {
  boolean bBuffOverflow = false;

  if (u8txenpin > 1) digitalWrite( u8txenpin, LOW );

  u8BufferSize = 0;
  while ( port->available() ) {
    au8Buffer[ u8BufferSize ] = port->read();
    u8BufferSize ++;

    if (u8BufferSize >= MAX_BUFFER) bBuffOverflow = true;
  }
  u16InCnt++;

  if (bBuffOverflow) {
    u16errCnt++;
    return ERR_BUFF_OVERFLOW;
  }
  return u8BufferSize;
}

void Modbus::sendTxBuffer() {
  uint8_t i = 0;

  // append CRC to message
  uint16_t u16crc = calcCRC( u8BufferSize );
  au8Buffer[ u8BufferSize ] = u16crc >> 8;
  u8BufferSize++;
  au8Buffer[ u8BufferSize ] = u16crc & 0x00ff;
  u8BufferSize++;

  // set RS485 transceiver to transmit mode
  if (u8txenpin > 1) {
    switch ( u8serno ) {
#if defined(UBRR1H)
    case 1:
      UCSR1A = UCSR1A | (1 << TXC1);
      break;
#endif

#if defined(UBRR2H)
    case 2:
      UCSR2A = UCSR2A | (1 << TXC2);
      break;
#endif

#if defined(UBRR3H)
    case 3:
      UCSR3A = UCSR3A | (1 << TXC3);
      break;
#endif
    case 0:
    default:
      UCSR0A = UCSR0A | (1 << TXC0);
      break;
    }
    digitalWrite( u8txenpin, HIGH );
  }

  // transfer buffer to serial line
  port->write( au8Buffer, u8BufferSize );

  // keep RS485 transceiver in transmit mode as long as sending
  if (u8txenpin > 1) {
    switch ( u8serno ) {
#if defined(UBRR1H)
    case 1:
      while (!(UCSR1A & (1 << TXC1)));
      break;
#endif

#if defined(UBRR2H)
    case 2:
      while (!(UCSR2A & (1 << TXC2)));
      break;
#endif

#if defined(UBRR3H)
    case 3:
      while (!(UCSR3A & (1 << TXC3)));
      break;
#endif
    case 0:
    default:
      while (!(UCSR0A & (1 << TXC0)));
      break;
    }

    // return RS485 transceiver to receive mode
    digitalWrite( u8txenpin, LOW );
  }
  port->flush();
  u8BufferSize = 0;

  // set time-out for master
  u32timeOut = millis() + (unsigned long) u16timeOut;

  // increase message counter
  u16OutCnt++;
}

/**
 * @brief
 * This method calculates CRC
 *
 * @return uint16_t calculated CRC value for the message
 * @ingroup buffer
 */
uint16_t Modbus::calcCRC(uint8_t u8length) {
  unsigned int temp, temp2, flag;
  temp = 0xFFFF;
  for (unsigned char i = 0; i < u8length; i++) {
    temp = temp ^ au8Buffer[i];
    for (unsigned char j = 1; j <= 8; j++) {
      flag = temp & 0x0001;
      temp >>= 1;
      if (flag)
        temp ^= 0xA001;
    }
  }
  // Reverse byte order.
  temp2 = temp >> 8;
  temp = (temp << 8) | temp2;
  temp &= 0xFFFF;
  // the returned value is already swapped
  // crcLo byte is first & crcHi byte is last
  return temp;
}

uint8_t Modbus::validateRequest() {
  // check message crc vs calculated crc
  uint16_t u16MsgCRC =
    ((au8Buffer[u8BufferSize - 2] << 8)
    | au8Buffer[u8BufferSize - 1]); // combine the crc Low & High bytes
  if ( calcCRC( u8BufferSize - 2 ) != u16MsgCRC ) {
    u16errCnt ++;
    return NO_REPLY;
  }

  // check fct code
  boolean isSupported = false;
  for (uint8_t i = 0; i < sizeof( fctsupported ); i++) {
    if (fctsupported[i] == au8Buffer[FUNC]) {
      isSupported = 1;
      break;
    }
  }
  if (!isSupported) {
    u16errCnt ++;
    return EXC_FUNC_CODE;
  }

  // check start address & nb range
  uint16_t u16regs = 0;
  uint8_t u8regs;
  switch ( au8Buffer[ FUNC ] ) {
  case MB_FC_READ_COILS:
  case MB_FC_READ_DISCRETE_INPUT:
  case MB_FC_WRITE_MULTIPLE_COILS:
    u16regs = word( au8Buffer[ ADD_HI ], au8Buffer[ ADD_LO ]) / 16;
    u16regs += word( au8Buffer[ NB_HI ], au8Buffer[ NB_LO ]) / 16;
    u8regs = (uint8_t) u16regs;
    if (u8regs > u8regsize) return EXC_ADDR_RANGE;
    break;
  case MB_FC_WRITE_COIL:
    u16regs = word( au8Buffer[ ADD_HI ], au8Buffer[ ADD_LO ]) / 16;
    u8regs = (uint8_t) u16regs;
    if (u8regs > u8regsize) return EXC_ADDR_RANGE;
    break;
  case MB_FC_WRITE_REGISTER :
    u16regs = word( au8Buffer[ ADD_HI ], au8Buffer[ ADD_LO ]);
    u8regs = (uint8_t) u16regs;
    if (u8regs > u8regsize) return EXC_ADDR_RANGE;
    break;
  case MB_FC_READ_REGISTERS :
  case MB_FC_READ_INPUT_REGISTER :
  case MB_FC_WRITE_MULTIPLE_REGISTERS :
    u16regs = word( au8Buffer[ ADD_HI ], au8Buffer[ ADD_LO ]);
    u16regs += word( au8Buffer[ NB_HI ], au8Buffer[ NB_LO ]);
    u8regs = (uint8_t) u16regs;
    if (u8regs > u8regsize) return EXC_ADDR_RANGE;
    break;
  }
  return 0; // OK, no exception code thrown
}

uint8_t Modbus::validateAnswer() {
  // check message crc vs calculated crc
  uint16_t u16MsgCRC =
    ((au8Buffer[u8BufferSize - 2] << 8)
    | au8Buffer[u8BufferSize - 1]); // combine the crc Low & High bytes
  if ( calcCRC( u8BufferSize - 2 ) != u16MsgCRC ) {
    u16errCnt ++;
    return NO_REPLY;
  }

  // check exception
  if ((au8Buffer[ FUNC ] & 0x80) != 0) {
    u16errCnt ++;
    return ERR_EXCEPTION;
  }

  // check fct code
  boolean isSupported = false;
  for (uint8_t i = 0; i < sizeof( fctsupported ); i++) {
    if (fctsupported[i] == au8Buffer[FUNC]) {
      isSupported = 1;
      break;
    }
  }
  if (!isSupported) {
    u16errCnt ++;
    return EXC_FUNC_CODE;
  }

  return 0; // OK, no exception code thrown
}

void Modbus::buildException( uint8_t u8exception ) {
  uint8_t u8func = au8Buffer[ FUNC ];  // get the original FUNC code

  au8Buffer[ ID ]      = u8id;
  au8Buffer[ FUNC ]    = u8func + 0x80;
  au8Buffer[ 2 ]       = u8exception;
  u8BufferSize         = EXCEPTION_SIZE;
}

void Modbus::get_FC1() {
  uint8_t u8byte, i;
  u8byte = 0;

  // check the answer length
  boolean bEvenOdd =
    ( au8Buffer[ ADD_HI ] % 2 == 0) ?
  false :
  true;

  uint8_t u8WordsNo =
    ( !bEvenOdd ) ?
  au8Buffer[ ADD_HI ] / 2 :
  au8Buffer[ ADD_HI ] / 2 + 1;

  for (i = 0; i < u8WordsNo; i++) {
    au16regs[ i ] = word(
    au8Buffer[ u8byte ],
    au8Buffer[ u8byte + 1 ]);
    u8byte += 2;
  }

  // cut last byte
  if (bEvenOdd) {
    au16regs[ u8WordsNo - 1 ] &= 0xff00;
  }
}

void Modbus::get_FC3() {
  uint8_t u8byte, i;
  u8byte = 3;

  for (i = 0; i < au8Buffer[ 2 ] / 2; i++) {
    au16regs[ i ] = word(
    au8Buffer[ u8byte ],
    au8Buffer[ u8byte + 1 ]);
    u8byte += 2;
  }
}

int8_t Modbus::process_FC1( uint16_t *regs, uint8_t u8size ) {
  uint8_t u8currentRegister, u8currentBit, u8bytesno, u8bitsno;
  uint8_t u8CopyBufferSize;
  uint16_t u16currentCoil, u16coil;

  // get the first and last coil from the message
  uint16_t u16StartCoil = word( au8Buffer[ ADD_HI ], au8Buffer[ ADD_LO ] );
  uint16_t u16Coilno = word( au8Buffer[ NB_HI ], au8Buffer[ NB_LO ] );

  // put the number of bytes in the outcoming message
  u8bytesno = (uint8_t) (u16Coilno / 8);
  if (u16Coilno % 8 != 0) u8bytesno ++;
  au8Buffer[ ADD_HI ]  = u8bytesno;
  u8BufferSize         = ADD_LO;

  // read each coil from the register map and put its value inside the outcoming message
  u8bitsno = 0;

  for (u16currentCoil = 0; u16currentCoil < u16Coilno; u16currentCoil++) {
    u16coil = u16StartCoil + u16currentCoil;
    u8currentRegister = (uint8_t) (u16coil / 16);
    u8currentBit = (uint8_t) (u16coil % 16);

    bitWrite(
    au8Buffer[ u8BufferSize ],
    u8bitsno,
    bitRead( regs[ u8currentRegister ], u8currentBit ) );
    u8bitsno ++;

    if (u8bitsno > 7) {
      u8bitsno = 0;
      u8BufferSize++;
    }
  }

  // send outcoming message
  if (u16Coilno % 8 != 0) u8BufferSize ++;
  u8CopyBufferSize = u8BufferSize +2;
  sendTxBuffer();
  return u8CopyBufferSize;
}

int8_t Modbus::process_FC3( uint16_t *regs, uint8_t u8size ) {

  uint8_t u8StartAdd = word( au8Buffer[ ADD_HI ], au8Buffer[ ADD_LO ] );
  uint8_t u8regsno = word( au8Buffer[ NB_HI ], au8Buffer[ NB_LO ] );
  uint8_t u8CopyBufferSize;
  uint8_t i;

  au8Buffer[ 2 ]       = u8regsno * 2;
  u8BufferSize         = 3;

  for (i = u8StartAdd; i < u8StartAdd + u8regsno; i++) {
    au8Buffer[ u8BufferSize ] = highByte(regs[i]);
    u8BufferSize++;
    au8Buffer[ u8BufferSize ] = lowByte(regs[i]);
    u8BufferSize++;
  }
  u8CopyBufferSize = u8BufferSize +2;
  sendTxBuffer();

  return u8CopyBufferSize;
}

int8_t Modbus::process_FC5( uint16_t *regs, uint8_t u8size ) {
  uint8_t u8currentRegister, u8currentBit;
  uint8_t u8CopyBufferSize;
  uint16_t u16coil = word( au8Buffer[ ADD_HI ], au8Buffer[ ADD_LO ] );

  // point to the register and its bit
  u8currentRegister = (uint8_t) (u16coil / 16);
  u8currentBit = (uint8_t) (u16coil % 16);

  // write to coil
  bitWrite(
  regs[ u8currentRegister ],
  u8currentBit,
  au8Buffer[ NB_HI ] == 0xff );

  // send answer to master
  u8BufferSize = 6;
  u8CopyBufferSize = u8BufferSize +2;
  sendTxBuffer();

  return u8CopyBufferSize;

}

int8_t Modbus::process_FC6( uint16_t *regs, uint8_t u8size ) {

  uint8_t u8add = word( au8Buffer[ ADD_HI ], au8Buffer[ ADD_LO ] );
  uint8_t u8CopyBufferSize;
  uint16_t u16val = word( au8Buffer[ NB_HI ], au8Buffer[ NB_LO ] );

  regs[ u8add ] = u16val;

  // keep the same header
  u8BufferSize         = RESPONSE_SIZE;

  u8CopyBufferSize = u8BufferSize +2;
  sendTxBuffer();

  return u8CopyBufferSize;
}

int8_t Modbus::process_FC15( uint16_t *regs, uint8_t u8size ) {
  uint8_t u8currentRegister, u8currentBit, u8frameByte, u8bitsno;
  uint8_t u8CopyBufferSize;
  uint16_t u16currentCoil, u16coil;
  boolean bTemp;

  // get the first and last coil from the message
  uint16_t u16StartCoil = word( au8Buffer[ ADD_HI ], au8Buffer[ ADD_LO ] );
  uint16_t u16Coilno = word( au8Buffer[ NB_HI ], au8Buffer[ NB_LO ] );

  // read each coil from the register map and put its value inside the outcoming message
  u8bitsno = 0;
  u8frameByte = 7;
  for (u16currentCoil = 0; u16currentCoil < u16Coilno; u16currentCoil++) {

    u16coil = u16StartCoil + u16currentCoil;
    u8currentRegister = (uint8_t) (u16coil / 16);
    u8currentBit = (uint8_t) (u16coil % 16);

    bTemp = bitRead(
    au8Buffer[ u8frameByte ],
    u8bitsno );

    bitWrite(
    regs[ u8currentRegister ],
    u8currentBit,
    bTemp );

    u8bitsno ++;

    if (u8bitsno > 7) {
      u8bitsno = 0;
      u8frameByte++;
    }
  }

  // send outcoming message
  // it's just a copy of the incomping frame until 6th byte
  u8BufferSize         = 6;
  u8CopyBufferSize = u8BufferSize +2;
  sendTxBuffer();
  return u8CopyBufferSize;
}

int8_t Modbus::process_FC16( uint16_t *regs, uint8_t u8size ) {
  uint8_t u8func = au8Buffer[ FUNC ];  // get the original FUNC code
  uint8_t u8StartAdd = au8Buffer[ ADD_HI ] << 8 | au8Buffer[ ADD_LO ];
  uint8_t u8regsno = au8Buffer[ NB_HI ] << 8 | au8Buffer[ NB_LO ];
  uint8_t u8CopyBufferSize;
  uint8_t i;
  uint16_t temp;

  // build header
  au8Buffer[ NB_HI ]   = 0;
  au8Buffer[ NB_LO ]   = u8regsno;
  u8BufferSize         = RESPONSE_SIZE;

  // write registers
  for (i = 0; i < u8regsno; i++) {
    temp = word(
    au8Buffer[ (BYTE_CNT + 1) + i * 2 ],
    au8Buffer[ (BYTE_CNT + 2) + i * 2 ]);

    regs[ u8StartAdd + i ] = temp;
  }
  u8CopyBufferSize = u8BufferSize +2;
  sendTxBuffer();

  return u8CopyBufferSize;
}

My testing indicates that the slave is responding. I made up a master from http://playground.arduino.cc/Code/ModbusMaster and tested it:

Channel 0 is master to slave.
Channel 1 is slave to master.

Zooming in:

I would like to know how you have analyzed this. Is it from an emulation, an oscilloscope or some PC-oscilloscope-software thing?


text:
Analog average sample wind speed sensor
I have wind speed sensor that can measure max speed upto 30 m/s with analog out put 0-5v. I have simple code calling from the loop. When I put the wind speed average code, the web server is not working and it just hangs. If I comment out web server it's working fine. Let me know What makes my web server hang or not get connected. Is there any way I can change average taking code?
Working code should like below:
if wind speed exceed 30 m/s
   mode =stow
else
   mode =track

My code. And how can write average of windload of day to SDcard
#include"wind.h"
#include"mode.h"

float sampleAverage(void)
{
  float accumulator = 0;
  for (int i = 0; i < SAMPLE_COUNT; i++)
  {
    accumulator += sample[i];
  }
  return accumulator / SAMPLE_COUNT;
}

void Wind_calc()
{

  static unsigned long lastSampleTime = 0;
  unsigned long currentTime = millis();

  // check if time for new reading
  if (currentTime - lastSampleTime >= SAMPLE_RATE)
  {
    lastSampleTime = currentTime;
    int sensorValue = analogRead(SENSOR_PIN);
    float voltage = sensorValue * (5.0 / 1023.0);
    /* Serial.print("voltage: ");
     Serial.println(voltage);*/
    // add the newest reading at the oldest pointer
    sample[sampleIndex] = voltage;
    // advance to next index which is now oldest
    sampleIndex++;
    // check for and handle rollover
    if (sampleIndex == SAMPLE_COUNT)
    {
      sampleIndex = 0;
    }
    // the sample array now contains the last ten readings
    // sampleIndex now points to the oldest reading
    // it will be replaced with the newest next time

    float average = sampleAverage();
    /*Serial.print("average:");
     Serial.println(average);*/
    Wind_Speed = (6 * average);
    Wind_Kmph = 3.6 * Wind_Speed;
    /*    Serial.print("Wind_Speed:");
     Serial.print(Wind_Speed);
     Serial.println("m/s");

     Serial.print("Wind_Exceed_count:");Serial.println(Wind_Exceed_count);Serial.println(".................");
     Serial.print("Wind_Kmph:");
     Serial.print(Wind_Kmph);
     Serial.println("KMPH");
     */
    if((Wind_Speed>4.0)&&(Stow_flag==0))
    {
      Wind_Exceed_count=Wind_Exceed_count+1;

      //Serial.println("Wind_Exceed_count");Serial.print(Wind_Exceed_count);
      if(Wind_Exceed_count<5)
      {
        Stow_flag=0;
      }
      else
      {
        Stow_flag=1;
        MODE=STOW;
      }

    }
    else
    {
      Redo_Wind_calc();
    }

  }

}

void Redo_Wind_calc()
{
  //  Serial.println("Wind_Exceed_count");Serial.print(Wind_Exceed_count);
  if(Wind_Speed>4.0 &&Stow_flag==1)
  {
    Wind_Exceed_count=Wind_Exceed_count+1;
    if(Wind_Exceed_count<=10)
    {
      MODE=STOW;
    }
    else
    {
      MODE=TRACK;
      Wind_Exceed_count=0;
      Stow_flag=0;
    }

  }
}

void loop()
{
 Wind_calc();
webcontrol();
}

void webcontrol()
{

//Web control function are defined here

}

Where is the sample[] array declared?

also thisseems to be the working code. Add the bad code!

And where's your setup() method? You seem to be missing a lot of code: can you add more please?

How much is SAMPLE_COUNT?

What arduino board is being used? I find that some webserver code takes up a lot of the SRAM and in an UNO this leaves very little space for other code.
To save SRAM use the F macro on all the Serial.print statements that have quoted text. i.e:
Serial.print("Some text you want output");

This takes up SRAM when running. 1 byte per letter and space.
Serial.print(F("Some text you want output"));

This takes up no SRAM as it is stored in program space and is makes a big difference.
Search for a freeRam() and use that in debugging your sketch to see how much free space you have.
Relevant question: What can I do if I run out of Flash memory or SRAM?

Is there way to checkSRAM memory occupied. I am using arduino UNO board .I have removed all Serial.println statement from my code

@AMPS this question has already been asked (and answered): http://arduino.stackexchange.com/questions/763/im-using-too-much-ram-how-can-this-be-measured

this is a really useful tip, though I think there are limitations with what can go in the argument of F(), for example this
Serial.print(F((int)lsm.magData.x*100));  seems to cause a compile error. I suppose I could do the maths in a seperate line and then offer its result to F as a variable, but I guess that would probably defeat the obejective of using less memory?


text:
Servo - Serial communication problem
I am sending data from an Arduino Uno to an Arduino Mega via serial communication.
The data is analog value. I'm getting that data and converting it to an int. There is no problem there. However, when I connect the servo to the attached pin, the serial communication on mega becomes disconnected. When I  remove the PWM pin, the serial communication is working again. Why does the servo stop serial communication?
Wiring: Mega-- 5v and gnd pins linked to servo ( 13kg/cm ), PWM 2 pin is linked to servo's pwm input, rx2 pin is linked to uno's tx pin

Don't power your servo from either Arduino.

Okey I will try to power servo from somewhere else. But what is the problem? I want to know how does it happen.

The problem is that the arduino can not supply enough current to drive the motor. So you might blow-up/fry your arduino (too much current through it).

Actually, you are really lucky to have a working Arduino Mega after your experiment.

But i drive 5 servo together with this mega. Why that time mega did not become fried or blowed up? This not power problem..

Servo current draw varies drastically depending on load and internal control loop behavior which can vary even as the potentiometer and motor age or timing components drift with age or heat.  But it is not just the average current that counts - excessive instantaneous current draw can reset or even crash your Arduino's microcontroller.  What you are trying to do is really not sound engineering - if you are going to persist in it and insist it is not an issue, then people here won't help you.

If you draw too much current from an Arduino microcontroller it can reset itself (brownout), that results in it not responding. To solve this do not power your servo directly from the Arduino, use an external power supply.

If you are using delay function then I guess the problem is due to that. Just try once using millis function to generate PWM signal at Mega.

authors: Б. Янжинлхам