text:
Reading temp data
I have hacked this kettle so that I can turn it on and off remotely via wifi and that is working perfectly.

Added this to get a better signal.

This is my micro controlling the 5v buttons on the kettle.

I keep running into a wall when it comes to reading the temperature of the water. The kettle does this automatically, but I want to transfer this information to my micro.
If I hook my multimeter to the ground and and yellow wire that connects to the lower voltage board (5v) that had the buttons and display I can use the voltage reading to predict the temp. The reading ranges from 0-5v, but my micro is a 3.3v micro so a direct connection isn't a great idea. I've tried using breakout boards designed to read voltage, but if I connect anything it throws the reading off.
The multi-meter is fine.
How can I get my micro to read the voltage as if it were a multi-meter? I even tried one of those little seven segment voltmeters but that threw off the reading just like the optocoupler and leds and other methods that I tried.
Here is how I have it set up:

Have you tried a voltage buffer followed by an attenuator yet?

no, but I'll research that next.

@IgnacioVazquez-Abrams - I couldn't quite work out if it was a duplicate or a follow-up question. I believed it to be the latter. However, on re-reading it, it does appear to be a duplicate. It would be better if the original question was edited or appended to...

I am voting to close this... but I think that it would be a shame to lose the extra information... That information should be added to your original question. :-)

Voltage divider
You can possibly use a simple voltage divider. Try connecting two 100K ohm resistors in series between the voltage you want to measure and ground.
Yellow->100K ohm resistor->100K ohm resistor->ground
Now connect your multi-meter to the middle connection between the two resistors.
Depending on the circuit that happens to be driving the yellow wire, you should hopefully see a voltage that varies between ~ 0-2.5 volts. If so, you can connect this voltage to your 3.3v micro analog input.
Note that the value of the resistors is not critical - you just want them to be about the same and pretty large.
Op Amp
If the yellow wire output is so weak that even a voltage divider with very large resistors is pulling the voltage down significantly, then you can use a high impedance op-amp with 1x gain to buffer the signal.
So, you'd connect the yellow wire to the + input of the op amp, and connect ground to the - input of the op amp. The output voltage of the op amp would not track the input voltage (the yellow wire) and you can use a voltage divider on the output as above.
Use digital temp sensor
This option does not directly answer you question, but might be the best solution.
You can get something like a DS18B20 digital temperature sensor for a buck or two and connect it digitally to your MCU and avoid the problem altogether. This chip is happy at 3.3 volts, so you'd just need to put it physically someplace where it is sensing the same temperature as the yellow wire.  This will likely be more accurate too!

When I do this (I tried this weeks ago) it changes the signal going to the micro in the kettle and the temp displayed by the kettle is no longer correct.

What size resistors did you use?

I tried a few combinations. 10k, 100k, 1M then I tried 200ohm just to see what would happen. It changes the voltage, but it also messes up the temp readings on the teapot.

So with 2x 100k ohm resistors in series connecting yellow wire to ground (nothing else) does the temp readings on the pot get messed up? Or only after you connect your ADC pin?

It's messed up before I connect it to the micro.

Even with 1M ohm resistors? Does checking the yellow wire with your volt meter mess up the temp display also? If so, then something else is probably going on and I'd just used an independent digital temp sensor.


text:
Arduino yun as ssh client
Is it possible to set the Arduino Yun up as an ssh client? If so, how?

The Atheros chip should have enough muscle for an SSH client. The ATmega has not enough resources for that: too little RAM and too slow for reasonable use. But what do you mean by 'SSH client'? An SSH client is a program that can connect to an SSH daemon (or server). So an SSH client can initiate a connection to your PC which runs an SSH daemon. The client can send commands to the PC, the PC executes them. Is that what you mean?

Yes that is what I mean. I need the arduino yun to act as an ssh client to start an ssh session with another box and then execute some basic commands.

What do you mean that the ATmega doesn't have enough resources for an ssh client. Is this dependent on the work being done by the client or just in the setting up of the client / server

You need memory for at least the IP packets and session information as well as for the SSH keys. It would be useful if there was some memory left for regular tasks too. If you manage to squeeze that into maximum of 4kB RAM in the ATmega, then the key exchange would take ages because asymmetric key exchange is very CPU intensive.

You need to install package openssh-client: it's available in the package list. See this tutorial about how to install optional packages.
You can call ssh on the Linux side using Process from the Bridge Arduino library.
Best is when you execute single or grouped commands using a syntax as:
ssh user@your_other_host 'echo 1; echo 2'

Managing an open ssh session is possible but I think may be troublesome, so avoid it if you can.

Hi. Thanks for that answer. Im still struggling to get a fully operational ssh client. I can connect to the ssh server from the client but how do I receive data back from the server?

You can grab the output produced by the commands run on the server

source: Stack Exchange

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

sort: votes


text:
>> << and -> Syntax in arduino
I was trying to follow this tutorial and came across >>. What exactly does this do?

>> is right shift a value by a certain number of bits.
<< is left shift a value by a certain number of bits.
-> is accessing a member of a class or struct that is referenced by a pointer.
Right Shift and Left Shift
If you have a binary number 0b00010000 and right shift it two bits you get 0b00000100. The C notation for that is val >> 2.  The same for left shift - val << 2 would result in 0b01000000.
Pointers and members
Normally when you access a member of a class or struct you use ., such as Serial.println().  However it is possible to make a pointer to a class instance, and when you do you need to access the members with -> instead of . - such as mySerial->println().
This arrow notation serves as syntactic sugar: mySerial->println() is interpreted as (*mySerial).println(). The parentheses are necessary because the dereferencing operator * has a lower order of precedence compared to the dot . operator.

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


text:
Arduino recieving binary
I was wondering if Arduino digital pin can receive binary data. For example, I might want one Arduino to send another Arduino a binary code. If the code is 01 it would turn a red led on, if it was 11 it would turn green on, etc. I would like to do this so that I don't have to use a lot of digital pins. Is this possible with Arduino or not?

Pretty much anything is possible.
There is a method known as bit banging which toggles a generic IO pin to create a protocol, and read changes on another generic IO pin to read in the data of a protocol.
The trick is in creating a protocol.
Fortunately that has all been done for you - the SoftwareSerial library. It will create a bit banged version of the RS232 serial protocol using any combination of IO pins to transfer data between devices.

As Majenko says, it is easily possible to implement using bit banging.  Assuming that you want to write your own protocol, you need to distinguish between the end of one data packet and the start of another.  This could be done by having all of the packets the same length (as in your example with length 2) or using a form of Huffman coding where only the external nodes of the state tree are results so you know when a full packet has been received.
Using a standard serial or I2C protocol would also work.  With serial you would be able to communicate via a serial emulator on a USB port so you could test with a computer.


text:
how to serially communicate the arduino leonardo to pc through hyperterminal
I have connected mc to a pc using USB. I need data on hyperterminal through serial to USB connection, hence I connected TX, RX and gnd pins of the Leonardo to the rs232 pins and one other side of rs232 to USB to pc. However, the data is still transmitting on serial monitor, but not on hyperterminal.
int count = 0;

void setup() {
  Serial.begin(9600);
  pinMode(3,INPUT); // This is the pin to which we have connected the button
  attachInterrupt(0, IRsensor, CHANGE);
}

void loop() {
  if (Serial.available()) {
    /* read the most recent byte */
    /*ECHO the value that was read, back to the serial port. */
    Serial.write(count);
  }
}

void IRsensor() {
  if(digitalRead(3) == 1) {
    count++;
    Serial.println(count);
  }
}

hi sir thanku but i want external tool to know the data of arduino processed and to control it i am transfering data but it is not displaying on hyperterminal window

r else pls suggest me any tool to operate this connection serially

no need to call. Connect your arduino to pc with same usb that you use to program and open hyperterminal

see my updated answer

To be sure, please add code.
You can use usb on Arduino to communicate with pc. You don't need RS232/USB converter. Just open hyperterminal with the port of arduino. Arduino port can be found in:

Arduino IDE Tools>Port
My Computer>Properties>Device manager>Ports

If you really need SoftwareSerial then connect Rx,Tx and don't forget GND!
UPDATE
To communicate with RS232/USB converter you have to add RS232/TTL converter to Arduino side. The schematic would look like PC <-> USB/RS232 <-> RS232/TTL <-> Arduino:

PC - your computer
USB/RS232 to convert from usb to RS232. On RS232 side the voltage is -5V to +5V
MAX232 RS232/TTL. To convert the voltage
Arduino - your MCU

UPDATE 2
As i said, connect your arduino to PC like you do while programming.

Next, upload this sketch:
void setup() {
  Serial.begin(9600);
}

void loop() {
  if(Serial.available()){
   Serial.print("\nReceived: ");
   Serial.write(Serial.read());
  }
}

Open HyperTerminal: choose port with Arduino,

Connect to arduino, Serial Monitor has to be closed


text:
Mysterious RX pulses on UART connect on OS X Arduino Due
Arduino IDE 1.6.8, Arduino Due, Mac OS 10.11.3
I am seeing eight mysterious pulses on the RX line when I connect to the serial port using multiple client libraries (Python, JavaScript as well as the built-in Serial Monitor in the IDE). About 78-79us apiece, sampled at 1MS/s with a Logic Pro 16.

These eight pulses when interpreted at 57600 baud will jam the Firmata firmware. And they happen on every connection.
This is using a new install of the Arduino 1.6.8 IDE and with multiple sketches (the normal "Blink" sketch will reproduce this also).
Repro steps on my machine:

Install any sketch
Start a logic analyzer if you want to catch it
Go to Serial Monitor. I have mine configured for 57600 baud, Newline line ending, but it doesn't matter
If you want, close and repeat step 3
Note pulses each time you connect to the serial port

Any suggestions for diagnosing this? It sounds like it's serial driver-level in some way.

Regardless of where it is coming from, consider that it has done you a favor by indicating a critical bug in the firmware you are running - this should not be able to put it in an unrecoverable state.  Is it a program logic bug, or does the UART handling code not deal appropriately with an error flag?

In terms of tracking down the source, it would be helpful to try another serial  client program, another computer/operating system, another USB-serial device, etc...

Thanks for the input, Chris. When the Firmata firmware sees a 0xF0 START_SYSEX, it will process bytes until it sees a 0xF7, and there is no provision for a timeout. So I think what is happening is that these pulses generate a 0xF0 (you can see this from my decoding) which effectively turns off further command processing since there is no terminating 0xF7. I think that the best thing I can do for Firmata is submit a patch to time out after some interval that is long enough for the longest legitimate data packet.

