text:
Can you tell me if this circuit will work?

Here's an image of my circuit diagram. There are 8 9g servos connected to the arduino gpio pins. The servos have an external power supply of 3 volts (may vary depending on the voltage requirement of the 9g) and the arduino is powered through an adaptor. Is this a convenient way of doing it? Have I gone wrong somewhere? I am new to circuit designing so I am confused.
Thank you! :)

That diagram is impossible to read. Redraw it so that wires dink mask other wires. Keep wires to horizontal or vertical with 90 degree bends only.

@Majenko       Apologies. I've edited the post with a breadboard design. I'll re-draw the whole thing in case even this one is difficult. :)

These servo are driven off of a PWM signal. This means that you need to connect the control line to a pin that is capable of PWM.
For the Uno it is D3, D5, D6, D9, D10 & D11.
Unfortunately there are only 6 PWM capable pins and you need 8.
You could consider bit banging the PWM for the 7th & 8th motor.
Alternatively, if two of the motors are to be driven exactly the same, they could share the PWM control line between them.
If you need to control each motor separately (without bit banging) you may have to upgrade to a Arduino Mega 2560. The Mega has 15 PWM channels.
An Arduino example of controlling the servo motor can be found in the Libraries section of the Arduino website.
https://www.arduino.cc/en/Tutorial/Knob

Thanks a lot for your insight! :) I want all the motors to work independently therefore I will need another pwm connection. But once I connect all the control lines to the pwm, would this circuit diagram work?

Providing you do it right, yes.

Edited my answer to suggest using an Arduino Mega 2560, which has 15 PWM channels. Or you could even use 2 Arduino Unos.

Yeah, I'll consider using a 2560. I could always do with more channels. haha. Thanks again! :)

Was the answer helpful? If so, please accept it by clicking on the "tick" icon next to the answer, and also possibly upvote it. This indicates to other users that you found the answer useful, and it also stops Stack Exchange from periodically "bumping" your question in the hope of getting an accepted answer. Thanks for your understanding and cooperation!


text:
Need Help in circuit diagram of 8*8 reed switch matrix
I am designing 8*8 reed switch matrix which will be connected to Arduino. I am using Arduino Duemilanove. I have completed the matrix portion but don't know how to connect and where to connect the other elements.

I decided to use the following items:

Arduino (Duemilanove)
64x Reed Switch
64x Diode (1N4148)
20x Resistors (10K)
1x 74HC595
1x 74HC165

I don't know where to place the Resistors and shift Registers and connection from shift registers to arduino. I need help in the circuit diagram. Please help me out with the circuit diagram.
Reference: https://mtifall10.wordpress.com/2010/12/10/magnetic-sensing-chessboard/

The linked "full photo set" from your article appears to show exactly how the switches and diodes are arranged. Did you not look at the photos? Is there something about them that you don't understand? Otherwise, your question seems very strange since you have cited a reference that appears to provide a complete answer.

I have completed the circuit of switches and diodes connection. I have mentioned in the last paragraph that I need help in the connection of shift registers and resistors whose circuit diagram is not given in the reference and that is where I am stuck.

How will the various pieces be recognised by Arduino? Top-down may be a better design approach in this case. In choosing reed switches you are constrained from the outset.

You know which pieces are where when the game starts.  You track which one is removed from the board and where it is replaced.  This way, you know where the pieces are without having to identify them.  You must also have the Arduino sound a warning and refuse to play any more if more than one piece is ever off the board at one time during a move.  It also has to recognize when a piece must be removed from the board (captured) and not throw a fit then.

This answer is based on a previous version of the question

Not necessarily. You can use the internal pullups of the arduino if you're willing to accept that reading a "1" means that no piece is there and reading a "0" means a piece is there.
Connect each wire up to a pin on the arduino. If you do it wisely, step 3 becomes fairly easy.
You need to configure the pins connected to the letter wires as inputs with their pullups enabled. Set the number pins to inputs as well, but without the pullup enabled so that they are floating. The number pins will be each set as an output in sequence with the value being low (non-active number pins are set back to inputs). As you do so, you can read the pins on the letter wires and build a picture of the board.

Example
This is how I would do it just taking a naive stab at it. I'm sure there are more effective ways to do this.
Wiring:

Configure the outputs and inputs in setup:
pinMode(2, INPUT_PULLUP);
pinMode(3, INPUT_PULLUP);
pinMode(4, INPUT_PULLUP);
pinMode(5, INPUT_PULLUP);
pinMode(6, INPUT_PULLUP);
pinMode(7, INPUT_PULLUP);
pinMode(8, INPUT_PULLUP);
pinMode(9, INPUT_PULLUP);
pinMode(10, INPUT);
pinMode(11, INPUT);
pinMode(12, INPUT);
pinMode(13, INPUT);
pinMode(14, INPUT); //A0
pinMode(15, INPUT); //A1
pinMode(16, INPUT); //A2
pinMode(17, INPUT); //A3
pinMode(18, INPUT); //A4

Make a function to scan the rows into an array of bytes:
void scan_rows(uint8_t *rows)
{
    uint8_t i, j;

    for (i = 0; i < 8; i++)
    {
        if (i)
        {
            pinMode(i+9, INPUT);
        }
        pinMode(i+10, OUTPUT);
        digitalWrite(i+10, LOW);
        for (j = 2; j <= 9; j++)
        {
            rows[i] <<= 1;
            if (digitalRead(j))
                rows[i] |= 1;
        }
    }
    pinMode(18, INPUT);
}

Now, just call that function with a pointer to an array with 8 bytes in it whenever you need to scan the board. Each byte in the array represents one of the rows and each bit represents a column.
[moderator note: This answer appears in this thread as a result of a merge]

Use 16 digital i/o pins on the Arduino. The ones connected to a-h should be configured as OUTPUT pins. The ones connected to 1-8 should be configured as INPUT pins. Start with all of the outputs (a-h) low.
You check for a closed switch at the lower left corner by making the output pin connected to 'a' HIGH then look at the value of the input pin connected to '1'. If it's high then that switch is closed. If it's low then that switch is open.
While the 'a' output is HIGH you can check the rest of the left column by looking at inputs '2' through '8'.
I don't see any need for the resistors or shift registers, but maybe your teacher had something in mind.
EDIT: I see that by using the shift registers you need only one INPUT pin and one OUTPUT pin on the Arduino. I'll leave that for you to figure out as I think I've given enough to get you started.

source: Stack Exchange

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

sort: votes


text:
MAC address arduino
The MAC address is hardwired onto the NIC card when a device is manufactured. How is it that, we get to set a 48 bit MAC address of our choice while programming the arduino ?

It may be factory set to a default value, but that doesn't mean you can't override it.

Arduino's have neither NICs nor MACs. Can you elaborate on where/how you're setting a MAC while programming your Arduino?

Arduinos don't have an Ethernet interface by default, so you have to add one; often this includes an EPROM e.g. http://www.microchip.com/design-centers/memory/serial-eeprom/getting-started/with-mac-address-chips

MAC address is not hardwired in the modern network interface cards; it is set during programming of the configuration of the card, which is loaded on the card's start/configuration.
Modern NICs usually have option for user to set custom MAC address.
If you talk about shield device based on network chip like W5100 - there's no initial configuration within this network card for Arduino; thus by "programming the arduino" you set this initial configuration of the "card". You act like a manufacturer of the NIC.

Your initial premise is incorrect. The MAC address is NOT "hardwired".  In many cases it is held in a very small non-volatile memory chip. But when the Ethernet driver is initialized you can feed it whatever MAC address you want.  For most people they just accept "defaulting" it to the address programmed into the tiny memory.
Remember that the MAC address must be unique. At least within your LAN.  If you start diddling the MAC addresses and you end up with a duplicate, at best you will kill connectivity for your node plus the other node with the same MAC address. Not a good thing to do. That is why people generally just accept the manufacturer's MAC address which is designed to be unique.

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


text:
Arduino (weird) ADC problem
I'm trying to read to voltage output of module ACS712. Here is my problem: The module outputs a voltage around 2.5V, however, arduino sends the value "1023" to the PC. (Gives a reading of 5V).
Arduino's analogRead function works, however, is slow so I used atmega registers to solve the issue. Which worked... Except only for the module. Here is the relevant part of my code:
Setup:
void setup() {
  ADMUX = 0xC0;
  ADCSRA = 0x8E;           // prescaler = 64
  ADCSRB = 0x40;
  sei();
  bitWrite(ADCSRA, 6, 1);    //This starts single converion.
  Serial.begin(250000);
}

Relevant ISR function:
ISR(ADC_vect) {
  sensorValue = ADCL;        // read adcl first. locks adc bytes.
  sensorValue += ADCH << 8;
  Serial.println((int)sensorValue);
  bitWrite(ADCSRA, 6, 1); // Set high so another conversion starts.
}

Now, this code runs as expected for another adc pin which is located at "A3", or in code:
ADMUX = 0xC3;

However, does not work for:
ADMUX = 0xC0;

Yes, I tried replacing the wires A0 and A3. This time "0xC0" works but "0xC3" doesn't. So my arduino somehow is resistant on reading the module output!
Also, this works on same hardware:
sensorValue = analogRead(A0);
Serial.println((int)sensorValue);

Arduino's analogRead runs as expected on same hardware.
So basically, the hardware seems okay, but there seems to be a problem with my code. I just can't read the modules output voltage and I'm all out of ideas. Can anyone help?

Please edit your question to include a Minimal, Complete, and Verifiable example of code, not just snippets.   For example, as is we've got no way to tell if sensorValue is volatile

Just a little precaution. Do not call Serial.print() on ISR. An Interrupt Routines should be completed and returned as soon as possible.

sensorValue is not changed on anywhere else on the code. I am aware that using    Serial.print()  on ISR is not a good idea. Serial print will be deleted from the code once the project is complete. Right now, I am using a high baud rate (actually 2000000 works best) to compensate.

However, does not work for:
 ADMUX = 0xC0;

See the datasheet:

An ADMUX of 0xC0 will be using a voltage reference of "Internal 1.1V Voltage Reference with external capacitor at AREF pin". Since you are supplying 2.5V that exceeds 1.1V and thus you get a reading of 1023.

  Serial.println((int)sensorValue);

Also, don't do serial prints inside an ISR.

Thanks!! You were right. I forgot all about that! I changed admux to '0x40' and that solves the problem. Also thanks for the serial print issue. I'm aware it's bad and will remove that bit once development is complete. Right now, I am using high baud rate (2000000) so that isr is not affected that much.


text:
Electrostatic Discharge Protection on Arduinos
I have been using Arduino for quite some time without providing any kind of ESD protection. Does the Arduino have on board ESD protection?

What does the documentation tell you?

Check the Arduino documentation, that will probably tell you with words. Alternativly you could check the schematic of the Aruduino board you're using, and see what it has there.

