text:
Arduino I2C long string
I am trying to get 2-Arduinos passing data. The Master will request the data and the Slave send it. But, the length of the string the Slave will send is unknown each cycle.
I found some things here on writing strings with I2C but it seems it is limited to 32 bytes no matter what the Master requests. How can I get the full string sent each time?
Master makes request for string that could be about 180 bytes max - ever.
Wire.requestFrom(8,200);  // I2C-ID = 8, Length = 200
while (Wire.available())
{char c = Wire.read();
cmdInStr.concat(c);
}

Slave sends
int len = cmdOutStr.length()+1;
char ascii_num[len];
for (int i=0; i<len; ++i)
{ Wire.write(ascii_num[i]);
}

You can only send and receive fixed length amounts of data with I2C. The master has to know how much to request from the slave - or the slave to accept from the master.
There's a number of ways around it though:

Splitting / joining.

The trick here is to split the data into packets and re-assemble it at the remote end.
For instance, you split your string into 16-byte chunks. Then you send each chunk separately. Prefixed to each chunk (so the chunk becomes 17 bytes) is a byte telling the remote end how many characters are in this chunk.  Any spare space in a chunk is padded with something (0x00 for instance) so it remains 17 bytes long in total.

two-stage transaction

In this method you first make a transaction which tells the remote end how many characters to receive in the next transaction, or retrieves the number of characters that need to be received from the remote end. The second transaction then receives (or sends) that specific number of characters.
If your strings are longer than the internal I2C buffer (32 bytes) then method 1 is probably the best way.
You can also combine the two methods so both ends know how much to expect to be transferred in total as well as how much of each packet is valid data. The sum of the second should match the first.

I may be being lazy but the data string is passed to other nodes on the network so getting it all the same meant I can manipulate it with common functions in my own project Library file. I wonder if there is a better or different Wire Library. This one shows four functions for directly sending Int/long but no "read" counterpart that I have found.

There is no maximum length for sending/receiving in I2C. It is the Wire library BUFFER_LENGTH 32 macro, causing this limitation.
You can either copy some code from Wire library and implement your own requestFrom function which will store data directly to your cmdInStr string buffer or you can change Wire.h to have bigger BUFFER_LENGTH.
Or another way is to extend Wire.h like this:
#ifndef BUFFER_LENGTH
#define BUFFER_LENGTH 32
#endif

and in your sketch:
#define BUFFER_LENGTH 180
#include <Wire.h>

All depends on your preferences, but implementing own requestFrom and storing it directly into your cmdInStr buffer will be little bit more efficient than copying it into Wire buffer and then into your own buffer again.
And do you really need all these data in one string, isn't it possible to proceed it on the fly?

Thanks before posting, I had tried changing the buffer size in Wire.h file but it had made no difference. I may need to go looking for specific buffer definitions as it seems that the Receive buffer was not set. But, I will try the second suggestion as that might fix it.

Well, there can be more hardware directories. Depends if you've upgraded boards. I've usually editted wrong one...


text:
"avrdude: stk500_recv(): programmer is not responding" when uploading sketch
When I try to upload any sketch to my arduino uno r3, the code compiles, the board resets and the RX light blinks 3 or 4 times.I have nothing from the TX light.
The uploading progress bar in the IDE stucks at it's end for a period and then gives me "avrdude: stk500_recv(): programmer is not responding" 10 times.
I've done the loopback test and it works well so, what should i do ?
thanks for help.

Are you sure avrdude is using the correct baud rate for the bootloader version? Has this board uploaded successfully for you before? Are you using the same avrdude settings you used then? Has any hardware been changed; the cable, for instance? Can you try uploading to another board, or to this board using another computer?

yes, it has worked before. I guess the problem isn't in my PC, I guess it's in the atmega328p-pu chip. uncorrect bootloader or something,,...

yes, it has worked before. ... uncorrect bootloader or something,,...

Does the last program you successfully uploaded write anything to the serial port? If you just run the Arduino (no upload attempt) with the Arduino IDE's serial terminal open, can you see that output? It's pretty hard to damage the boot-loader without actually writing a new, bad one to the chip.
If the current program seems to running but not writing to serial when it should, a likely cause of upload failure is the code in 16U2 processor (or the chip itself) that handles the USB to serial conversion; it's the square 32-pin chip between the 16 MHz crystal and USB connector. Its firmware can be re-loaded - search here for how to do that. If the chip itself is damaged it is probably not worth attempting a repair.
Update: Is the +5v pin on the power header (left edge of the board, if the USB connector is pointing up) reading 5v? You'd expect the output pins to read 0v, 5v, or be noisy if they are floating. A steady 1v sounds strange. At this point it would be worth trying this board on another computer, and another board on your computer, and see which one fails.

No, there's no outputs in the serial monitor and all arduino pins'(2:13) outputs are 1v , which wasn't written in last code. it's like the arduino is completely new

source: Stack Exchange

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

sort: votes


text:
The most effective way to format numbers on Arduino
I made a big search about how to Format Numbers with the Arduino. I want to format unsigned Longs into a String in this format: "23,854,972".
The most of the snippets I found work only with the standard C / C++ Libraries. They dont work on the Arduino until I should put some STL libraries on the Arduino, which I want to prevent. It would be too bit of a overhead to import these only for this task. Also these Libraries will of course use some additional Flash and SRAM.
For my Application it is very important that the solution uses the minimum Flash, SRAM and is fast.
Even if a solution does not use STL or works only with the native Arduino Libraries, I would need help to decide which one is more effective in the sense of speed.
Incoming Number: 23854972
Arduino Program Output: 23,854,972

Have you tried writing a function that does what you're asking?

Here is my try at it: The usual way to write a number in decimal is to
get the digits from right to left with a loop that looks something like
digit = '0' + val % 10;
val /= 10;

The following function does exactly this, with the addition of adding
commas at the correct positions:
/*
 * Format an unsigned long (32 bits) into a string in the format
 * "23,854,972".
 *
 * The provided buffer must be at least 14 bytes long. The number will
 * be right-adjusted in the buffer. Returns a pointer to the first
 * digit.
 */
char *ultoa(unsigned long val, char *s)
{
    char *p = s + 13;
    *p = '\0';
    do {
        if ((p - s) % 4 == 2)
            *--p = ',';
        *--p = '0' + val % 10;
        val /= 10;
    } while (val);
    return p;
}

Note that the string is right adjusted in the buffer, and the unused
characters are not touched. This means you can get a right adjusted
string by:

pre-filling the string with spaces (for padding)
calling the function above
using the original buffer as the right adjusted string

Otherwise you would use the returned pointer to have a string with no
padding.
Here is a simple test program:
unsigned long vals[] = {0, 1, 2, 9, 10, 999, 1000, 0xffffffff};
const int COUNT = sizeof vals / sizeof vals[0];

void setup()
{
    Serial.begin(9600);
    char buffer[14];
    for (int i = 0; i < COUNT; i++) {
        unsigned long val = vals[i];
        Serial.print(val);
        Serial.write('\t');
        Serial.println(ultoa(val, buffer));
    }
}

void loop() {}

The most effective way to format numbers on Arduino

If "effective way" is minimum effort you could hack the avr-libc source code for ltoa and do something like below:
char *ultos_recursive(unsigned long val, char *s, unsigned radix, int pos)
{
  int c;

  if (val >= radix)
    s = ultos_recursive(val / radix, s, radix, pos+1);
  c = val % radix;
  c += (c < 10 ? '0' : 'a' - 10);
  *s++ = c;
  if (pos % 3 == 0) *s++ = ',';
  return s;
}

char *ltos(long val, char *s, int radix)
{
  if (radix < 2 || radix > 36) {
    s[0] = 0;
  } else {
    char *p = s;
    if (radix == 10 && val < 0) {
      val = -val;
      *p++ = '-';
    }
    p = ultos_recursive(val, p, radix, 0) - 1;
    *p = 0;
  }
  return s;
}

void setup()
{
  Serial.begin(9600);
  while (!Serial);

  char buf[32];
  Serial.println(ltos(12345678, buf, 10));
  Serial.println(ltos(-12345678, buf, 10));
}

void loop()
{
}

Gives the output:
12,345,678
-12,345,678

Cheers!
PS: Please see the table driven, non-recursive, number conversion in Cosa (source and benchmark) for a lean and faster implementation.

How would I check which answer/solution gives the faster result? I always print delta-micros() but is there a better way?

The above solution is slow. This is a fast hack to show that you do not need all the libraries mentioned in your original question. See @EdgarBonet's answer for a solution that runs much faster. It can be improved with table lookup to avoid division/modulo. That is what the Cosa version does.

Thank you very much. But how you know if this one or the other one is faster? How to determine it?

Estimate the algorithms complexity and behavior. Read the generated assembly code and calculate the number of clock cycles. Write a test program and verify.

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


text:
Sending LCD commands to a slave micro
I need to split up code which I've already developed for one micro into two different Arduinos connected by serial. The "remote" micro is directly connected to a 20x4 character LCD and the main micro will be sending it a command set to print, move cursor, etc.
My plan was to make functions that used existing code such as
lcd.print("This or that");
to replace the lcd library on the main micro and send command bytes and data bytes up to the remote micro. Seems pretty straightforward.
Then I discovered that apparently lcd.print cannot be a function name. Fine, so I changed it to lcd_print(). So far, so good. But in the existing library, lcd.print accepts strings, bytes, just about anything any length. For example:
lcd_print("any string of any length");
lcd_print(a_2d_array [x] [y]);
lcd_print(this_byte);
lcd_print(this_integer);
Now it's getting over my head. I know I can painstakingly turn a single function into many different functions, but wouldn't it be nice to replicate the functionality of the Arduino LCD library with a single command:
lcd.print();
Then all I have to do is create the function and keep the existing code and send the bytes up to the slave micro. Wouldn't that be nice! I appreciate any thoughts. Thanks.

Just inherit Print class and implement virtual size_t write(uint8_t); and you can use all kinds of print/println that Print implements. See Print Class @arduino.cc.
It implements these methods for you:
size_t print(const __FlashStringHelper *);
size_t print(const String &);
size_t print(const char[]);
size_t print(char);
size_t print(unsigned char, int = DEC);
size_t print(int, int = DEC);
size_t print(unsigned int, int = DEC);
size_t print(long, int = DEC);
size_t print(unsigned long, int = DEC);
size_t print(double, int = 2);
size_t print(const Printable&);

size_t println(const __FlashStringHelper *);
size_t println(const String &s);
size_t println(const char[]);
size_t println(char);
size_t println(unsigned char, int = DEC);
size_t println(int, int = DEC);
size_t println(unsigned int, int = DEC);
size_t println(long, int = DEC);
size_t println(unsigned long, int = DEC);
size_t println(double, int = 2);
size_t println(const Printable&);
size_t println(void);