As for trying other serial programs, there are multiple libraries that interact with the Firmata protocol and use different underlying serial implementations (Python, JavaScript and the built in Arduino IDE Serial Monitor) that exhibit the same behavior. My next plan is to try this on a Linux machine and see if I see the same behavior, which will hopefully isolate if this is OS X-specific.

You get a single pulse on Linux that is interpreted at 57600 as 0xF0

You also get one when you disconnect. The connection baud rate has no effect on the length of the pulse. My suspicion is that it's the ATMega16U2's firmware that is doing it (or whatever chip it is on whatever version).

Is your Arduino taking the power from the USB?

When you start the serial monitor, software resets the arduino module. If arduino module has bootloader in it, i think these are the STK500 protocol signals.

Short:
Looking at the ATMEGA16U2 firmware (https://github.com/arduino/ArduinoCore-sam/blob/master/firmwares/atmega16u2/arduino-usbserial/Arduino-usbserial.c) I find that, when you configure/change settings of the USB emulated serial port, the USART is resetted. This happens even when you open the Arduino Serial Monitor (it must configure the serial speed, etc.). This causes your spike.
Long:
Look at function:
void EVENT_CDC_Device_LineEncodingChanged(USB_ClassInfo_CDC_Device_t* const CDCInterfaceInfo)
There you'll see that after some lines, it resets the USART, by zeroing its registers:
/* Must turn off USART before reconfiguring it, otherwise incorrect operation may occur */
    UCSR1B = 0;
    UCSR1A = 0;
    UCSR1C = 0;

At page 168, of the current ATMEGA16U2 datasheet, you'll find that, by setting  UCSR1B's bit 3 (TXEN1), you enable the transmitter,  overriding the normal port operation (i.e. it becomes output). Quoting the datasheet:

Writing this bit to one enables the USART Transmitter. The Transmitter
  will override normal port operation for the TxDn pin when enabled. The
  disabling of the Transmitter (writing TXENn to zero) will not become
  effective until ongoing and pending transmissions are completed, i.e.,
  when the Transmit Shift Register and Transmit Buffer Register do not
  contain data to be transmitted. When disabled, the Transmitter will no
  longer override the TxDn port.

Therefore, by writing UCSR1B = 0; you no longer override the TXD1 pin, which will act as input.
The ATMEGA16U2 TXD is connected to the ATSAM3X8E's RX line. In normal operation, with the UART enabled, that line stays high if no data is being transmitted. If you disable the UART, that particular line is no more driver to 1. Since the initialization code does not set the pull-up on that pin (and neither it's configured as output), the pin becomes a floating input, and any leakage to GND or even the input impedance of your probe (which is between your pin and GND), will slowly bring the logic level to 0.
To override this, problem, you should either:
1) Modify ATMEGA16U2 firmware, by setting that PIN as OUTPUT, with value 1.
2) Modify ATMEGA16U2 firmware, by enabling the pull-up on that pin.
3) (suggested) Enable the pull-up on the RX line on the ATSAM3X8E.


text:
Stopping Serial on RX/TX pins while running Serial on USB
The Arduino/Genuino Micro has RX/TX pins and can do serial via USB.
But, Arduinos Serial ties them both together, so when using Serial.begin(9600) to send messages between my PC and the Arduino, I cannot use the RX/TX pins as GPIOs.
From what I can tell reading the Atmega32u4s Datasheet, the USART module on the chip is completely separate from the USB controller, so it should be possible to somehow disable the USART Transceiver and Receiver after executing Serial.begin(9600).
Is there something fundamental preventing me from doing this or can it be done? If it can, how would I do it?

The Serial and Serial1 are two seperated ports. They are not connected. The Serial is the USB serial and does not use pin 0 and 1 at all. The Serial1 is the hardware serial port at pin 0 and 1, but if Serial1 is not used then pin 0 and 1 are normal digital pins that you can use.
Don't be confused by the text labels printed on the board. Pin TX (also called TX1) is D1 and pin RX (also called RX1) is D0.
This is the pinmapping for the Micro: PighiXXX - Micro.
The Arduino Zero uses 'SerialUSB' to indicate the serial port via USB. You can do the same for the Leonardo and the Micro and use the alias 'SerialUSB' in your sketch instead of 'Serial'.
I found it more convenient to use 'SerialUSB' in my sketch, but not many people use it.
The Serial port at pin 0 and 1 is still called 'Serial1'.

