text:
String to Int Array
I have a string:
String cod=server.arg("codice");

where codice (an IR sequence) is retrieved from a webserver.
For example:
codice=1, 2,  3, 4
In which the syntax can be modified.
So, cod is a string that contains numbers separated with ", "
To send the IR code i use:
irsend.sendRaw(rawData, 67, 38);

I don't know how to convert the String to Int (rawData) as requested by rsend.sendRaw.

@darimos on Stack Exchange sites, solutions are not to be edited into questions.  Rather, accept an answer which provides the solution, or if none does, post your own answer and return to accept that once the few-days waiting period of self answers has elapsed.

Use strtok to split the char array into the different parts, then use atoi on each of the parts to convert it to an int. (atoi ignores whitespace)
char* str = "4532, 4488,  548, 1694,  574";

const size_t bufferSize = 5;
int arr[bufferSize];

char *p = strtok(str, ",");
size_t index = 0;

while (p != nullptr && index < bufferSize) {
  arr[index++] = atoi(p);
  p = strtok(NULL, ",");
}

for (size_t i = 0; i < index; i++)
  Serial.println(arr[i]);

Edit: You just edited your post, and it seems like you really need to use Strings (capital S).
There are two ways to go about it: you have to keep in mind that String::c_str() returns the actual pointer to the internal null terminated char array inside the String object, and that strtok is destructive (it replaces the delimiters with null characters).
If you need the String for other things after converting it to an array of ints, you'll have to make a copy first:
String cod = "4532, 4488,  548, 1694,  574";
char *str = new char[cod.length() + 1];
strcpy(str, cod.c_str());

Don't forget to free the memory afterwards:
delete[] str;

If you don't care about destroying the String, you can just use:
String cod = "4532, 4488,  548, 1694,  574";
char *str = cod.c_str();

Edit 2: The ESP8266 compiler doesn't allow implicit conversion from const char* (read only) to char* (as strtok argument). To get around it, the clean solution is to copy it, as explained in my first edit.
If you really don't need the String afterwards, and you don't want to waste memory on the copy, you can just use an explicit type cast:
String cod = "4532, 4488,  548, 1694,  574";
char *str = (char*)cod.c_str();

The AVR compiler doesn't have any problems converting String::c_str() to char*

Hello, thanks for the answer. I tried your solution but i got this error:  char  *_EXFUN(strtok,(char *, const char *));
    ^

exit status 1
invalid conversion from 'const char*' to 'char*' [-fpermissive]

Do you mean for (size_t i = 0; i < index; i++) { Serial.print(arr[i]); Serial.print('\t'); } Serial.println(); ?

Since i need to send irsend.sendRaw(rawData, 67, 38); i need an int array called rawData or whatelse is the name. I hope it is clear, thank you.

arr is the array of ints

yes, i tried to do Serial.println(arr); but i received "call of overloaded 'println(int [5])' is ambiguous" which is the problem?

You're not being clear here. To send the code over IR, use irsend.sendRaw(arr, index - 1, 38);, to print the array, use for (size_t i = 0; i < index; i++) { Serial.print(arr[i]); Serial.print('\t'); } Serial.println();


text:
Bootloader and Boards Definition for Atmega2560V-8AU at 8 MHz / 3.3v
I am working on a home made project,where i am using Atmega2560V-8AU (note the suffix, this part has an 8 MHz maximum clock rate) as my main controller, supplying 3.3V to this chip.
I want this controller to work exactly same as standard Atmega2560-16AU like on Arduino Mega(perhaps at a slower baud rate on account of the slower clock)
Does there already exist a suitable bootloader image and board definition for an ATmega2560 operating from an 8 MHz crystal?
If not, what changes would need to be made to the usual 16 MHz bootloader and boards definition to support 8 MHz operation, both for the bootloader and for correct time functions and serial buad rates in sketches?

@Gerben - how do you propose the lower clock speed be handled?  If you are suggesting there is already an option for it, mentioning that would be clearer.

@Gerben - you seem to be ignoring the whole point of the question - the poster wants to use an atypical chip which cannot operate at the normal clock rate.  It either needs a custom bootloader to operate at a usual baud rate, or programming support for a slower baud rate.   Your responses so far have been the exact opposite of helpful.

In actual fact, the ordinary bootloader will work, but the problem will come when then trying to talk to it - it will be operating at half the expected baud rate due to the 8 MHz vs expected 16 MHz clock, so the usual board definitions won't allow the IDE to talk to it.  What the poster needs is a good board definition package for an 8 MHz Arduino Mega.

There is a fair amount of coverage here and elsewhere for 8 MHz / 3.3v usage of the ATMega328p - the situation with the 2560 will be similar enough that those solutions could be used as a model for the necessary modifications or workarounds, but of course an ATMega328p board package won't actually work on a 2560.

Hello,
I am sorry for not providing enough information my task! I am using 8Mhz crystal and the chip runs on 3.3V, I cannot upload bootloaders of Atmega2560-16AU which runs on 16Mhz cystal.
Yes! the ordinary boorloaders should work! but i need to change 16Mhz set to 8Mhz set somewhere in some files of ARduino IDE
How do i dot that.? and is there any more things i have to do like Fuses etc.?
and I am using my Arduino UNO as "Arduino as ISP" programmer in the list, which will have +5V on the SPI lines and I am running my target chip on 3.3V,
Does it hurts to my chip.?
Thank you

Sparkfun used to sell a board with this chip, and seems to still have downloadable resource at https://www.sparkfun.com/products/retired/10744 however, the way the Arduino IDE does things has changed over time, and those files may not work with a current one.  I believe there is now some drop-down menu support for various clock options for some boards, so that may be an alternate route.

thank you for reply,
I have tested with the above mentioned Sparkfun board with the files on bootloaders, But the board is not showing in the boards section.
Is there any chance of customising stock Arduino Mega bootloaders with this chip.?
Thank you

As I said, the way the Arduino handles board definitions keeps changing, so it unsurprising that the old one doesn't work with a recent IDE.  You'll need to find our figure out how to make a definition for a modern IDE (perhaps using the old one and new ones for an 8 MHz ATmega328p as guides), or (less preferably) use an old version of the IDE.

Thank you very much for reply, which version of arduino ide should I try?

If you want to use the old sparkfun files, one contemporary with them.  If you want to create something new, figure out what the latest stable version is, and combine what you can learn from the old sparkfun files and current guidelines for 8 MHz ATmega328p solutions to develop a configuration for an 8 MHz ATmega2560v.  You may also need to set brownout fuses appropriately for 3.3v operation.

hello, I have used this Megacore and it solved my problem
https://github.com/MCUdude/MegaCore

@MudassirHussain, then post your solution as answer (yes you can self-answer!), and accept it. This way, 1) The question won't be marked as unaswered anymore b) other users will benefit from you useful information. c) you'll gain reputation.

I have used megacore bootloaders, and it solved the problem

source: Stack Exchange

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

sort: votes


text:
Basic questions on Inputs
I'm completely new to Arduino or even micro-controllers, I'm not even good in physics.
First of all, I'll explain what I am trying to build:
I have an Arduino Nano, for a university project (computer science) I'm trying to make an alternative controller(HID). This controller will be a simple glove, which contains conductive yarn from the Arduino to each finger. If two fingers connect their conductive yarn, I know which fingers are connected and I map this to an input for the computer, which I connected to the Arduino.
For example, if the thumb touches the index finger, it means an X on the computer.
To get the code done is not the problem I guess.

Since I'm completely new, I have some pretty basic questions:
1) Can I use the circuit diagram I created or won't it work? Imagine the switches are my hand, which works like a switch.
2) Does my circuit need a connection to 5V and ground, or can one of the pins be a GROUND / 5V?
3) To know if a switch is active, do I have to watch for changes on the pin? For example, the pin is LOW, is it HIGH after the circuit is "closed"?
If you guys can provide me further information for my project or nice tutorials to get in touch with micro-controllers, I would really appreciate it.
Thank you in advance!

That is not even close to what almost every switch input tutorial explains.

Are both hands independent or would it be possible to e.g. contact left thumb with right index?

1) Can i use the circuit diagram i created or wont it work?

It won't work. The reason is when the switches are open the input pins are floating and that means they could be HIGHor LOW or flipping back and forth. You want the pins to be always in a specific state whether the switch is open or closed. To do this a pull-up or pull-down resistor is used. This resistor sets the pin to HIGH or LOW respectively when the switch is open but the value of the resistor is chosen so that when the switch is closed it overpowers the resistor and the pin reads the opposite state. Since you have your switches connected between the input pin and 5 V you would need to add a pull-down resistor to every pin. That's easy enough but there is an even easier way. The microcontroller on your Nano has internal pull-up resistors you can turn on by doing this:
pinMode(inputPin, INPUT_PULLUP);

See: https://www.arduino.cc/en/Reference/PinMode
So using the internal pull-ups meas you wouldn't need to add any extra components. But a pull-up isn't helpful if you have your switches connected to 5 V because that would make the pin read HIGH whether the switch is opened or closed. So you would need to connect the switches to GND instead. This would mean that the input pin will read HIGH when the switch is open and LOW when the switch is closed.

3) To know if a switch is active do i have to watch for changes on the Pin?

Of course. The easiest way to do this is with digitalRead().
See: https://www.arduino.cc/en/Reference/DigitalRead
You need to make sure your code is non-blocking. When blocking code like delay() is used the microcontroller will not be able to check the state of the input pins and so you could miss touches or have the controller not be responsive enough.

When you're dealing with switches, you need to watch out for 'bounce'. This means that a switch is never perfect and when it changes state from ON to OFF or vice versa, usually there are several fluctuations that take place before the switch settles on a final ON/OFF value.
You could debounce your switches by either hardware or software. If you're debouncing your switches by software basically you run a check on each switch to see if it's digital value has stabilised over some finite time period (usually a few milliseconds) and take action on the switch value only AFTER its value has stabilised.
Hardware debouncing makes use of capacitors in your circuit that prevent high frequency fluctuations in the line from reaching your digital pin. Put simply, the capacitor acts like a channel to 'drain' away variations in voltage. If you are implementing hardware debouncing, you can just do a digitalRead() to read your pin.
http://dduino.blogspot.in/2012/03/arduino-button-debouncing.html

You can also buy ICs that debounce switches.  They are supposed to be for reset switches on microprocessors.

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


text:
Arduino play many piezo at once
I need to play sound on 10 piezos at once. How to do that without delay() function.

You could use the millis() function of your Arduino...

@Fusseldieb post example please

Use the blink-without-delay pattern https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay, a TimeMarker https://github.com/mikaelpatel/Arduino-Timemark or a Scheduler https://github.com/mikaelpatel/Arduino-Scheduler