However you have to implement 2D array print if you really need this, I don't see why do you need it but whatever (you can print each line separately). It just saves you time with implementing everything else.
And for std::ostream like approach I like this (works with anything inherited from Print class):
template <class T> inline Print & operator<<(Print & p, const T & val) {
  p.print(val);
  return p;
}

// ...

void loop() {
  float variableA = 221.23;
  String variableB = "Some string";
  Serial << F("flash string to save some ram: ") << variableA << F(" / ") << variableB << "\n";
}

Then you can implement some commands interface.

Dear KIV: Thank you for your response! I'm afraid I don't know how to "inherit Print class". It's beyond my current programming experience. I often see the "uint8_t" in code I've looked at and puzzled over what it does. I'll try to do some research but would appreciate a jump start!

Dear KIV: Thank you.
Assuming I add this code, would it be in setup?
class lcdclass: public Print
{
public:
virtual size_t write(uint8_t);
};
Given the old lcd command sans library: Will the old command work?
lcd.print(some_crazy_set_of_data);
if I write a function:
void lcd.print()?
Don't know how to pass the many different formats of possible parameters to this function. Maybe cause it's inherited, but please advisee.

That answers it, KIV! Thanks. You're right. Now I have to decide if it's gonna be easier to retain all the lcd.xxx commands in the current code and write new functions, or go through the code line by line and revise it to send serials up to the remote micro. Despite the attraction of the print class it sounds more attractive to me to just revise the code because some of the commands are 2d, some are 1d, etc. and you're absolutely right, eventually it's going to be sent down serial as one byte followed by another!!!

At the remote micro end, it's going to reassemble those bytes into lcd.xxx commands anyway! As the remote is going to use the existing lcd library.

You can find an implementation of this in the Cosa VLCD library. It implements the Cosa LCD interface but uses I2C/TWI as an adapter. The library contains both the application interface and the TWI slave implementation. https://github.com/mikaelpatel/Cosa/blob/master/libraries/VLCD/VLCD.hh


text:
Wiring LED strips in parallel & ground
Schematic:

I am making some light fixtures controlled by an Arduino UNO. Each fixture will host two approx. 1 meter long analog RGB LED strips with a current draw at full power of ~1.2 A per meter. I have a 12 V power supply that I will wire directly to the strips, with the RGB channels wired to the Ardiino PWM pins via NPN MOSFET (note in the schematic I've only shown one color channel for simplicity, but there would of course be three transistors hooked up to three PWM pins). The Arduino itself will be powered by USB.
My main difficulty in wiring the system is that for so much current I need fairly thick wire. The pads on the LED strips are delicate and I have several times damaged them by mechanical stress from the wire while soldering. The thick wire also crowds the narrow space between the pads creating a risk of a short. Therefore my first question is (bear with me, I'm pretty new to this):
1) How should I wire the LED strips?
My thought is to wire up the strips in parallel with thinner, more flexible wires. This brings up two sub-questions:
1a) How should I join the thinner wires to the thick wire coming from the power supply?
1b) At the junction between the wires leaving the lights and running to the transistor, does the wire need to become thick again? (I think the answer is yes – the current should be the same as coming out of the power supply.)
I also am unsure about the ground.
2) Does the wire coming from transistor to ground need to be joined to the ground pin on the Arduino or can it run directly to the ground terminal of the power supply?
Sub-question:
2a) Does the wire coming from transistor to ground need to be thick?
I don't really understand how transistors work (basically my understanding is that the Arduino uses a small amount of current over the PWM pins to somehow control how much current is allowed to flow through the rest of the circuit.
I've drawn a schematic showing how I think maybe this system needs to be wired up. Do I need to make changes?

You need to connect the two grounds. Otherwise there isn't a path for the electrons to flow from to Arduino to the mosfe, and back!

Thank you! No one else has addressed that question yet.

It's all a question of losses.
Wire is basically a resistor. The thinner and longer the wire the higher the resistance. Current flowing through a resistor causes a voltage drop across the resistor.
Long thin wires with large amounts of current through them will basically mean you get less than your 12V at the LED strips. The question has to be: how much less a voltage is tolerable?
Each strip takes 1.2A. Take for example 24AWG wire. That has a resistance of 0.0842Ω per meter. With 1.2A flowing through a meter of that you get 0.10104V dropped across the wire. That turns your 12V into 11.9V.
Conversely, a meter of 14AWG wire has a resistance of 0.00829Ω - so you would lose 0.009948V over that length.
Now you want two strips - which is double the current, and thus double the voltage drop. On 14AWG you would lose about 0.02V over a meter. Not really enough to worry about. But you can't connect 14AWG to the LED strips. You can connect thinner wire (say 24AWG as above) to them. But that looses too much voltage. Well - over a meter it loses too much voltage. But what about over, say, 10cm? That's a 10th the length of before, and so a 10th the voltage loss: 0.01V.
So what is to stop you having a short length of thin wire connected to the LED strips, which then connects to a longer length of thick wire? Answer: absolutely nothing.
And how do you join them together? Well, I find the best way is with solder. Insert the thin wire (stripped) into the end of the fat wire (stripped) and twist them together (axially) then flood the joint with solder.

Is there any heat dissipation risk?

From what ... ?

Resistive/Joule heating in the thin gauge wire.

Not at those lengths / currents. P=I²R = (10cm wire) 1.2²x0.0842 = 0.121W

I think you are overestimating the size of wire required to attach to the LED strips, I have connected a lot of single color LED strip (in excess of 1mtr) with the wire that was already attach and it was reasonably light gauge.
Look at this Example on Ebay and you can see what i mean.
I am note an Electrical Engineer so i don't know the method to calculate the minimum wire gauge, but if in doubt contact the manufacturers and ask them or search on the web.
As for the Transistor mounting/wiring you would mount that on a small circuit board with terminal block fitted for ease. Any power/connecting wire should not be less that used to the LED strip.
Also you will need a current limiting resistor attached to the Base pin on your transistors. You will have to work out the value of that based on the spec sheet.
There is a bit of learning required first, once you have researched the above you will have you exact answers.

For mosfets the base resistor isn't strictly necessary. To calculate the wire gauge you have to measure the resistance. After that combined with the max current you can calculate the voltage drop across the wire, and the power disappated in the wire.

@Gerben It depends on the gate capacitance. Too much gate capacitance can cause too much inrush current which can cause voltage droop on the pin. With big MOSFETs often come big gate thresholds. If the droop drops below the threshold the MOSFET will fail to switch properly and you will get large switching losses. By including a small resistor you limit that inrush current and thus avoid the droop.  I like to include a 100Ω resistor in all my gates to be safe. Yes, it slows down switching slightly, but helps protect the pin from stress.


text:
Servomotor losing its connection right after being connected to Arduino
I am working with two servomotors and both are having the same problem: right after i connect them to the arduino and upload the code, they do as the code says for a really small amount of time (0.1s maybe), and then they simply stop. If i keep connecting and reconnecting it again the servo answer to the code for a really small amount of time and then stop, as I said before.
#include <Servo.h>

#define SERVO 6 // Porta Digital 6 PWM

Servo s; // Variável Servo
int pos; // Posição Servo

void setup ()
{
  s.attach(SERVO);
  Serial.begin(9600);
  s.write(0); // Inicia motor posição zero
}

void loop()
{
  for(pos = 0; pos < 90; pos++)
  {
    s.write(pos);
  delay(15);
  }
delay(1000);
  for(pos = 90; pos >= 0; pos--)
  {
    s.write(pos);
    delay(15);
  }
}

I am using the code above, and it looks totally fine. Does anyone know what might be causing this problem?

In case it's a hardware problem, add a photo of setup + circuit schematic or reference to how you wired stuff up.  Add model numbers of the servos and specs of the power supply that's powering the servos.  Indicate what actually happens, rather than saying "they do as the code says", because nobody but you knows what you think the code does.  Also report results that occur with only one or the other servo attached, and results when you change delay(15) to eg  delay(150)

Your code is correct. Check the following:

Arduino works from 5V, but most servos need 6V.
Even if your servo works from 5V, don't ever connect your servo power directly to Arduino pins. These pins are not able to provide adequate power for servo.
Check that grounds of both power supply for Arduino and power supply for servo are connected together.

would it work if I attach it to a shield, instead of directly in the arduino pin?

it will work only if shield has its own power supply AND is dedicated for providing power its to servo


text:
Faster and lighter approximate timing code without using timer
I want to use loop() iterations counter to execute some tasks periodically or tasks like debouncing. My other sketch is running every loop() at least 20 ms, and if i am using 5 ms time to wait to
debounce a button, it will still be at least 20 ms waiting, also cpu will have to compare two not zero values, which is a bit slower.
I think it is more difficult for cpu than just incrementing and decrementing one variable and comparing it to 0. So i came up with pattern like that:
boolean onOff=1; // arduino led state. My task here is LED blinking.
byte loopCounter=2; // number of iterations made by loop(). Set as little variable as possible to save ram and cpu time.
//Code will be executed every "loopCounter" iteration of loop().
void setup() {
  pinMode(13, OUTPUT);
}

void loop() {
      if (--loopCounter == 0) { //comparing with 0 should be a bit faster and easier for Arduino to process. Correct me if i am wrong.
        loopCounter=2; // That digit sets how often your code will be executed. Every 2(3,4... set your own value) iterations of loop().
        digitalWrite(13, onOff= !onOff); // the task itself.
        }
}

It may be more convenient in some ways than millis() and micros() patterns. Also i do want want to use hardware timers for timing.
It may be convenient in cases, when you don't care when exactly task will be done, you just want it to be done ASAP (as soon as possible), but
not during that particular iteration of loop(). Basicly you can use it as a timer if you know how it takes one iteration to be done.
So, if your sketch runs 1 iteration of loop() for 1 ms, and you need some action to be done every 1 sec, 1ms*1000 == 1 sec. So you
need it to be done every 1000 iterations.

So, is that really can save some ram and cpu time?
Is comparing with zero is faster for arduino than comparing with not
zero?
Are millis() and micros() timing patterns using more operations
(setting value to variable, computing the difference between 2
values and than comparing it to a period you have set) instead of
decrementing and comparing to zero with my pattern?
Any side-effects of using my pattern? I can only think of very
unaccurate timing and delays more than you think if your sketch done
smth more than usual, because of button push for example or some
sensor changed value.
Thank you!

Your use of digitalWrite will be the slow thing there, not comparing to zero, or comparing two numbers. Try looking up the digitalWriteFast library.