There is no real reason why it should be tied somehow. And running simple test program seconds that:
void setup() {
  pinMode(0, OUTPUT);
  pinMode(1, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  digitalWrite(0, LOW);
  delay(400);
  digitalWrite(0, HIGH);
  digitalWrite(1, LOW);
  delay(1000);
  digitalWrite(1, HIGH);
  Serial.println("something");
}

LEDs on TX and RX pins blinks and USB Serial is sending the message (Genuine Arduino Micro, Arduino IDE 1.8.1)


text:
Upload of sketch with avrdude stuck only outside of IDE
When uploading my sketch to my Genuino Micro with the Arduino IDE, everything works perfectly. This is the command issued:
C:\Users\<user>\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino8/bin/avrdude
-CC:\Users\<user>\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino8/etc/avrdude.conf
-v -patmega32u4 -cavr109 -PCOM10 -b57600 -D
-Uflash:w:C:\Users\<user>\AppData\Local\Temp\arduino_build_31080/KeyboardBase.ino.hex:i

All just working like it should (except that the com-port selected is actually COM6, not COM10).
But, if I try to use that exact same command from the command line, avrdude gets stuck for minutes and the arduino is still executing the sketch I've put on it.
C:\Users\<user>\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino8/bin/avrdude
-CC:\Users\<user>\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino8/etc/avrdude.conf
-v -patmega32u4 -cavr109 -PCOM6 -b57600 -D
-Uflash:w:C:\Users\<user>\AppData\Local\Temp\arduino_build_31080/KeyboardBase.ino.hex:i

avrdude: Version 6.3, compiled on Dec 16 2016 at 13:33:19
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Users\<user>\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino8/etc/avrdude.conf"

         Using Port                    : COM6
         Using Programmer              : avr109
         Overriding Baud Rate          : 57600
         AVR Part                      : ATmega32U4
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PA0
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : butterfly
         Description     : Atmel AppNote AVR109 Boot Loader

Connecting to programmer: .^C

avrdude needs to be run from cmd because I'm building a sketch with partly modified libraries, so it's built and uploaded manually with make.
I already tried running cmd as administrator, using -v -v to get more info, and changing the baud-rate, plugging the Arduino into a different USB port and restarting my machine (the same problem occurred yesterday but I didn't manage to fix it) none of that helped. What else can I try?

Are you sure that the com port is 6 instead of 10? If the Arduino IDE doesn't have problems uploading on that port, should you try 10? Or did you just plug it into a different port that time you programmed it

I recommend reading the "Uploading Code to the Leonardo, Leonardo ETH and Micro" section of https://www.arduino.cc/en/Guide/ArduinoLeonardoMicro. There are some special things that need to be done to upload to the ATmega32U4 boards: First the serial port is opened at 1200 baud and then closed, which signals to the firmware that it should reset the microcontroller. After the reset that serial port disappears and the IDE waits for a new port to appear before uploading to that port. Some of this may be done via the IDE rather than solely AVRDUDE. You could try using the Arduino IDE CLI instead.

@CarrotM No, the two commands you see where issued directly after one another, the Arduino was plugged into the exact same port. The IDE displays the Arduino being connected on COM6 in the GUI as well.
Trying to use COM10 on cmd leads to a hard fail with a "system couldn't find this path" error message, so it's just the IDEs verbose mode bugging out there.

@per1234 that seems to be a good indication of what's going wrong, I'll try that out this evening!

Ok, I managed to make it happen. Thanks for your help!

@per1234 was correct:

Note that the auto-reset is initiated when the computer opens the serial port at 1200 baud and then closes it

From Arduino.cc
In practise, this means that avrdude first has to be executed like so:
$ avrdude -patmega32u4 -cavr109 -PCOM6 -b1200

Where COM6 is the same serial port the arduino is being displayed on in the Arduino IDE. The exit code of this will not be 0 and display a lot of error messages (even with -q -q), but it does exactly what it should.
After a short delay (in a makefile, use sleep 1), the Arduino will reconnect, ready to be programmed. That's when the actual programming command has to be issued:
$ avrdude -v -patmega32u4 -cavr109 -PCOM10 -b57600 -D -Uflash:w:mysketch.ino.hex:i

Notice that the serial port is now a different one! That's why the Arduino IDE actively searches for a new Arduino instead of using the same serial port set in the "Tools" menu, as I pointed out in my question.


text:
How does avrdude burn a bootloader much quicker than the Arduino IDE?
To burn a bootloader to the Arduino Micro (ATMega32u4), I'm using an Arduino Uno with the ArduinoISP program uploaded to it.
1st case: Arduino IDE
Very straightforward, using the ArduinoISP sketch included in the IDE.

From clicking on "Burn Bootloader" to the output window displaying "Done burning bootloader", it takes 61 seconds.
2nd case: avrdude
I'm running avrdude directly from the Arduino IDE's folder like so (line breaks added for your reading pleasure):
D:\Programme\Arduino\hardware\tools\avr\bin>avrdude.exe -v -v -c arduino
-p atmega32u4 -P com4 -b 19200
-U flash:w:"..\..\..\arduino\avr\bootloaders\caterina\Caterina-Genuino-Micro.hex"

From pressing Enter to avrdude.exe done.  Thank you. displaying on stdout, it only takes 11 seconds. Full output is posted below.
 D:\Programme\Arduino\hardware\tools\avr\bin>avrdude.exe -v -v -c arduino -p atmega32u4 -P com4 -b 19200 -U flash:w:"..\..\..\arduino\avr\bootloaders\caterina\Caterina-Genuino-Micro.hex"

avrdude.exe: Version 6.3, compiled on Sep 12 2016 at 17:24:16
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "D:\Programme\MHV AVR Tools\bin\avrdude.conf"

         Using Port                    : com4
         Using Programmer              : arduino
         Overriding Baud Rate          : 19200
         AVR Part                      : ATmega32U4
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PA0
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : Arduino
         Description     : Arduino
         Hardware Version: 2
         Firmware Version: 1.18
         Topcard         : Unknown
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

avrdude.exe: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.02s

avrdude.exe: Device signature = 0x1e9587 (probably m32u4)
avrdude.exe: safemode: hfuse reads as D8
avrdude.exe: safemode: efuse reads as CB
avrdude.exe: NOTE: "flash" memory has been specified, an erase cycle will be performed
         To disable this feature, specify the -D option.
avrdude.exe: erasing chip
avrdude.exe: reading input file "..\..\..\arduino\avr\bootloaders\caterina\Caterina-Genuino-Micro.hex"
avrdude.exe: input file ..\..\..\arduino\avr\bootloaders\caterina\Caterina-Genuino-Micro.hex auto detected as Intel Hex
avrdude.exe: writing flash (32730 bytes):

Writing | ################################################## | 100% 0.25s

avrdude.exe: 32730 bytes of flash written
avrdude.exe: verifying flash memory against ..\..\..\arduino\avr\bootloaders\caterina\Caterina-Genuino-Micro.hex:
avrdude.exe: load data flash data from input file ..\..\..\arduino\avr\bootloaders\caterina\Caterina-Genuino-Micro.hex:
avrdude.exe: input file ..\..\..\arduino\avr\bootloaders\caterina\Caterina-Genuino-Micro.hex auto detected as Intel Hex
avrdude.exe: input file ..\..\..\arduino\avr\bootloaders\caterina\Caterina-Genuino-Micro.hex contains 32730 bytes
avrdude.exe: reading on-chip flash data:

Reading | ################################################## | 100% 0.35s

avrdude.exe: verifying ...
avrdude.exe: 32730 bytes of flash verified

avrdude.exe: safemode: hfuse reads as D8
avrdude.exe: safemode: efuse reads as CB
avrdude.exe: safemode: Fuses OK (E:CB, H:D8, L:FF)

avrdude.exe done.  Thank you.

Question:
Where does this discrepancy come from? The baud rate is hard coded to be 19200 in the ArduinoISP sketch, so that can't be it.

Given that the IDE uses avrdude to do this, it's a bit odd, but you should probably turn on verbose mode and look at the actual command line issued.  Note that the baud rate of sending data from the ISP sketch to the target is distinct from the baud rate of communicating with the ISP adapter.   avrdude supports varying this, but my memory was of the ISP sketch ignoring that specification.

@ChrisStratton It looks like the problem isn't with avrdude, but the hex file. Arduino IDE ships with both a Caterina-Micro.hex and a Caterina-Genuino-Micro.hex. The former is what the IDE uses, the latter is what I used with avrdude. There are differences between the files and burning the latter is very quick but doesn't actually work.

In the Arduino IDE do this:

File > Preferences > Show verbose output during: > upload (check) > OK
Tools > Burn Bootloader

After it finishes examine the output in the black console window at the bottom of the Arduino IDE window. If you look carefully you'll see that the Arduino IDE actually runs two separate AVRDUDE commands when you Burn Bootloader. The first sets the fuses according to the settings in boards.txt for the selected board, the second actually burns the bootloader. So your comparison is not really fair unless you run both commands in your test of using AVRDUDE directly.
Edit by OP:
Full output in the Arduino IDE:
D:\Programme\Arduino\hardware\tools\avr/bin/avrdude -CD:\Programme\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega32u4 -cstk500v1 -PCOM4 -b19200 -e -Ulock:w:0x3F:m -Uefuse:w:0xcb:m -Uhfuse:w:0xd8:m -Ulfuse:w:0xff:m

avrdude: Version 6.3, compiled on Sep 12 2016 at 17:24:16
     Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
     Copyright (c) 2007-2014 Joerg Wunsch

     System wide configuration file is "D:\Programme\Arduino\hardware\tools\avr/etc/avrdude.conf"

     Using Port                    : COM4
     Using Programmer              : stk500v1
     Overriding Baud Rate          : 19200
     AVR Part                      : ATmega32U4
     Chip Erase delay              : 9000 us
     PAGEL                         : PD7
     BS2                           : PA0
     RESET disposition             : dedicated
     RETRY pulse                   : SCK
     serial program mode           : yes
     parallel program mode         : yes
     Timeout                       : 200
     StabDelay                     : 100
     CmdexeDelay                   : 25
     SyncLoops                     : 32
     ByteDelay                     : 0
     PollIndex                     : 3
     PollValue                     : 0x53
     Memory Detail                 :

                              Block Poll               Page                       Polled
       Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
       ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
       eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
       flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
       lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
       signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

     Programmer Type : STK500
     Description     : Atmel STK500 Version 1.x firmware
     Hardware Version: 2
     Firmware Version: 1.18
     Topcard         : Unknown
     Vtarget         : 0.0 V
     Varef           : 0.0 V
     Oscillator      : Off
     SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x1e9587 (probably m32u4)
avrdude: erasing chip
avrdude: reading input file "0x3F"
avrdude: writing lock (1 bytes):

D:\Programme\Arduino\hardware\tools\avr/bin/avrdude -CD:\Programme\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega32u4 -cstk500v1 -PCOM4 -b19200 -Uflash:w:D:\Programme\Arduino\hardware\arduino\avr/bootloaders/caterina/Caterina-Micro.hex:i -Ulock:w:0x2F:m
Writing | ################################################## | 100% 0.01s

avrdude: 1 bytes of lock written
avrdude: verifying lock memory against 0x3F:
avrdude: load data lock data from input file 0x3F:
avrdude: input file 0x3F contains 1 bytes
avrdude: reading on-chip lock data:

Reading | ################################################## | 100% 0.01s

avrdude: verifying ...
avrdude: 1 bytes of lock verified
avrdude: reading input file "0xcb"
avrdude: writing efuse (1 bytes):

Writing | ################################################## | 100% 0.01s

avrdude: 1 bytes of efuse written
avrdude: verifying efuse memory against 0xcb:
avrdude: load data efuse data from input file 0xcb:
avrdude: input file 0xcb contains 1 bytes
avrdude: reading on-chip efuse data:

Reading | ################################################## | 100% 0.01s

avrdude: verifying ...
avrdude: 1 bytes of efuse verified
avrdude: reading input file "0xd8"
avrdude: writing hfuse (1 bytes):

Writing | ################################################## | 100% 0.01s

avrdude: 1 bytes of hfuse written
avrdude: verifying hfuse memory against 0xd8:
avrdude: load data hfuse data from input file 0xd8:
avrdude: input file 0xd8 contains 1 bytes
avrdude: reading on-chip hfuse data:

Reading | ################################################## | 100% 0.01s

avrdude: verifying ...
avrdude: 1 bytes of hfuse verified
avrdude: reading input file "0xff"
avrdude: writing lfuse (1 bytes):

Writing | ################################################## | 100% 0.01s

avrdude: 1 bytes of lfuse written
avrdude: verifying lfuse memory against 0xff:
avrdude: load data lfuse data from input file 0xff:
avrdude: input file 0xff contains 1 bytes
avrdude: reading on-chip lfuse data:

Reading | ################################################## | 100% 0.01s

avrdude: verifying ...
avrdude: 1 bytes of lfuse verified

avrdude done.  Thank you.

avrdude: Version 6.3, compiled on Sep 12 2016 at 17:24:16
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "D:\Programme\Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM4
         Using Programmer              : stk500v1
         Overriding Baud Rate          : 19200
         AVR Part                      : ATmega32U4
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PA0
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : STK500
         Description     : Atmel STK500 Version 1.x firmware
         Hardware Version: 2
         Firmware Version: 1.18
         Topcard         : Unknown
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x1e9587 (probably m32u4)
avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed
         To disable this feature, specify the -D option.
avrdude: erasing chip
avrdude: reading input file "D:\Programme\Arduino\hardware\arduino\avr/bootloaders/caterina/Caterina-Micro.hex"
avrdude: writing flash (32730 bytes):

Writing | ################################################## | 100% 35.65s

avrdude: 32730 bytes of flash written
avrdude: verifying flash memory against D:\Programme\Arduino\hardware\arduino\avr/bootloaders/caterina/Caterina-Micro.hex:
avrdude: load data flash data from input file D:\Programme\Arduino\hardware\arduino\avr/bootloaders/caterina/Caterina-Micro.hex:
avrdude: input file D:\Programme\Arduino\hardware\arduino\avr/bootloaders/caterina/Caterina-Micro.hex contains 32730 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 19.92s

avrdude: verifying ...
avrdude: 32730 bytes of flash verified
avrdude: reading input file "0x2F"
avrdude: writing lock (1 bytes):

Writing | ################################################## | 100% 0.02s

avrdude: 1 bytes of lock written
avrdude: verifying lock memory against 0x2F:
avrdude: load data lock data from input file 0x2F:
avrdude: input file 0x2F contains 1 bytes
avrdude: reading on-chip lock data:

Reading | ################################################## | 100% 0.01s

avrdude: verifying ...
avrdude: 1 bytes of lock verified

avrdude done.  Thank you.

Thanks, that seems to be correct! There's quite a lot of stuff the IDE is doing, including reading a lock byte apparently.

So as it turns out, there seems to be more to this. Burning the fuses takes less than a second. I'll investigate further.

If you look at the output above, you'll notices that not only does the Arduino IDE write the firmware, it also verifies it. The verification process has to read the entire flash memory after the firmware is written, and the result must be compared to the source file. As shown in the output, the firmware verification takes almost a full 20 seconds.

authors: Станислав Царюк

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


text:
Trouble using proximity sensor as input and LED output
I was wondering if anyone had any pointers or advice to make this project work. Essentially I would like to have the LED fade (meaning like fade on and off at a calm rate) at one rate when there is nothing close to the proximity sensor, and then to speed up the fade amount when there is something close to the sensor.
#include <NewPing.h>   //include the library

int led = 9;           // the PWM pin the LED is attached to
int brightness = 0;    // how bright the LED is
int fadeAmount;    // how many points to fade the LED by

int triggerPin = 12;   //pin conneccted to the Trig pin on the sensor
int echoPin = 11;       //pin connected to the Echo pin on the sensor
int maxDistance = 200;  //set the max distance for the sensor to read (helps with errors)
int distanceVal;        //variable to hold the distance val

int sampleRate = 200;   //how fast to sample the value
long lastReading;       //used for the timer

NewPing proximity1(triggerPin, echoPin, maxDistance);   //sets up the sensor object

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

void loop() {

    if(millis()-lastReading>=sampleRate) //this very simple statement is the timer,
  {
  distanceVal = proximity1.ping_cm();  //get the distance value in centimeters

  lastReading = millis();

  Serial.print("Distance Reading CM : ");  //print the value to the Serial monitor
  Serial.println(distanceVal);

if(distanceVal<20){

fadeAmount = 5;
}
else{
  fadeAmount = 2;
}

  // set the brightness of pin 9:
  analogWrite(led, brightness);

  // change the brightness for next time through the loop:
  brightness = brightness + fadeAmount;

  // reverse the direction of the fading at the ends of the fade:
  if (brightness <= 0 || brightness >= 255) {
    fadeAmount = -fadeAmount;
  }
  // wait for 30 milliseconds to see the dimming effect
  delay(30);
  }
}

https://github.com/sanaalla/Fade-LED-with-Proximity-sensor
Above is my code, which is not working. I am fairly new to Arduino and so would greatly appreciate some more seasoned wisdom!

I'm on my mobile, so I can't test anything. For me the link is not working in the app (you can copy the code in the question, formatting it as code, this is recommended as in the future the link may be broken). And "it's not working" is not the most accurate way of describing your problem. Does the code not compile? Does your actual physical setup not work? Post a schematic!

You want 2 independant loops, one for the measurement and one for the dimming effect. The latter one must also be able to run when not measuring.
if(millis()-lastReading>=sampleRate) //this very simple statement is the timer,
{
  distanceVal = proximity1.ping_cm();  //get the distance value in centimeters

  lastReading = millis();

  Serial.print("Distance Reading CM : ");  //print the value to the Serial monitor
  Serial.println(distanceVal);
}

if(millis() - lastFade >= fadeRate) //other timer
{
  lastFade = millis();
  if(distanceVal<20){
    fadeAmount = 5;
  }else{
    fadeAmount = 2;
  }

  // set the brightness of pin 9:
  analogWrite(led, brightness);

  // change the brightness for next time through the loop:
  brightness = brightness + fadeAmount;

  // reverse the direction of the fading at the ends of the fade:
  if (brightness <= 0 || brightness >= 255) {
    fadeAmount = -fadeAmount;
  }
}

*update! I fixed the code and got it to do what I want.
#include <NewPing.h>   //include the library

int led = 9;           // the PWM pin the LED is attached to
int brightness = 0;    // how bright the LED is
int fadeAmount1 = 10;    // how many points to fade the LED by
int fadeAmount2 = 2;    // how many points to fade the LED by

int triggerPin = 12;   //pin conneccted to the Trig pin on the sensor
int echoPin = 11;       //pin connected to the Echo pin on the sensor
int maxDistance = 200;  //set the max distance for the sensor to read (helps with errors)
int distanceVal; //variable to hold the distance val
int lastFade;
int fadeRate = 200;

int sampleRate = 200;   //how fast to sample the value
long lastReading;       //used for the timer

NewPing proximity1(triggerPin, echoPin, maxDistance);   //sets up the sensor object

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

void loop() {

  if(millis()-lastReading>=sampleRate) //this very simple statement is the timer,
{
  distanceVal = proximity1.ping_cm();  //get the distance value in centimeters

  lastReading = millis();

  Serial.print("Distance Reading CM : ");  //print the value to the Serial monitor
  Serial.println(distanceVal);
}

if(distanceVal<20){

    // set the brightness of pin 9:
  analogWrite(led, brightness);

  // change the brightness for next time through the loop:
  brightness = brightness + fadeAmount1;

  // reverse the direction of the fading at the ends of the fade:
  if (brightness <= 0 || brightness >= 255) {
    fadeAmount1 = -fadeAmount1;
  }
  // wait for 30 milliseconds to see the dimming effect
  delay(30);
}

else{

    // set the brightness of pin 9:
  analogWrite(led, brightness);

  // change the brightness for next time through the loop:
  brightness = brightness + fadeAmount2;

  // reverse the direction of the fading at the ends of the fade:
  if (brightness <= 0 || brightness >= 255) {
    fadeAmount2 = -fadeAmount2;
  }
  // wait for 30 milliseconds to see the dimming effect
  delay(30);
}

}


text:
Arduino 4wd rover
Guys i have made an arduino 4wd rover using L298N BRIDGE MODULE, HC-05 and Arduino uno but the power supply output of L298N was very low that even 1 motor is working too slow so please help me with power out put please...
Here is the code...
#define enA 9
#define in1 4
#define in2 5
#define enB 10
#define in3 6
#define in4 7

int xAxis, yAxis;
int  x = 0;
int  y = 0;

int motorSpeedA = 0;
int motorSpeedB = 0;

void setup() {
  pinMode(enA, OUTPUT);
  pinMode(enB, OUTPUT);
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);
  pinMode(in3, OUTPUT);
  pinMode(in4, OUTPUT);

  Serial.begin(38400); // Default communication rate of the Bluetooth module
}

void loop() {
  // Default value - no movement when the Joystick stays in the center
  xAxis = 510;
  yAxis = 510;

  // Read the incoming data from the Smartphone Android App
  while (Serial.available() >= 2) {
    x = Serial.read();
    delay(10);
    y = Serial.read();
  }
  delay(10);

  // Makes sure we receive corrent values
  if (x > 60 & x < 220) {
    xAxis = map(x, 220, 60, 1023, 0); // Convert the smartphone X and Y values to 0 - 1023 range, suitable motor for the motor control code below
  }
  if (y > 60 & y < 220) {
    yAxis = map(y, 220, 60, 0, 1023);
  }

  // Y-axis used for forward and backward control
  if (yAxis < 470) {
    // Set Motor A backward
    digitalWrite(in1, HIGH);
    digitalWrite(in2, LOW);
    // Set Motor B backward
    digitalWrite(in3, HIGH);
    digitalWrite(in4, LOW);
    // Convert the declining Y-axis readings for going backward from 470 to 0 into 0 to 255 value for the PWM signal for increasing the motor speed
    motorSpeedA = map(yAxis, 470, 0, 0, 255);
    motorSpeedB = map(yAxis, 470, 0, 0, 255);
  }
  else if (yAxis > 550) {
    // Set Motor A forward
    digitalWrite(in1, LOW);
    digitalWrite(in2, HIGH);
    // Set Motor B forward
    digitalWrite(in3, LOW);
    digitalWrite(in4, HIGH);
    // Convert the increasing Y-axis readings for going forward from 550 to 1023 into 0 to 255 value for the PWM signal for increasing the motor speed
    motorSpeedA = map(yAxis, 550, 1023, 0, 255);
    motorSpeedB = map(yAxis, 550, 1023, 0, 255);
  }
  // If joystick stays in middle the motors are not moving
  else {
    motorSpeedA = 0;
    motorSpeedB = 0;
  }

  // X-axis used for left and right control
  if (xAxis < 470) {
    // Convert the declining X-axis readings from 470 to 0 into increasing 0 to 255 value
    int xMapped = map(xAxis, 470, 0, 0, 255);
    // Move to left - decrease left motor speed, increase right motor speed
    motorSpeedA = motorSpeedA - xMapped;
    motorSpeedB = motorSpeedB + xMapped;
    // Confine the range from 0 to 255
    if (motorSpeedA < 0) {
      motorSpeedA = 0;
    }
    if (motorSpeedB > 255) {
      motorSpeedB = 255;
    }
  }
  if (xAxis > 550) {
    // Convert the increasing X-axis readings from 550 to 1023 into 0 to 255 value
    int xMapped = map(xAxis, 550, 1023, 0, 255);
    // Move right - decrease right motor speed, increase left motor speed
    motorSpeedA = motorSpeedA + xMapped;
    motorSpeedB = motorSpeedB - xMapped;
    // Confine the range from 0 to 255
    if (motorSpeedA > 255) {
      motorSpeedA = 255;
    }
    if (motorSpeedB < 0) {
      motorSpeedB = 0;
    }
  }
  // Prevent buzzing at low speeds (Adjust according to your motors. My motors couldn't start moving if PWM value was below value of 70)
  if (motorSpeedA < 70) {
    motorSpeedA = 0;
  }
  if (motorSpeedB < 70) {
    motorSpeedB = 0;
  }
  analogWrite(enA, motorSpeedA); // Send PWM signal to motor A
  analogWrite(enB, motorSpeedB); // Send PWM signal to motor B
}

What is the battery? Are you using geared motors?

I am using 9v battery and yes it is a geared motor.....

A wimpy PP3? ...?

The 9V battery is meant for low power applications. You will need to find another powersource

While your primary problem is improper battery selection (try 6 to 8 AA cells) also beware that the L298 (and L293D, etc) is an antiquated, horribly lossy driver.  These really shouldn't be sold for Arduino or other low-voltage projects - they continue to be because people keep copying a mistake that was already wrong even when it was made now many years ago.  Typically when using AA cells and an L298, you need an extra cell or two in the pack just to offset the L298's losses.

Can i use a powerbank with 10000 Mah battery...?

@CodeGorilla That question doesn't have an answer though.

You need more power!
The formula for power is Volts * Amps. A PP3 has about 500mAh, which means its can (in theory) output 9V at 500mA for an hour, which means you have about 4.5 watts.
So what power do your motors need? I'll assume they are about 1.5W motors, which means you need 6W to drive all the motors.
Your PP3 can output 6W, but it won't last long if it does and it will get hot.  Also, if you have 12V motors and are only giving the 9V then they are going to be asking for 1/3 more amps to balance the equation and get their power.  You are probably asking the PP3 to supply 1A which means it will last less than 30 minutes if it is brand new and good quality.
A "simple" solution would be to use two (or more) batteries in parallel.  Parallel gives you more power without changing the voltage.  A better solution would be to look at alternative battery packs, a couple or LiPo 3.7V 1100mAh battery packs, a sealed lead acid gel (heavy).  An even better solution would be to see if you can get lower power motors that can supply the same torque.
Failing that, get a meaty desktop power supply and a long cable :)