Use the Timer library.
You can attach up to 10 events to each Timer object you declare. That will suit your use case.

Post a code please.

Why this code not work? `long ids[10];
void playNote(int pin, unsigned long freq) {
int ms = 1000/freq;
ids[pin] = t.oscillate(pin, ms / 2, HIGH);
}
void stopNote(int pin) {
t.stop(ids[pin]);
}`

Post a new question with your full code and not just a snippet, You'll get much better help. I'll also participate.


text:
Battery level indicator
In this arduino project we have 3 Leds that lights up according to the voltage of a battery but when we the voltage read is very close, it results into an uncontrolled switching between  Leds  can any one help me ?
int Batpin = A0;
int Led1  = 12;
int Led2  = 11;
int Led3 = 10;

void setup() {
  // put your setup code here, to run once:
  Serial.begin (9600);
  pinMode(Led1,OUTPUT);
  pinMode(Led2,OUTPUT);
  pinMode(Led3,OUTPUT);

}

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

void volt(){
int sensorVal = analogRead(Batpin);
float voltage = sensorVal * (5.0/1023.0);

 Serial.print(" volt: ");
 Serial.println(voltage);
 if (voltage < 3.80){
     digitalWrite(Led1,HIGH);
  }

   if (voltage > 3.80 && voltage <= 4)
   {
      digitalWrite(Led1,LOW);
      digitalWrite(Led2,HIGH);
   }

   if (voltage > 4)
   {
      digitalWrite(Led1,LOW);
      digitalWrite(Led2,LOW);
      digitalWrite(Led3,HIGH);
   }
   delay (1000);
}

This is an interesting project.  But why stop at adding hysteresis?  After all, you have the flexibility of a micro processor.  Start thinking "out of the box" and make a more useful tool.  What about the battery's internal resistance, its elasticity and how that effects its performance?

You can reduce this effect a bit by using the average of multiple reads. This will give you a more stable value and less hysteresis. You could for example use a rolling average. To absolutely eliminate this proble use majenko's solution.

What you could do with for this is hysteresis.
Instead of simple threshold ranges (0 < A < B < C < 5) you instead need to watch the voltage over time and decide what it is doing compared with what it has done in the past.
You need to keep a record of what state the voltage is in at any one time - That is, is it in band A, B or C in the thresholds above. You then need a second set of thresholds, A1, B1 and C1.
The two thresholds overlap:

If, for example, the voltage rises from between A and B to between B1 and C1 then you switch states to the BC state.
If it falls from between B1 and C1 to between A and B then you switch to the AB state.
Basically, if the voltage rises, it needs to transition between the lower set of thresholds to the upper set of thresholds to register as a change. If it drops it has to transition between the upper set of thresholds and the lower set of thresholds to register as a change.
So, in pseudocode,
if (State == 0A && Voltage > A1 && Voltage < B1)
    State = AB
    Turn on LED 1

if (State == AB && Voltage > B1 && Voltage < C1)
    State = BC
    Turn on LED 2

if (State == BC && Voltage > C1)
    State = C5
    Turn on LED 3

if (State == BC && Voltage < B && Voltage > A)
    State = AB
    Turn on LED 2

if (State == AB && Voltage < A)
    State = 0A
    Turn on LED 1

if (State == C5 && Voltage < C && Voltage > B)
    State = BC
    Turn off all LEDs

It's up to you to decide what a good level of separation is suitable for your system.


text:
Do all arducam need the "Arducam-F Shield"?
The information on this is so greatly lacking to the extent that no related youtube videos could be found, no internet material and the seller seems to be very important and not answer to my questions as he is supposed to.
Also he appears to be the only seller to offer such a variety of arduino cameras.

I want to choose colored arduino camera for my project, but I am unable to receive enough information so that I can choose the appropriate arduino camera.
The most important for me to know is does all arduino cameras need the arducam-f shield board in order to work properly (i.e be programmable, colored, with "decent" quality and be able to capture photos in less than 1~2 seconds)

This is "5MP Mega pixel OV5642 Sensor Camera Module w CS mount Lens" It costs US $29.99. The description doesn't mention the need of any other 3rd party hadware in order to work.

This bellow is "Arducam-F Shield V2 Camera module shield /w OV2640 for Arduino UNO MEGA2560 DUE" it costs US $29.99 and is a camera that evidently comes with this magical shield. We can see that the version is slightly older than that on the other cameras.

This is "2 Mega pixel Camera Module MT9D111 JPEG Out + HQ lens" for US $21.99 and also, like in any other description, the need of shields is not mentioned

And this is "2Megapixel MT9D111 Auto Focus lens camera flex module with Adpater board" that has autofocus, is 2MP like the one above, comes with .... ?Adapter board"? (nothing like that is shown in the pictures or described in the description) and costs only US $9.99. It looks ugly compared to other cameras.

These was the 4 example arduino cameras I would choose from and do all of them need arduino shields in order to do what a camera should do?
(Explaining differences, pros and cons will be very useful to everyone who are in the same boat as I am)

@CodeGorilla Any references/tutorials/examples or items I can buy?
I can surely not learn how to operate with it out of nowhere, I need to start from somewhere. Also how come only lo res images? Only with shields I can do hi res images?

@CodeGorilla Also do you imply that I should choose to buy the arducam-f shield module with its humble camera? Since buying the camera for 10$ won't give me good quality, resolution and speed and I would probably need to spend more money, time and efforts to get it work fine.

The only way to get high Res, good quality, and speed all together is to not use an Arduino with a camera.

@CodeGorilla So with the Arducam-shield I can not make photos every 2 seconds, that will be enough for proving the intruder's identity? (I thought the shield has its own processor and memory)

P.S I also thought arduino uno has 2KB of RAM and 16MHz processor.

@Edenia - I think it would be best if you experimented to see if the hardware works as you want it too.  I'm sorry that I am unable to explain the reasons why I believe you have chosen the wrong solution, again.

For a project I'm doing I added 128 KB SRAM, however, you have to 'manually'  program it (meaning you cannot use easy variables as heap/stack). But for a 1024x768x16 bit pic you need 1,5 MB (uncompressed). You probably can get bigger (S)RAM but that cost either more and uses many more pins, which the Arduino has not that many. And of course there is the speed of 'just 16 MHz' .

You have three requirements:

Good quality (colour)
High resolution
Fast operation

Those three requirements together mean you cannot use a normal Arduino.

The Arduino has nether the memory nor processing power to directly communicate with a camera module.
The ones you can communicate with have internal buffer memory and use a slow UART interface to transfer a frame. That is not fast.
The Arduino cannot deal with a large picture regardless of speed. All you can do is pass the image through to somewhere else for processing. Slowly.

So you can either have very low resolution or slow speed.
So use a Raspberry Pi or something similar which is more capable of using a camera (indeed, the Pi has a dedicated camera connection).

What about the variant with the arducam-f shield?

It doesn't magically make your Arduino more powerful. It's just convenience, but still slow/low resolution.

The "F" version contains a FIFO. You trigger a snapshot and the image is saved in the FIFO. You then download it (slowly) through the Arduino to somewhere else (SD card, etc). You can't process it in any way.

Let's say I don't want to process the photo, but to send it via gps module

How do you send through GPS...?

GPRS* The shield provides GPRS connectivity.

Then you don't care about speed that much anyway a nice the GPRS will slow you down. I do that very same thing in a project. Takes about 20 seconds to send a frame.

I will dig info about TTL Serial Camera.. see if it can make photos fast enough.
From what I saw it is possible to have camera make JPEG photos and save them to memory stick for 1 second with acceptable quality and not so good resolution.

Then I will use MMS or hard compression and I will buffer the images. See if I can make them uploaded for 10 seconds or so


text:
Encrypting data for webserver
I'd like to send sensor values over ethernet shield to a webserver. But for this I'd like to encrypt the data on the arduino and decrypt it on the webserver (PHP).
Do you have any suggestions or examples?

XTEA is probably your best bet.  It's lightweight, easy to implement, and secure enough for a bit of sensor data...

https://en.wikipedia.org/wiki/XTEA

There's also the slightly more complex, and also slightly more secure, XXTEA:

https://en.wikipedia.org/wiki/XXTEA


text:
4 IR sensors on Arduino pro micro. 2 are working other aren't
#include <Keyboard.h>
int IRpin = 5;
int IRpin2 = 6;
int IRpin3 = 8;
int IRpin4 = 9;
int led = 13;

void setup() {
  Serial.begin(9600);
  //start the serial port
  Keyboard.begin();
  pinMode(led, OUTPUT);
  digitalWrite(led, LOW);
}

void loop() {
  float volts = analogRead(IRpin);
  Serial.println("volts1:");
  Serial.println(volts);
  delay(1000);
  if (volts>500.00){
    Keyboard.press(KEY_RIGHT_ARROW);
    Keyboard.releaseAll();
  }
  float voltss = analogRead(IRpin2);
  Serial.println("volts2:");
  Serial.println(voltss);
  delay(1000);
  if (voltss>600.00){
    Keyboard.press(KEY_LEFT_ARROW);
    Keyboard.releaseAll();
  }
  float voltsss = analogRead(IRpin3);
  Serial.println("volts3:");
  Serial.println(voltsss);
  delay(1000);
  if (voltsss > 500.00) {
    Keyboard.press(KEY_UP_ARROW);
    Keyboard.releaseAll();
  }
  float voltssss = analogRead(IRpin4);
  Serial.println("volts4:");
  Serial.println(voltssss);
  delay(500);
  if (voltssss > 600.00) {
    Keyboard.press(KEY_DOWN_ARROW);
    Keyboard.releaseAll();
  }
}

I connected 4 IR infrared sensors to Pro micro and only 2 of them are working. The other 2 are sending random values.
Connection for all 4 IR sensors.:
IR VCC->Arduino VCC
IR GND -> Arduino GND
Output-> 5,6,8,9

What is your question?

Pin 5 is not analog pins.
On the pro-micro only pins A0-5 and D4, D6, D8-10, D12 can convert an analog voltage to a value.
Just use the A0-5 pins instead, as that will work on any Arduino.


text:
How to prevent shoot-through when swiching a motor with a bridge?
Ideally, when wiring a motor with an H-Bridge one would ensure that all "open" operations are performed before and "close" operations in order to prevent a short circuit. How does one ensure that these operations are performed in order when using a bridge?
I see on some forums that the L298 IC is a recommended bridge for controlling motors with the Arduino, but this condition is seemingly never discussed. It is not an issue with the speed of modern ICs or are the common tutorials overlooking shoot-through in the interest of simplicity?

It's only an issue with discreet components when driving each part separately and manually. It's not an issue with a dedicated bridge chip.

Shoot through may be desirable when the H-bridge is fed from a constant current source to prevent interruption of that source. Does L298N allow this?