To put it another way, you are optimizing the wrong thing. :)

I know about digitalWrite, thank you. But readability is more important for stackoverflow i guess)

millis() is one of the fastest function of the Arduino core. It just returns a copy of a global variable (timer0_millis) which is updated by a timer interrupt. The copy is performed with interrupts disabled in order to avoid a race condition. See the implementation.

I know about digitalWrite, thank you. But readability is more important - what's unreadable about: digitalWriteFast (13, onOff= !onOff);?

Oh, it is perfectly readable, Ijust did not know about it:)  Thank you!

Personally I wouldn't be putting too much effort into optimizing away your timers. millis() is pretty fast - the work needed to calculate the result is done in the background anyway (by interrupts). I tried some test code:
void setup ()
  {
  Serial.begin (115200);
  Serial.println ();

  unsigned long start, finish;

  start = micros ();
  for (byte i = 0; i < 100; i++)
    digitalWrite (13, HIGH);
  finish = micros ();

  Serial.print ("Time taken to do digitalWrites: ");
  Serial.println (finish - start);
  Serial.flush ();

  start = micros ();
  volatile unsigned long now;
  for (byte i = 0; i < 100; i++)
    now = millis ();
  finish = micros ();

  Serial.print ("Time taken to do millis: ");
  Serial.println (finish - start);
  Serial.flush ();

  }  // end of setup

void loop ()
  {

  }  // end of loop

Results:
Time taken to do digitalWrites: 520
Time taken to do millis: 188

You can see that the digitalWrite() (which you weren't worried about) takes 5.2 µs, whereas calling millis() (which you were worried about) takes 1.88 µs.

Are millis() and micros() timing patterns using more operations (setting value to variable, computing the difference between 2 values and than comparing it to a period you have set) instead of decrementing and comparing to zero with my pattern?

Yes, just adding one to a variable and then comparing will be faster. Whether it is worth the effort is debatable.

If 'millis()' is using interrupts, it's benchmarked time will be a bit more, at lest by the time needed to increment variable, starting and stopping an interrupt also takes some time i guess. So thank you very much for telling about interrupts:)

Or did i miss smth about interrupts? One more thing here. I have heard from an experienced programmer, that is is nice to count from 'n' to zero to optimise 'if()', especially in larger loops. Compilers usually do it themselves, but you can never be sure about that. So, it will be done 'for (byte i = 100; i >= 100; i--)' instead of 'for (byte i = 0; i < 100; i++)'. by arduino compiler?

I assume you mean 'for (byte i = 100; i >= 0; i--)'. Here's the flaw. In trying to outguess the compiler and maybe save one machine cycle, you've introduced a bug. The byte type is unsigned, and thus i will always be >= 0. Thus the loop will never terminate.

Well, i can see my mistake. And that is the reason i want to know if compiler can do hard work for me. I need to know should i think about it at all or not. I would find out about my mistake pretty soon in real code i guess, but still it is a loss of time...

Well, compilers are pretty good these days. You can help them out by choosing good data types (for example, byte as you did, rather than unsigned long when you only have to count to 10). I wouldn't be sweating over whether it is faster to count up to 10, or down to zero.


text:
No power_usi_disable() on Arduino Uno
we have an error after compiling the code in arduinouno that is displayed as
error: 'power_usi_disable' was not declared in this scope   in Board: "Arduino/Genuino Uno".how to rectify this error. please reply us fast

The Arduino Uno does not have a USI peripheral. Thus, you cannot disable
the power of the (non-existent) USI, and there is no
power_usi_disable() function.
Solution: remove the call to power_usi_disable() from your code.
Update: To answer your new question in the comment, WDTCR is the
Watchdog Timer Control Register on some AVR chips. On the Uno it is
called WDTCSR, because it is a control and status register.
Looks to me like you have downloaded from somewhere a program you do not
understand. That program was written for an ATtiny chip and you are
trying to compile it as-is for an Arduino Uno, which is based on an
(incompatible) ATmega328P. That's not the way to do it: you have to
understand the program and rewrite all the ATtiny specific stuff to fit
the Uno.

Thank you ,but we have an other error exit status 1
'WDTCR' was not declared in this scope. plz help us

Check the board selection in the Arduino IDE Tools menu. Also please post source code and compiler warnings/errors.

@ppsrc: Se amended answer.


text:
How much time does the Arduino need to call a Function or to read a Variable?
How much time does an Arduino Uno or Mega need to only call a function. And how does the time change if this function is inside a Class, for example inside a Library?
The same thing for a variable. How much time does a micro-controller need to read a declared variable?
How to determine this values? Is there a mathematic formula? Can we predetermine this type of delays and other similar micro-controller related delays?

Is this question really about how to optimize performance for a micro-controller? What are your performance goals? Why not start with high level system optimizations first. They give XN instead of N%.

It is hard to give a general answer, as it depends on the specifics of
your code and on how the compiler compiles it:

How much time does an Arduino Uno or Mega need to only call a function.

This can involve a number of things:

the caller puts the arguments on some predefined CPU registers, unless
they are already there from a previous operation (the compiler tries
to optimize the code so that this happens whenever possible)
the caller issues the call instruction to do the actual function
call
the callee pushes some CPU registers into the stack in order to use
them without clobbering the caller's data
the callee does its job
the callee pops the previously pushed registers
the callee issues the ret (meaning return) instruction
the caller finds the return value in some CPU registers

On the Uno, the call and ret instructions cost 4 CPU cycles
each (0.25 µs). On the Mega, it's 5 cycles (0.3125 µs)
each. push and pop are 2 cycles each, and you need one such
pair for every 8-bit register you need to save.

And how does the time change if this function is inside a Class, for
  example inside a Library?

The only difference is that a class method receives an extra hidden
parameter called this. Except if it's a virtual method, which is more
expensive because it involves some pointer dereferencing.

How much time does a micro-controller need to read a declared
  variable?

“Reading” generally means transferring the contents of the variable to
some CPU registers. Local variable are usually allocated to CPU
registers in the first place, so there is no need to read them. Global
(and local static) variables are stored in RAM, and reading them takes
2 cycles per byte (e.g. 4 cycles for a 16-bit int).

How to determine this values?

Disassemble the code generated by the compiler. Then look up the
instructions in the instruction set manual: it documents the number
of clock cycles needed by each instruction.

Would add that the compiler may inline functions to allow further optimizations. Also the compiler may eliminate a variable if const, reuse value from register, etc. In these cases the time needed is zero or even negative :)

How much time does an Arduino Uno or Mega need to only call a function.

Why do you want to know? This sounds like an X-Y problem.
It will vary, depending on a lot of things.

The number of arguments, because the more arguments the more work involved. Plus if an argument involves copying it might invoke a copy constructor.
Whether or not the compiler in-lines the function. If it is in-lined (copied into the other function) then there is less work, for example the compiler doesn't need to generate call and ret instructions.
What the function does. The more things a function does, the more registers the compiler may have to push and then pop afterwards to save the state of registers which had useful information in them, outside the called function.
The size of the arguments. Longer arguments take longer to copy onto the stack, or put into registers. For example, long arguments will take longer than char arguments.

How much time does a micro-controller need to read a declared variable?

Again, it varies. It depends on the variable size, and whether or not it is already in a register. If the variable happens to be in a register at the time, you could argue it takes zero time to read it.

How to determine this values?

The sensible thing to do is to time some test code. Here's an example from another thread:
void setup ()
  {
  Serial.begin (115200);
  Serial.println ();

  unsigned long start, finish;

  start = micros ();
  for (byte i = 0; i < 100; i++)
    digitalWrite (13, HIGH);
  finish = micros ();

  Serial.print ("Time taken to do digitalWrites: ");
  Serial.println (finish - start);
  Serial.flush ();

  }  // end of setup

void loop ()
  {
  }  // end of loop

In the middle of the code there I time doing digitalWrite 100 times. By dividing the resulting output by 100, I can work out how long each digitalWrite takes.

You don't normally need to know how long, exactly, it takes to read variables, and call functions. Either your code works at an acceptable speed, or it doesn't.
Trying to answer this question on test code may give meaningless results. For example, in my test code the compiler may have in-lined the digitalWrite call. But if I use digitalWrite in many places it will no longer in-line it, which means the timing figures are now incorrect.

The Questions is how much time the millis() and micros() functions need to finish their work, so the measurement is accurate.

If that was what you wanted to know, it would have been better to ask that exact question. That saves us waffling on about copy constructors and so on.
I tested with the code below, which calls micros() and saves the results to a variable foo. I made it volatile so that the compiler wouldn't be tempted to optimize away the saving altogether (because it isn't used anywhere else).
void setup ()
  {
  pinMode (13, OUTPUT);
  PORTB = 0;
  }  // end of setup

volatile unsigned long foo;

void loop ()
  {
  PINB = bit (PB5);   // toggle D13
  foo = micros ();
  PINB = bit (PB5);   // toggle D13
  }  // end of loop

I measured 3.380 µs on my oscilloscope for the time when D13 is high. That would be 54 clock cycles. A couple (only) would be the time taken to toggle D13. Thus you can probably reckon micros() in general as taking 3.38 µs.
Changing it to call millis() instead, it only takes 1.760 µs (28 clock cycles). This is probably because all millis() does is return a variable which has already been calculated (in the timer ISR).
Test done on an Arduino Uno running at 16 MHz.

The Questions is how much time the millis() and micros() functions need to finish their work, so the measurement is accurate.

You don't need to save the return value of micros() to RAM. Doing so takes 8 extra cycles. The compiler can't optimize the call away because it is not aware that micros() has no side effects.

Well, the OP was also asking about time taken to read variables. If I needed to time some thing, I would need to get the start time, save it, and then get the end time, and subtract one from the other.

No need to save to RAM though: if you use local variables, they are likely to be allocated to CPU registers by the compiler. I tried compiling your first example and that is exactly what happened: neither start nor finish were committed to RAM. The overhead of timing the loop was 2 cycles (a couple of movw) + the cost of a call to micros().


text:
How to change Arduino Nano MODEL_ID
I'm working on a project using a set of different Arduino Nano connected to a Raspberry Pi through USB.
Now my question is: "how can I, from the Pi's point of view, differentiate all of those Arduino and associate them with their respective tty?"
I found some part of my answer in this question. The answering guy proposes to manually change the Arduino MODEL_ID when compiling and to use it afterwork to identify the device. The problem is that I don't know how to achieve that.
I tried to edit the boards.txt file to add a new board configuration with custom vid.x and pid.x (why all those 4 different values?) but after selecting my board and uploading, the MODEL_ID still stays the same:
ID_MODEL_FROM_DATABASE=HL-340 USB-Serial adapter
ID_MODEL_ID=7523