Can i use a powerbank with 10000 Mah battery...?

Maybe -\o/-  It will either work or it won't

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


text:
Multiple timers with different frequencies
I have to use multiple timers (for example, to blink different LEDs) with different frequency (for example, 7.3 Hz). Cannot you tell me, what is the preferred way to implement it?
Just now I use one simple TimerOne timer and just check what LEDs should be inverted and what are not, but I don't think it's a good idea.
#include <TimerOne.h>

#define PIN_RED 52
#define PIN_GREEN 50
#define PIN_BLUE 48
#define PIN_YELLOW 46

#define N_LEDS 4

float freqs[N_LEDS] = {1, 2, 3, 4};
int pins[N_LEDS] = {PIN_RED, PIN_GREEN, PIN_BLUE, PIN_YELLOW};

long int usec_to_invert[N_LEDS];
long int full_usec_to_invert[N_LEDS];

boolean led_states[N_LEDS];

int who_is_next()
{
  int next_to_invert = 0;
  for(int i = 0; i < N_LEDS; i++)
  {
    if(usec_to_invert[i] < usec_to_invert[next_to_invert])
    {
      next_to_invert = i;
    }
  }
  return next_to_invert;
}

void process_timer()
{
  int to_invert_now = who_is_next(); // Смотрим, кого надо инвертировать на этот раз
  long int time_past = usec_to_invert[to_invert_now];

  for(int i = 0; i < N_LEDS; i++)
  {
    usec_to_invert[i] -= time_past;
  }
  led_states[to_invert_now] = !led_states[to_invert_now];
  digitalWrite(pins[to_invert_now], led_states[to_invert_now]);
  usec_to_invert[to_invert_now] = full_usec_to_invert[to_invert_now];

  int next_to_invert = who_is_next();
  long int time_to_pass = usec_to_invert[next_to_invert];
  if(time_to_pass <= 200)
  {  // The interrupt processor should finish work
    Timer1.setPeriod(200);
  }
  else
  {
    Timer1.setPeriod(time_to_pass);
  }
}