Almost certainly not. What's the point in protecting the inputs to a bare board where people can touch any point? You can't protect every single trace on the board, that would result in a system where ESD protection took up half the board area.

ohkk, I did check the documentation and schematic of arduino but such a thing is not mentioned there. But, I came across the datasheet of atmega 328 maybe it will give me a better insight. Thanks for your comments

Does the arduino have on board ESD protection? The chips on the board will have ESD protection. As long as you're not purposely exposing the board to excessive ESD events, that protection is enough. Next time, do more research on what is ESD, what does a protection circuit look like etc, what does ESD mean to a user like me. Before asking here.

Just use ESD protection, better safe than intermittent

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


text:
Hardware damage from executing tight polling loop over extended periods of time?
I want my project to be standing by at the ready for months and years at a time, so I started writing my code to throttle back from polling at delayMicroseconds  to just delay. Like, after 15 minutes with no user input, switch from 10 microsecond delay intervals to 10 millisecond (or even 10 second intervals). I wonder if spinning its wheels at warp speed for months on end will wear a path in the circuit pathways? This has got to be a stupid question (or at least make someone chuckle), but I'm really 50/50 at this point: worth the effort for the extra code or won't make a lick of difference? (I know there's my implementation and then there's the right one, but this is where I am right now. FYI, I went with 17 GPIO's in parallel to link my Pi to my teensyduino. add 17 optocouplers, hot glue, hinges, scavenged enclosures etc and this thing looks ridiculous.  But I LOVE IT! (It's a mouse that I control over the web)
EDIT
Although I didn't mention any concerns about using batteries, their mention didn't really detract from anything. Rather, I welcomed their inclusion because I realized that I had overlooked things more fundamental. I'm always telling others how important ventilation can be and the impact heat can have, but it went right by me this time!
I do value and appreciate the feedback I have gotten. I don't think I will be writing any code to vary polling speed after timing out. But I would still like if someone wanted to directly answer the specific concern I had when posting this question: "At certain times, my program waits for a GPIO pin to change states. I am using the polling method to determine the status of the pin, and I am using this bit of code to do so:
do
{

} while (digitalRead(pin#) == 0); //wait for pin to go high

So, my question is, "Does it make any difference at all, in terms of wear & tear or stress placed on the CPU, how many loops I choose to make in one second? I'm considering something in the range 0.1Hz -> 100kHz  Assuming that I keep heat under control and other vital parameters within their nominal operating levels, is it true that the frequency I choose won't make a bit of difference, one way or another?"
Thanks in advance for any interest given to this question.

You are just reading inputs? Then I don't see any point in increasing the interval between reads. (Also note that delay, will still keep the CPU busy. It will just continuously poll the time and see if enough time has passes). PS there isn't really a right way. PSS sounds like an awesome setup you have. Maybe ugly but working!

@Gerben  I have the teensyduino standing by waiting for instructions from the RPi. When an input changes state, then read the other pins for the screen coordinates (up to 1920 x 1080). My first impression was that doing 10k to 100k loops a second was more CPU load, but then its clock speed doesn't change so it just the same, but then, still there's a factor of 10,000 when comparing activity. So I don't know what to think. It's hard for me to imagine what the physical reality is like at that scale. I just keep imagining the difference between 100 RPM and 100,000 RPM. SILLY!! (or is it?)

Yes, it made me chuckle, that's for sure. There is no difference in doing a delay compared to reading an input as far as the CPU and power consumption are concerned. The CPU doesn't care what it is doing, unless you specifically tell it to go to sleep it will always be "spinning its wheels".

As for the car analogy. Delay is like going 100,00 RPM during checking the inputs, and then pressing on the clutch, but keep the engine going at 100,000 RPM. There is no difference. Delay doesn't halt the CPU or something.

There's nothing to save except battery charge (if your system even uses a battery). It will take just as much energy to delay() as it would to keep polling. The only way to save energy is to put the processor to sleep instead of delaying. And polling will be so brief that you might as well keep the sleep time short, too.
You probably don't need 10 uSec poll intervals; I should think your mouse would be plenty responsive with 1 mSec intervals. If polling takes, say, 100 uSec (and that's a total guess) and you sleep the processor for the other 900 uSec, you'll cut the energy use by 90%. If you don't need to save energy, it won't matter whether, or how long, you delay.
Update:

"Does it make any difference at all, in terms of wear & tear or stress
  placed on the CPU, how many loops I choose to make in one second? I'm
  considering something in the range 0.1Hz -> 100kHz Assuming that I
  keep heat under control and other vital parameters within their
  nominal operating levels, is it true that the frequency I choose won't
  make a bit of difference, one way or another?"

Yes, it is true. Your CPU can run full speed continuously, safely. It won't overheat from continuous running. Only if some part of your project is trying to draw too much current through the CPU; then that will cause heating, but the CPU polling a bunch of inputs is well within its specs.

For many applications within the realm of Arduino software & hardware development, the only practical concern is to limit the need to write to non-volatile types of memory.  Non-volatile types of memory, such as that which stores the Arduino program, do have a finite number of write cycles.  However, it is in the 10s (perhaps 100s) of thousands of writes.  So is not a concern to most developers.
Running code, however, does put a load on the processor's power source.  First we need to understand that a switch in a modern processor require only a minuscule amount of current if left alone.  But if asked to change from a 0 to a 1 or 1 to 0, the current spikes.  In processors pushed to their limits with 100s of thousands of switches, this extra current turns into heat which must be mitigated less damage is done.
Fortunately, most processors used in Arduinos are not pushed to their limits. So this is rarely a concern. To be clear, the processor chip used on most Arduinos will mostly likely not need a heat sink or fan.
However, even for an Arduino not pushed to its limits, this extra power demand is devastating to the long term life of portable battery operated devices.  Programming an Arduino to extend battery life is by no means a trivial task.  And certain processors (Arduinos can be made with many different processors) are orders of magnitude better at this then others. But, since most Arduino applications are powered from mains, this too is of little concern.

No, there won't be any writes to any non-volatile locations. Maybe store some macros there down the road. And there aren't any concerns about battery life since it draws power from the host USB port it plugs into (in a device running off AC mains). I'm itching to accept your right away if you could just add a line that says (pretty much verbatim) '

Hmmm I hit 'post

Apparently I can't edit my own comments... Anyway, I'll make sure the heat doesn't pose a problem (I've got all sorts of old cooling fans and heat sinks).  If I could just ask  you to add a line reassuring me that "there's no need to worry, that chip will be just as happy polling an input pin 100 times a second as it would doing 100,000" I would be most grateful and happy to dispatch your well earned green check-mark! Thanks in advance.

The processor chip used on most Arduinos will mostly likely not need a heat sink or fan.  I'll add this to the answer.  I believe everyone can only edit a  comment for 5 minutes.  My rule of thumb is you don't have a heat problem until the chip feels very warm to the touch.

I wasn't allowed to edit for any amount of minutes. Not so much a criticism as surprise.  I just need to be more careful of the enter key!

You have about 5 minutes to edit a comment. After that it is committed. The point is, I think, that editing a comment hours later makes follow-up comments make no sense. See Can the timeout on editing comments please be increased?

If you accidentally hit Enter you can either: 1) Quickly edit it and finish what you were saying; or 2) Delete the comment immediately and then retype it with what you really wanted to say.


text:
Microcontroller software shutdown with transistor 2N4401
I am trying to understand why connecting, say, an Arduino digital pin 4 to a 2N4401 pin 2 as well as 5V PSU to 2N4401 pin 1 and Arduino VCC  to 2N4401 pin 3, won't keep power.
When shorting pin 1 and pin 3 on the 2N4401 the MCU is powered on and in-software pin 4 is set to pinMode OUTPUT and HIGHwhich should allow the 2N4401 to let power flow to the MCU for as long as power is available even when the short circuit between 2N4401 pin 1 and 3 is cut.
Instead what happens when the short between pin 1 and 3 is cut, the MCU is turned off instantly.
It's as if the transistor isn't reacting to the pin 4 MCU signal at all.
Could anyone explain why this is happening?
I'm sure I lack a lot of knowledge here and I want to know how I could utilize a 2N4401 to make a SW shutdown system.
Why 2N4401? Why not a MOSFET?
MOSFET's circuits that do SW shutdown are available, but no transistor base SW shutdown circuits are to be found anywhere, and the 2N4401 is all that I have right now.
Update

void setup(){
  pinMode(4, OUTPUT);
}

void loop(){
  digitalWrite(4, HIGH);

  delay(3000);

  digitalWrite(4, LOW);
}

Can you draw your schematic and show your code?

Yes, I updated the question.

Ok, but that Fritzing thing is not a real schematic! However, in you code, there is a problem in the loop function - you probably need another delay after the digitalWrite(4, LOW) otherwise it will immediately write HIGH again on the next loop - so you won't really see the effect of the LOW as it will be too short. A proper schematic is necessary to see which way you have the transistor connected.

Yeah sorry, I thought I'd show you the visual physical representation of what I'm working with. But wait, the HIGH tells the transistor to allow electricity to flow to the board, right?
So my question is why would a delay after LOWbe needed when LOWwould turn it off, which is what I want?

Because loop is executed continuously - so it would turn it back on again at the start of the next loop. It would only be off for a few microseconds. It looks a bit strange to me, are you trying to use the Arduino to turn itself off?

But how? At LOW the power is cut off completely, thus the loop never actually loops.

A proper circuit diagram please (for adults and not babies). If I wanted cartoons I'd watch spongebob squarepants.

How long does it take for the power to decay to the point where the code stops executing? There is capacitance in the supply that will maintain it maybe even for a few hundred milliseconds. Rather than arguing about it, just add another 3 second delay and see if anything changes.

Updated image. It behaves the same way with the extra delay.
I think it's so weird that the transistor is not letting electricity flow through while it's base is set high. When using the same transistor and connecting an LED to it (as an independet purpose ofcourse, not for SW shutoff) then the LED turns on and after a while off, just as expected.

If the base is high, a pnp transistor will be off. How come your battery is only 3 volts too when the arduino is shown as 5 volt? Accuracy in stating and circuitizing what you have done is a fundamental part of EE.

@Andyaka Sorry about that. I updated the image, it should now be corrected and accurate.

A edit was made to the schematic, but that raises more questions than it answers.  It's time to close this mess.

@OlinLathrop no it's not. I updated the image once again, now it really should be correct and I can't see any more errors in it.

The questions gets net three down votes. Only @Olin and Andy answers the question. I admire the patience of you both in teaching the future EE.

There is a [popular among beginners] bug where the I/O pin is set low at the end of the loop then immediately set high at the top of the loop.  In other words, a delay is missing.  More on that here  (that thread is about PICs, but it deals with the same sort of bug).