You only get this kind of problem when you are manually controlling the high- and low-side switches manually.  Bridge chips seldom make you do that and include the logic and drive circuitry within them so that you just control a HIGH or LOW to a "leg" and it switches the two transistors properly for you.
You normally get an "enable" and a "direction" input.
For instance, take the L298 internal circuit:

If we look at the left-most transistor pair you can see they are driven by a pair of gates. One has an inversion on the input.  The gates are mainly there to AND the enable signal in, but the inversion on the upper input of the lower gate is the vital thing. That makes sure that one transistor is on when another is off. You can't turn both on, or both off - you only have a single signal that indicates which should be on.
Of course, that circuit is very simplified, and there is additional circuitry that ensures that during the switching period one transistor switches off before the other switches on.  Matched transistors with known switching characteristics, adding offsets to the base voltages with diodes, etc are all methods that are used internally.
With MOSFET based bridges it's less of an issue since gate threshold (VGS) come into play and choosing and matching the transistors correctly automatically creates a "dead zone" in the switching input voltage range.

Thank you, examining the internal wiring diagram is helpful.

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


text:
Multiple definitions of "xxxx"
I really need your help. I use VisualStudio and PlatformIo I still get this error:

Linking .pioenvs\esp12e\firmware.elf
  .pioenvs\esp12e\src\main.cpp.o:(.data.DebugX+0x0): multiple definition of `DebugX'
  .pioenvs\esp12e\src\customFunctions.cpp.o:(.data.DebugX+0x0): first defined here
  collect2.exe: error: ld returned 1 exit status
  *** [.pioenvs\esp12e\firmware.elf] Error 1

I use header guards in my file, so I do not understand why is this part of code redeclared. I had to miss some elementary in cpp programming but I still can't get it to work.
Copy of my project:
https://bitbucket.org/fires/programingtesting/src/master/ESP8266/cpp/RedefinedError/
main.cpp
    #include <Arduino.h>;
    #include "../include/defines.h"
    //#include "../include/customFunctions.h"
    // Time
    uint32_t mTimeToSec = 0;
    uint32_t mTimeSeconds = 0;
    void setup() {
    etc. etc. etc.

customFunction.h
    #pragma once
    #ifndef CUSTOMFUNCTIONS_H
    #define CUSTOMFUNCTIONS_H
    void connectWiFi();
    void initializeOTA();
    #endif

defines.h
    #pragma once
    #ifndef DEFINES_H
    #define DEFINES_H
    #include <jled.h>
    #define BowlingLed 5
    #define StatekLed 4
    int DebugX = 1;
    #endif

Thanks for the help, I read many articles and many issues but I still do not understand why DebugX is redefined if it is in header guard.

In the file defines.h, you declare an integer DebugX. It is not a good idea to declare an integer in a *.h file. The compiler somehow sees two declarations of DebugX. There are no strange characters and there is no typo error. It works in the arduino ide without the pragma. Perhaps the pragma works against the header guard for that specific ide.

Included files are included before compilation, really replacing the #include with the content of the file.
If you write int DebugX = 1; you define a variable. And it is defined in every source file which includes it. Then the linker finds it in more then one unit and ends with "multiple definitions" error.
The variable must be defined only in one compilation unit (.c, .cpp). For example in your case customFunctions.cpp. To make it available in other source files put extern int DebugX; into the .h file.

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


text:
Optimizing an Arduino code
I am working on project and using Arduino Pro Mini (Atmega328p running on 2xAA) to measure the time to charge a capacitor (when the volt level is high). This is the code I used while testing:
int counter = 0;

// Charge the capacitor
digitalWrite(8,HIGH);

while (digitalRead(7) == LOW) {
    counter = counter +1;
    if (counter > 250) {
        break; // CHARGING FAILED!
    }
}

The code was working fine when the board was running at 16MHz since the loop was fast enough to give good result. ( counter =~ 28 when the test cap is charged).
However, the intention is to run the system on a battery with clock of 1MHz (to reduce power consumption) and when tested at that speed the counter only reaches 2~3 because the loop it too slow now that the cap will charge in about two to three cycles.
So I did two changes which are using byte instead of int for the counter, and reading the value of the pin directly from the PIND register:
byte counter = 0;

// Charge the capacitor
digitalWrite(8,HIGH);

while ((PIND & (1<<PD7)) == 0) {
    counter = counter +1;
    if (counter > 250) {
        break; // CHARGING FAILED!
    }
}

Both of these changes increased the speed and now counter reads ~20 which is much better and almost close to the 16MHz.
Is there any further optimizations?
Can I use one of the general registers instead of the counter, if yes then how? and will that improve the speed?
Is there a more clever and faster way to do this loop?

Update:

I am going to follow the suggested answer and use the analog comparator, but I also wanted to add to my finding which might help others with general optimization.
Instead of incrementing the counter and comparing if it is larger than some value, it is faster to decrements and compare if it is equal to zero. The counter improved to ~23.

You can change the CPU clock prescaler in software, so you can make the CPU run at 1MHz most of of the time, but increase it to 16MHz during measurements.

the intention is to run the system on a battery with clock of 1MHz (to reduce power consumption) - however it takes longer to do whatever-it-is you are doing. I have a page about minimizing power usage which you may find helpful.

Actually your page is what I used when doing my power optimizations. But the reason I switched to 1MHz is because I do a lot of slow UART with long delays, so I think instead of wasting 16MHz on no-op i will put it into saving energy.

Also the multi-meter I have (FLUKE 179) is not good enough to measure low values in mA and for some unknown reason it damaged two atmega328p chip when i tried to program them using USBasp while the ammeter was connected in series with the power! I didn't think it was the cause at first, but after the second one died in the same way I started to believe!

I haven't confirmed this on the Atmel processor but most processor have a decrement and jump if zero/not zero machine code instructions. This will typically be much faster than an increment, compare and jump if greater than/less than. I suspect this is why your optimization worked.

@linhartr22 that is true, I found that info in a website about avr assembly optimization.

It looks like Ignacio Vazquez-Abrams and I have been doing similar things. :)
I have a page about making a capacitor tester:
Turn your Arduino into a capacitor tester
However since link-only replies are frowned on (the link might go down) I'll summarize it here.
The simple approach is to charge the capacitor until it reaches 63.2% of the charging voltage.
That is because:
1 - e^(-1) = 0.63212

See RC Time constant - Wikipedia.
We can use the Analog Comparator to trigger an interrupt when the voltage reaches that level.
We need the capacitor to be on pin D6 on the Uno and a reference voltage on pin D7.
See Using the Arduino Analog Comparator for more details about the Analog Comparator.
This is much faster than using analogRead, because it triggers on an exact voltage.
Your basic objective is to find how long it takes to reach 63.2% of the supplied voltage (in the example being 1 volt):

In this particular example it took 47 µs for a 47 nF capacitor:

Instead of using an exact reference voltage (ie. 63.2% of 5 volts) you can do some fancy maths instead. Here is my test circuit:

DUT = Device Under Test
We plug the values of the resistors into the code like this:
const float Rc = 10000;    // charging resistor
const float R1 = 1000;     // between ground and D7
const float R2 = 1800;     // between +5V and D7
const float clockRate_us = 16;  // 16 MHz
const float k = 1000 / (clockRate_us * Rc * log ((R1 + R2) / R2));

Note: For high accuracy you should use the measured resistance values, not just the nominal ones.

Now with some fairly simple code we can use the constant k to work out the capacitance:
/*
Capacitance meter

Author: Nick Gammon
Date:   2 July 2013

Pulse pin (D2): Connect to capacitor via 10K resistor (Rc)

Reference voltage connected to D7 (AIN1) as per below.

Measure pin (D6 - AIN0) connected to first leg of capacitor, other leg connected to Gnd.

Like this:

Capacitor to test:

D2  ----> Rc ----> D6 ----> capacitor_under_test ----> Gnd

Reference voltage:

+5V ----> R2 ---> D7 ---> R1 ----> Gnd

*/

const byte pulsePin = 2;   // the pin used to pulse the capacitor
const float Rc = 10000;    // charging resistor
const float R1 = 1000;     // between ground and D7
const float R2 = 1800;     // between +5V and D7
const float clockRate_us = 16;  // 16 MHz

const float k = 1000 / (clockRate_us * Rc * log ((R1 + R2) / R2));

volatile boolean triggered;
volatile boolean active;

volatile unsigned long timerCounts;
volatile unsigned long overflowCount;

ISR (TIMER1_OVF_vect)
{
  ++overflowCount;               // count number of Counter 1 overflows
}  // end of TIMER1_OVF_vect

ISR (TIMER1_CAPT_vect)
  {
  // grab counter value before it changes any more
  unsigned int timer1CounterValue;
  timer1CounterValue = ICR1;  // see datasheet, page 117 (accessing 16-bit registers)
  unsigned long overflowCopy = overflowCount;

  if (active)
    {
    // if just missed an overflow
    if ((TIFR1 & bit (TOV1)) && timer1CounterValue < 0x7FFF)
      overflowCopy++;
    // calculate total count
    timerCounts = (overflowCopy << 16) + timer1CounterValue;  // each overflow is 65536 more
    triggered = true;
    digitalWrite (pulsePin, LOW);  // start discharging capacitor
    TCCR1B = 0;    // stop the timer
    }  // end if active
  }  // end of TIMER1_CAPT_vect

void setup ()
  {
  pinMode (pulsePin, OUTPUT);
  digitalWrite (pulsePin, LOW);

  Serial.begin (115200);
  Serial.println ("Started.");
  ADCSRB = 0;           // (Disable) ACME: Analog Comparator Multiplexer Enable
  ACSR = bit (ACIC);    // Analog Comparator Input Capture Enable
  DIDR1 |= bit (AIN1D) | bit (AIN0D); // Disable digital buffer on comparator inputs
  PRR = 0;
  }  // end of setup

void startTiming ()
  {
  active = true;
  triggered = false;
  noInterrupts ();

  // prepare timer
  overflowCount = 0;            // no overflows yet
  // reset Timer 1
  TCCR1A = 0;
  TCCR1B = 0;
  TCNT1 = 0;      // Counter to zero
  // Timer 1 - counts clock pulses
  TIMSK1 = bit (TOIE1) | bit (ICIE1);   // interrupt on Timer 1 overflow and input capture

  // get on with it
  digitalWrite (pulsePin, HIGH);  // start charging capacitor
  // start Timer 1, no prescaler
  TCCR1B =  bit (CS10) | bit (ICES1);  // plus Input Capture Edge Select
  interrupts ();

  } // end of startTiming

void finishTiming ()
  {
  active = false;
  Serial.print ("Capacitance = ");
  float capacitance = (float) timerCounts * k;
  Serial.print (capacitance);
  Serial.println (" nF");
  triggered = false;
  delay (3000);
  }  // end of finishTiming

void loop ()
  {
  // start another test?
  if (!active)
    startTiming ();

  // if the ISR noted the time interval is up, display results
  if (active && triggered)
    finishTiming ();

  }  // end of loop

For extra accuracy the code uses the Input Capture Unit, which is something that remembers the exact value in Timer 1 when the match occurs. This avoids the delay of 2 to 3 µs while the ISR kicks into action.

Results
I measured a few values using a capacitance-substitution box. To check on the box I measured also with a high-precision multimeter. The value on the right is what the sketch gave (rounded).
(All values in nF)
Nominal    Meter     Sketch
Value      Measure   Measure

    40         42        42
   100         98       102
   200        202       201
   300        312       313
   400        389       391
  1000       1004      1010
  2000       2011      2012
  3000       2950      2953
  4000       4160      4170

The sketch output certainly seems to be close to the nominal and measured values.

What about using the internal voltage reference (1.1v) instead of AIN0? which one will be better as the 2xAA batteries voltage drops over time?

The voltage doesn't matter as it is not in the equation. It is the ratio that matters, and that will scale with battery drop (ie. the ratio between the two resistors will always be the same).
You need to use Vcc because it is turned on and off at an output pin (to start charging the capacitor).

Also what is the difference between TIMER1_CAPT_vect which you used here and ANALOG_COMP_vect which you used in the example in your site?

If you are not using the Input Capture Unit, then you need to get the Analog Comparator interrupt. However if you use the Input Capture Unit then you use the Timer1 Capture Event which is triggered when you get the capture.

Nice! Given the level of accuracy this approach could potentially shoot for, I'd also suggest measuring the actual resistance of Rc, R1, R2 rather than using the nominal values

Thank you Nick, I just leaned about the analog comparator from you. If I want to monitor 2 caps (1 is used as reference to tackle changes in temp and other effects) and by looking at the datasheet it seems that I can use the analog inputs instead of AIN1 by changing ADEN and ADMUX, will that work? any side effects?

I'd also suggest measuring the actual resistance of Rc, R1, R2 rather than using the nominal values - I'll amend that just to make sure readers realize that should be done.

it seems that I can use the analog inputs instead of AIN1 - that should work. Make sure you turn the ADC off as mentioned in the datasheet. I don't see what could go wrong. :)

What about using the internal voltage reference (1.1v) instead of AIN0? which one will be better as the 2xAA batteries voltage drops over time?

Also what is the difference between TIMER1_CAPT_vect which you used here and ANALOG_COMP_vect which you used in the example in your site? the datasheet didn't explain: "The comparator’s output can be set to trigger the Timer/Counter1 Input Capture function. In addition, the comparator can trigger a separate interrupt, exclusive to the Analog Comparator."

See amended reply.

Get rid of the loop altogether. Instead of twiddling and checking bits manually, use timer 1 to trigger the output and capture the input.
If you perform the output on pin 10 and the input on pin 8 then you can use timer 1's output compare to send the pulse out and its input capture to detect when the capacitor has charged.
Untested:
#include <avr/interrupt.h>

void setup(void)
{
  cli();
  DDRB |= _BV(PB2); // Configure OC1B as output
  TCCR1B &= ~(_BV(CS12) | _BV(CS11) | _BV(CS10)); // Stop timer 1
  TCNT1 = 0; // Initialize timer count
  OCR1A = 0xffff; // Reset the timer at this count
  OCR1B = 0xf000; // Upper limit of the timed value, plenty of time before timer reset
  ICR1 = 0xff00; // Set to an invalid initial value
  TCCR1A = _BV(COM1B1); // Trigger output at 0, clear at upper limit
  TCCR1B = _BV(ICES1); // Capture on leading edge
  TCCR1B |= _BV(WGM13) | _BV(WGM12); // High bits for 16-bit fast PWM
  TCCR1A |= _BV(WGM11) | _BV(WGM10); // Low bits for 16-bit fast PWM
  TIMSK = _BV(ICIE1) | _BV(OCIE1B); // Enable input capture and limit interrupts
  sei();
  TCCR1B |= _BV(CS10); // Start the timer at its highest clock speed
}

ISR(TIMER1_CAPT_vect)
{
  TIMSK &= ~(_BV(ICIE1) | _BV(OCIE1B)); // Disable input and limit interrupts
  TCCR1B &= ~(_BV(CS12) | _BV(CS11) | _BV(CS10)); // Stop the timer
  PORTB &= ~_BV(PB2); // Kill the charging output
  // Check ICR1 for the captured value
}

ISR(TIMER1_COMPB_vect)
{
  if (ICR1 == 0xff00)
  {
    // WELL CRAP, charging is taking too long
    // Maybe try with a slower clock?
  }
}

void loop()
{
  // Do other stuff
}


text:
Send Color value from Processing into Arduino
I know this has been asked before, but I'm new to Arduino and Processing, and I'm trying to take this step by step.
I would like to pass an RGB value from processing, into Arduino via the Serial.Write/Read.
I have my Processing as:
void draw(){

  //orange colour in RGB values
  color _rgbColor = color(255, 40, 0);

  //convert colour into hex
  String _hexColor = hex(_rgbColor, 6);

  //convert colour into binary
  String _binaryColor = binary(_rgbColor);

  //pass colour to port
  myPort.write(_hexColor);
  delay(500);
}

I assume I can just pass the HEX value straight across, right?
First problem I get is that I can't debug what my Arduino device is getting (when I run the Processing program, the Serial Monitor wont work. Seems like I can only use one or the other). I can print the myPort.read within my Processing after the delay, and I get:

-1

So I'm not quite sure what I'm doing wrong there.
On the Arduino side, I'm using Serial.read() to retrieve the Serial data, which I assume will all be broken down into bytes, so I need to then convert it into a HEX formate, right?
----- Update -----
I now know that I need to break down my color variable into a char-message. I'm guessing I can do something like this then, for example: And then on the other side (Arduino), I need to rebuild the message, right?
if(mousePressed == true){
    //Red
     myPort.write('2');
     myPort.write('5');
     myPort.write('5');
     myPort.write(',');

     //Green
     myPort.write('0');
     myPort.write('3');
     myPort.write('0');
     myPort.write(',');

     //Blue
     myPort.write('0');
     myPort.write('0');
     myPort.write('0');
     myPort.write('\n');
  }

My Arduino script is as follows, is this an okay route to go down?
String message;
void loop() {

  int _size = Serial.available();

  if(_size > 0){

    char value = Serial.read();
    message += value;

    //full message received (255,255,255)
    if(message.length() == 11){
      String _red = message.substring(0,3);
      String _green = message.substring(4,7);
      String _blue = message.substring(8,11);
      Serial.println("R:" + _red + " G:" + _green + " B:" + _blue);

      //apply to light system
      setColour(_red.toInt(), _green.toInt(), _blue.toInt());

      //clear buffer
      message = "";
      Serial.flush();
    }
  }
}

You should digest this first: https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/

Also you should understand exactly how the UART protocol (RS-232) works.

Surely someone, somewhere has already made a defined script for this? To simply pass a colour variable to the Serial?

Many people have, yes. It is a simple enough operation once you understand how a UART works that it becomes a non-entity and you don't need to really worry about finding special code for it.

The simplest way is to print the three colour values as a comma-separated line, maybe with a prefix character to indicate the start (C23,49,119\n for example). Then it is a case of reading that string and interpreting it properly.

Okay yes, I now understand that the serial reads one character at a time, thus I need to break down the 'color' to something like '225,40,0\n'. And then rebuild it once received all.

Yep, you got it. I think processing's Serial.write() just sends one character, so the lowest 8 bits of your HEX colour. You need to print it in such a way that the whole of the data is there, and that takes multiple characters. ASCII is a simple way of doing it, though not very efficient. Quick and dirty is all you need for this though really.

It also means you can test it easily with the Arduino serial monitor directly without needing your processing program - great for getting the Arduino code right first.

I've updated my question, does that now make sense? Am I heading in the right direction?

You can probably compress it down using myPort.print("255,030,000\n"); or even myPort.print(red); myPort.print(green); myPort.println(blue); where red, green and blue, are integer variables.

You need some sort of delimiter or you won't know where one number ends and the next one starts.

@NickGammon Hello, what do you mean? Surely when the current number ends, and the next on starts is when the next Serial.read comes in?

Updated my question.

I was commenting on @Majenko's comment. Doing a "print" on its own is likely to suppress leading zeroes, so you won't be able to tell the difference of 142 being 1 followed by 42, or 14 followed by 2.

Oops, forgot to add myPort.print(","); in between them. My bad.

As for Serial reads, Serial is a streaming protocol. You don't "read a number" you read a byte. You have no way of knowing when a "number" ends except for the passage of time, fixed length numbers, or finding some delimiter (usually the delimiter would be a "not number").

I knew Majenko would realize that, I added the comment for the benefit of others reading these comments. :)

Being Java, in processing you could also: myPort.println(String.format("%d,%d,%d", red, green, blue));

@Majenko Thanks for that reply - but could you elaborate, what does that exactly do differently? '%d'

%d indicates the presence of an integer in the output string. It formats the string with three numbers from variables with commas between them then outputs it. No messing around with multiple prints.

I know I'm late, but actually got a working solution, when I was working out a solution for this.
Code in Processing assuming variable myPort is handled in setup():
void draw() {
    int r = 255;
    int g = 123;
    int b = 2;
    myPort.write('S'); // tell the arduino to do something with leds
    myPort.write(r);
    myPort.write(g);
    myPort.write(b);
}

Code for Arduino loop:
void loop() {
  int r;
  int g;
  int b;
  if(Serial.available()) {
    if(Serial.read() == 'S') {
      while(!Serial.available()){}
      r = Serial.read();
      while(!Serial.available()){}
      g = Serial.read();
      while(!Serial.available()){}
      b = Serial.read();
    }
    delay(10); // some recovery time, not sure if nessecary

    // do something with rgb values
  }
}

This works for me with every possible RGB range. It's not the most elegant solution, but by far better then converting between strings/chars and ints with different bit counts on different devices.

002 is an octal number. In this case it's still 2, but 020 would be 16. Don't use leading zeros, unless you actually want octal numbers.

you're right, I wrote this on the fly!

Add print(_hexColor); to you processing sketch. The value it's sending should appear in the Processing Console (at the bottom)


text:
Can't open "COM1" on Linux with Trinket Pro
At work, on a Ubuntu 14.04 system, I can access my Trinket Pro without any difficulty whatsoever.
At home, using either Linux Mint or Ubuntu across two laptops, I can not communicate with the device no matter what I try.
I have the correct board selected, the correct processor, and trying to use USBTiny ISP.
Currently, I'm getting:
avrdude: ser_open(): can't open device "COM1": No such file or directory
An error occurred while uploading the sketch

It's really getting frustrating having to take my devices to work just to upload a sketch, and I've been banging my head for over a week and a half. My UNO R3 boards work without issue on the same laptops.
Here's what dmesg says:
[  863.471315] usb 1-1.1: Product: USBtiny
[  863.471316] usb 1-1.1: Manufacturer: Adafruit
[  876.438778] usb 1-1.1: USB disconnect, device number 12
[  880.921492] usb 2-1: new low-speed USB device number 5 using xhci_hcd
[  881.092152] usb 2-1: New USB device found, idVendor=1781, idProduct=0c9f
[  881.092157] usb 2-1: New USB device strings: Mfr=1, Product=2, SerialNumber=0
[  881.092161] usb 2-1: Product: USBtiny
[  881.092163] usb 2-1: Manufacturer: Adafruit
[ 1004.305143] usb 2-1: USB disconnect, device number 5
[ 1019.935505] usb 2-1: new low-speed USB device number 6 using xhci_hcd
[ 1020.106524] usb 2-1: New USB device found, idVendor=1781, idProduct=0c9f
[ 1020.106530] usb 2-1: New USB device strings: Mfr=1, Product=2, SerialNumber=0
[ 1020.106533] usb 2-1: Product: USBtiny
[ 1020.106536] usb 2-1: Manufacturer: Adafruit

I am running IDE version 1.8.3, with sudo, the exact same way I'm doing at the office.
Can someone please advise on what I'm missing here? Windows is not an option; I haven't used it in many years. I'd just like to figure out what's wrong.
I do have an FTDI connector, but didn't have much luck with it either, and to be honest, don't want to use it as I just want to plug the Trinket in, and upload.
Update: I've tried both USB2 and USB3 ports repeatedly with the same results.

Linux doesn't have "COM1". Are you sure that's what you're supposed to be using?

I'm not using that. In "Port", I have /dev/ttyS4 and /dev/ttyS5. Selecting either one produces the same error. Technically, the serial port selection should be irrelevant with USBTiny, at least to my understanding.

heh. Upon changing the port from ttyS4 to ttyS5, I now get "programmer is not responding".

There's a clue that you are on the wrong one.  But that it exists.  One thing you know for sure is that unless it shows up in the IDE you can't reach it.  And now you know that tty55 is wrong.  For my systems it is usually something like /dev/ttyUSB0 (Nano) or /dev/ACM0 (Uno)

My point is that with the Trinket, the Port should not matter... ie. at the office, it can be ttyS4, ttyS5 whatever. There is no ttyUSBx at all.

Small update... I connected the Trinket to a Windows Virtualbox VM (guest), and ran into the exact same issue. However, I found somewhere online that said to try Sketch->Upload Using Programmer, and that actually worked. Will try this at home as well.

[  881.092161] usb 2-1: Product: USBtiny
[  881.092163] usb 2-1: Manufacturer: Adafruit
[ 1004.305143] usb 2-1: USB disconnect, device number 5
[ 1019.935505] usb 2-1: new low-speed USB device number 6 using xhci_hcd
[ 1020.106524] usb 2-1: New USB device found, idVendor=1781, idProduct=0c9f

The USB Tiny ISP device which this logs shows being connected to your system is not a USB serial device.  Therefore, it will not have any /dev/ttyXXX device associated with it.  Instead it should be used with the -c usbtiny argument to avrdude.
Adafruit documents their products fairly well, and this is no exception.  The Linux section of the user guide is at https://learn.adafruit.com/usbtinyisp/avrdude#for-linux
That guide goes on to explain that you will typically need to create a udev rule to allow an ordinary user account to access the device.  Depending on Linux installation, typical contents might be
SUBSYSTEM=="usb", SYSFS{idVendor}=="1781", SYSFS{idProduct}=="0c9f", GROUP="users", MODE="0666"

or
SUBSYSTEM=="usb", SYSFS{idVendor}=="1781", SYSFS{idProduct}=="0c9f", GROUP="adm", MODE="0666"

The above linked guide will more comprehensively explain how all of this works.
Note that the above pertains to the USB Tiny ISP programmer shown in your dmesg output.  According to the Adafruit page on the Trinket Pro, the Trinket Pro "bootloader looks just like a USBtinyISP" therefore, you would talk to it in the same way as the USB Tiny ISP that your system reports finding, ie, without using a /dev/ttyXXX device, but rather by specifying -c usbtiny in the avrdude command line, or using an Arduino IDE board configuration which does so.
Your error message suggests that avrdude is not being run with the correct command line options.  You may want to turn on verbose mode to see what is being run - it would especially helpful if you did that on both the working and the non-working Linux systems.

Thanks Chris. I will check what the avrdude upload command is on the home machine tonight. At work, it does get sent in with the -cusbtiny flag. What I meant by the serial port is that I'm aware it's irrelevant in this case, but on the work machine, the Port within the IDE can be set to any ttyS# and this doesn't affect the upload. The only thing I can think of is that at home, for some reason, the -c flag isn't being sent in. After some research, I've found how to upload via the command line, so I'll try that first, then troubleshoot the IDE if necessary.

Also, my understanding was that the udev rules are only necessary for running as a non-root user. That said, I did configure them on both machines in the same fashion already. I'll redo these steps if the steps in my above comment fail to produce positive results.

So, in the end, although Chris' answer didn't directly lead me to the solution, by delving through his links, I eventually ended up at a page that suggested using the Sketch->Upload Using Programmer feature.
That corrected the issue both as root and my normal Linux user account, without any other changes necessary. I find it odd that it isn't required on my work PC, but I digress. It works on both, so I'm pleased.

Sounds like you do not have a valid configuration for a Trinket Pro installed, or at least not selected as the board in use, on your home machine.

It works; I will completely review my setup, but I know for fact that things are the same on both machines IDE-config (UI) wise. There is no doubt. Again, I will review again, but I've been at this for a while. I may just redo everything from scratch to see if I did happen to go wrong somewhere.


text:
Issue programming breadboarded Arduino via FTDI chip
I am trying to upload the Blink sketch to my ATmega chip which is now on a breadboard connected via an FTDI chip.
My clock is running, power is OK. I connected the reset pin via a 100 kohm to the vcc and have a 0.1 uF capacitor between the reset pin and the DTR pin of my FTDI chip.

Connections to the PCB with the FTDI chip:

Does anybody know what I am doing incorrectly?
On a side note, I am running Ubuntu 16.04
All this seems correct to me, yet when I try to program the controller I get this exact:
/home/yalishanda/Downloads/arduino-1.8.5/arduino-builder -dump-prefs -logger=machine -hardware /home/yalishanda        /Downloads/arduino-1.8.5/hardware -tools /home/yalishanda/Downloads/arduino-1.8.5/tools-builder -tools /home/yalishanda    /Downloads/arduino-1.8.5/hardware/tools/avr -built-in-libraries /home/yalishanda/Downloads/arduino-1.8.5/libraries -libraries     /root/Arduino/libraries -fqbn=arduino:avr:uno -ide-version=10805 -build-path /tmp/arduino_build_476404 -warnings=none -build-        cache /tmp/arduino_cache_889393 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.arduinoOTA.path=/home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr -prefs=runtime.tools.avrdude.path=/home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr -prefs=runtime.tools.avr-gcc.path=/home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr -verbose /home/yalishanda/Downloads/arduino-1.8.5/examples/01.Basics/Blink/Blink.ino
/home/yalishanda/Downloads/arduino-1.8.5/arduino-builder -compile -logger=machine -hardware /home/yalishanda/Downloads/arduino-1.8.5/hardware -tools /home/yalishanda/Downloads/arduino-1.8.5/tools-builder -tools /home/yalishanda    /Downloads/arduino-1.8.5/hardware/tools/avr -built-in-libraries /home/yalishanda/Downloads/arduino-1.8.5/libraries -libraries /root/Arduino/libraries -fqbn=arduino:avr:uno -ide-version=10805 -build-path /tmp/arduino_build_476404 -warnings=none -build-cache /tmp/arduino_cache_889393 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.arduinoOTA.path=/home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr -prefs=runtime.tools.avrdude.path=/home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr -prefs=runtime.tools.avr-gcc.path=/home/yalishanda/Downloads/arduino-1.8.5/hardware    /tools/avr -verbose /home/yalishanda/Downloads/arduino-1.8.5/examples/01.Basics/Blink/Blink.ino
Using board 'uno' from platform in folder: /home/yalishanda/Downloads/arduino-1.8.5/hardware/arduino/avr
Using core 'arduino' from platform in folder: /home/yalishanda/Downloads/arduino-1.8.5/hardware/arduino/avr
Detecting libraries used...
"/home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10805 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-I/home/yalishanda/Downloads/arduino-1.8.5/hardware/arduino/avr/cores/arduino" "-I/home/yalishanda/Downloads/arduino-1.8.5/hardware/arduino/avr/variants/standard" "/tmp/arduino_build_476404/sketch/Blink.ino.cpp" -o "/dev/null"
Generating function prototypes...
"/home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10805 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-I/home/yalishanda/Downloads/arduino-1.8.5/hardware/arduino/avr/cores/arduino" "-I/home/yalishanda/Downloads/arduino-1.8.5/hardware/arduino/avr/variants/standard" "/tmp/arduino_build_476404/sketch/Blink.ino.cpp" -o "/tmp/arduino_build_476404/preproc/ctags_target_for_gcc_minus_e.cpp"
"/home/yalishanda/Downloads/arduino-1.8.5/tools-builder/ctags/5.8-arduino11/ctags" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives "/tmp/arduino_build_476404/preproc/ctags_target_for_gcc_minus_e.cpp"
Compiling sketch...
"/home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10805 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-I/home/yalishanda/Downloads/arduino-1.8.5/hardware/arduino/avr/cores/arduino" "-I/home/yalishanda/Downloads/arduino-1.8.5/hardware/arduino/avr/variants/standard" "/tmp/arduino_build_476404/sketch/Blink.ino.cpp" -o "/tmp/arduino_build_476404/sketch/Blink.ino.cpp.o"
Compiling libraries...
Compiling core...
Using previously compiled file: /tmp/arduino_build_476404/core/wiring_pulse.S.o
Using previously compiled file: /tmp/arduino_build_476404/core/WInterrupts.c.o
Using previously compiled file: /tmp/arduino_build_476404/core/hooks.c.o
Using previously compiled file: /tmp/arduino_build_476404/core/wiring.c.o
Using previously compiled file: /tmp/arduino_build_476404/core/wiring_analog.c.o
Using previously compiled file: /tmp/arduino_build_476404/core/wiring_digital.c.o
Using previously compiled file: /tmp/arduino_build_476404/core/wiring_pulse.c.o
Using previously compiled file: /tmp/arduino_build_476404/core/wiring_shift.c.o
Using previously compiled file: /tmp/arduino_build_476404/core/CDC.cpp.o
Using previously compiled file: /tmp/arduino_build_476404/core/HardwareSerial.cpp.o
Using previously compiled file: /tmp/arduino_build_476404/core/HardwareSerial0.cpp.o
Using previously compiled file: /tmp/arduino_build_476404/core/HardwareSerial1.cpp.o
Using previously compiled file: /tmp/arduino_build_476404/core/HardwareSerial2.cpp.o
Using previously compiled file: /tmp/arduino_build_476404/core/HardwareSerial3.cpp.o
Using previously compiled file: /tmp/arduino_build_476404/core/IPAddress.cpp.o
Using previously compiled file: /tmp/arduino_build_476404/core/PluggableUSB.cpp.o
Using previously compiled file: /tmp/arduino_build_476404/core/Print.cpp.o
Using previously compiled file: /tmp/arduino_build_476404/core/Stream.cpp.o
Using previously compiled file: /tmp/arduino_build_476404/core/Tone.cpp.o
Using previously compiled file: /tmp/arduino_build_476404/core/USBCore.cpp.o
Using previously compiled file: /tmp/arduino_build_476404/core/WMath.cpp.o
Using previously compiled file: /tmp/arduino_build_476404/core/WString.cpp.o
Using previously compiled file: /tmp/arduino_build_476404/core/abi.cpp.o
Using previously compiled file: /tmp/arduino_build_476404/core/main.cpp.o
Using previously compiled file: /tmp/arduino_build_476404/core/new.cpp.o
Using previously compiled file: /tmp/arduino_build_476404/core/core.a
Archiving built core (caching) in: /tmp/arduino_cache_889393    /core/core_arduino_avr_uno_fbfa3aa7d5698fed1dc5326dc32eae8f.a
Linking everything together...
"/home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr/bin/avr-gcc" -w -Os -g -flto -fuse-linker-plugin -Wl,--gc-sections -mmcu=atmega328p  -o "/tmp/arduino_build_476404/Blink.ino.elf" "/tmp/arduino_build_476404/sketch/Blink.ino.cpp.o"     "/tmp/arduino_build_476404/core/core.a" "-L/tmp/arduino_build_476404" -lm
"/home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr/bin/avr-objcopy" -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0  "/tmp/arduino_build_476404/Blink.ino.elf"     "/tmp/arduino_build_476404/Blink.ino.eep"
"/home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr/bin/avr-objcopy" -O ihex -R .eeprom      "/tmp/arduino_build_476404/Blink.ino.elf" "/tmp/arduino_build_476404/Blink.ino.hex"
Sketch uses 928 bytes (2%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.

/home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr/bin/avrdude -C/home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr/etc/avrdude.conf -v -patmega328p -cstk500v1 -P/dev/ttyUSB0 -Uflash:w:/tmp/arduino_build_476404/Blink.ino.hex:i

avrdude: Version 6.3, compiled on Jan 17 2017 at 11:00:16
     Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
     Copyright (c) 2007-2014 Joerg Wunsch

     System wide configuration file is "/home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr/etc/avrdude.conf"
     User configuration file is "/home/yalishanda/.avrduderc"
     User configuration file does not exist or is not a regular file, skipping

     Using Port                    : /dev/ttyUSB0
     Using Programmer              : stk500v1
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
...

Start with connecting all power pins. You've left Vcc on pin 20 and GND on pin 22 unconnected.

@KIIV ok, did that although I was not sure whether that was really necessary. Unfortunately it still doesn't work

Why it's showing stk500v1 protocol instead of arduino for the avrdude?

@KIIV I don't know, I chose the following options in the arduino ide: "board: arduino/genuino UNO" "port:/dev/ttyUSB0" "programmer: AVR ISP" isn't that correct?

No, you should just upload the code. Just like it's UNO board.

@KIIV ok, I managed to upload it in a different way (upload it like if it were an arduino rather than going via sketch > upload using programmer): https://paste.ubuntu.com/26432421/
But that still doesn't work

And is that chip extracted from the UNO board or it's a new one (without the arduino bootloader)?

@KIIV it is a new one but it normally already should have a bootloader

@KIIV I can see the DTR line on the ftdi chip being low, for a short period being high and the low again. So I think the DTR line is doing its job. In other words the ATMEGA chip is I think correctly being reset.

Do you have a normal Arduino Uno board? You can swap out the chip there and see if you can program it. The board is guaranteed to have all the connections right. If it still fails, your ATMega328P has not been programmed with the Arduino Bootloader. You'll need another working Arduino or a ICSP programmer for that. Also: https://www.youtube.com/watch?v=5fvdxd0QhTw and https://www.baldengineer.com/diy-arduino-schematic-checklist.html might be good references for you.

@MaximilianGerhardt I can't do that because the arduino uno I have uses a mcu in an smd package not through hole

There are only 3 possibilities: Wrong wireup (use above reference to check that), no bootloader on your chip, or chip is straight out dead. After you compared the wireup, I would still try to burn the Arduino bootloader to the chip. You can't destroy it further with that anyways. Try to follow https://www.youtube.com/watch?v=VX0P8B3pk7g .

@MaximilianGerhardt I am able to get the board info (Tools > get board info). Can I infer from that that the chip is alive and wiring is OK? And I am maybe unable to upload code due to a corrupt bootloader?

if you disconnect the avr chip, do you still get board info? (leave ftdi connected)

@LandonZeKepitelOfGreytBritn How do you know the chip should have a bootloader when new? Did you specifically buy one with a bootloader installed? They don't come from the factory like that.

@Majenko yes I specifically bought one with a bootloader

Right now you don't have a bootloader on your chip that's the reason why it wouldn't be programmed via UART so to flash the bootloader you need an ISCP programmer and an arduino bootloader.hex file.

10K reset pullup.
Check your crystal caps, they should be 22pF.
The response does look like the chip does not have a bootloader tho.
Or Rx & Tx lines are swapped.


text:
Nano-like Board - Programmer Not Responding
I am trying to upload a basic sketch to my unofficial Nano-like board and keep getting this error. I understand that it is a generic connection error between the Arduino and my PC, but can't figure out why it is having this problem.

Semi-compatible nano-like board
Drivers
Arduino IDE 1.8.3 freshly installed
Windows 10 64-bit
Also tried on Mac OSX with the same result

I've looked up the drivers from the manufacturer's website and installed them, and the Arduino Nano shows up just fine under my Device Manager. The green power light comes on, it is recognized by my PC, and blue flashing 'L' light blinks, making me think that the manufacturer had uploaded the Blink sketch to test it. However, when I try to upload a sketch from the IDE I get this error:
avrdude: stk500_recv(): programmer is not responding

Under 'Tools" I have the board set to 'Arduino Nano', the processor set to 'ATmega168' and the port the same COM port as what it's listed as in Device Manager. Assuming that all of those are correct, I have tried a few things with no luck:

Reinstalling the IDE, drivers and restarting my computer.
Letting Windows find its own driver.
Pressing the 'reset' button just before hitting 'upload' in the IDE
Using different micro USB cables and USB ports on my computer.

Any other ideas or is the unit possibly just faulty?
Please note that I have already at similar questions and tried a bunch of their suggestions with no luck.

@user43648 The chip on the board says ATmega168PA, but I have tried both with no luck.

Maybe you have to burn the Arduino Bootloader to it? You would another Arduino (Uno, Nano, whatevere) or a ICSP (in curcuit serial programmer) to do this.

This is a generic message, yes, so there are several possibilities.  1) that port was somehow busy with another program  2) bad cable  3) bad board, or maybe the PC is confused and a reboot will straighten it out.  Presuming you have rebooted then maybe try switching boards and/or cables..

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

That is a Chinese NANO clone, using the notorious CH340G chip.
macOS does NOT have a driver, and it is difficult, if not impossible to get a driver which 1. macOS will let you install, and 2. Actually works.
I do not know the state with current Windows.
In my experience, in addition to poor support the chips are unreliable and fail to respond.
You could try using a Uno as ICSP, bypassing the boot loader, or (untried) use an external USB serial interface. Both of these approaches are documented on the Arduino site.

The official website offers a mac version: http://www.wch.cn/download/CH341SER_MAC_ZIP.html Is that not good enough ? In Windows and linux the CH340G is very reliable.

There was a problem with the official CH340 driver not being compatible with macOS Sierra but I see there was a new official release since that time so hopefully it's fixed. You can also find a fixed unofficial version with a few minutes of searching: CH340 has always worked great for me on Windows. The only problems people have is that the driver isn't included with the Arduino IDE but it only takes a minute to download and install the driver.

For issues like this, you have to narrow down the problems first. For example
is the computer plus programmer combo able to program any avr? If so, the issue us with your target, including wiring.
If not, can the programmer able to program any chip? If so, the issue is with your pc plus programming software.
...
Going backwards and with solid logic, which means making zero assumption, you will narrow the issues down further.

It's a wiring problem (soldering), check by multimeter (continuity mode).
between RST and GND. Then between ICSP pins. you have to get (1) that mean no shorts between the PINS.
Good luck!

No, it's not.  Your post shows a complete disregard for the actual contents of the question.  ICSP is not involved here. Please read more carefully next time!

@Ziad please provide more content to your answers to make them more useful for others with the same problems.


text:
Burning Arduinos one after another
I very accidentally caused a short-circuit to two completely different cheap (under 4$ each) Arduino Uno clones, rendering Windows sound alert for unplugged USB several times.
This subsequently led to a problem with uploading code and not blinking green light on reset on both the Arduinos. Now, I am aware what this means but I am unable to see why this happens. I thought it has protection against that.
Is it normal for them to react like that so easily? How can I prevent this happening AGAIN?

There are companies who sell "ruggedised" Arduino clones that are designed to withstand most bad things you can reasonably do to them without actively trying to break them. One I've had particular luck with is the Ruggeduino. Dunno if that's still sold, but just google it.

DO NOT use the Arduino-UNO tag for other boards, and doubly so when the differences are likely related to the problem.

Which boards? What did you short-circuit exactly? An output pin to ground? See Have I bricked my Arduino Uno? Problems with uploading to board - possibly the board can still be used in some capacity.

Beware there is the danger of frying your computer's usb ports with a short circuit (like I did a few days ago..)

@NickGammon I didn't realise you were on here - the articles on your site taught me a tonne! I should spent some more time here; Arduino + Stack Exchange sounds like heaps of fun! :D

From the title, I was expecting a question about the health & safety hazards of placing dozens of arduinos side-by-side and igniting them like a chain of dominos.

@ChrisStratton we should replace the Uno tag with atmega 328, then.

Stop causing short circuits. Fear the vibrating electrons. It helps if you shock yourself immediately after.

@tuskiomi - no, that would be equally wrong. The problem is with the USB interface, or the power supply, probably not the ATmega328.

@ChrisStratton you and I both know that there is not enough detail in this question do make such deductions.

@tuskiomi - untrue. The windows behavior is cased by a USB chip or power failure, not an ATmega328 failure.  Windows will be quite happy with no ATmega328 even present on the board.  Reality is that the CH340 is notorious for failing in this way, which strongly suggests that is what the poster has - technically not an "uno" clone at all.

@Edenia, It would be useful if you added a link to the exact boards you bought and also posted your schematic.

I thought it has protection against that.

Genuine Arduinos do have some protection, yes.

Is it normal for them to react like that so easily?

Cheap rubbish? Sure. You get what you pay for.

How can I prevent this happening AGAIN..

Buy a real one. Also be more careful.
But at the price you pay for cheap clones, do you really care if they end up broken? You can buy many clones for each genuine one, and while a genuine one may last longer, when you do manage to kill it (they aren't that much more rugged, but some components are more reliable, such as the USB interface chip), which you seem adept at, you would be far more upset than if you'd killed a clone.
So I would suggest invest in one Genuine one for special projects, and to support Arduino (if no one buys Genuine boards there will be no Arduino), and a pile of clones that you can experiment and learn with. Blow them up at will, and when you are happy with your project transfer it over to the genuine board for showing off to people.

I agree, although I think also for learning it might be better to use cheaper ones than burning real ones (although they have more protection). So far I burnt one and that was a genuine one (after putting it in a case and used a 12V adapter).

That is fine if you are going to treat them as a disposable item. Use it a few times and throw it away. Personally I have two Uno R2 boards that I have had for many years and treated them like crud. They will work well.

Actually I do, at least for now, until I'm getting more confidence in my electronics knowledge ... of course I try to be regularly safe. But it's always a trade off - buying a decent product which breaks less often or a 'cheap one' which breaks easily.

Aren't there a little more expensive (say 10$) ones that are more secure. One mentioned Ruggeduino

Ruggeduino is OTT protected (ruggedized) for industrial applications.

I don't think even a supposedly superior "genuine" board would have protection on the I/O pins for instance, at least any of the popular standard ones. At most, they might be using a regulator that has better overcurrent protection. And it shouldn't be too hard to put a better regulator on a cheap Chinese board, and save a lot of money by avoiding boards where the price is 20% substance and 80% brand image.

@MattiVirkkunen The genuine Uno has a decent PTC on it. One has to question the quality (and thus efficacy) of the PTC (if there even is one) on a Chinese clone. Also you only have to cough in the same room as it and the CH340G dies. All adds up to far more fragility than a genuine one - and none of it is to do with the MCU.

This is generally good advice, but keep in mind, there are exceptions. My first Arduino was a Chinese clone (cost about £3 and came with a USB cable too) but it has managed to outlive two genuine ones, even though I usually try risky things on it first.

@AleksandurMurfitt The USB cable on it probably has so little metal in the power wires it acts like a resistor limiting the current and protecting everything ;)

This would be a better answer in the opposite order. Someone who isn't following the basic rules can, and often will, fry a board within 30 seconds of taking it out of the box, no matter how "genuine" it is. There aren't all that many protections in the design — and speaking of regulators, aren't they still using those little SOT-223 ones that get blistering hot when you draw rated current at rated input voltage? There are also clones out there that have noticeably better builds.

I disagree with buying a genuine one. I mean sure if you've got the money, go for it, but unless your goal is to support Arduino, just go to eBay and buy a Chinese-made Arduino. I get mine from eBay. The trick is to find the good ones. Start by limiting the search to your local country and setting Price Low > High. Find the ones with the DIP socket chip as they're usually better-made (not sure why), then find the cheapest one from a reputable seller (I'm in Australia, so I look for sellers that use solid English and take their own photos - my favourite seller is LearCNC, for instance).

@Majenko I've been using clones with CH340G chips for years, am not particularly careful with them, and have never had a related failure. I see several suggestions online that their internal power management is flaky and that they should therefore be used with an external regulator, but checking the clone boards I have that seems to be the way it has been done.  As to the PTC, I'm not sure how to test it, but there definitely is a component labelled as one on the boards I have.  All in all, I've had nothing but good experiences with clone Arduinos, so I'm really not sure what the issue is.

No need to be so racist. I'd rather buy Chinese electronics than Italian electronics - The Chinese knows what they are doing and have a huge industry.

Your comment that you would rather buy Chinese than Italian is racist itself. @Majenko - it might be better to say "cheap clones" rather than insult a particular country.

Sure - a lot of them are coming out of Malaysia and Vietnam now anyway.

Besides, China make all of my PCBs...

Measurements to prevent breaking an Arduino (or AVR in general):
Precautions

Always remove the USB or adapter plug when you make a change in the circuit.
Check all wires before you switch it on.
Remove or make sure (temporary) loose wires/jumpers do not touch other components or the Arduino (better take them out or 'park' them somewhere else in the breadboard.

Preventing wanted changes resulting in shortcuts

Check again the wires/jumpers you just changed/added.
Make sure no other components/wires/jumpers are touching the Arduino or the breadboard (components).
Clean your desk (if you have space), so if something metal falls/moves, it does not hurt your Arduino.
When changing a shield, always check all wiring to and from it, to your Arduino and the components on the shield itself if needed.

Preventing component shortcuts or overpowering

If you have a wire from a pin to GND or a pin to VSS, always make sure there is either a resistor, or you know why a resistor is not needed. This can also damage directly your Arduino.
Make sure that every component does not get more power than it can handle.
More specific: If you have components using 3.3V, make sure they don't get 5V.
If you have components using 3.3V, make sure they don't get 5V.

Preventing too much heat

Do not just put an Arduino in some case/enclosure ... heat may destroy it, so check before there is enough cooling, add a fan, heatsink or make holes in the enclosure.
If you connect any power source other than USB, check again if it does not generate unnecessary much heat. Unused voltage will generate much heat.

Preventing static electricity

Do not touch components when not needed
If you touch components, make sure you are discharged (touch a radiator, use a wrist band, use an ESD mat, touch grounded wire).

Preventing trivial mistakes

Do not keep drinks next to your Arduino or breadboard (or if you, keep it on the other side).
Watch out for heavy cables not dragging your Arduino from the table/desk ... a USB cable can easily drag an Arduino down.
Watch out when you change cables, not to pull your Arduino from the table/desk.
Keep animals (and people too, to your own judgement) away from your electronics project.

I've been very scared when accidentally used a shield while a different-purpose program is loaded in the arduino. Like PWM program on a display or using gsm library incompatible with a gsm module I am using. Can this also be an issue?

Yes I will add it ... if a sketch is putting 0V or 5V on a pin than several things can happen under the chapter Preventing wanted changes resulting in shortcuts

Can't tell if this was intentional, but I like the "two rules of Fight Club" approach to your advice about supplying 5V to 3.3V components.

Always use a series resistor when connecting anything to your IO pins. In many cases you will need one anyway (like driving a LED or a BJT), and in other cases it will not hurt (like driving MOSFET gates or UART lines). A 100 Ohm resistor will limit the current to 50 mA (keeping it within the safe range), while having little effect on your circuit in most cases.

I have used a current limiter (a cheap LM317 will do) occasionally, though even 100mA will burn your devices. It is good practice to limit current.
Generally don't wire a live circuit. Pull caps from the breadboard as well. Eventually you can disregard this, as you become more adept. I burned 4 arduino clones in the first few months.

You can't use an LM317 unless you have a substantially higher voltage power input.  And it won't provide any protection against ESD type damage, which is more likely at issue here.


text:
Only 2 decimal places in printed float
There was a similar thread before but it didn't solve my problem. I had an issue with sending GPS data, which is float, and I couldn't receive the float with the same amount of significant figures as I was sending. I always received a number with 2 digits after a decimal point. So I started debugging and wrote this simple code just to check if floats work as intended:
#include <SoftwareSerial.h>
void setup() {
Serial.begin(9600);
}
void loop() {
float number1;
number1=1.45436;
Serial.print(number1);
delay(200);
}

And the serial monitor showed 1.45 as an output. How can increase the precision of the float I am saving in memory?

It is working , im m looking for adxl335 using as vibretion meter and balancer
Any one have code for ardiuno r3

By default, the Serial print function shows only 2 decimals, however I'm sure the float has the full (unrounded) value, even if it does not show it.
You can read about it in the official documentation here
With the following code you can use more decimals (fragment from the official documentation):
-Serial.println(1.23456, 0) gives "1"
-Serial.println(1.23456, 2) gives "1.23"
-Serial.println(1.23456, 4) gives "1.2346"

Also, probably the next link (PrintFloat) will help:
PrintFloat
It works roughly by iterating through the digits and printing them.

Arduino floats are not particularly accurate.  They have 6-7 significant digits, counting those on both sides of the decimal point.  For higher accuracy a double may be used.

Also note that the Arduino is not really good (i.e. fast) with floats/doubles.

@ChrisStratton Regarding the higher accuracy comment: On Arduino, a double is just another name for float. See: https://www.arduino.cc/reference/en/language/variables/data-types/float/ "Unlike other platforms, where you can get more precision by using a double (e.g. up to 15 digits), on the Arduino, double is the same size as float."

Also String() will do the same thing. It takes a second argument so if the number is a float or a double: String(floatVariable, 3) gives you 1.234.

By default, Serial.print() prints floats with two decimal digits.
float num = 7.875;
Serial.println(num, 4);

will print num with 4 decimal digits, thus: 7.8750.
The precision of float is not decreased in the way you think it decreases. See this answer for a better explanation.

Multiply your float by 10000 (or whatever number you wish), send it as an integer, and convert the received integer back to float.
Alternatively change the library or write your own.

Do you mean change serial library? Besides that, that's what I am doing(multiplying by something etc.). The problem is, it seems arduino does not save the numbers with the precision I give them to it. If what you suggested was to work, first arduino should be able to display the float correctly on the serial monitor. Am I wrong?


text:
mega include a library
This question is a little related to this one: How to compile and upload the specific (.cpp + .h) code?
I've installed MdbBillValidator to my arduino libraries collection. I tried both on ubuntu & windows.
How can I include it? Default inclusion, by arduino ide, was:
#include <MdbSerial.h>
#include <wiring_private.h>
#include <MdbBillValidator.h>
#include <MdbMaster.h>
#include <Arduino.h>

void loop() {

}

void setup() {

}

And here is error comes in:
/home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.cpp: In function ‘void __vector_37()’:
/home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.cpp:289:23: error: ‘TXB8’ was not declared in this scope
       UCSR1B |= (1 << TXB8);
                       ^
/home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.cpp:291:24: error: ‘TXB8’ was not declared in this scope
       UCSR1B &= ~(1 << TXB8);
                        ^
/home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.cpp: In function ‘void __vector_52()’:
/home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.cpp:314:23: error: ‘TXB8’ was not declared in this scope
       UCSR2B |= (1 << TXB8);
                       ^
/home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.cpp:316:24: error: ‘TXB8’ was not declared in this scope
       UCSR2B &= ~(1 << TXB8);
                        ^
/home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.cpp: In function ‘void __vector_55()’:
/home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.cpp:339:23: error: ‘TXB8’ was not declared in this scope
       UCSR3B |= (1 << TXB8);
                       ^
/home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.cpp:341:24: error: ‘TXB8’ was not declared in this scope
       UCSR3B &= ~(1 << TXB8);
                        ^
In file included from /usr/lib/avr/include/avr/iom2560.h:38:0,
                 from /usr/lib/avr/include/avr/io.h:160,
                 from /usr/lib/avr/include/avr/pgmspace.h:88,
                 from /home/asiniy/sketchbook/libraries/MdbBillValidator/Arduino.h:8,
                 from /home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.cpp:31:
/home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.cpp: At global scope:
/home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.cpp:554:135: error: expected ‘)’ before numeric constant
   MdbSerial MdbPort1(&rx_buffer1, &tx_buffer1, &UBRR1H, &UBRR1L, &UCSR1A, &UCSR1B, &UCSR1C, &UDR1, RXEN1, TXEN1, RXCIE1, UDRIE1, U2X1 UCSZ12, UCSZ11, UCSZ10, UPM11, UPM10, UMSEL11, UMSEL10);
                                                                                ^
/home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.cpp:554:189: error: no matching function for call to ‘MdbSerial::MdbSerial(ring_buffer*, ring_buffer*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, int, int, int, int, int, int, int, int, int, int, int)’
   MdbSerial MdbPort1(&rx_buffer1, &tx_buffer1, &UBRR1H, &UBRR1L, &UCSR1A, &UCSR1B, &UCSR1C, &UDR1, RXEN1, TXEN1, RXCIE1, UDRIE1, U2X1 UCSZ12, UCSZ11, UCSZ10, UPM11, UPM10, UMSEL11, UMSEL10);
                                                                                ^
/home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.cpp:554:189: note: candidates are:
/home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.cpp:352:1: note: MdbSerial::MdbSerial(ring_buffer*, ring_buffer*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t)
 MdbSerial::MdbSerial(ring_buffer *rx_buffer, ring_buffer *tx_buffer,
 ^
/home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.cpp:352:1: note:   candidate expects 20 arguments, 19 provided
In file included from /home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.cpp:38:0:
/home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.h:52:7: note: MdbSerial::MdbSerial(const MdbSerial&)
 class MdbSerial
       ^
/home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.h:52:7: note:   candidate expects 1 argument, 19 provided

What I need to do to avoid this error and get the code worked?

Could you try adding this to your program?
#define RXB8 1
#define TXB8 0
#define UPE 2
#define OVR 3
#define FE 4
#define UDRE 5
#define RXC 7

#define FRAMING_ERROR (1<<FE)
#define PARITY_ERROR (1<<UPE)
#define DATA_OVERRUN (1<<OVR)
#define DATA_REGISTER_EMPTY (1<<UDRE)
#define RX_COMPLETE (1<<RXC)

I found someone with similar code, who had these defines and as your code seems to miss/cannot find something, this might fix it.
Though I'm not sure if these defines apply in your specific implementation. For that I should have to see the code where the error is pointing at.

Regards, done compiling! What do you think about it? Why author set these values empty?

He might have had another file, that he didn't upload to github.
You do have an idea of what these values do? Because TXB8 is bit 0 from the register, so instead of using 0, you can use a define or definition, which is easier to understand.
Also, you should check the error message when it won't compile.
error: ‘TXB8’ was not declared in this scope Which mean that the compiler could't find the variable 'TXB8'. So either missing a variable, out of scope, or missing a define ;D And if you look at the code on that position, you should see what is missing there.

I asked him at github about this. In general, this library allows to connect mdb bus with PC through arduino

btw, it's still don't work on windows. I get this: C:\Users\User\Documents\Arduino\libraries\MdbBillValidator\MdbSerial.cpp:554:135: error: expected ')' before numeric constant    MdbSerial MdbPort1(&rx_buffer1, &tx_buffer1, &UBRR1H, &UBRR1L, &UCSR1A, &UCSR1B, &UCSR1C, &UDR1, RXEN1, TXEN1, RXCIE1, UDRIE1, U2X1 UCSZ12, UCSZ11, UCSZ10, UPM11, UPM10, UMSEL11, UMSEL10);

You're sure you have all the RXEN1, TXEN1, RXCIE1, UDRIE1, U2X1 UCSZ12, UCSZ11, UCSZ10, UPM11, UPM10, UMSEL11, UMSEL10 defined or initialized somewhere? And can you see on what character/position on that line the error is?

Thanks for helping, this was a typo: https://github.com/justintconroy/MdbBillValidator/pull/4

Ah I see, yea, it's hard to just see such an error in code you haven't made yourself.
But, the error usually gives a good idea of what is wrong (though it might sound a bit technical) expected ')' before numeric means that it simply didn't expect another numeric to come, thus wanted to close the function call (with a ')') before it could take another numeric. But in this case we didn't need a ')' there but a ','... But that's also why I asked for the position/character on the line.


text:
Send signal to vibrate a Restaurant buzzer via web based app to a PC
I'm new to Arduino, I want to create a restaurant buzzer using Arduino and it should turn on/off via web based interface. It will be locally connected only.
Is it possible to send a signal with the mac address of the master transmitter pc to vibrate the buzzer?
What are the materials should I need? Suggestions or any tips is greatly appreciated.

You need a webserver, a defined interface for the client to connect to and a buzzer you can make some noise with.
Because you want to do it over WIFI, an Arduino is probably not the best choice.  As 'Look Alterno' says you might be better with an ESP8266 based device, because that has inbuilt WIFI.  I would suggest a Wemos D1, its an ESP8266 12 with a power supply and 2.54 pitch connectors, which means its easy to use with things.

Now you can program an ESP8266 using LUA, but I really wouldn't try that. Also if you do that you won't get any help on this forum.  Use the Arduino IDE and program it in the same language as an Arduino (You will need to download support for the ESP via the Board Manager in the IDE).  There is an example called "Advanced Web Server", done by Majenko on here, that will suit your needs.  You just need to change the root handler to activate the buzzer for n seconds and then return HTTP code 200.
Then your client just needs to connect to the root page of the webserver and the buzzer will sound.  You don't say how many clients will use this, but this will allow 5 simultaneous clients, if you need more that can be achieved easily.
You can then expand this to identify which client sounded the buzzer.
As to keeping it local, use the firewall on your router.

I want ESP8266 to connect my web site locally, not to connect in ESP8266. So my PC will act as the webserver and if ES8266 reads something to the code that will send signal to buzz.

OK.  I didn't get that from the question.  Strangely the solution is the same :)  The easiest way of connecting from your PC to the ESP is to use WIFI and run a webserver on the ESP that the PC talks to.  This gets around the 5 connection limit.  You could go to the effort of writing a serial client for your PC that sent the messages when the webserver got a request, but that's not going to be easy.  You are also going to have to write serial code for the ESP to parse the messages.  Its a lot of effort.  Does using WIFI from PC to ESP fit in with your plan?


text:
Writing int/long on Sd card
I'm working on a project with SDcard, and I would like to write int and long in a file.
If I try to write 0x1954 I had 0x5419 on my file with file.write() so I did a circular shifting like:
  data=(data<<8)|(data >> (16-8)); //circular shift
  file.write((char*)&data,sizeof(data));

But with a long, I have 0x54195521 on my file instead of 0x19542155.
So I don't know how to fix this. If you have any idea, I would like to read it ! (Or another way to do it)
Thanks !

Finally, after some searchs on internet, to have the maximum writing speed, I choose to keep the original writing and post-process it in Matlab. Thanks for your help !

Please don't add "thank you" as an answer. Instead, accept the answer that you found most helpful.  - From Review

(Its not circular shifting, its bit shifting, the bits don't go round in a circle they disappear off the end and are lost forever.)
So in the library you are using you are writing bytes to the SD Card.
If you write the data 0x1954 on the card you get 0x5419.
So what is happening is you are writing the least significant byte followed by the most significant.  This is because you have take your int 0x1954 and cast it to a char[2] which contains c[0] = 0x54 and c[1] = 0x19  and then you write that out in the order c[0]c[1] et voila you have reversed you number.
The solution is to reverse the buffer before you write it:
char tmp = buf[0];
buf[0] = buf[1];
buf[1] = tmp;

HOWEVER - If you are only reading and writing from this code, who cares.  As long as you read it in backwards does it matter how it is stored on the SD Card?

I'm not only reading and writing from this code, I will read my file with matlab later

@bouaaah - OK, didn't want you wasting time on it if it didn't matter. :)

Sry i not finished my comment and can't editing it so here is the full comment:
(I don't lost my bits because I'm doing a right shift on MSB and left shift on LSB, so it's like a circular shifting)
I'm not only reading and writing from this code, I will read my file with matlab later.
And if i want to reverse the buffer like you did, it's only 3 lines for a int but for a long it will be 6 lines at least. And i need to be as fast as possible so i prefer to work with bits shifting/masking instead of writing/reading a temp variable.

but if it's the only solution i will do by this way ;)


text:
Can I use an Arduino Uno-style Shield with the Arduino Mega, Tre, or Zero? How about the Intel Edison?
Can I use an Arduino Uno-style Shield with the Arduino Mega, Tre, or Zero? How about the Intel Edison?

Those are two different questions. Please edit one of them out of this post and create a new post with it.

Zero, Mega and Tre all have the same basic pinout layout as Uno, which provides at least physical compatibility for the pins. Sparkfun has a breakout board for the Intel Edison.
Mini, Micro & Nano obviously have a different pin layout. I would consider them mainly for projects that have challenging space requirements, since their main advantage is their small size. The Micro should be the easiest to plug'n'play (native USB COM serial). Nano is still stuck with FTDI drivers, so it's going to require separate drivers from the Uno/Mega family. And finally Mini doesn't have USB at all.
Maybe take a look at Wikipedia list of Arduino boards and compatible systems to evaluate better what suits your needs best.