Can't I just specify somehow the USB_PID macro to the compiler command line?

That question is about Arduino Micro, which has a ATmega32u4 with USB support. Yours has a ATmega328 with separate USB to serial chip.

How to change Arduino Nano MODEL_ID?

The Arduino Nano used a special USB-Serial adapter (FTDI FT232RL). You can change the ID but this requires some special hacking. Please see the provided links.
Cheers!

OK I see the problem then. Thanks! Unfortunately, the Arduino Nano that I have are chinese clones and so they use the ch341 USB serial driver, rather than the FTDI one. I keep investigating...

BW: Could your sketch on the Arduino Nano identify itself by sending an ID on startup? This would have to be unique for each connected board.

I think this is what I'm going to end with. Because even if I could change the vendor and product ID in the EEPROM, this would make a mess in the drivers that will not be able to recognize my devices anymore. I found an interesting link which propose a simple API to make this as easy as possible :)

Finally find the solution =)
You don't have to change the ID vendor or ID product: it is possible to attribute a permanent name with devpath (where the device is plugged)
The only downside of using the devpath is that the devices will always have to stay plugged into the same physical port.
Answer here:PersistentUSBDevices / Alternative filtering via Devpath

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


text:
Issues graduating to AVR-C
I'm trying to make the transition from coding in the Arduino language to AVR-C, but I'm having some issues with my microcontrollers.
I don't have an ISP, so I'm using one of my Arduino UNOs with the ArduinoISP sketch. The problem is that when I try to run avrdude it gives me this error:
avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.
  Double check connections and try again, or use -F to override
  this check.

However, when I try to run the command with the sugested -F it uploads the code to the Arduino UNO I'm using as an ISP instead of the ATmega328p on my breadboard.
Does anyone have any idea about whats going on here, or how to fix it?

Have you disabled reset on your Arduino?

@Majenko I don't think so, how?

You would know if you had, so you obviously haven't. Add a 10uF capacitor between reset and gnd on the Arduino.

will a 1uF or 50uF capacitor work?

1uF might. 50uF will.

Note that switching to writing in plain C doesn't mean you have to change the method you use to get code into the chip - you can still use the Arduino bootloader.  And of course you can also use ISP to load Arduino sketches - the sources used to generate hex files and the process of loading them into the target are orthogonal subjects.

This does not seem to work, the arduino still resets, and i get the same error. I'v tried with 1uF and 50uF between reset and gnd, and with 120 ohm between reset and 5V

@Majenko ok, so now i tried with a 1000uF, this time there was a difference atleast, now i get the error "avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00" instead...

Note the baud rate of the ISP sketch will probably differ from that of the bootloader (often this is intentional, to make sure that the wrong target will not be programmed).  Your question should really include your full avrdude command line.

avrdude -c avrisp -p atmega328 -P /dev/tty.wchusbserial1410 -U flash:w:main.hex
This one?

THERE IS NO ARDUINO LANGUAGE!!!!!!!!!!!!!!

This is nothing to do with languages. I'm trying to make the transition from coding in the Arduino language to AVR-C, but I'm having some issues with my microcontrollers. You have a problem uploading your code, that is all. Since this question has been abandoned by the OP I'm going to close it.

Just read the arduino source and libraries, they provide an abstraction layer to AVR-C.

"invalid device signature" is due to bad connection or inability to reset the device (RST pin fuse setting for example).


text:
Strange adding behaviour
I have an Arduino Nano and was adding up some values 2^i from 0..7:
void setup() {
  Serial.begin(9600);
  int i,k;
  k = 0;
  for (i=0;i<8;i++){
     k += pow(2, i);
     Serial.println(k);
  }
}

Those numbers should sum up to 255, but that's the output:
1
3
6
13
28
59
122
249

Is my Arduino not working or what can be the reason for this behaviour?

As a tip for the future, printing the intermediate results would have given you a clue.  For example, adding Serial.print(pow(2, i), 7); gave me:  1.0000000, 2.0000000, 3.9999995, 7.9999980, 15.9999961, 31.9999885, 63.9999771, 127.9999542. The default output of Serial.print rounds so doing Serial.print(pow(2, i)); masks the problem: 1.00, 2.00, 4.00, 8.00, 16.00, 32.00, 64.00, 128.00,

No, there is nothing "wrong" there. In fact it's the expected results.
The problem here is that pow() returns a float, and some numbers just can't be represented with floating point. When that floating point value is converted to an integer it truncates the decimal portion leaving you with the wrong integer value.
void setup() {
    Serial.begin(115200);

    int t = 0;
    for (int i = 0; i < 8; i++) {
        float f = pow(2, i);
        int d = f;
        t += f;
        Serial.print("2^");
        Serial.print(i);
        Serial.print(": float = ");
        Serial.print(f, 10);
        Serial.print(" int = ");
        Serial.print(d);
        Serial.print(" total = ");
        Serial.println(t);
    }
}

void loop() {
}

2^0: float = 1.0000000000 int = 1 total = 1
2^1: float = 2.0000000000 int = 2 total = 3
2^2: float = 3.9999995231 int = 3 total = 6
2^3: float = 7.9999980926 int = 7 total = 13
2^4: float = 15.9999961853 int = 15 total = 28
2^5: float = 31.9999885559 int = 31 total = 59
2^6: float = 63.9999771118 int = 63 total = 122
2^7: float = 127.9999542236 int = 127 total = 249

Instead you should use bit-shifting to perform the same operation on an integer:
void setup() {
    Serial.begin(115200);

    int t = 0;
    for (int i = 0; i < 8; i++) {
        int d = 1 << i;
        t += d;
        Serial.print("1<<");
        Serial.print(i);
        Serial.print(": int = ");
        Serial.print(d);
        Serial.print(" total = ");
        Serial.println(t);
    }
}

void loop() {
}

1<<0: int = 1 total = 1
1<<1: int = 2 total = 3
1<<2: int = 4 total = 7
1<<3: int = 8 total = 15
1<<4: int = 16 total = 31
1<<5: int = 32 total = 63
1<<6: int = 64 total = 127
1<<7: int = 128 total = 255

Actually the values in question most definitely can be precisely represented as floats - all small integers can be, and these are even powers of two on a binary system.  The issue is rather imprecision within the implementation of the pow() function, possibly having to do with intermediate values.  And yes, it is not the way to do this - even apart from the inaccurate results, it is far more computationally intensive.

@ChrisStratton Float is still crap either way. Q15 etc are the way forward.

Granted that integer arithmetic is a computationally better approach to this problem; if your intent was to learn to use floating point and float to int conversions, then you need to round up the floating result before the conversion truncates it. As you saw in @Majenko's example, the floating results are close but not quite exact. In your own example, you'd change
k += pow(2, i);

to
p = pow(2, i); k += (p < 0. ? -0.5 : 0.5);

to so the float would truncate to the nearest int instead to the next lower int.

Note: that trick only works for positive numbers. For negative ones you should subtract 0.5. Or use the round() function.

Yup, shot from the hip. Edited to show the non-round() version.


text:
interrupting an interrupt
What should be expected if the code in the timer interrupt ISR does not finish before the interrupt is called again?  For example Timer0 ISR(TIMER0_COMPA_vect){} on the Uno.  This is for debugging purposes in a complex program.  Thanks.

the timer will set the Timer Interrupt Flag (TIFR0 register)
The ISR will be called, and the flag will be cleared
you do some long calculations or something
the timer will match OCR0A, and set the interrupt flag again.
you calculations are done, and the ISR function will end.
the uC will jump back to the main loop code, and execute 2 1 instructions.
The uC will see the flag, and call the ISR again. As per step 2.

PS please note that by default the ISR macro will turn off global interrupt (cli) at the beginning of the function, and set it back at the end. You can re-enable interrupts inside the ISR, but you have to be very careful here, as interrupts can be nested, and cause stack-overflows.
You can re-enable interrupts inside the ISR, but that only means other interrupt may interrupt this ISR, but never the same vector. (i.e. only one ISR per vector can run at the same time). So in your case the timer ISR can't be interrupted by the same timer interrupt.

Congrats, that's a pretty good summary of what happens in this situation.

1.- My understanding is that the uC will execute a single instruction (not 2) of the main code before entering the ISR again. 2.- Where did you read that only one ISR per vector can run at the same time? It's the first time I read anything like this.

Note that if you re-enable interrupts inside the ISR, then the same interrupt definitely can re-enter the same vector. This is one reason why re-enabling interrupts inside an ISR needs careful thought... You said it yourself: (step 2) - "...the flag will be cleared."

Apparently I was wrong in the last paragraph. I'm not sure where I got that from, but it doesn't appear anywhere in the datasheet.

It won't be called until the current interrupt is finished. As soon as the current interrupt function returns the pending interrupt would trigger and call the ISR again.

You need to explicitly allow interrupts to be interrupted. For more information I suggest you see section nested interrupts on avr-libc.


text:
Why is one LED more luminous (brighter) than the other?
Given that there is a circuit with two pins (12 and 10) from an Uno providing power to LEDs on two separate branches, why is the yellow LED dimmer than the green LED? (Please see below image.) To my understanding, the branches attach to GND in parallel, so the LEDs should be equally bright.
If it helps, the two branches are programmed so one LED is off when the other is on and vice versa, with a 1s interval between changing pin state. This isn't a PWM thing as using pin 8 instead of 10 makes no difference.

Different colour LEDs have different forward voltages and require different value resistors to get the same current through them.

What do you mean by "forward voltages"? Does voltage not travel in only one direction?

You will need to read some tutorial about LED functioning in order to properly handle your circuit. I highly suggest https://learn.adafruit.com/all-about-leds/overview in it all terms like forward voltage and forward current are explained, among others.

Just like men, all LEDs have been made different.
Practically, that means two different LEDs (one green and one yellow for instance) will have different brightnesses (more precisely, luminous intensities) when they are traversed by the same current (forward current).
LED luminous intensity is a function of the current that traverses it (among other factors).
If you want the same brightness for those 2 LEDs, then you'll have to:

Get both LEDs datasheets (should be a couple of A4 pages for each)
Find the luminous intensity/forward current function curve in each
Determine which brightness you want for both
Deduce the current for each
Calculate the resistor value to get that current for each

Then you will have to use two different resistors values in your wiring, based on calculations of step 5.
Simpler, you could just replace one of your 2 resistors with one small pot that you can use to tune brightness of the second LED until it fits brightness of the first one.
Be careful with pot manipulation though, as a 0 resistance would probably grill your LED (and potentially the Arduino pin it is wired to).