This is what you appear to be wanting... A manually operated contact (S1 in your "diagram") momentarily shorts out the NPN transistor and applies power to the Arduino. In that short time the contact is active, you want a transistor to by pass this switch and keep applying power to the Arduino so that should the contact go open circuit, power remains on the Arduino.
The main problem, assuming my guess about what you want is correct, is the use of an NPN transistor as an emitter follower; whatever voltage you apply to the base will be about 0.7 volts lower on the emitter so, when the contact opens, the emitter voltage drops to about 4.3 volts to keep the NPN turned on but, that in turn leads to a drop in base voltage and quite rapidly you end up with nothing on the emitter.
You need a PNP transistor that can be turned on much more effectively with an NPN pulling the PNP base towards ground. In other words you need two transistors to do what you want: -

This one is shown at 5.5 volts on the power rail but 5 volts will be fine. It is also shown using a p-channel MOSFET instead of a PNP because the MOSFET will act as a much better "short" when activated.
Here's one that shows a PNP transistor - ignore the 12 volts - it will work on 5 volts: -

The "lamp" is where you connect the Arduino (aka PIC in the circuit). You will be better off with a p-channel FET though but, just in case you decide to use the PNP version you might need to lower R3 to maybe 470 ohms to provide enough base current to pass sufficient collector current to power the Arduino.
You also need to have S1 wired across the "pass" transistor - at the moment you have it connected back on itself and therefore does absolutely nothing. Note that this has been fixed in the question now!

when the contact opens, the emitter voltage drops to about 4.3 volts to keep the NPN turned on but, that in turn leads to a drop in base voltage and quite rapidly you end up with nothing on the emitter. that's what me and a friend discussed earlier today but we weren't too sure, thanks for confirming our suspicions.

Answer accepted! Edit: You don't understand what this will do to the maker community, you will be considered the holy master of self-shutdown Arduinos.

Your question is rather confusing, but some problems are evident just from looking at the schematic:
The schematic is crap.  I have no idea what you're trying to say with the dotted line between the - terminal of the the battery and the processor GND pin.
The line going thru the middle of the transistor is apparently meant to be the connection to the base, but this is sloppy at best.
It took me a while to realize you have the positive power connection at bottom and the ground at top.  Don't do that.
All these things make your schematic hard to read.  Now that I've had to waste time deciphering the schematic, I'll be more brief once we get to talking about the circuit itself.
You say the transistor is a 2N4401, which is NPN, but you show a PNP.  Huh?  Which is it?
There is no base resistor.  The E-B junction looks like a diode to the driving circuit.  When the digital output tries to go low, it will be held one diode drop below power.  That could damager the digital output or collapse the power supply.

Update
You have edited the schematic to show a NPN, but now you have a chip trying to drive itself thru a emitter follower.  The switch also does nothing at all since both its ends are already shorted together.

This isn't an answer, this is criticism, which is 100% fine by me, but leave in the comments. I'm not trying to say anything by the dotted line, I could not connect it in software. By the way, no one is forcing you to help me, whoever does take the time to help me and teach me something new will be appreciated, if respectful. It is an NPN transistor. The base resistor is something new to me that I'll have to read more about. This answer is not an answer, I will not accept as it does not answer my question "why does MCU not stay ON while pin 4 keeps NPN base high".

@vaid: This is too long for a comment, and points 2 and 3 do actually address issues with your circuit.  There are many ways to draw good schematics, including the schematic editor built into this site.  "I could not connect it in the software" is no excuse at all.  So use better software!  And, respect is earned, which you haven't.  In fact, complaining about people pointing out your disrespect only makes it worse.

Hey, I'm new to these things, alright? Not everyone is Nikola Tesla. I'm not complaining at all, you have a requirement? State it and I'll handle the rest. Want me to use the built in editor? Say it. I didn't even know there was one. Be a little bit more considerate. I'm fine with criticism, but keep it on a respectful level, that's all I'm asking for regarding communication. This is getting too off topic and I'm now going to ignore you because I'm here to have a dialog and learn, not a monolog insult.

"you have a requirement? State it".  No.  We expect you to learn to communicate properly elsewhere.  Drawing a schematic is something you are expected to already know how to do before coming here, unless you're explicitly asking about schematic drawing.  "keep it on a respectful level".  Again, respect is earned.  You're not there yet.

Neither are you. But Andy aka is. Get rekt.


text:
How is the bootloader activated when device is running?
For the sake of specificity I am referencing my question to Arduino. It applies to all AVRs with hardware USB and a bootloader though.
The bootloader is capable of receiving new program data over the USB interface, and, after programming, releases the interface. It can then for instance be used for the emulation of a serial port, or even register as a HID.
I know what a bootloader is and how it reads program data from the PC and how it writes it to the devices flash memory.
I am asking how the bootloader is triggered again if the user wants to upload a new program. The PC needs to reset the AVR in order to fire up the bootloader. How is this reset instruction implemented in Arduinos with built-in USB hardware (e.g. the Arduino Micro)? Is it solved by performing a software reset after the DTR line goes low just as in e.g. the Arduino Nano, except that the DTR line only exists in software?
EDIT: If that is the case, the solution is unique to Arduinos. I was thinking that there would be some standard way of doing it common to all AVRs.

AFAIR, the Arduino uses the DTR signal from the serial port as a way for the host to trigger a reset of the board (it has nothing to do with USB). This is documented somewhere but I don't recall where.

@RogerRowland So you are saying that after the USB-to-serial decoding is done (in software, on the MC), a change in the (virtual) DTR line triggers a reset?

What I'm saying (or half remembering!) is that the host - the PC end - uses one of the unused serial signals - I think DTR - to reset the Arduino and therefore force it into the bootloader again. If you look at a recent Arduino schematic, you may see what the reset pin it tied to. In the original Arduinos it was necessary to manually press the reset button when programming, which was imprecise and frustrating.

Yes, I know that, but I am specifically asking about AVR with built-in USB capabilities, like the ATMega32u in the Arduino Micro. The USB data lines go directly into the chip. There is no physical DTR signal that could be wired to the reset pin.

So are you asking about Arduino boards or AVR microcontrollers? The former (may) include the latter but they are not the same. Using "Arduino" in your question implies that you're talking about a specific development board, not just a micro. Can you clarify? The general subject of bootloaders is a broad one indeed.

Closing this question was premature, the OP asks a very specific question, which I don't see answered on the linked question.

Check https://www.arduino.cc/en/Guide/ArduinoLeonardoMicro#toc10 for a little bit of explanation. In a micro application that uses the arduino USB-serial library and functions correctly the boot sequence can be triggered by doing something that should rarely occur in normal use (setting the baudrate to 1200). The library (which is part of the application) intereprets this as a request for a reset.

When the library is not used or the applicaton doesn't function correctly you can't reset/bootload a micro "hands-off", you will need to press the reset buttonb manually. This is only needed for arduino's that uise a single chip for both the applicaion anb the serial-USB interface. With the arduino's that have a separate USB-serial chip the DTR line is used, so you can always force a reset, independent of the application controller.

Funny side note: the arduino Due (my favourite) has a separate usb-serial chip, but still uses the "1200 baud" reset (but because it is handled by a separate chip it is a hard reset, unlike on the micro). Unaware of this I once spent a few hours trying to get the serial interface of a Due to work at 1200 baud....

On microcontrollers with bootloader (not just AVRs), the bootloader is a separate executable in flash, and it's typically the program that runs on system startup.  The application will have a special trigger, such as a button sequence, getting a specific byte sequence over I2C, or really anything that will tell the bootloader to enter into its "update" mode.  From there, the bootloader will have some communication (I2C, USB, WiFi, serial, etc) to download and the flash the new application image.
This link has more information about the Arduino bootloader

On the PC side, to trigger a reset on the RESET pin, the PC (avrdude.exe or GNU/Linux equivalent) opens the serial port to Arduino when your press upload and the code is ready to upload. This causes the Data Transmit Ready (DTR) line of the USB/TTL chip to go LOW. The Arduino board has a capacitor charging circuit that uses this LOW (charging the capacitor) signal to momentarily pull down the RESET line of the ATMEGA328P chip before returning it to HIGH (capacitor charging completes). So Arduino resets each time its serial port is opened.
Upon reset, Arduino enters the bootloader.
The bootloader looks at the source that caused the reset. There are several sources that can cause a reset. If the reset was caused by the RESET pin, then it waits for one second for the PC to send in commands. When it receives valid commands, it will start accepting new Arduino code in HEX format and erase the existing code to load new one. If it doesn’t receive valid commands, it times out after one second and triggers a Watch Dog Timer (WDT) reset.

For Arduinos with built-in USB, such as the Micro, the Arduino library (firmware) triggers the system reset.  There's a little chunk of code that looks for the virtual COM port to open at 1200 baud and then close.  When that happens, the code triggers a system reset (by writing a register, typically) which launches the bootloader.

Rather than requiring a physical press of the reset button before an upload, the Micro board is designed in a way that allows it to be reset by software running on a connected computer. The reset is triggered when the Micro's virtual (CDC) serial / COM port is opened at 1200 baud and then closed. When this happens, the processor will reset, breaking the USB connection to the computer (meaning that the virtual serial / COM port will disappear). After the processor resets, the bootloader starts, remaining active for about 8 seconds. The bootloader can also be initiated by pressing the reset button on the Micro. Note that when the board first powers up, it will jump straight to the user sketch, if present, rather than initiating the bootloader.
Because of the way the Micro handles reset it's best to let the Arduino Software (IDE) try to initiate the reset before uploading, especially if you are in the habit of pressing the reset button before uploading on other boards. If the software can't reset the board, you can always start the bootloader by pressing the reset button on the board.

Personal story: I wrote an I2C bootloader for the PIC32.  The only communication with the device was through the I2C bus.  The main application had a special 3 byte trigger that would set a non-initialized variable in RAM, and then trigger a system reset.  The bootloader, which runs on system startup, would check that variable and if it was set, would wait for commands over I2C to download and flash the new application image.  That variable in RAM had to be specially marked as non-initialized, otherwise the C startup code would clear it and the bootloader would never update.
The bootloader also calculated a CRC32 over the application image to validate it before attempting to boot.  If the calculated CRC32 didn't match the stored CRC32 (which was part of the application image), then the bootloader would enter its firmware update mode.  This was a guard against trying to run a corrupted firmware image, which could happen if power was pulled during the update process.

Thanks for the answer. Unfortunately it still misses my main point. I know that e.g. the Arduino Nano has the DTR line hardwired to the reset pin, so the PC can reset the AVR by pulling DTR to ground. How is it done for AVRs with built-in USB hardware? Do the Arduino libraries perform a software reset upon a change in the virtual DTR line?

@polwel I updated the answer to hopefully provide more information about Arduinos with buit-in USB.  The bootloader trigger is done within the Arduino virtual COM port library.