void setup()
{
  Serial.begin(115200);
  for(int i = 0; i < N_LEDS; i++)
  {
    pinMode(pins[i], OUTPUT);
    led_states[i] = false;
    full_usec_to_invert[i] = (long int)(1000000. / freqs[i] / 2.);
    usec_to_invert[i] = full_usec_to_invert[i];
  }

  int next_to_invert = who_is_next();
  Timer1.initialize(usec_to_invert[next_to_invert]);
  Timer1.attachInterrupt(process_timer);
}

void loop()
{
   delay(1000);
}

My suggestions would be:

Implement a class that handles the queue and timer settings and uses callbacks.
If you do not need perfect accuracy, remove the loop making the program wait and do that part just setting the timer.
digitalRead() on an output pin returns the value it was last set to, therefore you do not need to waste that extra RAM.
DO NOT wait in the ISR "process_timer()", since you might lose other interrupts! (for the Serial communication, for example)
is it neccessary to have only values above 200? if not, then don't prevent them from going below that.

--or
use a total overkill system for this situation, such as my multitasking-library arduOS that also covers a some other things.


text:
Error: 'SofwareSerial' does not name a type
I have trouble compiling this sketch. The error I get is

'SoftwareSerial' does not name a type

Any ideas how could I fix it?
#include SoftwareSerial.h

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

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

  Serial.println("Ready!");

  // set the data rate for the SoftwareSerial port

  // for HC-05 use 38400 when poerwing with KEY/STATE set to HIGH on power on
  mySerial.begin(9600);
}

void loop() // run over and over
{
  if (mySerial.available())
    Serial.write(mySerial.read());
  if (Serial.available())
    mySerial.write(Serial.read());
}

After doing this, I find that SoftwareSerial has a problem in it. Simply by coding #include "SoftwareSerial.h" and not even doing this: //SoftwareSerial Serial(RX, TX); Without SoftwareSerial, I have no idea where to get the output. It does not seem to want to send it to the Serial monitor. That's because there is no Port to select. So I am still stuck. I still get this error: C:\Users\mikey\Documents\Arduino\libraries\attiny_software_serial-master/SoftwareSerial.h:70:17: error: redeclaration of C++ built-in type 'bool' [-fpermissive] typedef uint8_t bool;

Add to @geometrikal.
or
#include <SoftwareSerial.h>

You forgot the quotation marks, try
#include "SoftwareSerial.h"

#include "SoftwareSerial.h" worked instead of

#include <SoftwareSerial.h>
ie " " not <>


text:
Formula / calculation of the function random() / randomSeed()
In which file can I find the calculation that is called with random()? If it is not too much could you also post the content in your answer? I am using an Arduino Uno and its standard IDE.
I found this in the "WMath.cpp" but that is not the final calculation.
void randomSeed(unsigned int seed)
{
  if (seed != 0) {
    srandom(seed);
  }
}

long random(long howbig)
{
  if (howbig == 0) {
    return 0;
  }
  return random() % howbig;
}

long random(long howsmall, long howbig)
{
  if (howsmall >= howbig) {
    return howsmall;
  }
  long diff = howbig - howsmall;
  return random(diff) + howsmall;
}

The underlying random() function isn't part of the Arduino code. It's actually part of avr-libc. The Arduino IDE only comes with pre-compiled object code for it (as far as I know).
It's open source though. You can get information about it here:

http://www.nongnu.org/avr-libc

If you look down the page a short way, you'll find the "Source code and documentation" link.
The random() function is under libc/stdlib/random.c. I would paste the source code here, but technically I'd have to include a whole copyright notice with it.

That are 76 lines with copyright, so why not post it?

@kimliv - To be honest, I'd feel discourteous posting a significant piece of someone else's library code without their permission.

But with copyright it is ok an the writer of the library was not the inventor of the algorithm I guess. (What is the main job for me)

Read Peter Bloomfield's answer here: https://arduino.stackexchange.com/a/1482/7727
Then read the following:
For everyone's reference, Arduino's WMath.cpp is found here.
Documentation for AVR-Libc's random() function is here.
Source code for AVR-Libc is found here, as linked-to from here.
I downloaded "avr-libc-2.0.0.tar.bz2.sig    08-Feb-2016" and extracted it. Like Peter said, the source code for "random" is in "avr-libc-2.0.0\libc\stdlib\random.c"
To save you the hassle, here's the source code, with their included copyright and license statement right at the top of it.
/*-
 * Copyright (c) 1990, 1993
 *  The Regents of the University of California.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * Posix rand_r function added May 1999 by Wes Peters <wes@softweyr.com>.
 *
 * $Id: random.c 1944 2009-04-01 23:12:20Z arcanum $
 */

/*
 * From:
static char sccsid[] = "@(#)rand.c  8.1 (Berkeley) 6/14/93";
*/

#include <stdlib.h>
#include "sectionname.h"

ATTRIBUTE_CLIB_SECTION
static long
do_random(unsigned long *ctx)
{
    /*
     * Compute x = (7^5 * x) mod (2^31 - 1)
     * wihout overflowing 31 bits:
     *      (2^31 - 1) = 127773 * (7^5) + 2836
     * From "Random number generators: good ones are hard to find",
     * Park and Miller, Communications of the ACM, vol. 31, no. 10,
     * October 1988, p. 1195.
     */
    long hi, lo, x;

    x = *ctx;
    /* Can't be initialized with 0, so use another value. */
    if (x == 0)
        x = 123459876L;
    hi = x / 127773L;
    lo = x % 127773L;
    x = 16807L * lo - 2836L * hi;
    if (x < 0)
        x += 0x7fffffffL;
    return ((*ctx = x) % ((unsigned long)RANDOM_MAX + 1));
}

ATTRIBUTE_CLIB_SECTION
long
random_r(unsigned long *ctx)
{
    return do_random(ctx);
}

static unsigned long next = 1;

ATTRIBUTE_CLIB_SECTION
long
random(void)
{
    return do_random(&next);
}

ATTRIBUTE_CLIB_SECTION
void
srandom(unsigned long seed)
{
    next = seed;
}


text:
XBee+Arduino communication problem
I tried testing the system and I’m not sure if the problem is with the XBee’s, the transmitting code, or the receiving code. Before I post my code, I will explain what we are doing with the signals.
We have three analog signals that will be sent serially through one XBee using an Arduino and XBee shield.  We want to send these signals to the receiving xbee where the Arduino will output these signals to be connected to a third Arduino through wires to be used in a Simulink program.
We are using an Arduino mega for the transmitting side and an Arduino uno for the receiving side. I was told I need to do serial streaming but I’m not sure how that’s done. I understand the XBee and Arduinos both digitize signals but we are hoping to get a signal very similar to the analog signals we are transmitting. Any amount of help is greatly appreciated!!
This is how I have my XBees configured (series 1) both in AT mode:

Transmitting XBee:
      Channel:10
      Pan id: 1234
      MY: 10
      DL: 11
Receiving XBee:
      Channel:10
      Pan ID: 1234
      MY: 11
      DL: 10

Transmitting Arduino code:
void setup() {
  Serial.begin(9600);
}
void loop() {
  // read the input on analog pins
  int sensorValue1 = analogRead(A0);
  int sensorValue2 = analogRead(A1);
  int sensorValue3 = analogRead(A2);
  // print out the value you read:
  Serial.println(sensorValue1);
  Serial.println(sensorValue2);
  Serial.println(sensorValue3);
  delay(1);
}

Receiving Arduino code:
int received1=8;
int received2=9;
int received3=10;
void setup(){
  pinMode(received1, OUTPUT);
  pinMode(received2, OUTPUT);
  pinMode(received3, OUTPUT);
  Serial.begin(9600);
}
void loop(){
  if(Serial.available() )
  {
    byte output1 = Serial.read();
    byte output2 = Serial.read();
    byte output3 = Serial.read();
    digitalWrite(received1, HIGH);
    digitalWrite(received2, HIGH);
    digitalWrite(received3, HIGH);
  }
}

There are several things here:

Increase your delay, you don't want to be sending the data that often, even if you only increase it to 100-200ms, although I'd recommend making it in the order of 1-30 seconds.
You're reading in analog inputs which will be in the range of 0-1023 but your serial reads are in byte format (which will actually be reading the first three bytes (or the first three DIGITS of the first reading). More about this below.
You're reading in three arbitrary bytes, you're not identifying them at all, you have no idea what you're reading (other than by testing for a 1ms delay--which over XBee is not practical).

You have two options, transmit the data as ASCII (not a good idea IMHO), pre-pending some identifier such that:
1:259
2:0
3:1019

or even some other delimiter:
259:0:1019

But I would probably lean towards byte encoding:
byte0 :0xEA    // just some custom header for yourself
byte1H:0x01
byte1L:0x03
byte2H:0x00
byte2L:0x00
byte3H:0x03
byte3L:0xFB
byte4 :0xXX    // checksum