Thanks for the warning about burning LEDs with pots; I already did that to one of them testing out how much luminous intensity I could get out of a red LED. :(

Don't worry that can happen to anyone, even not beginners (I grilled a few LEDs myself, including 7-segment displays, and also a few transistors :-))

Eish. At least LEDs are cheap...

Add to that the human eye responds in different ways to different colours of light - green being the most sensitive... so you have visual intensity as well...

@Majenko correct, but that is not shown in the datasheets. This is why in the end, the pot solution is probably the most relevant.

Or use PWM to set the brightnesses to be visually equal...

Personally I'd use PWM only if I need to vary the brightness during my program; if I can fix it, I'd go with the pot solution and just the digital pin out.

Just like men, all LEDs have been made different.  - and women. ;)


text:
Sketches won't upload to Uno
Today I tried to update the sketch on my Arduino Uno, but was unable to due to this error:
Sketch uses 1,870 bytes (5%) of program storage space. Maximum is 32,256 bytes.
Global variables use 188 bytes (9%) of dynamic memory, leaving 1,860 bytes for local variables. Maximum is 2,048 bytes.
D:\Users\User\Desktop\arduino-1.6.10\hardware\tools\avr/bin/avrdude -CD:\Users\User\Desktop\arduino-1.6.10\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM4 -b115200 -D -Uflash:w:C:\Users\User\AppData\Local\Temp\build2f7b4a32c3810b2d8e42648954faba05.tmp/nes_controller.ino.hex:i
An error occurred while uploading the sketch

Nothing will upload to the board now. I tried uploading a simple sketch with empty setup() and loop() functions, I've tried different PCs and gotten the same error, I've swapped USB cables, I've double-checked that I'm using the right COM port, I've disconnected every wire from the Arduino pins - nothing has helped.
The old sketch is still running fine on the Uno. It was uploaded a few days ago using the exact same setup I'm trying right now.
The Arduino IDE doesn't even indicate any errors, everything compiles and looks good until "An error occurred while uploading the sketch"

I'm going to put this in a copy buffer I think...  "Do you have a genuine Arduino or a (sigh) cheap Chinese clone?"

Genuine Uno from Arduino.cc

Can you ask Arduino IDE to put some more verbosity (there is a preference for that IIRC)? Also how did you check that was the right COM port? Sometimes COM ports can change after a reboot. I always use listComPort.exe to check this first.

That's as verbose as it gets. No error description as to what happened. Ive tried different USB ports, Ive triple-checked the COM port.

You can set the verbosity level in the Arduino IDE:

File menu
Preferences
Settings tab
"Show verbose output during" => check "upload"
Click OK

Upload again, and note the additional output telling you what is wrong.
It should also point you to this URL, which points out the most occurring issues.
The issue I have most, is that I forget to switch between Micro and Uno board (as I deploy my sketch on both boards).

assumption is windows, so with the old ide's a reboot to free up the usb ports, or sometimes simply swapping the usb port, and changing the port in the tools > port menu.
does it identify the board you are using when you choose the port? (Genuino / Arduino)

Yes "Get Board Info" works and identifies my board.

In my experience, sketch upload error occurred due to 4 different mistakes:
(1) Silly mistake: did not connect the serial cable to the PC
(2) I did not choose the right com port (Tools/port).
(3) I chose the wrong board type (Tools/board). connected a Nano, but selected Uno while uploading.
(4) While updating my Arduino IDE to the a version, I failed to select 'download USB drivers' option. There are 2 or 3 of them.

This is a guess based on what I have encountered previously. With all the information given remember I just took a guess!
Is it possible you are experiencing a serial flood, ie it is constantly sending something to the console.
Take these steps several tries may be needed:

Power off the board completely
Remove the USB cable
Hold down the Reset button
keep it held down (or, run a jumper wire from the RESET pin to the GND pin).
Still holding down Reset reconnect the USB cable.
Start uploading a sketch that does not have this problem (I use the Blink sketch).
When you see the Receive light blink, release the Reset button
Note: I have seen this happen several times when I flood the serial output. An indication is the tx light is on.