text:
Programming ATMega328p using VP812 programmer (for AVR/Atmel chips)
I bootloaded an ATMega328p (the one that uses the basic Arduino bootloader). Then, I used the VP812 for dumping other programs written in C (in Atmel Studio).
The process of erasing, blank test, programming and verification are all working fine and it seems that the program is actually being flashed. However, when I insert the same chip (controller) back in the Arduino Uno board, the controller doesn't function as programmed. Also, I am not able to dump any other example sketches.

Does this mean that the chip is damaged?
Does using the bootloaded chip with VP812 cause such problems?

Also, I used the "Write Fuse" option with the standard fuse configuration (all marks checked) in the VP812 configuration dialog box. Did this setting in any way create the problems I am facing now?

There is no way for us to tell, you have to check power and comm, the oscillator. You could have ESDed the chip and get intermittent results.

Yes - the settings created this problem. You have erased and disabled (via default fuses) the bootloader. It means that your application will run perfectly fine on an Arduino board, but you will not be able to flash over USB.
If you want to use Arduino USB bootloader again then you have to follow this guide


text:
Several Piezo contact mics with Arduino
I'd like to connect about 6 contact mics to my arduino and receive simultaneous signals to be used in my computer for an art installation.
Nonetheless, I don't know what's the ideal way to go. Shall I use Analog pins or Digital? How should I connect them - what schematics shall I follow? I read that ADC is CPU intensive, but I couldn't really find any viable alternative that explicitly shows the Digital deal.
Can I connect several contact mics to different analog pins and receive their input simultaneously as shown here? If this works, then it's perfect.
https://www.arduino.cc/en/Tutorial/Knock

What are you trying to do with the audio?

You'd probably damage your Arduino using that method - nothing to stop excess voltage or current from the piezo if hit too hard.

Thanks for comments! I'm going to create other audio :). So I only need data actually, which in turn I can use to create audio... So should I connect digital pins, or use some different parts in the circuit? Andy, how can I simply connect then?

Without a spec for the signals these transducers put out, and what you want to interpret from those signals, there is no question here.

Just a heads up, processing 6 audio signals and synthesizing other audio is a task unlikely to be able to be performed by the Arduino. Even a single-in, single-out audio is fairly limited, and typical synthesis requires assembly-level optimization.

simulate this circuit – Schematic created using CircuitLab
A piezo element can be connected to an analog input (A0 for example) of your microcontroller, but extra resistors are advisable if you wish to have a digital sample that is linearly proportional to the element's alternating voltage.
Andy's caution about over-voltage is relevant too - these elements can produce voltages far greater than your Arduino's DC supply voltage. Such over-voltage can cause damage. Resistor R3 helps limit potential damage.
Each piezo element will require its own set of three resistors (duplicates of R1, R2, R3). Many microcontrollers have multiple analog inputs - you can have as many piezo circuits as there are analog inputs. You cannot sample them all simultaneously, since most microcontrollers usually have only one analog-to-digital converter, which is switched between its various analog inputs by program control. A piezo element would have to be sampled, then switched to the next element for sampling, then the next....etc.
Sampling can be done fast enough that "audio" (however you define it) is fairly represented by the digital sample stream. However, be aware that processing these audio samples may be beyond the speed capability of simple microcontrollers like Arduino. That part is up to you.
Be aware that piezo elements make poor microphones. Units mounted in plastic shells are designed to output audio tones, and have significant resonant peaks. Frequency response is not flat, as required by a proper microphone.

You're a GOD. Much more information than I asked, but all needed. Thank you very much! I'll surely give it a try! By the way, it'll be activated with touch, so all I need is just the basic data to when people are touching, and in what degree... So the ideal seems to be to connect to digital pins but not sure how to do that either... But thanks!

@Emo , Thought your application was audio, not finger-pushes. Piezo's are sensitive for finger-pushes - a hard push will easily produce full output. With no push, data should eventually settle to half-way. "Release" should yield data opposite a "push". A constant-pressure "push" will also settle to half-way. These piezo elements are very brittle - cannot take much pressure before snapping (but then you have TWO piezos).


text:
IR communication not consistent
I have an IR Receiver hooked up to my arduino and a remote with an IR Trasmitter in it. I have some code to decode the values that are received but the values change even when I am pressing the same button!
Here is the code I am using:
#include <IRremote.h>

int IRpin = 8;
IRrecv irrecv(IRpin);
decode_results results;

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

void loop()
{
  if (irrecv.decode(&results))
    {
      Serial.println(results.value, HEX);
      irrecv.resume();
    }
}

and here is me pressing the same button 10 times and the output for it:

9C01C8E1
  FFFFFFFF
  82A6A14C
  FFFFFFFF
  FFFFFFFF
  70D67871
  FFFFFFFF
  BCB5C227
  FFFFFFFF
  B358F5ED
  FFFFFFFF
  FFFFFFFF
  FFFFFFFF
  FFFFFFFF
  FFFFFFFF
  FFFFFFFF
  58EE9A27
  FFFFFFFF
  90750A0D
  FFFFFFFF
  FFFFFFFF
  FFFFFFFF

Maybe the hardware is wrong. Can you show your wiring?

@NickGammon https://circuits.io/circuits/3614549-the-unnamed-circuit/edit#breadboard Its a 470 Ohm resistor.

Which IR receiver do you have? Not all of them require a resistor. See here. Also maybe you have the pins the wrong way around.

Try using a different remote...

It is not the remote that encodes the signals, it is the IR receiver. Changing the remote would do nothing.

@NickGammon I solved it.

Get TSOP1738 or any good IR receiver to decode. Above code is appropriate and does not need any changes. you will surely get some fluctuations and different decoded hex codes but it would provide only 2 different values for single button so that while controlling any device using ir , you can use 'or' operator in conditional statement and hence you will get desired results.
Getting absolute results from a cheap IR receiver is a myth.But it will work well for your project at lower level.I had worked with that and my device is working in my room with no difficulty.

You were right. The IR receiver that I had isn't yet supported by the IRremote library.

I eventually figured it out. The IR Receiver that I had was made by a company called Sharp. Every company has different methods of encoding and decoding IR signals, and it just so happens that decoding Sharp messages is not yet supported in the IRremote library, the library I was using for IR communication. I found a different IR receiver from an old electronic device that I had, I tried that and it worked perfectly.


text:
Multiple tones with one piezo buzzer
I have figured out how to make a piezo buzzer play two tones at once with analogWrite() and tone() but how would I make an actual song by playing both bass and treble, such as this one. Here is the circuit I had to do it:

and here is the code I had to do it:
int buzzer1 = 9;
int buzzer2 = 10;

void setup() {
  pinMode(buzzer1, OUTPUT);
  pinMode(buzzer2, OUTPUT);
}

void loop() {
  analogWrite(buzzer1, 100);
  tone(buzzer2, 262);
}

That circuit looks dangerous to me: you have two outputs shorted together, and each will be driving the other. It will damage the outputs, if it hasn't already. You need some sort of voltage adder I think.

First of all - You can drain max 20mA via pin, when one of the pins is HIGH and the other LOW, there is 5V between them, so there should be at least 250 Ohm resistor placed there, if you do not want damage your Arduino. I sugest add, to each of the red wires, at least a 200 Ohm resistor (to be safe).
For playing melody you have to save it somewhere, probabely easiest way is in arrays, and then play it note by note at regular intervals.
something like this (but insert your notes and set the length correctly):
int num_tones=6;
int tones1[] = {100,200,400,200,100,50};
int tones2[] = {262,131,131,262,131,524};

void loop() {
  for (int i=0;i<num_tones;i++){
    analogWrite(buzzer1, tones1[i]);
    tone(buzzer2,tones2[i]);
    delay(250);
  }
}

@Amorris: thanks for edit, I am not native speaker (not good speaker too)

I completed the following project https://github.com/linhartr22/count
Plays PWM files on Arduino through piezo speaker.
Most of the results came from the following page:
http://highlowtech.org/?p=1963
I'm using the https://github.com/damellis/PCM/zipball/master library mentioned there. count.ino is my sample sketch. As the web site mentions the audio comes out on Digital I/O pin 11. I've tested with both a piezo buzzer and a 4 ohm speaker. I'm really impressed. It does mess with some of the PWM timers so this may not be suitable for all applications.
I used Audacity to convert the sample wave files I was provided into PWM. The .h files are included in this repo.
The number of notes you can hold on the Arduino will depend on the size of the wave samples. If you need more notes, it might be possible to extend this with an SD card reader or other form of memory. It wasn't required for my project.


text:
RS232-TTL Data Transmission
I'm developing an computacional module to create risk maps in agriculture, I am using one arduino mega as "GreenSeeker", generating "fake" data to transmit via RS232 connection to one Raspberry PI, where she is process the data and generate the maps with GPS coordinates.
But, I have this cable.

I need to transmit data throught Arduino mega, and catch this data in the Raspberry PI.
I`ve have doubt about where connect the Serials pins on Arduino, the USB go on connect on the Raspberry PI USB, and the Serial go on Arduino, i need the right pins and where to connect them, and some code example.

Do you need a full 9 pin connection with hardware handshaking, or just an Rx/Tx? The latter is a simple affair with just a bit of soldering, but the former is going to be an ordeal.

Please edit the question and add an explanation of whatever might be the meaning of  “I need connect the Raspberry PI in one GreenSeeker, and the connector of this machine uses RS232 connection”

better this way?

The device pictured in the question Must Never be directly connected to a modern Arduino, as it uses RS232 levels, while an Arduino can only tolerate lower voltage "logic level" serial signal which are additionally inverted in sense.  Essentially you bought the wrong cable, and getting an adapter to make it work will be more awkward and expensive than getting the right cable.

You can indicate me the right cable?

I think you just want a normal USB A-B cable, exactly like you'd use on a PC.
You probably could use the cable you picture, but you'd need a female DB-9 connector.  If you really want to do that for some reason, you need to connect the Tx pin on the DB-9 (pin 2) to the Rx pin on the Mega, and the Rx pin on the DB-9 (pin 3) to the Tx pin on the Mega.

I really want to do that, because, I need connect the Raspberry PI in one GreenSeeker, and the connector of this machine uses RS232 connection.

@Avoxy way to spin this question and suddenly add other info. Where does the Mega come in? You can connect the greenseeker via this usb-to-rs232 adapter directly to the Pi.

I is using arduino to simulate the GreenSeeker data, i am is on University holidays, and the GreenSeeker machine is available only in my university, which is in other city.

The cable pictured in the this answer has possibility, but the one pictured in the question cannot and must not be used without an inverting level translator.  Attempting to use it without will destroy the Arduino.

@ChrisStratton Do you believe they run at full RS232 voltages? I suppose one should presume they might - but in reality I think many of them run at 5v. But it's a fair point - Avoxy, you should definitely check before you connect it.


text:
MATLAB+Arduino+LCD

I am trying to send some integers to an LCD. But it is not working. I have tried in Proteus. Please help. I have uploaded MATLAB and Arduino code below.
MATLAB code:
clear all
clc

 answer=1; % this is where we'll store the user's answer
 arduino=serial('COM1','BaudRate',9600); % create serial communication object on port COM4

fopen(arduino); % initiate arduino communication

while answer
fprintf(arduino,'%s',char(answer)); % send answer variable content to arduino
answer=input('Enter led value 1 or 2 (1=ON, 2=OFF, 0=EXIT PROGRAM): '); % ask user to enter value for variable answer
end

fclose(arduino); % end communication with arduino

Arduino code:
#include <LiquidCrystal.h>
int matlabData;
LiquidCrystal lcd(12,11,5,4,3,2);

void setup() {
  lcd.begin(16,2);
  Serial.begin(9600);
}

void loop() {
  if(Serial.available()>0) {
    matlabData=Serial.read();
    lcd.print(matlabData);
  }
}

What exactly is not working? The LCD?  Setting up the COM port on the host? Receiving serial data on the arduino? What have you tried?

lcd shows nothing.I have given the input with the help of MATLAB but still lcd shows nothing.

Not a Matlab expert, but if you enter '1', doesn't `input' yield the int 1? If sou, you are trying to display not the character '1', but the byte 1.