Or you could map the inputs down to a range of 0-255 for single byte transmission.
Next you'll need to work on receiving the data, how you do that is going to depend on how you encode the stream.
edit: I've removed the code sample that was here and replaced it with two working sketches below.

I have two XBees, running in AT mode, mine are Series 2, but programatically I THINK they are the same. If not, you'll have to tweak these, but I'm pretty sure you'll be right.
What we have are two apps, the first is the "SENDING" app, it takes three arbitrary values, they are: minutes (0-60) the micro has been running, seconds (0-60) the micro has been running, and 100 (it was random, and you can put that back if you want). Also, if you comment out the #define TESTAPP instead of using these values, it can pull three analog values from A0-A2 instead. (If you change it in the receiving app, you could have three LEDS on Pulse Width channels and vary the brightness).
/* * * * * * * */

XBEE SENDER (131)

#define TESTAPP        // Just serial data based on time

#define PACKETLENGTH   7
#define LED            13

/* * * * * * * */

void setup(){
    Serial.begin(9600);
    Serial.println("\nSender");
    randomSeed(analogRead(0));
    pinMode(LED,OUTPUT);
}

unsigned long m1 = 0;
unsigned long m2 = 0;

void loop(){
    m1 = millis()/1000;
    if(m2 != m1){
        m2 = m1;

#ifdef TESTAPP
        uint8_t  s = m1 % 60;           // how many seconds on millis()
        m1 /= 60;                       // now we're working with minutes
        uint8_t  m = m1 % 60;           // how manu minutes on millis()
        uint8_t  r = 100; //random(256);
        Serial.print("x.x");            // this is just pre-pended data for testing
        Serial.print('<');
        Serial.write(m);
        Serial.print('-');
        Serial.write(s);
        Serial.print('-');
        Serial.write(r);
        Serial.print(">  x-x");        // we want to ignore these chars
#else
        Serial.print('<');
        Serial.write(map(analogRead(A0),0,1023,0,255));
        Serial.print('-');
        Serial.write(map(analogRead(A1),0,1023,0,255));
        Serial.print('-');
        Serial.write(map(analogRead(A2),0,1023,0,255));
        Serial.print('>');
#endif
        digitalWrite(LED,!digitalRead(LED));  // toggle the LED everytime we're here
    }
    // do other stuff here...
}

You'll notice garbage characters around the data we are transporting, this is to demonstrate cycling through all serial communications to arrive at the 7 particular characters we need. That's done in the next app, the receiver:
/* * * * * * * * */

XBEE RECEIVER (121)

#define TESTAPP  // if you attach 3 LEDS to 9, 10 and 11, the remove this line.

//#define DEBUG  // uncomment this line to see all the data stream coming in

#define PACKETLENGTH  7

/* * * * * * * * */

int LED[3]={9, 10, 11};

void setup(){
  Serial.begin(9600);
  Serial.println("\nReceiver");
}

byte  buffer[PACKETLENGTH]; // what holds our serial data
byte  idx         = 0;      // the index for the buffer character being written
byte  validBuffer = 0;      // flag to tell us if we're ready to go

void loop(){
  if(validBuffer){
      #ifdef TESTAPP
          // we're just going to print it out in a different format
          validBuffer=0;
          #ifdef DEBUG
              Serial.print('\n');
          #endif
          Serial.print("Data: (");
          if (buffer[1]<10) Serial.print("0");
          Serial.print(buffer[1]);
          Serial.print(":");
          if (buffer[3]<10) Serial.print("0");
          Serial.print(buffer[3]);
          Serial.print(") (");
          Serial.print(buffer[5]);
          Serial.println(")");
      #else
          // this is the more practical side of things
          // instead of serial.printing, change the brightness
          // on three attached LEDs via PWM Pins (9, 10, 11)
          analogWrite(LED[0],buffer[1]);
          analogWrite(LED[1],buffer[3]);
          analogWrite(LED[2],buffer[5]);
      #endif
      memset(buffer, 0, PACKETLENGTH);  // we've used the data, clear it out
      idx = 0;                          // and reset the index marker
  }
}

// This is where the real magic is done. We have a buffer of
// PACKETLENGTH that takes in all Serial data and waits until
// it finds PACKETLENGTH characters in the format we're after
// Probably not the best method, but it would be unlikely to
// stumble across this pattern, although not impossible :)
// use at your own risk

void serialEvent(){
    if(validBuffer) return; //we don't want to process new Serial
                            //until we've processed the buffer
    buffer[idx] = Serial.read();
        #ifdef DEBUG
        Serial.write(buffer[idx]);
        #endif

    if (++idx==PACKETLENGTH){
        // we have enough bytes for testing, this next part could be handled better
        if(  buffer[0]=='<' &&
             buffer[2]=='-' &&
             buffer[4]=='-' &&
             buffer[6]=='>' ) { // we have a valid data packet
               validBuffer=1;
        } else {    // we don't have valid data yet, but keep
                    // what we have, shift it all over one byte and
                    // we'll check again once the next byte is received
            memmove(buffer, buffer + 1, PACKETLENGTH-1);
        }
        idx--;
    }
}


text:
Which Timer can I use on the Arduino/Genuino Micro?
I'm trying to implement charlieplexing with bit angle modulation on my Arduino Micro, and for that I need to use the internal timers.
Which timers of the Atmega32u4 are unused by the standard firmware? Ideally I'd like to use either Timer1 or Timer3 as they have the highest resolution.

You are using those timers to generate periodic calls so the simplest would work. Aka the use of a 16 bit timers adds no value.

Only Timer0 is used for millis and micros, just as with the Arduino Uno and Mega 2560.
Timer0 is used in "wiring.c".
That same file is used for the Uno, Mega 2560, Leonardo and Micro. The differences for the Leonardo is the pin numbers in "pins_arduino.h".
If you don't use PWM output with analogWrite, then you can use all of the other timers. The timers are set to certain values in the function init (also in wiring.c). But you can ignore that if you never use analogWrite.


text:
Accessing 3rd party driver
This is a newbie question but I'm not having much luck googling.
I'm wanting to write code that accesses an InvenSense MPU-6050 motion sensor package. I've obtained the Embedded Motion Driver 5.1.1 package. It contains example code plus a driver in the form of a directory tree of .c and .h files. The file structure of the driver is
\---msp430
    |   msp430USB.cmd
    |   msp430_clock.c
    |   msp430_clock.h
    |   msp430_i2c.c
    |   msp430_i2c.h
    |   msp430_interrupt.c
    |   msp430_interrupt.h
    |
    +---F5xx_F6xx_Core_Lib
    |       HAL_FLASH.c
    |       HAL_FLASH.h
    |       HAL_MACROS.h
    |       HAL_PMAP.c
    |       HAL_PMAP.h
    |       HAL_PMM.c
    |       HAL_PMM.h
    |       HAL_TLV.c
    |       HAL_TLV.h
    |       HAL_UCS.c
    |       HAL_UCS.h
    |
    +---USB_API
    |   +---USB_CDC_API
    |   |       UsbCdc.c
    |   |       UsbCdc.h
    |   |
    |   +---USB_Common
    |   |       defMSP430USB.h
    |   |       device.h
    |   |       dma.c
    |   |       types.h
    |   |       usb.c
    |   |       usb.h
    |   |       UsbIsr.h
    |   |
    |   +---USB_HID_API
    |   |       UsbHid.c
    |   |       UsbHid.h
    |   |       UsbHidReq.c
    |   |       UsbHidReq.h
    |   |
    |   +---USB_MSC_API
    |   |       UsbMsc.h
    |   |       UsbMscReq.c
    |   |       UsbMscReq.h
    |   |       UsbMscScsi.c
    |   |       UsbMscScsi.h
    |   |       UsbMscStateMachine.c
    |   |       UsbMscStateMachine.h
    |   |
    |   \---USB_PHDC_API
    |           UsbPHDC.c
    |           UsbPHDC.h
    |
    \---USB_eMPL
            descriptors.c
            descriptors.h
            eMPL_CDC.inf
            usbConstructs.c
            usbConstructs.h
            usbEventHandling.c
            UsbIsr.c

It's intended to be used with a development environment called "Code Composer Studio." I'm trying to use it with the stock Arduino development environment (1.8.1). I create a new sketch and copy the example code into it. It includes various files from the driver tree;
#include "USB_eMPL/descriptors.h"

#include "USB_API/USB_Common/device.h"
#include "USB_API/USB_Common/types.h"
#include "USB_API/USB_Common/usb.h"

#include "F5xx_F6xx_Core_Lib/HAL_UCS.h"
#include "F5xx_F6xx_Core_Lib/HAL_PMM.h"
#include "F5xx_F6xx_Core_Lib/HAL_FLASH.h"

#include "USB_API/USB_CDC_API/UsbCdc.h"

#include "usbConstructs.h"

I've read about how to import libraries. However this isn't a library- copying it into the "libraries" folder of the project and restarting the IDE doesn't make anything new appear in Sketch->Include Library and nor does it allow the program to compile.
Copying the driver files and subdirectories into the same folder as the sketch gets me past the first hurdle of those include files not being found, but then similar lines in files in the driver subdirectories also cause errors because the paths are wrong. The files are obviously intended to be in a central dev environment "include" directory so the search always starts from the same point in the filesystem.
I've therefore tried copying the driver files into C:\Program Files (x86)\Arduino\libraries as the folder "msp430." This added an "msp430" item to the "Include Library" menu, but compilation still fails with unresolved includes. Using trial and error, it seems that I can only get files to be recognised if they're in their own folder in 'libraries.' So by pulling all the nested subfolders out and changing the paths in the top level again gets me past the first hurdle of the include files in the top level of code, but all the includes in the driver files then fail because they're looking for files in nested directories. I could go through and remove all the path information from every #include, but then everything's in the same "namespace" and with such generic names as "types.h" I can see that screwing up very quickly. So I can't believe that's how included files are generally managed on here.
So having said what hasn't worked, does anyone know what I can do that will work?

If you just google "Arduino MPU6050" you will get billions of hits, including a large number of Arduino-specific libraries, code samples, examples, tutorials, schematics, etc. Everything you need to get it working.

Yeah I've got examples that just read the sensor outputs, but there's a "motion processor" in there that lets you do things like FFT filtering of the raw data before it comes out of the device, calculate quaternion data for you and a few other things. That's what this driver gives access to.