You can check the hardware as follows.
Here is a trick I use on some boards but first be the baud rate is the same in the terminal as in the sketch (Serial.begin(115200). If so then remove everything then put a jumper between ground and reset. Then put a jumper between TX and RX (pin o and pin 1 on uno). launch the IDE and what you type in the console should be echoed back to you. If this works the hardware is connected fine.

right click on computer, manage, device manager and disable the usb driver and enable it again.

This answer does not provide enough detail for it to be useful to the OP. Please provide more info such as: on which OS you do what, screenshots to show each step. If you could also explain why that way shall work, that would be even better.

Tried, no change.


text:
Arduino - stepper motor wrong steps number
I just bought a new stepper motor (400 steps for revolution, 0.9°/step) and I would like make a turn of 180° by 200 steps, but it doesn't work as expected.
It looks like the motor needs only 110 steps to make a turn of 180° and I don't know the cause. The driver motors is the Keyes L298. It is wired to my Arduino UNO rev3.
In order to clarify, please see the image below:

The code is as follows:
#define negativeSteps -55
#define positiveSteps 55
#define Speed 7500

int motorPin1 = 11;
int motorPin2 = 10;
int motorPin3 = 9;
int motorPin4 = 8;

int steps;
unsigned int tmp2;

byte modeR[] = {B00001001, B00001010, B00000110, B00000101};
byte modeF[] = {B00000101, B00000110, B00001010, B00001001};

void setup() {

  Serial.begin(115200); //Opens serial connection at 115200 baud.

  pinMode(11,OUTPUT);
  pinMode(10,OUTPUT);
  pinMode(9,OUTPUT);
  pinMode(8,OUTPUT);

  pinMode(3,OUTPUT);    // Enable pin motorA
  pinMode(2,OUTPUT);    // Enable pin motorB

  digitalWrite(2,HIGH);
  digitalWrite(3,HIGH);
}

void loop()
{
    while (Serial.available())
    {
      char cmd = (char)Serial.read();
      if (cmd == 's')   while(1) Seek();
    }
}
void motorR(){
  int bitMask=B00001111; // bitmask to modify only last 4 bit

          for (int id = 0; id <4; id++) {
            PORTB = (PORTB &~bitMask) |  modeR[id];
            while (tmp2++<Speed);
            tmp2=0;
          }
}
void motorF(){
  int bitMask=B00001111; // bitmask to modify only last 4 bit

          for (int id = 0; id <4; id++) {
            PORTB = (PORTB &~bitMask) |  modeF[id];
            while (tmp2++<Speed);
            tmp2=0;
          }
}
void Seek() {
  steps = negativeSteps;      //Init Steps
  while (1)
  {

    while (steps<positiveSteps) //  starts from "negative" steps to "positive" steps ( -55 to +55)
    {
       if (steps<0) motorF(); // if steps = 0 it will change the direction
       else motorR();

      Serial.println(steps);
      steps++;
   }
 }
}

I don't know if this is an answer, but I use a shield: Motor Shield for Arduino, is low cost and the library is very easy ti use.
I recommend you try with this module for easy drive stepper motor like the NEMA

You're driving the stepper too fast, unintentionally though.
The while loop you use to delay is likely optimized out by the compiler:
while (tmp2++<Speed);

Easiest way to fix would be to declare tmp2 as a volatile variable when you declare it up in the top of your program.  Thusly:
volatile unsigned int tmp2;

This will inform the compiler that tmp2 might possibly change at any time and not to optimize it away. It's more complicated than that really, but it'll fix your issue in a single tweak.
Better, would be to use the delay() function, to pause execution for some specified milliseconds, much like you're attempting to do with the empty while loop.
You're using an UNO, so probably running at 16Mhz, so your delay of 7500 loops is technically about 5 instructions long, multiplied by 7500... so 37,500 instructions executed, and at approximately 16,000,000 instructions per second, that's (37500/16M) that's about 2.34 milliseconds.  So maybe a delay() of 3-5 milliseconds would be useful.
Basically, you're trying to step the motor too fast, and it can't keep up.  Mass, inertia and all that stuff are involved too.
Try replacing the while statements with delays, start with big delays (25 or so), and work lower as long as stepper motion is consistent.  As you said, 200 steps should be 180°.
replace:
while (tmp2++<Speed);

with:
delay(Speed);

and change Speed to an appropriate value (25 or so to begin with, play with it!).
There are many improvements to your code which could be discussed, but you need to crawl before you walk, before you run.  Get THIS code working, then finesse it.


text:
Arduino Uno VIN 2A
Trying to get started with the Arduino, so I'm trying to do something kinda simple. I'm following this tutorial: Build Your Own Dynamic Ambient Lighting For A Media Center
However, I'm still confused about one, most likely simple and self-explainatory, thing:
Take a look at this image - is that DC connector on the bottom left the one that's one my Arduino? Do I simply have to connect the 12V wire from the RGB LED stripe to Vin?
After using google for a bit, I read this: the diode and trace width are other limiting factors. The diode is rated at 1 amp and the board traces can't handle much above 2 amp.
Does that mean I can only use 1A because of the diode? If so, why does it matter how much the board traces can handle?
I'm trying to power a 12V 2A RGB LED stripe.
I'd appreciate your help and I hope this is the correct subreddit to ask that. :S

No, that connector is a completely separate one.
You can connect a power supply to the on-board power socket of the Arduino and take power out from the VIN pin to power other things.  However the total current that is used by both the Arduino and whatever you power from it cannot exceed 1A.
So to have more than 1A available you have to have the power connected externally to the Arduino. That doesn't mean that the Arduino can't share that power, just that the Arduino can't provide that power.
You can connect the +12V of the LED strip to VIN on the Arduino as long as the 12V power supply is connected to the LED strip not to the Arduino - that way the power for the Arduino comes from your external circuit.

It will be dangerous to take 12V from VIN pin. Please have a look at following picture. That is the diode you mentioned. the diode can burn out if the current get exceeded.

there are three ways to solve this.

Use two different supplies. Use a 6V battery(or 5V USB power) to power arduino and 12v supply for LED strip. You should connect both grounds( grounds of supplies)

Solder a wire from bottom(from the point shown in picture) of arduino board for 12v
connect 12v power directly to VIN (not by using power jack)


text:
connecting two keypad with arduino
I am pretty new to arduino.I am working on a project which requires comparison of two keypad inputs to operate a relay using arduino. I have found lot of info on connecting single keypad but none about connecting two keypad inputs.So how can i connect two keypad and a relay to arduino?Thanx in advance.

It should be no problems as long as you can get enough digital inputs into the Arduino.  Search for the library KeyPad, it lets you define the pins that control each row and column and so you could use 2 2*2 keypads quite easily.
I think Keypad is very easy to use, but if you get stuck, just show what code you have so far and describe the problem and people will help you.


text:
Arduino which library for led 4x20
I am having an Arduino Uno and I want to add a LCD to it. My LCD is a C2042A with I2C shield on it. I tried the LiquidCrystal_I2C library but it doesnt work. I am not getting any errors the LCD is just not showing the text. I just used the example code 'Hello World' from the library. I only changed the adress from 0x27 to 0x63 because I found that with the I2C scanner.
So all in all the LCD is connected right. It shows I2C mode which is also fine and it is find by the I2C Scanner code. Which library do I have to use that it will work? http://www.wentztech.com/filevault/Electronics/Arduino/

Do you see white squares on the first line, but not the second? If not, you have to adjust the contrast with the potentiometer.

No when you turn the LED on it shows the standart text: LCD03 REVISION9 (next line) I2CMODE @ 0xC6

0x63 is the correct address - the module is at 0xC6 which is the 8-bit equivalent of 0x63 (0x63 shifted left once for the read/write bit to be added).
The LCD03 uses its own custom I2C protocol, not compatible with the "normal" I2C LCD library. Instead you have to use their own special commands.
The commands are detailed here: http://www.robot-electronics.co.uk/htm/Lcd03tech.htm
There may be a library available that wraps those commands, I don't know, but you can just use the Wire library to send the commands you need to send.

ok that looks complicated can you write an example code how to for example turn the blacklight off with the wire library?


text:
How to power Arduino and shields with 4 rechargeable AA batteries?
To start, I am a software guy, and I really want to ensure I not going to destroy any components. I previously looked at power through a USB power bank, but the issue with these is that they turn themselves off with low current pull.
My question is: I have a number of Arduino shields and would like to power them with 4 rechargeable AA batteries, and therefore would like some advice on what to use without frying any electronics.
The rechargeable batteries I have are these 1.2V AA (NiMH). Going on their rated value they should supply 4.8V. Testing the 4 batteries in serial gives me 5.3V overall, or around 1.325V per battery at full charge.
So if the batteries provide more than 5V, I cannot safely plug them into the 5V pin on the Arduino. But if the batteries could potentially provide around 4.8V to 5.5V plugging them into VIN means that the voltage regulator will take too much power, reducing the overall voltage to be too low for all of the shields (Which require 5V). What should I do in this situation?
This is a list of the current equipment that will require power:

Arduino Mega 2560
SIM900 GPRS/GSM Shield
Sparkfun GPS Logger Shield
Sparkfun Wifi Shield - ESP8266

The shields will be stacked on top of each other.

Check the absolute maximum ratings for the main ICs and modules on those boards - you will most likely find that they are fine up to 5.5V, except those that take 3.3V of course. The only issue you may have at 5.5V is a 3.3V device sending data to the Arduino may not have a high enough voltage on the HIGH logic level to register on the Arduino so will need a level shifter.

Hey, I asked a very similar question and just saw yours. Did you end up using an UBEC?

I did end up using a UBEC and it worked great!

Most 5V devices will function fine at up to 5.5V - however, check the datasheets for the major components and modules on the boards.
The main thing to watch though is that a 3.3V device, which can normally communicate fine with a 5V one, may not be able to. The problem is that the logic HIGH signal from the 3.3V device may be below the threshold for a logic HIGH on the Arduino:
V_IH = 0.6Vcc = 0.6 x 5 = 3V

V_IH = 0.6Vcc = 0.6 x 5.5 = 3.3V

Thus a 3.3V device would have to output at the very minimum 3.3V as a logic HIGH in order for it to register as one on the Arduino, which may be a problem...
You can easily drop the battery voltage by 0.7V though by inserting a single silicon diode (such as the trusty 1N4001) in series with the batteries. That will take your voltage down from your measured 5.3V down to 4.6V which will improve matters somewhat.
However, it is important to note that you have so far measured the open circuit voltage of the batteries. That is, the voltage with no load on them. The voltage will most likely be lower once they are actively driving the Arduino etc.
The Arduino itself will be fine running off 5.3V, so I suggest you power just the Arduino direct into the 5V pin from the batteries and measure the actual voltage while powering the Arduino. That will give you a more accurate voltage reading. Then, if needed, you can add the diode to drop it by 0.7V.

The sim module I am using (this one) lists a max voltage of 5.2V. The other 2 boards say they take Arduino 5V and regulate it down to 3.3V (can't find a max voltage). Would it potentially be better to use 6 of the same AA batteries in the VIN pin, giving around of 7 - 8V regulated down to 5V on the Arduino?

Using the in-built regulator is wasteful. You'd be better off using a switch regulator from 6 batteries (search: UBEC).

So using a UBEC such as this would allow me to wire from 6 AA batteries -> UBEC -> 5V Arduino pin, with a maximum available current of 5A for Arduino and shields (of which I should only need max 2A)?

Yep, that would be ideal. Feed it at least 6.6v and you will get lots and lots of 5v power.

Make sure you have a UBEC with low quiescent current. I found one that had 20mA of quiescent current, which would by itself drain the batteries in 3.5 days.

@Gerben That's still far better than an LDO though...

Also, all 3 shields have level shifting circuitry, so the logic HIGH threshold problem described here doesn't apply in this case.

@Gerben That's good then - it should be OK with just the batteries into 5V then as long as the loaded voltage drops fractionally from the OC voltage, which I would expect it to.

@Majenko  quiescent current of the LDO on the Mega (NCP1117ST50T3G) is around 6mA

@Gerben ... as long as the level shifters work in both directions, and not just to drop the 5V down.

@Gerben Add to that the losses from the voltage regulation...

@Majenko Kind of depends on how much the uC is sleeping. If it sleeps a lot, those extra 14mA of current can make a bit difference. So it (as always) depends. PS The level shifting was with mosfets, or dedicated ICs. No resistor divider nonsense.

@Gerben A rubbish UBEC us usually somewhere between 80 and 90% efficient. An LDO barely manages to break 60% efficiency, and then only if the input voltage is only slightly higher than the output voltage.

@Gerben But if sleeping is involved, as well as shutting off power to peripherals, then you need a better regulator that can switch between PWM and PFM at low current draws.

@Gerben My regulator of choice for battery operation is the TC105 - 57µA quiescent, 92% efficient. Runs a sleeping PIC32 off a PP3 for a year.

@Majenko To confirm, feeding the power through the arduino 5v pin allows the full 5A of current to be available to all shields on the stack, whilst also safely powering all shields with the 5v?
As the docs for the SIM900 state that I should be powering with external power, this setup does do that, just via the 5v pin instead of the jack connector?

Yep. Just don't melt the pins with too much current...


text:
How do I find names of components I don't know?
I recently started with Arduino and I have my starter kit. However, there are some strange looking components I can't recognize. Is there some way to find out the names of these components?

You could try adding a picture to your question, and ask us. (but please mark the ones you don't know).

I wouldn't want to post a new question for every single component I don't know

@Max So maybe put it in this question?

In your kit, you have a list of all provided components. Just google those you don't know and you should find images that match your kit. This should work.

The Arduino webpage has a section about their Starter Kits, including pictures (and technical specs if you scroll down the page). Particularly, if you go to the Arduino store, there is a sub-menu for components - for example, for actuators (there are more categories to the left of the image).
There is a blog by Aaron Eiche, Arduino Starter Rundown, that if you scroll down, there is a chart that labels the main components.
There are several websites that have pages that identify components by image - an example is the uCHobby webpage Identifying Electronic Components, with pictorial menus of the main types of components.
In Google images, searching "arduino starter kit components" yields a considerable amount of labelled component charts.

A slightly more general answer to this question would be to browse the catalogue of a component supplier. Printed catalogues seem to be becoming rarer (Maplin used to sell a catalogue, but it seems to be discontinued this year), but RS and Farnell still seem to have printed ones.
I'm not suggesting you find specific components by searching the catalogue, but skimming through a catalogue will give you an idea about some of the components that do exist, and will help you to narrow things down a little.


text:
How to interface an arduino to load sensor with darlington transistor?
I have a load sensor for measuring weights , it has for wires labelled E+,E-,S+,S-. I assume S means sensor and E means excitation and the power is sent into E+ and E-.
The output of any load sensor would be the order of typically millivolts if it takes a load (depending on the weight of the load of course) so I guess amplifying it with a darlington would make its output useful for an interface to an arduino.
What would be a generic circuit using a darlington transistor (e.g. a TIP 120) that can make the load sensor output useful for building an interface to an arduino with the minimal number of components? Ans this circuit is to be as simple as possible.
Im trying to build a circuit with the components I have which does include a tip 120 and I have a lot of other common components.

You'd be better of with an opamp, if you have that.

First decide if you are trying to weigh something, design a product, understand load cells, or "golf" a TIP120 solution.  For the first, order an HX711 module, for the second or third do more research, and for the fourth see if you can find a meter stick and some string to go with your TIP120.

@Gerben Gerben I do have an lm358 opamp but isnt the gain of a tip120 sufficient? I dont have an hx711 module chris. Im trying to make a circuit that can weight betwteen 0 and 3000 grams. But I think there should be a generic circuit to do this.

Chris my understanding  of load cells is its simply a variation of a wheatstone bridge which is of course a configuration of four resistors. But it differs from the standard wheatstone bridge as the resistors are replaced by variable ones which detect strain converting to changes in rresistance-though the change is so small it needs suitable amplification. There's more to it than that of course but that basically how the sensor works.

What you have there is (or sounds like) a full wheatstone bridge.
You require either a special amplifier (such as the HX711) or a highly sensitive and accurate differential ADC (such as the MCP3428 - (on  a shield)).

Ok Ill try and get the HX711 or MC3428 if I can. Yes I think it is a full wheat stone bridge too. But cant you build it without special parts? Even just to detect rough weight measurements? I have lm358, tip120  to build it?

The best you could hope for is to build an instrumentation amplifier which consists of (at least) three op-amps. Yes, you could build an op-amp out of transistors and resistors, but it's far from easy (I wouldn't like to try it). Just get a HX711, it's the simplest option and there's plenty of tutorials.

I mean, this is the schematic for the internals of the LM741 - and you'd need three of those, and it would still be inferior to an HX711.  http://i.stack.imgur.com/JmQjc.png

I agree with you I would not build an op amp from scratch-I already have a few lm358's-what I had in mind it could be done with a few transistors to amplify the mill volts output by the load sensor and use a simple circuit to convert them to useful voltages. It just seemed like you could make simple circuit from 20 components maximum.


text:
Powering a 12v lock with batteries, via WiFi, and with low energy consumption
I'm a complete newbie in anything related to electronics, software or hardware; yet with a couple of friends we're going ahead with an interesting project related to automation through wireless devices: more or less IoT but involving electric locks.
The case scenario: there's a room without any power outlets. It has a regular door. We want to be able to open this door through the internet, with a lock that lies inside the room, on the other side of the door; all this, given we:

Can't make any modifications to the door's structure.
Can't drill or make holes or whatever so as to get a power cable to
the inside of the room.
But we can glue certain pieces behind the door, this is, inside
the room that hasn't any power outlets.

We've planned, so far, to use an Arduino Uno; enhance it with WiFi features (i.e. a module or shield) so as to bypass the limitation of not being able to connect an ethernet cable; and glue a solenoid or lock to the inside of the doors, so that it acts as a second lock that can only be unlocked through the internet, accessed via Arduino.
Our ideal scenario would be opening this door remotely, from our home, even if this door is a hundred blocks away. If someone wants to get in, they should ask for our permission, as we don't control the built-in handle, but we do control a latch fixed on the inside.
All this setup should be powered with a long-lasting battery: we can't plug anything, and we can't risk getting our batteries depleted fast, because we'll never be able to open the door once again. We need these batteries to last long enough so as to be able to change them in a prudent time window; a back-up battery system should also work well.
Standard solenoid locks are 12v. Arduino powers 5v devices, not 12v ones, as far as my understanding goes.
We should open this door only 5 times a day. That's it; the remaining time in between, the whole device setup can well stay 'dormant', in low-energy consumption mode, only to 'wake up' when we give the order: "Arduino, please tell the solenoid to open".
We haven't specified which battery we would use; ideally, the most cost-efficient option. If it lasts 3 months and costs, say, 20 dollars -- well, we would love that.
I've done this really inaccurate, schematic drawing to illustrate our idea and research. I know there's many details missing but I wanted to prove our point:

(The Arduino should be positioned on the wall and not on the door! My bad.)
I hope I'm clear enough up to now.
The questions, then, are:
I've done some research, and I've seen that Arduino can be enhanced so that it consumes the minimum possible energy so as to remain 'aware', but not in full-power mode, which in our case would be unnecessary.

So, can we make Arduino super efficient in terms of power consumption, even if we attach WiFi functions, which, as far as I'm concerned, really takes on battery life? So that we can make Arduino run for months before replacing the battery?
Arduino can send only 5v; but the solenoid powers on 12v; then, getting a second battery to power our solenoid sounds straightforward, except that as far as my knowledge goes, this battery should last next to nothing (maybe I'm wrong here). And we want it to last for months -- if not, our door will remain sealed forever! Can I make the solenoid dependant on the Arduino, so that it's part of the "almost-no-battery-consumption" scheme, and battery lasts, as I would really like, some months? We would be talking of only one battery to power the whole set-up, instead of two that I guess that we'll need.

I'm a newbie, but can't Arduino power 12v through a relay or a transistor? Can't post links.
To clarify: Getting two batteries for our complete setup (one for the Arduino, one for the solenoid), if these two batteries both last, is not a problem; but it would be catastrophic to make a battery last long enough while the other depletes in 48 hours. The solenoid needs to get electricity a modest 5 times a day; that's why I believe we can make it super efficient.
With our friends, we've so far programmed Arduino to open a solenoid from the Internet. The solenoid we've used was 220v because we had it in stock; it won't be what we need for our project. It was just a trial. On top of this, the Arduino has no WiFi module, just an Ethernet shield.

There's a remaining problem to solve, which is: what would happen if the Arduino fails? The door would be sealed 'forever'. We'll tackle that issue afterwards.
TL;DR: we'd love to open a lock via WiFi: the lock and Arduino should run solely on batteries that last more than 48 hours: a couple of months would be ideal! Can we work this out?
Thank you very much for your help, opinions, and time. I hope my question is up to the standards.

How to change the batteries when they go flat: Turn the handle and push. Then glue everything back on again.

"we can't risk getting our batteries depleted fast, because we'll never be able to open the door once again." It should go without saying that this is overall a very bad idea... entirely apart from the comparatively high power consumption of wifi.

Its a shame that noone likes your question, since you have obviously put some work into asking it. However, you've asked a very general question (or actually several distinct questions) relating to a system design which isn't really thought through. Each of the following ought to be addressed individually: Comms-physical, comms-protocol, power consumption, battery capacity/technology, mechanical security, encryption, failsafe, EMC, fire/electrical safety. Some of these you can maybe answer, and for an educational project they may not matter. As presented, your project has many possible flaws.

What kind of lock do you have? Mine for example has a knob to lock/unlock the door. I could simply add a small motor to the knob to unlock it using an Arduino while still being able to use a regular key (in case of low battery or no internet connection ).

Wifi uses s lot of power (relatively). You could make the Arduino only connect to wifi every minute or so to check some web api, but in your case that would probably be unacceptable (having to wait up to a minute for the lock to open). You could have a wifi base station on a location that does have wall power, an use a different wireless module, or wire to connect to the Arduino on the door.

You can instead use Low consumption bluetooth like the kwikset kevo does

[I'm coming in late but since this question got reposted, here goes:]
If this not to be just a Proof of Concept, but to be actually installed, you really have to address the several points of failure (Arduino, Arduino power, solenoid, solenoid power) that could lock you out of the room forever ("ever" being the time needed to fetch and apply destructive tools :).
Assuming it's a POC, here are a few more ideas:

You need 12v for the solenoid. You can take your 5v from the same source using an efficient regulator. Advantage: one fewer point of failure (power source), and the Arduino could monitor the 12v source and send an alert if/when it starts to sag (which would only be useful if there's some head-room between its charged voltage and the minimum needed to drive the solenoid).
If you use Bluetooth LE on the Arduino instead of WiFi, but place another Arduino outside the door, somewhere with power (locked into the wall, the ceiling, or an adjacent room), the outer Arduino with "unlimited" power could talk BTLE to the inside Arduino. Advantage: Lower power consumption by the inside Arduino (unless step 1. makes it unnecessary). Disadvantage: More equipment (second Arduino); more complex system has additional ways to fail, though not necessarily to lock you out; possible additional point of vulnerability to intrusion.
Is that a steel door? If not, an inductive charging coil on the inside of it might let you temporarily apply an inductive charger from outside to provide power - or charge a small battery or even a capacitor - enough to unlock the door. Advantage: One less point of failure (loss of 12v). Disadvantage: More equipment; applicability depends on door material and thickness.

This is not the place to answer all the questions and design options that you have, but, to give you a starting point, you need to look at very low power arduino-compatible boards.
My suggestion is to use an ESP8266 module which can be programmed as an Arduino (have a look at here). The module is quite low power, and it may run for some days with AA batteries. You can use a 12V power source for both the module and the solenoid (you need a voltage regulator). The solenoid will only be activated when needed, so the rest of the time it won't consume any power.
The whole project is not a simple one. I would definitely suggest you to go step by step.
Good luck.

As far as the 12V motor is concerned, you can construct a decent H-bridge to shift polarity. I am assuming you are using a linear actuator or servo. Use a mechanical relay with 2 channels. Wire GND to NO1 and NO2, VCC (12V) to NC1 and NC2, and pull VOUT  to motor from COM1 and COM2 - IIRC - and in your code track state of when each channel is on or off... It will short out if both relay channels are ON simultaneously, so that must not be possible.
Mechanical relays are slower to switch than transistors (can haul 230VAC/30VDC/10A with no voltage drop), but if you want a transistor H-bridge use the rather old TIP120 NPN Darlington (0.6-0.7V voltage drop per transistor), or MOSFETs. At least the TIP120s require heatsinking for >=0.5A, but can drive 5-6A upto 60V, which is plenty.
As far as the wifi bit goes, I don't have enough experience. I would use a GET request to a web server/page and read what state the lock should be in at short intervals... no more than 5 seconds. A simple '1' or '0' in a text file will do. To output state, heartbeat (is the Arduino OK right now, or is something wrong?) and other stuff from the Arduino, use POST requests. You should use a simple database for this... PostgreSQL is my favourite, but you may want something simpler.
If you need precise timekeeping for events like open at 9.00 am, use a DS3231. Be careful to conserve SRAM, the Uno has only 2KB. There are guides on arduino.cc to help you with that (PROGMEM for immutable variables and the F macro for static strings). This is a good method, hope it helps.

And if you are making a lock, glue is not your friend. I'm going to assume you know that.


text:
How to convert bool array to byte?
I have following problem:
I'm reading 8 bit signal from one Arduino pin and store all informatin in bool array. Now I want to convert this array to single byte in decimal. How to do this?
I've tried this:
bool ID[8] = {0, 0, 0, 0, 0, 0, 1, 1};
int recivedID = int(ID);

and
bool ID[8] = {0, 0, 0, 0, 0, 0, 1, 1};
int recivedID = ID.toInt();

non works.

Why save it in a bool array in the first place? You could make a byte and set each bit individually. That will be more efficient.

try with this:
int recivedID = ID[0] | (ID[1] << 1) | (ID[2] << 2) | (ID[3] << 3) | (ID[4] << 4) | (ID[5] << 5) | (ID[6] << 6) | (ID[7] << 7);

which is the same as
int recivedID = 0;
for(int i=0; i<8; i++){
   recivedID |= ID[i] << i;
}

I haven't tested it though.

byte BoolArrayToByte(bool boolArray[8])
{
  byte result = 0;

  for(int i = 0; i < 8; i++)
  {
    if(boolArray[i])
    {
      result = result | (1 << i);
    }
  }

  return result;
}


text:
DMX dimmer appears to receive data from Arduino but connected lights do not respond
I'm trying to control a DMX dimmer (eurolite ES-12 IEC DMX Switchback) through an Arduino Mega. In an earlier test, we were able to make one RGB DMX light run through the color spectrum. Now, a technician has installed this ES-12 dimmer pack with 12 1-channel DMX lights attached to it. The dimmer has some kind of built-in testing program and all the lights work.
The documentation on the dimmer is very sparse regarding the programming side of things. The dimmer is set to mode d--- and when the Arduino is running its program, a little green light flickers next to the d---, apparently responding to the signals it's receiving, like so: d---. Unfortunately, that the only light that responds.
I've tried using the DMXSimple library (the DMX is connected to pin 3), but even the example code (after correcting the brightness-- to ++) does not get any response -- none at all, not even the little green light. The only thing the little green light responds to is an analogWrite() on pin 3.
I'm guessing it's an addressing issue, but I don't know enough to fix it. As I understand it, the dimmer is seen as the controller and is sent a LOW on channel 0 as the Start Code (SC): http://www.dmx512-online.com/packt.html. The first light on the dimmer will then be channel 1, the second light channel 2, etc. (since, the technician tells me, they are 1-channel lights). Is this correct? Or is the dimmer its own universe that should be addressed in some other way?

What hardware are you using? You can't just connect an Arduino to a DMX device and have it work since DMX is built upon RS485.

I'm assuming the same DMX connector we used to run the tests on the RGB lights. I can't tell you the make and model, but the guy in charge of the hardware does this kind of thing for a living. Unfortunately, he's on vacation and he's built everything into a black box -- literally. I just do the software.

@Dan Nixon, I'll see if we can open the black box.

The light technician, Toby Peperkamp, came with the solution. I'm not sure exactly where he found the information, but apparently the protocol for non-RGB DMX lights requires that the lights be switched on to maximum (255) at the beginning of the connection. So I added that to the setUp() and all the lights started to respond.


text:
Why isn't this pushbutton program working?
Here is my circuit:

and here is my code:
int LED = 13;
int BTN = 7;

void setup() {
pinMode(LED,OUTPUT);
pinMode(BTN,INPUT);
}
void loop() {
if(digitalRead(BTN) == HIGH) {
digitalWrite(LED,LOW);
}
else{
digitalWrite(LED,HIGH);
}
}

When I press the button, the LED is supposed to go low, but it doesn't. What is wrong with this circuit/code?

Where did you base your button connection on? To me it seems that it's always connected to GND. Pressing the button will send the electricity to GND, through the resistor, it's unlikely that it goes into the pin, since it has higher resistance (as far as I know).

It may be worthwhile to search up some electronics tutorials and/or Arduino basic tutorials.
When following a (good) tutorial, they would explain how to set up the electronics (and why it works).
Just connecting stuff in a way you think will work, is going to cause headaches or worse ;)

Max - A really useful site for you might be https://123d.circuits.io/ which allows you to blow up components virtually.  It lets you simulate your circuits (and code) and means you don't fry real Unos, which you may well do.  I've never yet managed to fry every component in a circuit on 123d, but I keep trying :)

I have a book which has this circuit...

Your code and schematic both seem to be wrong.
Try out this schematic:

And then code:
const int kPinLed = 6; // LED - Pin 6
const int kPinBtn = 7; // Push Button - Pin 7

void setup()
{
  pinMode(kPinLed, OUTPUT);       // LED as OUTPUT
  pinMode(kPinBtn, INPUT_PULLUP); // Push Button as INPUT wiith pullup
}

void loop()
{
  if(digitalRead(kPinBtn) == LOW)  // When Push Button is pressed
  {
    digitalWrite(kPinLed, HIGH);   // LED ON
  }
  else digitalWrite(kPinLed, LOW); // LED OFF
}

Paul is correct. Your button is wired wrong. The GPIO pin should be connected to the same side as the resistor. Also the button needs rotating through 90 degrees.
Also check how your LED is wired up. At the moment it looks like it's set up so that the GPIO sinks the current (LOW turns the LED on) yet the LED looks like it's connected the wrong way around for that.
In fact, I can't actually find anything right about that circuit...

And button seems to be shorted in breadboard too

Well spotted.  Updated answer.

The Input port is going to always be at Gnd, because you have connected it to ground.  Sorry to put it in such basic terms but this is the way I understand it.  It needs to be more difficult for the output of the button to get to ground than to get to the BTN pin of your UNO.  So put a bigger resistor (1K-10K) in place of your yellow wire between the button and ground.
And your LED is the wrong way round in the diagram.
(And Majenko is a quicker typist than me! :) )

In addition to the answers from Matt and Majenko, you code uses the wrong pin for the LED.
You have int LED = 13; whereas your LED is connected to pin 6.
NB: Pin 13 is connected to an LED soldered on to the Arduino board - as seen in the image below.

authors: Максим Зверек


text:
Arduino program does not start when plugged in
I am having trouble with my Arduino Mega with getting the program to start when the Arduino is plugged into a computer via USB.  All that happens is the LED turns on and stays on.  The device does not initialize, and only when I press the reset button does it begin the setup.  How can I make the Arduino start the program when it is first plugged into the computer?
EDIT: my code
void setup() {
  Serial.begin(115200);
}

void loop() {
  Serial.println("test");
}

very simple, which is why i don't understand why this is happening

The arduino will start executing immediately, unless you have serial statements looking for a connection holding up execution. can you share your code?

As said by @sspence65, the Arduino starts as soon as you power it. You are simply missing the startup message because it is sent before you open the serial connection on the PC end.

Actually the message is sent repeatedly but the arduino will probably reset a second time when the virtual serial port is opened.

@ChrisStratton, actually it doesn't reset and that is another problem I am having.  For some reason when the connection is established, the Arduino does not reset and sometimes there is already data in the buffer and it confuses the program and often I have to restart the program one the buffer has been read empty

Try explicitly toggling RTS and DTR via your computer's serial api.  At some point you may need to look into details of the USB serial implementation on your specific "mega".

I would recommend you to follow the following instructions step by step to verify your Arduino Mega.

Reboot your computer
Connect the Arduino using the USB cable to PC and check the Arduino itself if there is any jumper wires connected/grounded. If there are then remove them all.
Upload a blank sketch first. Go to File -> New
Verify the Arduino has accepted the blank sketch and resetted.
Upload the Blink sketch from the File -> Examples -> 0.1Basics -> Blink
Verify if the Pin 13/onboard LED is blinking. If yes then go to uploading your sketch, if no then there is a hardware/bootloader problem with your Arduino. Watch this video on how to burn bootloader here. https://www.youtube.com/watch?v=X5achE10rCI


text:
Start to build a robot
I would like to start with a very simple robot, which should be based on an arduino uno.
I already have an uno and made the decision fpr my robot chassie:
https://www.roboter-bausatz.de/en/diy-electronics/kits/robotic-kits/97/2wd-motor-smart-car-chassis-fuer-roboter-mit-getriebemotor-und-batteriebox
Additionally I want to by an ultrasonic distance sensor and a infrared sensor.
What else do I need to start ? Only a DC motor driver or anything else?
Thanks in advance
LStrike

You'll need:

Emergency switch (it should be easy to cut the power off, even for small robots)
A chassis (you've found one already)
Motors (Obviously)
Motor control (Probably a dual H-bridge, think if you need reverse or not.)
Power (powering on (single use) batteries may not be your best option)
Controller (Arduino Uno, or something smaller or faster)
Sensors (Can be anything, depending on the requirements)

A way to communicate with the robot is also nice, often wireless (bluetooth/wifi/443mhz).
And also, it will be nice if the robot fits some kind of purpose, but this could be added later.
You could think of the robot having to pick up and carry something, extinguish a flame etc.
I advise to check out one of the many tutorials on building a robot, they often have a detailed parts list (sometimes even shopping links).

Thats a nice list, thx. Never thought about an Emergency switch. I think I will start small with just driving an avoid crashing into objects ;-)

@LStrike, to avoid crashing into objects, it's often better to use at least 2 sensors that rely on different principles. If you have a "sonar" sensor, and you aim it at a plushy object, at may not work as well. So an extra IR sensor is a nice safety feature. You can check if you need to know the distance to the object, or just registering the object from a set distance is enough.
But yeah, sensors can be added later.


text:
Compilation Error
Hi everyone I seem to have run into a problem while uploading a library to the board. I managed to import the library to Arduino Uno, however, i could not upload it
Please Help :)
Thanks in Advance
This is the error i received:
Arduino: 1.6.11 Hourly Build 2016/08/05 02:12 (Mac OS X), Board: "Arduino/Genuino Uno"

In file included from /Users/pendukenipandeni/Documents/Arduino/SimpleTimer/SimpleTimer.ino:1:0:
/Users/pendukenipandeni/Documents/Arduino/libraries/SimpleTimer-master/SimpleTimer.h:37:22: fatal error: functional: No such file or directory
 #include <functional>
                      ^
compilation terminated.
exit status 1
Error compiling for board Arduino/Genuino Uno.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

Where did you get that library?

I got the library from gitHub : https://github.com/schinken/SimpleTimer

Looks like that uses std::function which is not in the normal Arduino compiler (by the looks of things) - or not in the version I have anyway. Maybe you need a specific installation for it to work. Simplest option is to pick one of the many other implementations of SimpleTimer out there.

Thank you Majenko, i picked another Simple Timer and it works now

please help, #include <IRremote.h> ^ compilation terminated. exit status 1 Error compiling for board Arduino/Genuino Uno.

I managed to fix this by simply downloading and uploading a different SimpleTimer Library from https://github.com/jfturcot/SimpleTimer


text:
Serial characters are corrupted
I try to send an "a" string via serial with
Serial.println("a");

and I receive "Oy=" in Ascii or {4F}{79}{3D} in Hexa.
Where should I start investigating? What could be wrong?  Baudrate is 9600 on all sides.
PS: I suspect the cable. Any hints how to check it?

It sounds like wrong baud rate. If you set them both the same then maybe the Arduino is running at the wrong speed.

On your setup function
Serial.begin(115200);//<- 115200 is the baud rate, serial monitor must match this speed
while(!Serial);//<-- wait for Serial to be ready

see: https://electronics.stackexchange.com/questions/9264/what-standard-uart-rates-are-there for more baud rates


text:
Use a 2.8" TFT with my Leonardo
for 2.8" diagonal color touchscreen TFT:
Readme states:
"Works with any classic Arduino '328. Solder closed three jumpers to use the ICSP header for use with Leonardo or Mega"
What should I solder? See image.

The things you should solder are on the TFT - we need a picture of that to point you to the right bit.

Thanks. How would I have guessed? Here's the underside of the TFT.

It looks like that display doesn't have a touch screen, only a tft and sd card. The modifications you would need to make pertain only to the SD card and the nonexistent touch screen interface. The tft portion should work with any arduino since it is a bit banged 8 bit parallel interface.


text:
How is IF( object ) evaluated? Follows from SD card example sketch
The "DumpFile.ino" example sketch from the SD library tries to open a file off an SD card, read its contents, and write them to the Serial Monitor. I am confused in how the following if() statement is evaluated:
File dataFile = SD.open("datalog.txt");

if (dataFile) {
// read and print, then close
}
else {
// print error message
}

There must be some implicit conversion on dataFile which depends on whether or not SD.open("myFile.txt") was successful. I would like to understand how this implicit conversion occurs. Which property of the File object determines if the if() statement evaulates true or false?

It calls the bool() operator.

There is an operator bool which does the test:
File::operator bool() {
  if (_file)
    return  _file->isOpen();
  return false;
}

When used inside an if the compiler invokes the operator bool() which does the test you see above.

Thanks, it is obvious now that I see it. I've indeed found that this defined in the File implementation.