First, try to write anything to the LCD. Not serial data, just 'hello world'. See if that works.

With the help of ARDUINO,it works.But if I use matlab,it doesn't work.I am gonna upload a pic,take a look....

With the help of ARDUINO,I have tried.It worked.The problem arises when i use MATLAB.

Sigh getting serial ports to work with Matlab is a nightmare. Are you sure that part is working correctly? Try hooking it up to a PC and use an app like RealTerm or TerraTerm to make sure that piece is working correctly.

You can use Matlab's Arduino support package, it allows you to control the Arduino directly without having to write code in the Arduino IDE. I never used it with an LCD though. Here is a link that might help.

I already have installed all the packages required for arduino.This is working for led only.With the help of matlab I can easily control a led.But in case of lcd,I am facing this problem.

while answer
  fprintf(arduino,'%s',char(answer)); % send answer variable content to arduino
  answer=input('Enter led value 1 or 2 (1=ON, 2=OFF, 0=EXIT PROGRAM): ');
  % ask user to enter value for variable answer
end

Is it just me or should asking the user to input something be before printing it?
Also, more importantly, isn't fprintf(arduino, '%s', char(answer)); printing raw bytes? In which case, you would be sending 0x01/0x02. Not a great idea... In your Arduino code, print out on Serial what you are receiving, in [hexa]decimal, not as char.
    matlabData=Serial.read();
    Serial.print("Received: [0x");
    if(matlabData<16)Serial.write('0');
    Serial.print(matlabData, HEX);
    Serial.println("]");

This should give you a better idea whether you received anything, and if so, what.


text:
How do I order the gcc compiler to generate -S flag in Arduino IDE
How can I set the Arduido IDE to generate the -S flag to gcc to see the machine code in Arduino? (the sketches)

avr-gcc's switch "-S" means "Compile only; do not assemble or link". Are you thinking of avr-objdump? It's "-S" switch means "Intermix source code with disassembly".

Compiler flags are defined in the platform.txt of the board you have selected in the Tools > Board menu. You can also add compiler flags via a build.extra_flags property in the boards.txt entry for the selected board.


text:
Volatile variable not updating from timer ISR
I know this is a problem that has come up many times but I can't seem to get this code fragment to update the count variable on an ATMEGA328P. I am using an Arduino Uno as a development board, with the LED on pin 13 set to flash for debugging. I have confirmed the timer and LED part work by toggling port B pin 5 in the ISR routine.
#include <avr/io.h>
#include <avr/interrupt.h>

volatile uint8_t count;

void init_100us_tick(void) {
    TCCR0A = _BV(WGM01) | _BV(WGM00);       // WGM mode 7 with OCRA as top
    TCCR0B = _BV(WGM02) | _BV(CS01);        // CLK / 8 prescaler
    TIMSK0 = _BV(OCIE0B) | _BV(TOIE0);      // Interrupt enabled on OCR0A
    OCR0A = 200;                            // 16 MHz / 8 / 200 = 100 us
    sei();                                  // Enable interrupts
}

ISR(TIMER0_COMPB_vect) {
    count++;
}

int main(void) {
    DDRB |= _BV(DDB5);                      // PB5 output
    init_100us_tick();                      // Initialise 100 us tick
    count = 0;                              // In case of micro reset

    for (;;) {
        if (count >= 100) {                 // Every 10 ms
            count = 0;
            PORTB ^= _BV(DDB5);             // Toggle PB5
        }
   }
   return 0;
}

This is being compiled and burned to an Arduino Uno with the following:
avr-gcc -Os -DF_CPU=16000000UL -mmcu=atmega328p -c -o test.o test.c
avr-gcc -mmcu=atmega328p test.o -o test
avr-objcopy -O ihex -R .eeprom test test.hex
avrdude -F -V -c arduino -p ATMEGA328P -P /dev/ttyUSB0 -b 115200 -U flash:w:test.hex

I have tried disabling the optimisation with no effect. AVR-GCC is version 4.9.2

Interrupt enabled on OCR0A - don't forget to change the comments if you change the code! You have an interrupt on TIMER0_COMPB_vect!

You want CTC mode for that to work. As in:
#include <avr/io.h>
#include <avr/interrupt.h>

volatile uint8_t count;

void init_100us_tick(void) {
    TCCR0A = _BV(WGM01);       // CTC mode 2 with OCRA as top
    TCCR0B = _BV(CS01);        // CLK / 8 prescaler
    TIMSK0 = _BV(OCIE0B) | _BV(TOIE0);      // Interrupt enabled on OCR0B
    OCR0A = 200;                            // 16 MHz / 8 / 200 = 100 us
    sei();                                  // Enable interrupts
}

ISR(TIMER0_COMPB_vect) {
    count++;
}

int main(void) {
    DDRB |= _BV(DDB5);                      // PB5 output
    init_100us_tick();                      // Initialise 100 us tick
    count = 0;                              // In case of micro reset

    for (;;) {
        if (count >= 100) {                 // Every 10 ms
            count = 0;
            PORTB ^= _BV(PORTB5);             // Toggle PB5
        }
   }
   return 0;
}

That toggles every 10 ms.

(Edited to add)
The PWM mode you chose will work providing you enable the correct interrupt. This also outputs 10 ms pulses:
#include <avr/io.h>
#include <avr/interrupt.h>

volatile uint8_t count;

void init_100us_tick(void) {
    TCCR0A = _BV(WGM01) | _BV(WGM00);       // Fast PWM mode 7 with OCRA as top
    TCCR0B = _BV(WGM02) | _BV(CS01);        // CLK / 8 prescaler
    TIMSK0 = _BV(OCIE0A);                   // Interrupt enabled on OCR0A  ***
    OCR0A = 200;                            // 16 MHz / 8 / 200 = 100 us
    sei();                                  // Enable interrupts
}

ISR(TIMER0_COMPA_vect) {                    // Compare A vector ***
    count++;
}

int main(void) {
    DDRB |= _BV(DDB5);                      // PB5 output
    init_100us_tick();                      // Initialise 100 us tick
    count = 0;                              // In case of micro reset

    for (;;) {
        if (count >= 100) {                 // Every 10 ms
            count = 0;
            PORTB ^= _BV(PORTB5);           // Toggle PB5  ***
        }
   }
   return 0;
}

Changed lines indicated by ***
Note that you should not have enabled _BV(TOIE0) because you have no interrupt handler for Timer 0 overflow. Without an interrupt handler the compiler probably generated code to jump to the reset vector.
The interrupt occurs when the timer matches the Compare A amount (not Compare B) so you need an interrupt on the A side.

You might want to set OCR0B to a defined value, instead of relying on the default value of 0.

Thank you, that worked! Can you please explain why changing to CTC mode has this effect?

See amended answer.


text:
Reading Infrared raw data
I'm trying to understand a few things about this code.

Why is digitalRead() slower than IRpin_PIN & (1 << IRpin)?
What does IRpin_PIN & (1 << IRpin) mean? I translated it to numbers and I figured out it's actually PIND & (0b100). What does PIND translate to and why is bitwise-and with 0b100 performed on it?
Why is the 20-microsecond delay (RESOLUTION) necessary?
What does _BV in while (! (IRpin_PIN & _BV(IRpin))) mean?

/* Raw IR decoder sketch!

 This sketch/program uses the Arduno and a PNA4602 to
 decode IR received. This can be used to make a IR receiver
 (by looking for a particular code)
 or transmitter (by pulsing an IR LED at ~38KHz for the
 durations detected

 Code is public domain, check out www.ladyada.net and adafruit.com
 for more tutorials!
 */

// We need to use the 'raw' pin reading methods
// because timing is very important here and the digitalRead()
// procedure is slower!
//uint8_t IRpin = 2;
// Digital pin #2 is the same as Pin D2 see
// http://arduino.cc/en/Hacking/PinMapping168 for the 'raw' pin mapping
#define IRpin_PIN      PIND
#define IRpin          2

// the maximum pulse we'll listen for - 65 milliseconds is a long time
#define MAXPULSE 65000

// what our timing resolution should be, larger is better
// as its more 'precise' - but too large and you wont get
// accurate timing
#define RESOLUTION 20

// we will store up to 100 pulse pairs (this is -a lot-)
uint16_t pulses[100][2];  // pair is high and low pulse
uint8_t currentpulse = 0; // index for pulses we're storing

void setup(void) {
  Serial.begin(9600);
  Serial.println("Ready to decode IR!");
}

void loop(void) {
  uint16_t highpulse, lowpulse;  // temporary storage timing
  highpulse = lowpulse = 0; // start out with no pulse length
//  while (digitalRead(IRpin)) { // this is too slow!
    while (IRpin_PIN & (1 << IRpin)) {
     // pin is still HIGH
     // count off another few microseconds
     highpulse++;
     delayMicroseconds(RESOLUTION);
     // If the pulse is too long, we 'timed out' - either nothing
     // was received or the code is finished, so print what
     // we've grabbed so far, and then reset
     if ((highpulse >= MAXPULSE) && (currentpulse != 0)) {
       printpulses();
       currentpulse=0;
       return;
     }
  }
  // we didn't time out so let's stash the reading
  pulses[currentpulse][0] = highpulse;
  // same as above
  while (! (IRpin_PIN & _BV(IRpin))) {
     // pin is still LOW
     lowpulse++;
     delayMicroseconds(RESOLUTION);
     if ((lowpulse >= MAXPULSE)  && (currentpulse != 0)) {
       printpulses();
       currentpulse=0;
       return;
     }
  }
  pulses[currentpulse][1] = lowpulse;
  // we read one high-low pulse successfully, continue!
  currentpulse++;
}