You mean the DMP? Then you want this: http://www.geekmomprojects.com/mpu-6050-dmp-data-from-i2cdevlib/


text:
Random data sending integers between two Arduinos
I'm trying to do something seemingly simple, but I'm running into difficulties. I want to send about 5 separate integers between two Arduinos over software serial. I have written the following, but I rarely get the two numbers on the receiving end - they're usually garbled or in the wrong order. I'm sure that I'm missing something obvious, but I can't work it out no matter how hard I try. Any help would be greatly appreciated.
Sender:
#include <SoftwareSerial.h>

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

int val, val2;

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

void loop()
{
  val = 123;
  val2 = 456;
  if(mySerial.read()=='#')
  {
    mySerial.write(highByte(val));
    mySerial.write(lowByte(val));
    delay(3);
  }
  if(mySerial.read() == '~')
  {
    mySerial.write(highByte(val2));
    mySerial.write(lowByte(val2));
    delay(3);
  }
}

Receiver:
#include <SoftwareSerial.h>

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

byte val;
byte low, high;

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

void loop()
{
  mySerial.write('#');
  byte h = mySerial.read();
  byte l = mySerial.read();
  int y = word(h, l);
  delay(2);
  mySerial.write('~');
  byte h2 = mySerial.read();
  byte l2 = mySerial.read();
  int z = word(h2, l2);

  Serial.println(y);
  Serial.println(z);
  Serial.println();
}

Have you tried doing a loopback test on both ends. That is, disconnect the serial link between the Arduinos and test them one at a time: Connect the Tx to Rx, send some characters and make sure you receive the characters you sent.

On your system have you connected the Tx line of one to the Rx line of the other. Ie crossed over the cables?

I have had a brief look at your code and you need to add a delay to the Receiver software immediately after you send the '#' and the '~' characters. The delay is needed so the microcontroller has enough time to send the character out of the serial port, have it processed by the other side and then the new data sent back.

Thanks sa_leinad. Those extra delays seem to have done the trick and everything is working as it should so far.

You need to add a delay to the Receiver software immediately after you send the # and the ~ characters.
void loop()
{
  mySerial.write('#');
  delay(8);    // <<<<<<<< Line added
  byte h = mySerial.read();
  byte l = mySerial.read();
  int y = word(h, l);
  delay(2);
  mySerial.write('~');
  delay(8);    // <<<<<<<< Line added
  byte h2 = mySerial.read();
  byte l2 = mySerial.read();
  int z = word(h2, l2);

  Serial.println(y);
  Serial.println(z);
  Serial.println();
}

The delay is needed so the microcontroller has enough time to send the character out of the serial port, have it processed by the other side and then the new data sent back.
Using 9600 baud, the time for each bit is around 104 microseconds. So a byte of data sent will take about 1.04 milliseconds. One byte sent + processing time + 2 bytes back is about 4 milliseconds. Adding a bit of margin, 8 ms delay would be a good value to use.
Using if (mySerial.Available() > 0) will not work on its own unfortunately, as Matt's answer suggests. What would happen is that you send the first # and then immediately it would check for any data recieved. From the calculation above we know it would take about 4 ms to get data back. So it just skips the if statement and goes onto the 2ms delay and then sending the ~. It then checks if serial is available. By this time the first response 'may' be back, so if it is, it then saves the data into h1 and l1. It then finishes the serial prints and loops back to the beginning. In this time the second response has come back, so after it sends # for the second time, the response to the ~ gets saved into h and l. This will continue forever.

Thanks. I was trying it with smaller delays (about 3ms), which didn't work. I just changed it to 8ms as suggested and it worked perfectly. I've managed to bring that down to 5ms, which seems to be the minimum before it fails.

You are being too impatient.
The receiver needs to wait until there is some data available.  if (mySerial.Available() > 0).  So before every read add that line and it should work.

Thanks @Matt. That seems to have cut down on the random numbers somewhat, but I still don't get a reliable stream of data. Often the two values are swapped, for example. Any other ideas?

I can't see a reason why the bytes would be swapped.  Try slowing it down make the delay between characters 500ms and see if that helps.  An alternative would be to send a byte array.


text:
Is it possible to burn a bootloader to an ATTiny85 with USB TTL and avrdude?
I have:

An Digispark clone (with no Arduino bootloader)
A USB -> TTL serial device
A development breadboard
Avrdude

I want to burn the micronucleus bootloader to the chip.
Is this possible, are there instructions?
ISP programmer is in the post but I'm not expecting it for 3 weeks.

AFAIK... No. The programming interface requires a, well, programmer. If you don't have any, you can't program. Since the microcontrollers usually used for arduinos can "self-program" (i.e. they can alter their programs), you can write a program to enable the serial interface and receive the new program, which then you can write and execute. This small program is called bootloader. But without bl you can't do these things, so at least the bl should be programmed with a programmer. If you manage to have someone lend you an arduino board, you can use it to program the ATTiny85 (search ArduinoISP)

Reading the attiny85 spec certainly has instructions for serial uploading but it's complicated.  I would have expected avrdude to have some bit bang setting to do this. I read some hacks for the ttl board that breaks out the reset pin but I have not tried this yet

Uhm, serial uploading means using the spi program interface, the one used by the programmer. You can use a USB-UART board (the TTL board you mentioned) even without hacks (you just have to "press" the reset button - or reset it in any other way - when the ide says "started uploading"). But you need the bootloader

Yeah i tried that with avrdude set to serial bitbanging

Tried hitting the reset button several times. Never seemed to get it right. Alway returned rc=1 No response from board. Everything seems to say you need a SCK (Sync Clock) but the TTL has only 5v+ GND RX TX and 3v3+
One of these
https://goo.gl/0IZAuH

Chips are these https://goo.gl/8nt2xY

Let me try again. SPI = programmer, TTL = UART. Both are "serial", but your TTL is th standard known as UART. No UART without bootloader

No bootloader. But we I should be able to burn the bootloader in spi mode using a serial bit bang as I understand. I wired up the auto reset to my pl2303 pin 2. (Tricky soldering) still not working. Response always low

Check this out.
http://nerdralph.blogspot.co.nz/2014/05/pl-2303hx-bit-bang-avr-programmer.html

Never knew this. Good to know. Anyway yes, he is using the serial interface as a generic I/O module, manually switching the pins. Ok. So, did you connect the pins as he suggested? I mean reset->txd sck->rts mosi->dtr miso->cts, then add the new programmer to the avrdude.conf file? Moreover what is the output voltage of the PL2303 you have? Is it a 5V or a 3.3V version? Depending on this, connect +5V or +3.3V to the attiny VCC and, of course, GND to GND. You will have six cables connecting the attiny to the programmer.

Well there i kinda got stuck. From what i understand by reading the manual was contrary to this configuration.
See table below from manual.
Notice data in and data out are MOSI and MISO
and TX = reset? this did not make sense to me.
    Table 20-10. Pin Mapping Serial Programming     Symbol Pins I/O Description     MOSI PB0 I Serial Data in     MISO PB1 O Serial Data out     SCK PB2 I Serial Clock
See. http://www.atmel.com/images/atmel-2586-avr-8-bit-microcontroller-attiny25-attiny45-attiny85_datasheet.pdf

Why? TXD, RTS, DTR, CTS are the pin names for the UART standard. But they are using them as general purpose IOs, so the name means nothing. Just connect them the way the blogger suggests you and do the modifications needed....

ok cool. will try.

No, you can't because a USB -> TTL serial device is not made for that. You CAN however use an Arduino Uno to burn a bootloader to another Atmel micro, including the Attiny85.
Now you may ask, can you use the Digispark in place of the Uno (and thus burn more Attiny chips). The answer is a qualified yes.  Another Arduino can do this -- search the web and find many examples.
You might (?) even adapt that sketch from the Uno to the Digispark (saving the cost of an Uno). I can't advise further and you're looking at a rabbit hole of possible issues.
Sparkfun does sell a chip which can perform boot-loading using minimal components:
https://learn.sparkfun.com/tutorials/how-to-install-an-attiny-bootloader-with-virtual-usb

Short answer, no. You can burn a bootloader onto the chip using a programmer, and then the bootloader does the serial communication magic so you can upload your sketches via serial or even low-speed USB (if your bootloader knows how to do USB bit-banging). But you can burn the bootloader only through SPI.

But SPI is what i am trying to achieve. USB to TTL is serial. Look
pic.twitter.com/JboHA3qq6d

Indeed TTL (well, UART in your case, that's a USB-UART chip) is a serial protocol but it's not the same as SPI. SPI is a synchronous serial protocol, which means it needs a clock line for timing, so it requires 3 lines for the communication to take place (SCK - clock line driven by the master, MOSI - for transmitting and MISO for receiving). UART is on the other hand an asynchronous serial protocol, so it requires only the 2 data lines (RX for receiving and TX for transmitting), the timing and synchronization is done by both the receiver and the transmitter.

Yes as i enquire i am seeing that i can do this. But i need to break out at least 2 more pins from the PL2303. Will do this tonight and see what happens.

From the datasheet of the chip you can't do it, it has an RS232 serial interface engine (that's UART) and 2 GPIO pins (you'd need 3 GPIO if you could even program the damn thing to do bit-bang SPI, which you probably can't). Why do you want to reinvent the lightbulb tho? Buy an ISP, it's 2 bucks or something like that. Or if you have an arduino laying around use it as an ISP.

With due respect i think you can do it if you breakout the extra pins of the PL2303. Well at least from what i have gathered so far. In the next few days i will attempt this and let you know how it goes.But yes. the ISP is in the post.

you can't program your hardware with just USB to tty converter you need a programmer for that now instead of buying expensive programmers you can buy an Arduino board and use it as ISP (In System Programmer) here is the link describing the whole process.
Adruino as a  ISP

In principle that is true; however a number of actual USB<>Serial chips have additional proprietary modes offering synchronous serial communication which with the right software on the host can be used for AVR ISP.

@ChrisStratton Care to list a few/all such chips and "right software", if it exists?


text:
Digispark ATtiny85 keyboard
I have a small project that I have in mind and I'm pretty new with Arduino.
I want to make a small device that if a key was pressed it would do something.
Now I know I could use a button with the device but I want to specifically use a Cherry MX Blue Switch.
So I wanted to know if the test code I wrote up would get me in the right stating place and I want to know where I would wire the key switch onto the board.
From how I have the code written I'm guessing I connect the positive pin from the switch to P0 on the board and the other pin to ground on the board, is this correct?
#include "DigiKeyboard.h"