void printpulses(void) {
  Serial.println("\n\r\n\rReceived: \n\rOFF \tON");
  for (uint8_t i = 0; i < currentpulse; i++) {
    Serial.print(pulses[i][0] * RESOLUTION, DEC);
    Serial.print(" usec, ");
    Serial.print(pulses[i][1] * RESOLUTION, DEC);
    Serial.println(" usec");
  }
  // print it in a 'array' format
  Serial.println("int IRsignal[] = {");
  Serial.println("// ON, OFF ");
  for (uint8_t i = 0; i < currentpulse-1; i++) {
    //Serial.print("\t"); // tab
    Serial.print("pulseIR(");
    Serial.print(pulses[i][1] * RESOLUTION , DEC);
    Serial.print(");");
    Serial.println("");
    //Serial.print("\t");
    Serial.print("delayMicroseconds(");
    Serial.print(pulses[i+1][0] * RESOLUTION , DEC);
    Serial.println(");");
  }
  //Serial.print("\t"); // tab
  Serial.print("pulseIR(");
  Serial.print(pulses[currentpulse-1][1] * RESOLUTION, DEC);
  Serial.print(");");
}

I expect the source for digitalRead() will explain a lot about why it's slower.

int digitalRead(uint8_t pin)
{
    uint8_t timer = digitalPinToTimer(pin);
    uint8_t bit = digitalPinToBitMask(pin);
    uint8_t port = digitalPinToPort(pin);

    if (port == NOT_A_PIN) return LOW;

    // If the pin that support PWM output, we need to turn it off
    // before getting a digital reading.
    if (timer != NOT_ON_TIMER) turnOffPWM(timer);

    if (*portInputRegister(port) & bit) return HIGH;
    return LOW;
}

1) so it

calls function digitalRead() (puts value on stack, jumps, prepare function frame - each cost some time)
calls 3 other functions (with all the same problems)
check for sanity of value
check for PWN (and eventually calls another function)
does the PIND & (0b100)
returns from function (so read stack, clear the frame, jumps, set the result)

just to obtain the same functionality

typical for library functions, that each call makes sure the environment is sane and expected each and every time it is called - in close loop you can check it onece before and then just do not broke it
translates parameter from nice arduino numbers to real addresses and bits each and every time again

2) it access the PORT D (see AVR (the processor) internal construction) and reads value of its 3. bit (which maps to the relevant pin of the chip/Arduino board
3) see following comment - it is expected length of the pulse (maybe with some safety limit)
4) _BV is for BitValue - shift 1 to position given by arg (that is macro doind 1 << IRpin) maybe more nice/readable version, compiles to the same. (the ! is ofcourse negaition)


text:
Timer3 Arduino maximum period
At the moment I'm trying to learn microcontrollers with Arduino, and have a problem with the timer.
Arduino works at 16MHz clock, and the best prescaler is 1024, which means the timer increments the value every 64 us. Timer 3 is a 16 bit timer, which gives us a maximum time of 64*65535= 4194240, ca. 4s
But what if I want to do a job every 8 seconds? Any idea?
Here's my code:
TCCR3A = 0;
TCCR3B = 0;
TCCR3B |= (1<<WGM32); //CTC
TCCR3B |= (1 << CS32);
TCCR3B |= (1 << CS30);// 1024 prescaler
TIMSK3 |= (1<<OCIE3A);
sei();

Schedule it every second time the interrupt fires.

You can't - not directly. Instead you do a job at a higher frequency which just counts. When it has counted enough you do your other job.
For instance, you might trigger your interrupt once a second. That interrupt just adds 1 to a count and returns. Unless that count just hit 8, when you reset the count to 0 and run your 8 second routine.

+1 This is indeed generally how it is done.  Though if the system doesn't need to do much else or more frequently, you can ultimately save power by activating the divider on the MCU clock itself (and/or put the MCU to sleep in between events). However those are advanced topics and introduce various complications that may not be warranted for the current goal.

You know that the inbuilt function millis() would let you achieve that goal?
For example:
unsigned long startTime;

void loop ()
  {
  if (millis () - startTime >= 8000)
    {
    startTime = millis ();  // reset start time to now
    // do something that needs doing every 8 seconds
    }

  // do other stuff

  }  // end of loop

If the 5% error (~4.2 sec vs. 4.0 sec) isn't a problem, 2 counter overflows will give 8 seconds with the same 5% error, or ~8.4 sec. If you need higher accuracy, either start the timer with a slightly smaller initial counter value, (62500 * 64 = 4000000 uSec), choose a divider value that naturally overflow at convenient sub-multiples of the intervals your program will need, and again count N overlows of the timer before your code responds.


text:
Is there a way to "list" (in BASIC, or "cat" in LINUX) the current sketch loaded in my xxxDUINO?
I was surprised when I couldn't find an old post where someone asked this question. Seems like a natural beginner, uh excuse me, "newbie" question, but then I'm a throw-back to the days when a home computer came with 3,583 bytes (three-thousand, five-hundred eighty-three). So again, as seen in the title, can I "list" my sketch? I'm pretty sure the answer is NO since if it were a good question someone would have asked it already. It just strikes me as odd that my old VIC-20 could do something this phenomenal techno-marvel can't. Not much of an accomplishment for the dinosaurs, but HEY! We're on the scoreboard now! [nothing's worse than that miserable goose-egg :(   ]

What is the problem you are trying to solve? You have an Arduino and you want to "list" its contents?

I was surprised when I couldn't find an old post where someone asked this question. -- How about the first in the "Related" list...?

Sorry about that, I really hate posting nuisance threads. I almost always prefer  to find a good answer and be on my way. I so don't want to be the that type of person who wont put in any effort. I know I can't see you or will ever meet you, but I find it embarrassing, unpleasant, uncomfortable, unnerving, and unsettling when I bring down the room or step on someone's leisure. I should have dug more, and not been so hasty when going through the search results. But most annoying to me, was dropping the ball when trying to articulate what I wanted, which wasn't LIST or PRINT, but DOWNLOAD! sorry

If you can't find your answer whilst searching it is often easier to start typing out your question. While you are doing so the system is constantly analysing what you are asking and offers you suggestions. Because you put so much more detail into a question than you do into a search box those can often be far better results than a simple search. Especially when search really relies on you knowing what to search for in the first place, which isn't always the case.

And anyway, when I'm around the room can't get any lower ;)

No. the code burned in an Arduino is compiled not interpreted like Basic.
Basically your C language sketch is compiled into AVR assembly language. The resulting hexadecimal is what is burned to the Arduino.
Yes you could disassemble the hex like we used to do in the good old days, but as before it is highly unpredictable and most of the time not very useful.
Just a quick example. The following simple Arduino sketch that just sets a pin in output and then sets it HIGH:
void setup() {
  pinMode(13, OUTPUT);
  digitalWrite(13, HIGH);
}

void loop() {
}

The resulting hex file is 3.5Kb.This include various sections of data and code. One would have to analyse the section, convert the hex (op-code) to assembly language and find which part correspond to the C code.
It is possible, and there are probably tools that do a fairly good job. Would the C language generated by the decompilation once recompile perform exactly like the original compiled cole. I doubt it.

Hmmm, I'm intrigued! I love a fool's errand (sometimes). Just out of curiosity then, could you briefly outline the disassembly process, and perhaps some idea in broad terms what makes this unpredictable and the obstacles that prevent useful results. I have not Idea what I'm asking of you, so please forgive me if this is an imposition. I know I'd be less than receptive to someone wanting to know what the average mass of a fastener was in my collection of old machine screws!

Well, you have to take the hex codes (called op-code) and convert that to assembly language. Then you have to match the part of assembly language and find what they would represent in C.

edited my answer to provide more details.

Regarding the disassembly process see my answer here.


text:
Using both a stepper motor and a DC motor with Arduino motor shield R3
We are trying to reprogram a remote control car with an Arduino Uno. This car runs the power with a DC motor, and it controls steering using a stepper motor.
We have the Motor Shield R3 attached to the Arduino, but it has just now occurred to us that we can't support both motors with the motor shield (as the motor shield only allows for two DC motors or one stepper motor). Is there a way to somehow work around this? Or is it possible that we would need to replace the stepper motor with DC?

You are right: Motor Shield R3 can drive two DC motors or one step motor. So, there are 2 (maybe  3) solutions:
1. Have another shield - now you can drive 2 step motors, or one DC motor(using 'half' of shield, and one step motor using another whole shield.
2. Replace your step motors with DC motor. This option can be more complicated, as no precise position control will be possible when you try to use DC motor for steering. (DC motor are hard to select and hold position, when stepper motors are quite easy to 'go to certain position' AND 'hold'). There is also good mechanical skill needed to remove/place it precisely.
optional option 3. Instead of Motor Shield R3 you can try to use cheap Easy Driver to drive your step motor.

authors: Мимо Траходил


text:
Issue with Arduino Timing
I am working with an Arduino on a project for which timing is very important. I use TimerOne to trigger timer interrupts and use micros() for delays (delayMicroseconds() was causing problems worse than the one explained below). The program is sending a manual PWM signal to an LED and it is very important that the signal is sent with an error that is less than 8 microseconds (ideally, the signal is sent at the same time in each period). My test code is shown below:
#include <TimerOne.h>
#include <SPI.h>

const int LED_PIN = 3;
const int CHIP_SELECT = 12;

const int PERIOD = 4000;
const double DUTY_CYCLE = .5;
const int HIGH_TIME = PERIOD * DUTY_CYCLE;
const int LOW_TIME = PERIOD - HIGH_TIME;
const int INITIAL_SIGNAL_DELAY = LOW_TIME / 2;
const int HIGH_TIME_TOTAL_DELAY = INITIAL_SIGNAL_DELAY + HIGH_TIME;

const int RESISTOR_VALUE = 255;

boolean triggered = false;
boolean data = false;

unsigned long triggeredTime;
unsigned long s;
unsigned long e;

boolean found;
int i = 0;

void setup()
{
  s = micros();

  Timer1.initialize(PERIOD);
  Timer1.attachInterrupt(trigger);

  pinMode(LED_PIN, 3);
  pinMode(CHIP_SELECT, OUTPUT);

  SPI.begin();

  digitalWrite(CHIP_SELECT, LOW);
  SPI.transfer(B00010001);
  SPI.transfer(RESISTOR_VALUE);
  digitalWrite(CHIP_SELECT, HIGH);

  e = micros();

  Serial.begin(115200);
  Serial.print("s: ");
  Serial.println(s);
  Serial.print("e: ");
  Serial.println(e);
}

void loop()
{
  if(triggered)
  {
    while(micros() - triggeredTime < INITIAL_SIGNAL_DELAY)
    { }
    s = micros();
    digitalWrite(LED_PIN, data);
    while(micros() - triggeredTime < HIGH_TIME_TOTAL_DELAY)
    { }
    digitalWrite(LED_PIN, LOW);

    data = !data;
    triggered = false;

    e = micros();
    //micros();

    if(s % 100 > 28 || s % 100 < 12)
    {
     found = true;
    }

    if(!found)
    {
      Serial.print("s: ");
      Serial.println(s);
    }
    else
    {
      Serial.print("ERROR: ");
      Serial.println(s);
    }
    //Serial.print("e: ");
    //Serial.println(e);
  }
}

void trigger()
{
  triggeredTime = micros();
  triggered = true;
}

(it should be noted that the first signal sent is always xx20, usually 5020).
So, with this code, I eventually get an error. I am not sure why, but this error occurs at the same point every single time:
.
.
.
s: 1141020
s: 1145020
s: 1149020
ERROR: 1153032
ERROR: 1157020
ERROR: 1161020
.
.
.

Now, the really weird part is if I remove the comments before micros() (the micros() right after e = micros()), there is no error (or at least there is not an error within the first 30 seconds). I was wondering if anybody could provide an explanation for why this happens. I have dedicated many hours trying to get the timing working properly and everything was working well until I encountered this error. Any help would be very much appreciated. Thank you!

Why not set up a timer interrupt to trigger every 8us then instead of depending on the Arduino timing routines to possibly get it right?

My apologies, perhaps I was unclear about the intention of my code. The signal is supposed to be sent once every 3 milliseconds. The time at which it is sent within each cycle should be the same, though (with a maximum deviation of 8 us). Also, I found that if I do not print s on every cycle, the problem goes away. I was wondering if anyone knew why this fixes the problem.

Fair enough. But replacing 8us with 3ms in my comment should fix that.

That was actually how my initial code was structured. Arduino does not work well with long interrupts, unfortunately,  and that was causing sporadic behavior (the interrupt would have to be able to be 1.5 milliseconds long)

The Seiral library uses interrupts, so will jitter the timings of other interrupts. This may or may not cause your error message, but it will mess up your other timings. If I rely on interrupt timing, and I need the UART for debug, I don't use Serial, but hit the hardware UART with single byte writes from within my sole interrupt routine (after it's done what it's meant to do) so only one thing is in charge of timing.

I don't understand from the code or the problem statement exactly what waveform you are trying to generate, but have the impression that it can be generated using timer 1 pwm.  Note that micros() resolution is 4 μs which eats up a lot of your ±8 μs tolerance, and the busy waiting adds jitter as well.

Your whole post makes little sense to me. You set up the timer to interrupt every 4 ms, but you send a signal only every other interrupt (because of data = !data). Thus you signal period is 8 ms, whereas in the comments you state you want a period of 3 ms. Why don't you rewrite your question clearly stating what you are trying to achieve? Please, describe precisely the shape of the waveform you want to generate. Your best bet is probably to configure Timer 1 as PWM. If you really want a 3 ms period, you can set the prescaler to 1 and have single-cycle resolution.

Don't cross post questions

the code flow doesn't make a lot of sense to me. seems to me that you can simplified quite a bit.

if(s % 100 > 28 || s % 100 < 12)

I would use a few brackets to make it clear to the compiler what you want it to do.


text:
Lighting LED with Arduino Uno from PC keyboard
I tried to turn on a LED with my PC keyboard and an Arduino Uno with the letter A.
I get the message

exit status 1
  'keypressed' was not declared in this scope

My code:
int led1 = 10;

void setup()
{

pinMode(led1, OUTPUT);
}
void loop()
{

 if(keypressed == 'a'){
               digitalWrite(led1, HIGH);
               delay(500);
}
}

What is the problem?

Uhh please don't tell me you just made up the term "keypressed" because I'm pretty sure that's NOT how programming works. By the way, getting a keyboard input to control a USB device is no where near simple. Along with the Arduino code for the Arduino, you need another program that will detect keyboard strokes, then interface serial with the Arduino.

Is not there something that can help me
Like plugin

I think keypressed() should be serial.Read() and then send the letter a from the serial monitor or maybe build a python script to find, connect to the arduino serial port then you are able to send this character. keypressed() is not a valid arduino function!

It tells you EXACTLY what your problem is: "'keypressed' was not declared in this scope". It means you never defined "keypressed". How is the Arduino supposed to know what you wanted it to mean? Arduinos can't read minds.

Firstly, you can't just make up the term "keypressed" because the programming language is unable to understand it (unless you assign it as a variable but it's purpose then would just be to store and retrieve values). Secondly the arduino itself is unable to detect keystrokes from the computer by itself. It needs a program on the computer to be able to detect keystrokes from the keyboard then send it to the arduino.
So how would one do this?
Assuming you use Windows, learn Python (A not-so-hard programming language on the computer), then look up the msvcrt library and from there learn how to get key strokes (this only works if you are currently selecting the running program). Then in arduino and python, learn how to use serial. For Python, you need to download this library and learn how to use it. For Arduino it's already in there you just have to learn how to use it. Then you can do the rest and make it turn on your LED.
I hope this helps.

Here you declared keypressed as a variable, so you need to assign an input to it using
'keypressed = serial.read()'
without quotes before if statement in void loop. Note make make use of serial monitor for input and also assign
'serial.begin(9600)'
without quotes in void setup function before pinmode statement.

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


text:
Arduino ATmega 2560 frequency measurement
I would like to measure frequency with an Arduino 2560 board. The approach is to use a timer interrupt set to one second and pin interrupt to count interrupts in one second.
The problem I have is that I get the wrong frequency. On my frequency generator I set up a frequency of 1000 Hz in my program I get 1006 Hz instead of 1000 Hz.
What am I doing wrong?
Here is my program. In the stup method I have declared a timer. When the signal comes on pin 2, the counter is increased by 1. After one second passed the flag bData is raised. If the flag is true then I print out a frequency on serial port.
#include <SPI.h>
#include <Ethernet.h>
#include <Math.h>

byte mac[] = {  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
IPAddress ip(192, 168, 1, 177);
EthernetServer server(80);
const byte interruptPinTemp = 2;
const byte interruptPinSlanost = 3;
//konstante za SBE-3
const double g = 4.85442486e-003;
const double h = 6.77300393e-004;
const double i = 2.65502731e-005;
const double j = 2.06782794e-006;
const double f = 1000.0;
volatile int cnt = 0;
volatile int cnt1 = 0;
volatile double slanost = 0;
volatile double slanost1 = 0;
int timer1_counter;
boolean bData = false;
volatile int dvesek = 1;

void beriTemperatura() {
  cnt++;
}

void beriSlanost() {
  slanost++;
}

double calcTemp(double frekvenca) {
  double logRes = log(f / frekvenca);
  return 1.0 / (g + (h * logRes) + (i * pow(logRes, 2.0)) + (j * pow(logRes, 3.0))) - 273.15;
}

void setup() {
  Serial.begin(9600);       // inicializacija serijskega porta
  noInterrupts();           // disable all interrupts
  // start the Ethernet connection and the server:
  Ethernet.begin(mac, ip);
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());
  pinMode(interruptPinTemp, INPUT_PULLUP);
  pinMode(interruptPinSlanost, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(interruptPinTemp), beriTemperatura, CHANGE);
  attachInterrupt(digitalPinToInterrupt(interruptPinSlanost), beriSlanost, CHANGE);
  TCCR1A = 0;
  TCCR1B = 0;
  timer1_counter = 34286;   // preload timer 65536-16MHz/256/2Hz
  TCNT1 = timer1_counter;   // preload timer
  TCCR1B |= (1 << CS12);    // 256 prescaler
  TIMSK1 |= (1 << TOIE1);   // enable timer overflow interrupt
  interrupts();
}

//Timer interrupt na 1 sekundo
ISR(TIMER1_OVF_vect) {
  // interrupt service routine
  TCNT1 = timer1_counter;   // preload timer
  cnt1 = cnt ;               // prepisemo vrednost v cnt1
  bData = true;             // postavimo flag
  cnt = 0;  // resetiramo counter
}

void loop() {
  // če je postavljen flag, da so podatki jih izpišemo ali naredimo karkoli drugega
  if (bData == true) {
    bData = false;
    Serial.println(calcTemp(cnt1), 3);
    Serial.println(cnt1);
  }
}

Here is the frequency from my generator:

And here is a frequency measured with my board:

What is wrong that I get 1006 Hz instead of 1000 Hz?
If I raise the frequency for example to 5 kHz then I get 5032 Hz in my program (32 Hz to0 much).
Thank you for any advice.

TCNT1 = timer1_counter;   // preload timer