void setup() {
    pinMode(0, INPUT);
}

void loop() {
    // put your main code here, to run repeatedly:
    if(digitalRead(0)==HIGH){
        DigiKeyboard.sendKeyStroke(MOD_GUI_LEFT,KEY_R);
        DigiKeyboard.print("test");
    }
}

Try Googling: "Arduino INPUT_PULLUP", "Arduino button edge detection" and "Arduino button debounce".

is there something special about cherry mx blue switch? ... i thought that it is just a SPST switch

I just really like cherry mix blue switches tbh

I would suggest to connect one pin of the with to 5v and the other to ground. The Arduino will be able to detect 5v as logic HIGH.
The code looks correct except for better programming technique I would suggest to indent you code, this make debugging easier for longer programs:
#include "DigiKeyboard.h"

void setup() {

   pinMode(0, INPUT);

}

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

  if(digitalRead(0)==HIGH){

    DigiKeyboard.sendKeyStroke(MOD_GUI_LEFT,KEY_R);
    DigiKeyboard.print("test");

  }
}

so should i connect it to pin 0 and 5v?
since in the code its telling it to look at pin 0.

The pin which you originally connected to gnd connect to 5v

So so the switch would be connected to 5v & p0?

Yes, this means when the switch is closed p0 will be able to detect 5v as login high

This wont' work unless you add an external pulldown resistor to GND. Connecting the switch between the digital input and GND has the advantage that you don't need an external resistor, as you can use the internal pullup by setting the pin mode toINPUT_PULLUP. This was already suggested by @tttapa in his comment.

When the switch is connected the pin will go high, and when disconnected the pin will be floating but will never reach 5v which still reliablly work

Do you want the absolute lowest power consumption? If yes then instead of using a microcontroller, use a dual D type latch. The circuit below will take the first break of the optical beam, turn on the output for that latch, and will block the other latch from turning on.
When the clock input goes high (beam broken) the high on the D input is transferred to Q and -Q will go low. That low will force the output of the other latch to stay low.
To reset the light the push button switch is used to clear the Q output. It is then ready again.
I didn't show the power supply (bypass cap). The chip is a CD74HC74. 14 pins containing two latches.The only current drawn is the LED current and the current of the opto-transistors.


text:
Arduino powered from motor shield and USB issue
I am using an Arduino (Elegoo) Mega with Motor shield to drive a digital train set. The Motor shield is powered from a 12v 1.1 amp dc power supply and I have the Arduino plugged into my laptop via USB. I have an app which sends commands via serial to the mega which are then turned into commands for the train set and sent down the line.
When using this all of a sudden the main chip on my Arduino blew up and my Laptop seemed to blow a re-settable fuse shutting off instantly (It was dead for about 10-20 minutes then worked again).
Would this be because something caused power to get back through the Arduino to my laptop?
The railway will short from time to time if a locomotive derails for example.
I know there is a trace on the Motor Shield which prevents the shield powering the Arduino. I have now cut this although it says you only need to cut it if using over 12v.

Is it a genuine Arduino or a cheap Chinese clone?

Its an Elegoo but I have used them for years without issue. To be fair this is the first time I have powered them from a motor shield though.

@Majenko This is part of an open source project to make getting into digital train sets as cheap as possible so we are trying to keep costs down hence the clone. If it does turn out that the official board would be a better choice though it would be good to know.

It could be that the voltage regulator on the clone is inferior and died allowing 12V through to the rest of the Arduino and hence your computer.

Looking at pictures of the Elegoo Mega 2560 they use a "hash fill" for the pour on the tab of the regulator, not a solid fill, and zero vias to another dissipation layer on the reverse. While this may look more funky it provides only a fraction of the heat dissipation of a solid double-layer fill, meaning the regulator is more likely to overheat. Also because this is a Chinese clone the component quality will be lower (cheaper) meaning the regulator probably doesn't have proper thermal overload protection.
So it gets too hot too easily, and pop your Arduino is dead as the regulator fails "short" and 12V gets pumped directly into the rest of your Arduino.
Byebye Arduino, and byebye computer (fortunately temporarily in the case of your computer).

Do you agree that by cutting the Vin trace on the motor shield there will no longer be a risk to my computer?

Sounds likely, yes.

Be careful dissing Chinese components as 'poor quality' Your TV, Phone, computer and practically any other electronic item you own has chines built components in it. Most of these items are assembled in China anyway. I agree the board design may be poor but component quality from China is fast becoming a thing of the past.


text:
How to call C functions from Arduino sketch?
I would like to know if there is a way to call functions that are contained within C files using an Arduino sketch?
My C file declares and defines a function. To save putting the messy function definition into my Arduino sketch, I'd like to call the function straight from the sketch.
Is there a standard way to do this using Arduino and C?
Here is the sketch:
#include "crc16.h";

void setup(){

}

void loop(){

  CalculateCRC16("<09M", 4);

}

and this is the trimmed down C file:
#include <stdio.h>
#include <stdint.h>

uint16_t crctable[256] =
{
    0x0000, 0x1189,.....

uint16_t // Returns Calculated CRC value
CalculateCRC16( // Call example CalculateCRC16("<09M", 4);
    const void *c_ptr, // Pointer to byte array to perform CRC on
    size_t len)        // Number of bytes to CRC
{

    uint16_t crc = 0xFFFF // Seed for CRC calculation
    const uint8_t *c = c_ptr;

    while (len--)
        crc = (crc << 8) ^ crctable[((crc >> 8) ^ *c++)];

    return crc;
}

Is there a reason why your file has to use C instead of C++?

Actually, yes. When I try to compile the file using C++, there are errors, but it is error free in C. The error is caused by the lines: const void *c_ptrand const uint8_t *c = c_ptr;. The error message mentions an invalid conversion between types.

Could you please post the 2 code files (or a simplified minimal version of them) that produce the error, and copy&paste the error message in full?

The error messages aren't so pretty:
In function uint16_t CalculateCRC16(uint16_t, const void*, size_t)':  46 invalid conversion from const void*' to const uint8_t*'   In function int main()':  57 system' undeclared (first use this function)    (Each undeclared identifier is reported only once for each function it appears in.)

When a function was called in the c file, how I notice this in the original Arduino file (ino)? Can I create any callback function form the c file to the ino file?

INO files are C++. If you want to call a C++ function from C you have to create it with C linkage. extern "C" void foo() { Serial.println("Foo"); }

You can extern "C" #include like the following:
extern "C"{
#include "crc16.h"
};

void setup(){
}

void loop(){
  CalculateCRC16("<09M", 4);
}

And the crc16.h file could be (some minor fixes, the #pragma once, a cast):
#pragma once

#include <stdio.h>
#include <stdint.h>

uint16_t crctable[2] ={ 0x0000, 0x1189};

uint16_t CalculateCRC16( // Call example CalculateCRC16("<09M", 4);
    const void *c_ptr, // Pointer to byte array to perform CRC on
    size_t len)        // Number of bytes to CRC
{
    uint16_t crc = 0xFFFF; // Seed for CRC calculation
    const uint8_t *c = (const uint8_t *)c_ptr;

    while (len--)
        crc = (crc << 8) ^ crctable[((crc >> 8) ^ *c++)];

    return crc;
}

Thanks, it works just fine now. Could you please explain the need of the pragma?

Sure, it is a good practice, though it is not needed in your example. It avoids the same header file to be included twice in a compilation file. Imagine a.cpp->(b.h and c.h) and b.h->c.h. That will duplicate the contents of c.h while compiling a.cpp. The #pragma once avoid this. Also guard directives #ifndef _MY_FILE_H_INCLUDED #define _MY_FILE_H_INCLUDED are common for this. Note, however, that as Peter R. Bloomfield points out, it might be better to put the implementation of CalculateCRC16 in a cpp file, and leave just the declaration in the header file.

Ok, I can see that becoming an issue when the code gets more and more complicated. Thanks for the advice.

Your CRC function can easily be converted to C++ so that it can go into a *.cpp file. All you need to do is use an explicit cast when you initialise your c pointer. Here's the 'proper' C++ way to do it:
const uint8_t *c = static_cast<const uint8_t*>(c_ptr);

However, an old C-style cast would also work:
const uint8_t *c = (const uint8_t*)c_ptr;

The problem is basically that C can be a little more permissive about letting you convert pointers implicitly between types. To do it in C++, you need to tell the compiler explicitly that the conversion is intentional.

Yes, just copy its declaration line in your sketch:
extern "C" {
    void myfunction(int arg);
}


text:
Resistance measurement using loop resistance technique
Im trying do a circuit to measure resistance between Neutral and ground, for this I tried ohm law method i.e., to obtain R = (V/I). Voltage is known value 25 Vac, Current value is measured using ACS712 and tried the coding is given below, I'm getting current value from it, but when I apply ohms law I'm not getting resistance value.Please guide me
/*
Measuring AC Current Using ACS712
*/
const int sensorIn = A0;
int mVperAmp = 185; // use 100 for 20A Module and 66 for 30A Module

double Voltage = 0;
double VRMS = 0;
double AmpsRMS = 0;

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

void loop(){

 Voltage = getVPP();
 VRMS = (Voltage/2.0) *0.707;
 AmpsRMS = (VRMS * 1000)/mVperAmp;
 Serial.print(AmpsRMS);
 Serial.println(" Amps RMS");

}

float getVPP()
{
  float result;

  int readValue;             //value read from the sensor
  int maxValue = 0;          // store max value here
  int minValue = 1024;          // store min value here

   uint32_t start_time = millis();
   while((millis()-start_time) < 1000) //sample for 1 Sec
   {
       readValue = analogRead(sensorIn);
       // see if you have a new maxValue
       if (readValue > maxValue)
       {
           /*record the maximum sensor value*/
           maxValue = readValue;
       }
       if (readValue < minValue)
       {
           /*record the maximum sensor value*/
           minValue = readValue;
       }
   }

   // Subtract min from max
   result = ((maxValue - minValue) * 5.0)/1024.0;

   return result;
 }

Welcome on this board! To increase the chance of getting a proper answer you should describe what you did, waht you expect and what didn't work as expected. Also please format your code (just select your code and press the{}-button).

What values do you actually get?

you should rename the variables