When you load the offset (timer1_counter), there are some values in the timer1 prescaler (and potentially TCNT1 if the prescaler isn't sufficient large, or the input pulse train is fast). By assigning a value to TCNT1, you would have written over the values in the prescaler / TCNT1 -> read the datasheet on that.
The solution?

Optimal: use a timer with auto-reload function. a timer with output compare can be adopted here as well.
Increment the counter: TCNT1 += timer1_counter; // preload timer, if timer has a 1:1 prescaler.

Or to use the timer to count the pulse and another to provide the time base.

Hi DannyF.. do you have some example? I'am new to microcontrollers (will check on google for auto-reload)

i'm happy to report that your code got accurate results when I drove it to 10Khz. the issue is likely the oscillator -> if they had indeed used a ceramic oscillator, they made a mistake. with a few cents more, they could have used a crystal instead.

with that said, it is generally desirable to NOT write to the counter. the optimal solution is to use auto reloading; if not available, try to increment it -> that typically can get the result down to two - three ticks.

The Arduino Mega 2560 is clocked off a ceramic
resonator, which
should typically have about 0.5% frequency tolerance. Your readings are
off by 0.6%, which is slightly more than the typical resonator
tolerance. I would them assume there is something wrong with your code,
check dannyf's answer.
Now, if you want significantly better accuracy, I would argue than
relying on the Arduino's internal clock is not a good idea. Even if your
code is perfect you cannot expect good accuracy. You could have better
results if you calibrate that clock instead of just assuming it runs at
16 MHz. But even then, ceramic resonators are notorious for having
a very significant frequency drift. Or you may get an Arduino clocked
off a quartz crystal instead, as these are far more stable.

authors: Александр Попов


text:
Using 8-bit instead of 16-bit in Adafruit library
I tried to modify the Adafruit_GFX and Adafruit_ST7735 libraries to make the color variable( as shown in code below) to use 8-bit instead of 16-bit for displaying 8-bit color on LCD screen.
void Adafruit_ST7735::pushColor(uint16_t color) {
 #if defined (SPI_HAS_TRANSACTION)
   SPI.beginTransaction(mySPISettings);
 #endif
  *rsport |=  rspinmask;
  *csport &= ~cspinmask;

   spiwrite(color >> 8);
   spiwrite(color);

   *csport |= cspinmask;
 #if defined (SPI_HAS_TRANSACTION)
   SPI.endTransaction();
 #endif
}

I changed it to the below
void Adafruit_ST7735::pushColor(uint8_t color) {
  #if defined (SPI_HAS_TRANSACTION)
   SPI.beginTransaction(mySPISettings);
  #endif
   *rsport |=  rspinmask;
   *csport &= ~cspinmask;

   //spiwrite(color);
   spiwrite(color);

   *csport |= cspinmask;
#if defined (SPI_HAS_TRANSACTION)
  SPI.endTransaction();
#endif
}

I have made similar changes in other portions of the code. This time nothing was displayed in the LCD(it was blank). However, when the spiwrite(color) is written twice i.e. the comment is removed, the code works fine.
Why is there a need to write 'spiwrite' function twice even in case of 8-bit color?
The original Adafruit library files are also attached.
drive.google.com/open?id=0B3x_NfKXnhtHR0VBcTNZbk5WT0E

If there is a publicly available version of the library that we can easily view online, why do you make us download a .zip file from Google Drive?

Did you read the datasheet of the LCD screen? The LCD expects you to
send the data in a specific format, and you should comply with that
format rather than invent your own and expect it to magically understand
it. If the LCD expects you to send 16 bits, you should do so. Or maybe
it has a 8 bit mode and there is a way for you to tell it “I'm switching
to 8-bit mode”. Read the datasheet to be sure.
If you want to display 8-bit color on an LCD expecting 16-bit, you
should find a way to map the 8-bit values into 16-bit values. The most
obvious way to map the range [0, 255] to [0, 65535] is to multiply the
8-bit numbers by 65535/255 = 257. Which is the same as sending the byte
twice.

I think you / someone asked an identical question here recently.
you didn't say a reason why you want to change a 16-bit type to 8-bit type.
with that said, this should work:
void Adafruit_ST7735::pushColor(uint8_t color_msb, uint8_t color_lsb) {
   ...
   spiwrite(color_msb);
   spiwrite(color_lsb);
   ...

basically, the original code.


text:
How do I accelerate a stepper motor?
I have a 24BYJ48 stepper motor, and my main problem is that I cannot make it rotate quickly. I've understood that in order to achieve a high speed I must start at a low speed and carefully accelerate the motor to higher speeds.
I'm not quite sure how this acceleration ought to be done, though. My idea is to execute the control sequences with an initially long delay, and then decrease the delay between each time I change the sequence for the motor wires.
Below is the code I have written. When I run it, the motor accelerates for a little while, but then all of a sudden it just stops and makes a high pitched noise.

https://www.tigoe.com/pcomp/code/circuits/motors/stepper-motors/

The Arduino manual says, that delay() function only excepts long ints > Arduino Delay.

You didn't include your entire program. Try including it as text, not an image. Stack exchange has some syntax highlighting. Also, as auoa said, delay() only excepts long integers. Use delayMicroseconds() instead for more precision (which still uses integers).

The basic technique is as you have tried to program. The time between stepper pulses if shortened to cause acceleration and lengthened to slow down. A real solution typically uses an "S" curve type acceleration profile that starts out with a slow ramp up to the acceleration rate and then as it nears the target rotational speed it slows the acceleration rate back down.
In your case you may be getting to the point where you have increased the acceleration rate too much and the motor cannot respond to it.

Does this mean the motor cannot go any faster? If so, are there any workarounds?

@user2157416 - I cannot answer your question for you. I do not know your motor characteristics nor am I in a position to unthread your code to see where any weakness that may exist. For all I know maybe the fact that you set the four output drive signals one at a time could be a problem, you may have a completely unsuitable power supply or even a stepper driver circuit that is not up to the job.

Also the motor driver circuit can be a problem, does it handle the dead time for you? If not your code can produce short circuits within a half bridge. Or the motor current is not sufficient for high speeds.

@auoa - the upper and lower drivers are not being distinctly controlled by software, so software can neither cause nor prevent short circuits.  Dead time from the perspective of what is being controlled would merely be time when there is no applied voltage difference across a coil from the drivers, however there may still be current flow through the catch diodes from inductive decay.

There are several things going on here....

If the load is purely inertial and small (~ equal to the rotor inertia), acceleration typical takes only a few steps.  No need to drag it out.  Try some different delays after the first step.
If you have a torque load (you are pushing something), at some point, during acceleration, the currents in the winding will be too small to generate the required torque.  As the speed increases, the currents will decay, due to the motor back-EMF and inductance (which is very significant).
Sometimes, at particular speeds, step motors exhibit a dynamic instability.  That is, they start hunting...faster, slower, faster, slower, etc. until the motor "stalls".  The resistance seen by the motor, looking back into the drive circuit, is the key factor here.  At high speeds, the current regulator runs out of voltage and the effective resistance drops...leading to instability.

So, do some experimentation!!!


text:
Is there anything special about Arduinos?
I've been using the stm32f4 discovery up until now but I've heard Arduinos are easier to use. While looking for an Arduino Genuino Uno Rev3 board, I was told to get a knock off instead.
Is there any real difference between Arduino boards and other knock off micros with similar specs?
I really just want to get a feel for what it's like using an 'easier' micro. It doesn't need to be extra special.

Are you sure you are looking for an "adruino" ?

"Arduino" is not the name of a microcontroller family. So you are trying to compare apples with oranges (Arduinos are microcontroller boards; most of the Arduino boards are based on Atmels ATmega controllers but there are also ones with an ARM controller)

You might want to look into this if you are interested in knowing the background of Arduino. Namely how it was ""adapted"" from Wiring.

Arduino have "standardized connectorss" for witch are many shields created. Also many manufacturers marks anything vaguely in power range of 5V as "for Arduino", because Arduino is so popular. And that is main reason, that Arduino is so popular. (This and that it came in the righ time with equipement targeting to be easy for beginners and a lot of educational materials).
I am using Arduino just because I start with it and bought a lot of AVR based boards and chips, but I may switch to STM for higher computing power, more pins and better equipement.
And the Arduino IDE is easy for beginners (and popular between them), because it have nearly nothing in it and it can compile+upload code to Arduino with just 2 buttons. (But it is like notepad with few more buttons - if you are a little more advanced you will run away for better editor/IDE/whatever at all cost. I use Vim + Make to create and run Arduino code and avoid the IDE totally, many do that too.)
So if you are used to STM32F4 kit, it would be big step back for you and it would satisfy you only if you need something cheap for work, where your STM is total overkill.

Just as a reference, STM boards are actually cheaper than the genuine arduino boards ;) plain microcontrollers and the smallest compatible boards are even cheaper, but plain microcontrollers are not so user friendly

This is Google Trend of Arduino (blue) versus four other boards: STM32 (red), Teensy (green), MSP430 (yellow) and PIC32 (magenta).
That means lot of people using Arduino, making hardware and software, writing blogs, answering questions. That's the biggest plus of Arduino.

I think the reason why people say Arduino is easier to use is because it has a nice IDE and code upload is rarely troublesome.
Especially, the IDE allows the user to code hardware related functions with simplified functions.
For example, when coding an Arduino Sketch, the user doesn't really have to bother about registers.
The Arduino family are based on Atmel chips, so when it comes to raw hardware performance, Arduino performances are identical to Atmel chips.
If you are familiar with what you have(STM32F4) and don't want to make things easier but rather challenging, you don't have to move to Arduino.
Of course, if you want a simple & fast prototyping, nothing beats Arduino. (<- my personal opinion)

"Nice IDE"? I find it terrible.

@EugeneSh.yeah well for beginners, it could be. Since they don't have to configure complicated options and all that.

I agree with @EugeneSh., and even as a beginner I despised it. I quickly moved on to PIC and MPLab, and since have done work in Atmel Studio on AVRs and so on. MUCH better! Gives you a lot more freedom and more tools to work with


text:
Burning the Arduino bootloader without an extra Arduino board
Is there any way to burn the Arduino bootloader on a standalone Atmega328 (internal clock 8MHz) from the Arduino official website without using an extra Arduino board to burn the bootloader?
I mean, is it possible to burn the bootloader on the Arduino and then remove the ATmega chip from the Arduino board and use it in a breadboard?
Thanks.

If you don't want to go the route of a dedicated programmer, you could try ArduinoISP where you can program an Arduino board (with a Mega on it) to be a programmer for another AVR device (e.g. another Mega). The instructions can be found at https://www.arduino.cc/en/Tutorial/ArduinoISP and allows you to do something like this:

Yes, use an ISP programmer. I personally use Atmel ICE, Arduinos as ISP and USBasp.
AVRISP is another popular option:

This tutorial might be useful: Sparkfun.

so it's not possible to burn the bootloader on the ATMega using the arduino board itself (conectet to the pc via USB) and then remove the MCU and use it standalone?

Not using the board itself. (It could be possible if you modified the USB>Serial Atmega to become some sort of USBtinyISP, cut and rewired a bunch of stuff, but it wouldn't be practical at all and you'd still need a programmer to reprogram it anyway). So you need a programmer at some point.


text:
Buffering output stream
I'm looking to toggle a pin on and off in a fast and timing-sensitive manner, and I'm wondering if the Arduino Uno has any built in "buffers" that would be able to hold a set of values and send them sequentially to the output pin at high speed, separately from the rest of the loop. I could then refill the buffer with the next set to be outputted, and so on.
Is this even possible? If anyone has any documentation on what's involved, I'd really appreciate some links (or tips!) :) thanks

The closest thing to what you describe is DMA (Direct Memory Access). The Arduino doesn't have DMA. More powerful microcontrollers often do, but not little 8 bit ones.
The closest you could do is to use a timer interrupt to run a small function periodically which reads the next value from an array and sets the pin to that state.
The TimerOne or TimerThree libraries can be of help to you here.

For most Arduino devices, using the USART in SPI mode is about the most effective way to generate a hardware-timed stream of bits out of one pin.  For background, see §21, “USART in SPI Mode”, in the ATmega328 data sheet.  For some example code and exposition, see ATmega Arduino USART in SPI Master Mode MSPIM,
Posted on February 17, 2015 by feilipu.
Ordinary SPI output on most Arduinos is single-buffered, hence subject to occasional delay if other interrupts get in the way of the SPIF-SPIE-SPDR interrupt handler.  However, the USART-in-SPI-mode method double-buffers output as well as input, allowing continuous data output.  That is, one can generate a continuous stream of bits clocked out at whatever rate one selects.
The Arduino Due is based on the Atmel SAM3X8E ARM Cortex-M3 CPU, a 32-bit ARM core microcontroller.  It supports DMA (direct memory access) and one can find webpages, eg arduino.cc topic 219291, describing waveform generation using DMA and the 12-bit DAC (digital to analog converter) on the Due.  More notably, the Arduino software compatible Teensy 3 series uses Cortex-M4 and M4F chips on boards running at 48, 72, 120, and 180 MHz, probably more suitable for elaborate waveform generation than are the Due or Zero.