text:
can this piece of a camera flash send an input signal to my arduino?
I have a piece of a broken camera flash (an old Yongnuo one) that has a single pin that tells the flash when to fire. The pin looks like this :
(I guess the ring is the return/ground?)
The other side of the piece looks like this:

If my guess isn't completely wrong, those four wires are the only thing that tell the rest of the flash unit what's going on, when. So if I plugged (two, three, all four?) of those pins into my arduino I could use it as an input, yes?
I.e. Arduino would detect when the camera has taken a picture via this unit, and do something else (in my case open the gate on a mos for a length of time). No actual camera flash involved (just the signal)
My question is: how do I determine which of these four wires carry the signal to the rest of the circuit, and can I plug this into my Arduino input pin? My multimeter is a cheap crappy one so I don't think it would react fast enough to measure a pulse like that...

First you need to determine how the flash works.  Does the camera send a pulse, or does it connect the pin to ground.  Try switching the flash on, then when it's charged, use a wire to connect the pin to the ring. If it flashes then you have the equivalent of an active low digital input.  You'd need to then know the voltage levels and maybe even isolate the whole flash unit form the Arduino. It's quite a broad question with lots of unknowns at the moment.

huh, i just tested it with one of my working flashes (similar model, and it is a yongnuo one) - and yes the flash (sans camera) is triggered by simply connecting the pin to the ring. So how do i figure out the voltage level? would my cheapo multimeter help at all? Thanks for your help so far, I had no idea that was how the flash triggered!

So let me get this clear - you want to have the flash attached to the camera, and add a feed off the flash to indicate to the Arduino when a photograph (using the flash) has been taken?  Or do you want the Arduino to make the flash trigger intendant of the camera?

nope sorry I wasn't clear. The flash that I took pictures of above is broken, it won't even turn on. I took it apart and gave up when I saw all the microscopic solder spots that I cannot fix by hand. So it stayed in pieces until now.
I now have another project which is a camera slider for timelapses - the camera sits on top of a wooden dolly which is pulled along a track by a bbq rotisserie motor. The rotisserie motor is currently too fast, pulling the dolly along the track in only 10 mins or so, and I need it to be a good few hours, so I need to find a way to slow it down... (cont)

Ok, so you want the Arduino to react when the camera would have fired the (non-existant) flash?  The pin in the middle of the camera's mounting will most probably be the drain of a MOSFET which is turned on (connecting it to ground) when the camera triggers.  Check the voltage (on the camera) between the centre pin and the ring while it's just idle.  If there is no voltage showing then that is most likely a safe assumption.  You can then just connect the ring to the Arduino's ground and the pin to an input pin.  Turn on INPUT_PULLUP and you should be able to read the state. You might want to

... use one of the interrupt pins so you can react fast enough.  If there is a voltage showing between the two pins and it's not 5V then you will have to build some kind of interfacing system to the Arduino, and that depends on what the voltage is.

(cont.) I tried strings and pulleys etc, but they weren't reliable enough. I figure if arduino can detect when the camera fires, then it can turn the rotisserie motor on for a few seconds, before shutting it off again. So I need a way of detecting when the camera takes a picture. I know from previous experience that my camera always fires the flash hotshoe at the end of an exposure (called "rear curtain sync") and I pulled out my box of broken flash bits and found the photographed piece.  make sense?

You've been a huge help Majenko - thanks so much!

I'd just connect the two green wires to the arduino and remove the entire circuit board. That is, if the camera just "shorts" those two contacts to signal a flash-request. However this connection could also be used to detect if a flash is present, so the camera can disable the internal flash. In that case my solution won't work.


text:
Using an Arduino as a electrical mains switch
How do I make an electrical switch using Arduino, that when it receives signal (wirelessly or through a LAN port) to switch off it disconnects the switch and then again told to turn on turns the switch on?
The main problem I am facing is that I need to give a 5V output to turn off the transmission between two wires having voltage rating of 230V.

Google the phrase "Arduino Relay"

Relays are the only solution which you are looking for.!

You need two shields: a Network (i.e. Ethernet/Wi-Fi/GSM/3G) shield, and (as already mentioned); a Relay shield. Plus, some code to glue the two together. See Ethernet Switching - with Arduino for an example of how to do it.

Depending on the nature of your load and how you need to switch it, the type of electronically controlled switching device you should use will vary.  A cheap mechanical relay module can indeed be a simple solution for low-current devices switched at a no more than moderate rate, but if you have something high current like a heating element, inductive like a large motor, or need to do duty-cycle based control, you will need a different sort of switching element, perhaps TRIAC-based, but likely requiring a fair amount of surrounding circuitry for safety and longevity.

You need to use Relays.  There all kind of relays.
Regular and Solid state ... for controlling a Regular Relay using Arduino you will need a transistor (so you will able to provide the right current to the relay to close a circle)
There are a lot of guides for Arduino and Relays (for example)

As pointed out in the comments, I would need to use something known as a relay with my Arduino.

source: Stack Exchange

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

sort: votes


text:
Write to EEPROM during power down
I am making a counting device, and I would like to be ensure that the count is not lost if the power is lost.
As I need to count to many millions I cannot use EEPROM writes as I will trash the nvm after ripping through the 100,000 max write cycles. I also need to ensure the count is accurate, so can't update 'every-so-often' either.
I want to write to EEPROM when the Arduino detects power down. I am reading on an Analogue input pin and am then planning on using a capacitor to hold the power on to complete the write. I have this set up but am having issues testing as I have found that when Ground is connected to GND pins and then when 5v is supplied to any I/O pin the device powers up. I have now tested a Nano and Uno and have found the same thing on both.
I have looked through the arduino site and tried looking for forums where this has been discussed, but to no avail.
Is this damaging to the Arduino if powered in this way? Does this pass the sanity check as a way of achieving my main objective of not loosing the count on power down?
thanks in advance :)

The name for it is "parasitic power" - it is a well-known phenomenon.

when 5v is supplied to any I/O pin the device powers up - why is this an issue anyway? How does this apply if the power is lost?

I wasn't sure if this was even an issue or not! I just wasn't expecting this to happen and wanted to know if I would damage the device. Thanks for your help

A more sophisticated version of @MikaelPatel's techique is not to store the individual counts, but to store a derivative:

Reserve a block of storage with (say) 8 counters. Each counter has as many bits as necessary to store the largest value - but see below for what "largest" means.
Each time the count goes up, write into the next counter along (modulo the number of counters).
But don't write the value of the counter, write the value divided by the number of counters - counter/8.
Here's the trick: while that looks like you're losing precision, you're not - because the counter location is information too! In fact you're gaining size.

It's best shown with an example. For ease, I'll assume an 8-bit counter, and only 8 counters:
0000: 03 03 03 03 03 02 02 02

Assuming that everything started at 00, that means that it took 8 counts for them all to get to 01, a further 8 counts for them all to get to 02, and only 5 counts to get the first 5 to 03. That's a total of 8+8+5 or 21.
At boot time, look for where the number sequence goes down. That's your current buffer position for future updates, plus the information for the current value:
CurrentCount = [Smaller number] * [Number counters] + [Number of larger];

Once you've worked it out, keep the current value for incrementing, and the buffer pointer for where to store the next count.
Advantages:
A. You write as often as you would storing a counter - but in different locations, spreading the load.
B. Each location (8, 16 or 32 bits) can store a certain maximum - but the total maximum is a factor of Number of Counters larger than that!
Odometer manufacturers use this exact technique to store the current mileage in digital dashboards - they have a legal requirement to maintain the correct number. They only use 16-bit counters (which would overflow after 65,535 miles), but then they use 16 counters, for a total mileage maximum of over a million. Each location only gets written every 16 miles, and they don't need to use 32-bit locations.

I would suggest powering it from the 12V input and monitor the 12V with a power supply monitoring chip or circuit which will send an interrupt to your system when the voltage drops to whatever voltage you design it for. This can be accomplished with a few resistors and a comparator.
Your hold up time will be controlled by the amount of capacitance on the 12V side.  When the interrupt is tripped write the value to EEPROM and then shut down.
The analog input is a good sounding idea but there is a lot of latency between the time the voltage starts to fail and is detected.  The hardware interrupt will be much faster giving you more time to save your counter and the additional capacitance on the 12V side will give you a lot more time then back feeding through the GPIO pins..

A typical method of increasing the number of writes to EEPROM is to use a vector of counters instead of a single value. The counter value is written to the EEPROM vector in a cyclic fashion.
On startup the vector is searched for current counter value, i.e. the highest counter in the vector. The write index is restored by locating the lowest counter value.
The number of writes is increased with the length of the vector.
Please read more about this method here.

The arduino chips have clamping diodes on all the GPIO pins. So if the voltage on one of the pins is above Vcc (which is 0v is there is no power applied to the chip), the internal diode will 'redirect' this voltage to the Vcc line. This will damage the chip, is too much current is going through the clamping diodes.
Instead, connect the 5v signal via a large resistor (e.g. 100k) to the input pin.
Using a capacitor (plus diode to prevent backfeeding) will work. You just have to be careful if you have connected anything to an output pin that uses current. An led running at 20mA will drain a charged capacitor pretty quickly.
What I've done in the past is use the entire EEPROM space to store a single value. Just write every next value to a higher address. On powerup read the entire EEPROM till you find two adjacent address that don't contain successive numbers. Then you know where the last written value was, and you can read this last value, and continue writing the the address right after that one.

As you have mentioned, the caps are draining quickly. They need to need to be too big for the space I have available. I am now going to work on using the EEPROM in blocks. Thanks for you help

Connect all external stuff, that uses power, via transistors. Also make sure signal outputs have resistors on them, as some ICs have clamping diodes, which would result in the external IC being power though the signal pin on the atmega if power is disconnected. Also make sure you have low voltage caps. The lower the maximum voltage the small a cap can be. Also you can parallel to smaller caps together to get double the capacity. I wouldn't dismiss the original idea too soon. But without some wiring diagram I can help you beyond the above hints.

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


text:
USB 1.1 Low Speed project for Arduino UNO/ATmega328P to learn USB protocol
Arduino UNO is 5V, 16 MHz.
USB 1.1 Low Speed spec operate:

at 5V level - so we avoid to maintain voltage level
at 1.5 Mb/s - so we have 16/1.5 ~= 10 instructions per elementary protocol signal

Is it possible to make Arduino as slave USB device from UART lines connected to USB D+/D- interface with careful timing and assembler programming?
I doesn't familiar with ATmega328P pin I/O capabilities, may be them can't operate at 1.5 MHz so project isn't possible?
UPDATE I found V-USB library that:
implementation of a low-speed USB device for Atmel’s AVR® microcontrollers,
making it possible to build USB hardware with almost any AVR® microcontroller,
not requiring any additional chip.

Still dig into docs to realize possibilities.

The V-USB library is certainly a way of making a Uno act as a low-speed USB device.

Not exactly the answer to your question, but have you tried the typical way to emulate slave devices with Arduino UNO?
It uses the 2nd ATMega present onboard (this applies only to UNO, afaik) and lets you use the main ATMega for other tasks, delegating the USB protocol to the smaller ATMega16.
Do you have any specific reason why you would use the serial lines?

From pointed post: LUFA is an “open source complete USB stack for USB-enabled Atmel Microcontrollers”. I don't fully deep into LUFA docs but pictures show that GPIO pins from microcontroller doesn't directly connected to USB bus and I think that project offloads electrical/protocol USB stuff to corresponding UNO board schematic which does that natively.

specific reason is educational, home DIY.

I have used extensively LUFA on the ATMega16 that is on the Arduino UNO and I can tell you that it does exactly what I said: the ATMega16 acts as USB gadget device. Are you sure that you are not confusing it with the main AVR chip, the ATMega328P? On Arduino UNO R3 there are 2 AVRs. I'm referring to the secondary.

If you look at the schematics, you'll see that the TX & RX lines do not only go to the pin header, they also go to the other AVR, which acts as serial to USB adapter.

With "specific reason" I meant: why do you want to emulate the USB protocol on the ATMega328P when everyone else does it on the ATMega16? From programming perspective, it's identical: they both are AVR, but you have the additional benefit of saving the 328p for implementing some custom functionality.


text:
Linking Arduino With Twitter
My project is having Arduino with my WiFi shield connect to Twitter and look for any messages that other users have tweeted at me that contain a certain color, (I.E. @myTwitterHandle I want red) and then changes an RGB LED to become that color.
I have been searching online for different methods, and found a few different solutions which I could use as a starting point. However, these apparently call to an old Twitter API that is not supported anymore (support stopped mid 2013).
One solution I came across was to use node-red as well as MQTT.  I am not too familiar with these programs.
Does anyone know how to have Arduino parse a twitter account for mentions containing certain strings and have it print to LED? Any help with be appreciated

The new Twitter 1.1 API requires OAuth authorization over SSL, for which Arduino is under-powered.
You will need to write a proxy application, which would parse the tweets and then send a RGB color value to your Arduino.
You should split your project into three parts.

Retrieving tweets with the Twitter API.
You can get some library to do it for you.
Communicating with your Arduino.
Just try to send an arbitrary color to your Arduino over internet.
And finally joining first two pieces of code together.

And if you get stuck somewhere, you can always ask for help here on StackExchenge.


text:
Querying streaming sensor data on the Arduino board
I am new to Arduino and this forum, so please forgive me if I am asking something really trivial and stupid.
I have an Arduino board which collects sensor readings from an MPU6050 sensor (acceleration+gyroscope). The next step for me would be to process these data directly on the board. I want to somehow store N last sensor values and then query this set (collection, vector, array, whatever you call it) to fetch certain values. This set will be constantly updated with new values, whereas older values will be pushed out, so that only the most up-to-date values are stored in the set. For example, I want to know if the acceleration exceeded 10 m/s in the last minute.
In the literature this kind of set with most recent values is sometimes called window - this approach allows limiting an unbounded sequence of constantly generated tuples to a bounded bag and then apply traditional SQL-like query operators. For example, Oracle has come with CQL - an engine and a query language for handling streaming data.
Before I start implementing this, I am wondering if there is a similar (and, of course, much simpler) library for Arduino? If not, which data structure should I use to implement such functionality?
Also, my intention is to query not just individual values, but certain patterns and sequences - e.g., I want to know if the acceleration first decreased and then increased again (something similar to the WHERE condition of an SQL query). Does it look realistic to implement with Arduino?

A circular buffer sounds like what you want. The library mentioned by Majenko sounds like it implements that.

It sounds like you are after my Average library:

https://github.com/MajenkoLibraries/Average

It allows you to store a rolling set of data where you get to "push" values into it and the oldest one drops off the end. (It's implemented internally using a circular buffer).
You can then do various forms of analysis on the data - get the mean average, the mode average, calculate the standard deviation, find the maximum and minimum values of the set, and even access individual entries within the set.
It's a fully templated library, so you can use it with any numerical data type (float, double, int, long, etc).

Thanks for your reply!
A few more questions. Given that I am running your code on Arduino Yun, am I right that the maximum number of elements I can store in the rolling set is limited to 2.5k (which is the size of RAM of ATmega32u4, where variables are stored)?
Also, are you still working on your library? Any plans to further extend it with features I mentioned at the bottom of my previous post (e.g. querying sequences and patterns)?
Thanks!

The number of variables depends on the type of variable and how much space each entry takes up. I am always open to suggestions for enhancements to my libraries.

I presume you can always query the current contents of the window at any time. Thus a simple set of tests would let you conduct any custom queries you want.

Yep.  The .get(n) method lets you access any raw entry in the circular buffer you like.  There's also a Least Squares function, and one that uses that function to predict the value at some finite point in the future.  I use it to control the heaters in my reflow oven to prevent overshoot.

Thank you both for your comments and suggestions! I'll give it a try.


text:
Serial.readString() - how does it work exactly?
Someone posted a solution for a problem I had which used Serial.read() .Why doesn't readString() seem to work though? From the docs it seems it reads the data as a String object which would make things a bit cleaner.
But here's my Python code:
import serial

arduinoSerialData = serial.Serial('com7', 9600, timeout=0)

while True:
    arduinoSerialData.write('ALIVE\r\n')

And Arduino code:
void setup() {
  Serial.begin(9600);

  pinMode(13, OUTPUT);

}

void loop() {
    if (Serial.readString() == "ALIVE") {
        digitalWrite(13, HIGH);
    } else {
        digitalWrite(13, LOW);
    }
}

If this was right, the green LED on the Arduino would light up when the Python program would run, but it doesn't. What is Serial.readString() expecting that it doesn't get?
I even tried if (Serial.readString().startsWith("ALIVE")) instead, as well as arduinoSerialData.flush() before arduinoSerialData.write()

All of your five questions so far seem to be about your issue with Python, and detecting if your USB connection is alive. They are just variations on a theme. Does reading work? Does writing work? Are there separate transmit and receive buffers? How does readString work? For example: Pyserial serial.write() doesn't work. I suggest you stick to one thread and work through your issues with the help of people who are genuinely trying to help you.

Nick, I'll suggest you "unstick" from me and get over the fact that I cross-posted before. Here's what happened: I had an issue and didn't know what was causing it, by experimenting for hours I wrongly deduced that the issue was reading and writing not working together properly, while it turns out it was me not understanding how readString() works. I have an eureka moment that the problem could be how readString() worked instead, and by asking it turned out to be the case. Answer below genuinely helped me. Monitoring my activity and bugging me continuously didn't, nor it seems ethical. Thanks.

BTW, these are separate questions (this one and the previous one). This is a Q&A site, as far as I know it's suggested to stick to one question per topic. Sticking to one thread per issue might be a good idea for forums.

I am not monitoring your activity. New questions are automatically shown to me (as to every visitor to the site). However if you prefer I do not respond to any future questions of yours I can certainly do that. It is hardly unethical to respond to further questions, and indeed the site encourages moderation by its users. Moderation being detecting cross-posts, poor quality posts, that sort of thing. However I am sure that others can achieve that if I do not.

I thought you understood what I meant... I think you noticed that I accepted one of your answers to one of the questions. Answers are welcome, criticizing me for making similar posts over and over again isn't very nice. I cross posted one of the questions, and you haven't gotten over it. Someone else even pointed out that one of my latest questions was different to another one you claimed to be the same, again.  I personally have nothing against cross posting, some people only visit Stack, some only visit the forums, but if it's against the rules, okay, I won't do it. And I'm not, anymore...

readString() will read characters from the serial (or other Stream) device until a timeout occurs.  That timeout is, by default, 1 second.  It is only appropriate to use readString() if your data is arriving in chunks with a minimum time between each chunk.
It is more appropriate to use readStringUntil() which will read characters from the serial device until either it times out, or it receives a certain character.  It is most common to use either the line feed (\n) or carriage return (\r) characters as the end of string marker.  You must, of course, ensure that your sending program sends the string terminated in the right way.
However, that all said, you really should avoid using String objects when possible, since the constant creation and destruction of temporary objects all over the place can make a real mess of your heap.
It is far better to learn to use character arrays and fill them using Serial.read().  A tutorial I wrote for that is here:

http://hacking.majenko.co.uk/reading-serial-on-the-arduino

Thank you. It's about time I also learned what the timeout is. Is there some quetion/answer about that here already? The Pyserial docs don't seem to mention that. Don't know what "heap" is either.

The timeout is a function of the arduino's reading, not the PySerial's transmitting.  The heap is an area of memory in the Arduino that is used to dynamically allocate space for variables.

Thanks. So timeout is the delay between all the Serial.read() functions in the Arduino code? Sorry, just don't want to start a topic for something small like this.

@LeoErvin The timeout is how long readString waits to receive a character on the serial port before it decides that there are no more to receive. If more than 1 second passes without it having received a character then it finishes reading and returns whatever it has managed to get up until then.  It does mean that there will be at least a 1 second delay in your program while it waits for characters to arrive.

@LeoErvin If you send one character every 900ms then it will never finish, because it never reaches 1 second while waiting for the next character.  If you send 30 characters together, then don't send anything for more than one second, then readString() will wait for 1 second after the last character has been received and then return those 30 characters as a string.

Got it, thanks. It seems if I have a newline I also don't need to flush() from Python for some reason.

@LeoErvin It is called a blocking function, because it blocks the operation of the Arduino until it is finished. You can't do anything else for the entire time it's waiting for those characters to come in.  Far from desirable.

But it seems if I set timeout to 0 (which is probably pointless here), then do readStringUntil('\n'), it works fine. Then again I'm only sending few characters.

@LeoErvin Not perfect.  If there is a slight delay between characters in your string then it will chop the string off at that point and return the first half, since it timed out, and then it will return the second half as a new string when it gets the terminator.  Better to use a non-blocking stateful system like in the link in the answer that will signal when it has got a full line for you to process, and otherwise just return and allow you to continue.l

Hm, why will it chop if there is no timeout?

@LeoErvin There is a timeout - 0ms.  It runs the read portion while the elapsed time is less than the timeout, so the elapsed time will never be less than 0ms since time doesn't run backwards, so it's an instant timeout if there is no character in the receive buffer for it. You're confusing "0ms timeout" with "infinite timeout". The two are complete opposite ends of the spectrum.

Doesn't that mean readStringUntil() should never read anything if timeout is set to 0?

@LeoErvin No, because it first attempts a read, and only if that failed does it check the timout.  Take a look in the file Stream.cpp in the Arduino core for the int Stream::timedRead() function to see how it works.

Well, I don't know C++ (only basic stuff to be able to code Arduino), but thanks for explaining. By attempting a read I suppose you mean reading one character, right?

Yep, that's right.

Okay, thanks for the answer plus the explanations in the commments :)


text:
Is the Serial buffer going from Arduino to PC and from PC to Arduino different?
I'm both sending and receiving strings to Arduino from my Python program on the PC and the opposite. I don't check by code if one is finished before doing the other. Are they seprate buffers, or is it just pure luck my program has been running fine until now and each program has been reading the right string ?

Yes there are separate buffers for Tx and Rx.

There shall be separate buffers for Tx and Rx (in Arduino Serial library). The actual buffer size may vary, but shall be around 8-16 bytes and there is also hardware buffer in MCU. Please try to increase serial baudrate, if possible.
UPD: In HardwareSerial.h:
#if (RAMEND < 1000)
#define SERIAL_TX_BUFFER_SIZE 16
#else
#define SERIAL_TX_BUFFER_SIZE 64
#endif

....

unsigned char _rx_buffer[SERIAL_RX_BUFFER_SIZE];
unsigned char _tx_buffer[SERIAL_TX_BUFFER_SIZE];

It seems for Atmega328 the buffers are 16 bytes each
UPD: As Nick pointed, for Atmega328:
#define RAMEND       0x8FF     /* Last On-Chip SRAM Location */

So the buffers are 64 byte each.

What is Tx and Rx mean?  Also, who downvoted the answer? If it is incorrect or unrelated, please comment what the issue is.

It was probably downvoted for factual inaccuracy. The Atmega328 has 2048 bytes of RAM and therefore the buffer will be 64 bytes, not 16. Tx is shorthand for Transmit and Rx is shorthand for Receive. Why? Historical reasons probably.

Well knowing they are separate is all I needed to know. I was worried that writing to Serial then reading could result in reading (a part of) what I had written to it. That would cause some issues. However, this might not only depend on the buffer...

BTW, you don't plainly downvote for inaccurate number, you point it out as comment and/or edit the post. That was just plain rude.


text:
Is it difficult to do high voltage parallel programming using Nick Gammon library?
I have bricked a few AT328P by invalid fuse settings.
Has anybody used the above sketches and the associated circuitry to perform high voltage programming?

above sketches? these?

I've used them, they seem to work fine, otherwise I wouldn't have posted them. What invalid fuse settings anyway? If you changed the clock you can supply an external clock and fix them up. See bootloader uploader - the part about an alternate clock source.

to be honest, I do not recall what I set the fuses to,  but since then, I can upload sketches to the chip, but it will not run the program.

I have placed the chip in an arduino uno  bored, but it still does not run.  I haven't tried a lower frequency Crystal, could this work?

Also,   in the reset circuit,   Does the  RC capacitor and  The emitter   Of  Q1  both connect to ground?

Can you clarify how "I can upload sketches to the chip" and "I have bricked a few AT328P by invalid fuse settings" work together? If it is bricked, you cannot upload sketches to it.

I suggest you run my signature detector sketch using another Arduino, to see if the first one is really bricked, and what the fuse settings are. If you can find out the settings please edit your question and post them.

Many thanks for your response. I've managed to sort it out, I used http://denki.world3.net/avr_rescue.html to set the fuse back to factory default and now your programmer software recognises it once again, yeepi. However, I am still interested in getting your High-Voltage solution working as it provides cleaner wiring. The only bit I don't fully understand in your reset circuit is does one end of C2 and emitter both go to GND?

I have not tried with those instructions, as I have an AVRDragon, but it's a good exercise for precision, since you have to wire lots of pins.
20+ iirc
My guess is that if anything fails, it's likely to be because of a mistake in the wiring.
If you are planning to do it often, you might consider soldering the wires and the ZIF socket to a prototype board, to preserve your mental sanity.

+1 for assuming the OP has some mental sanity in the first place.

Igor Stoppa insomnia


text:
Arduino circuit diagram help
I'm new to the arduino and to EE in general. I've built the basic examples and a, now trying to get a deeper understanding of what the physics is doing. As such, I'd like some help in understanding the diagram here:
https://www.arduino.cc/en/Tutorial/Blink
Question 1:
Specifically,it seems that the flow is going from Pin 13 to Ground. Is the diagram using the conventional flow or the electron flow approach.
Specifically, is it the electrons flowing from Pin 13 to ground or does the diagram show protons flowing? It seems that its showing the electron flow as the diagram has the anode attached to the resistor so the electrons flow from the pin to the resistor to the positive end (anode) of the LED.
Question 2:
This is about bread boards, like one shown here:
https://www.google.com/search?q=arduino+breadboard&biw=1696&bih=988&tbm=isch&tbo=u&source=univ&sa=X&ved=0CFEQsARqFQoTCIjsw5WhkMgCFdWYiAodttcKIw#tbm=isch&q=breadboard&imgrc=KwnTrtjnYJdB1M%3A
1) Would I connect Pin 13 (or say the 5V pin) to the + (the red line). Then I would connect the blue line (the -) to the ground on the arduino? Do I need to connect the blue line?
2) Also, is it again the electron flow notation so that from Pin 13, the electrons flow to the + (red), then to one of the lettered columns and then to whatever component I have?
Thank you for your help! I realize these are basic questions but I want to go a little beyond building the examples and start trying things out myself. As such I want to make sure I'm getting the theory behind it right!

This is not really about Arduino, it is about electronics theory. You might get a more extensive explanation of things like which way electrons flow from  the Electronics Engineering Stack Exchange.

The thing to remember about electrons is they are a negative charge.  That means that the direction of current flow (positive charge) is opposite to the direction of flow of the actual electrons (negative charge). Picture it like those "compression jams" you get on the motorway (freeway) where cars that are travelling too close together have to slam their breaks on to avoid running into each other.  The one at the front slams its breaks on briefly then carries on. The one behind has to do the same, and so on and so forth.  You then get a wave effect travelling in the opposite direction to the direction of travel of cars as they slam their breaks on in turn.  The cars are moving forwards, but the compression jam is moving backwards.  Similar in a circuit - the electrons are moving forward, but the charge is moving backwards.
Another way to visualize it is as a bubble in a pipe of stationary water.  The bubble moves in one direction, but in order for it to do that the water has to flow past the bubble in the opposite direction.*
So the current flows out of pin 13 through the LED and to ground, but the electrons themselves are actually flowing from ground through the LED and in to pin 13 (where they eventually return back to ground through the power supply).
For how the IO pin works it's best to picture it as a pair of switches - one connected to Vcc and one connected to GND.  For instance, this is the LED wired up with the IO pin set to HIGH:

You can see that S1, being on, forms a circuit between the battery and the LED to allow the current to flow.
When the IO pin is set to LOW the circuit looks a bit like this:

You see that S1 is now turned off, and S2 is turned on.  the connection from that battery is now broken, and current can't flow.
But, you ask, what is the point of S2 here? It doesn't actually do anything.  No, not in that circuit it doesn't. But consider if you re-arrange the circuit to be like this:

Now it's S2 that is controlling the connection to the battery.  S1 is now the redundant switch.
This leads to some terminology.
When S1 is closed the IO pin is said to source current since it is pretty much connected directly to the positive power source.
When S2 is closed instead the IO pin is said to sink current since it is connected to ground, so current can "sink" down to ground through it.
As far as breadboards are concerned - they are just collections of metal strips that are used to join wires and component leads together in whatever way you need to.  There is no one part of it that is any different to any other, and there is nothing that says you must use this bit in a certain way, or that bit in another way.
Your typical breadboard has sprung metal clips that are arranged in this pattern:

You can use any collection of holes for any purpose you choose.
That said, normally the blue (or black) marked line of holes down each side is used for ground, and the red line of holes is used for power.  As both sides of the board are separate it is possible to use different voltages on each side, or the same voltage on both sides, etc.  That can be especially useful when you're working on a circuit that has, say, +3.3V and +5V in it.  Another common split usage is for a positive voltage on one side and a negative voltage on the other - common when working with op-amps.  Just remember which is which.

* This is a complete lie, but it's as close as you need to know at this point in your education. https://en.wikipedia.org/wiki/Lie-to-children

So if the electrons leave ground, then from the first diagram, the thing they hit is the LED before it hits the resistor. Is that not a problem in that too much voltage is going through the LED? I understand it's a series circuit, but to be safe, wouldn't it make more sense to have it before the LED?

@user1357015 No, because the LED and resistor are in series. At all points in the circuit the current is equal. It's only the voltage that changes at different points in the circuit.

@user1357015 Theory to learn: https://en.wikipedia.org/wiki/Kirchhoff%27s_circuit_laws#Kirchhoff.27s_current_law_.28KCL.29

But what would actually burn out the LED? The voltage or the Current? I'm a little confused why it can't be either. If there's too much force (voltage) it breaks (similar to how a water wheel would break if spun to fast)? If there are too many coulombs/sec (current) it breaks as well? Or are you saying that since I = V/R, that since the resistor is there, regardless of how the voltage drops, the current through the circuit is always the same?

The LED will blow if too much current flows through it. That is the only reason it will blow. It is what is called a non-linear device in that it doesn't (directly) obey Ohm's Law.  it has a fixed voltage drop (Vf) which is used in conjunction with the resistor and Ohm's law (applied to the resistor) to limit the amount of current that is able to flow.  Think of the current as the chain on a bicycle. You can't have more chain in one place than in another. Apply the brakes to the bike wheel (resistor) and the whole chain movement is slowed.

@user1357015 In its crudest form an LED has a fixed voltage drop (say 2V) and zero resistance.  Connect that to a voltage source with no limit on current and Ohm's law says I=V/R.  Since R = 0, no matter what V is (except 0), the answer is infinity. That's infinity amps.  So you put the resistor in to make Ohm's law work. But the resistor only sees a part of the overall voltage because the LED has stolen some. So you have I=(V-Vf)/R.

Ah, I get it. The LED uses some of the potential energy in the voltage to light itself. Then there's (V-Vf) left. However, the energy is 'carried' by the current (by the energetic Coulombs/Second). Too much current means to much energy delivered to the LED & it blows. Enough current, means there's enough energy delivered that it can safely convert the potential energy of the current to the light energy that we see. Is that about right?

Regarding current flow -- I've read about about the notation set by Franklin. So in your analogy, I can think of as the negative current flows from the ground to the LED 13. However, as that happens, the ground becomes more positive "albeit imperceptibly from an observer on the ground*. Thus, that's the same thing as thinking as the positive flow (current) goes from the pin to the ground. Although this doesn't actually happen (as it's the electrons) that are moving, logically, either one can be considered the same?

@user1357015 That's about it, yep! The resistor is the device that throttles the coulombs/second for you, which stops the LED from getting too much.  In actual fact the LED blowing is all about heat. Too much current = too much heat produced = bits inside melt.

@user1357015 Unless you're working with quantum physics there's no real benefit to knowing what the electrons are doing. All you need concern yourself with is the current flow. Leave the electrons to the likes of Hawking.

@user1357015 Also the slight change in charge of the ground is instantly nullified by electrons flowing from the negative terminal of the battery (or whatever your power source is). Like I said - bike chain. The whole lot moves together, and the battery is the pedals.

would you mind adding in your circuit diagram where the vcc and ground are?

They are implicit in the orientation of the battery.

In the Arduino world we work with positive voltages so therefore the + side of the battery is Vcc and the - side is ground. There are devices that work the other way around (negative voltage regulators spring to mind) but in general you can expect that Vcc is more positive than ground when working with digital electronics.

And ground itself is just any arbitrary point of the circuit you choose to measure voltages relative to. For convenience it's most often the most negative point of the circuit.

It doesn't matter whether you use conventional current or electron current to describe a circuit; in the end they give the same results.
Protons are not a charge carrier in 99.99999% of circuits; positive charge carriers are the quasiparticles known as holes, but they only flow in semiconductors.
The power rails on a breadboard should be used for power only, never signals. It is possible to use them for other things, and it is possible to not use them at all, but when they are used they should only be used for supply in order to cause the least confusion.

Protons don't flow. They are part of the atom nucleus. If they flowed the copper wire would be flowing. Electrons are what flow, particularly if there are some free ones hanging around, like teenagers hanging around a mall.
You don't need to worry about that however. Most people think of current as flowing from positive to negative (ie. pin 13 to ground) even if in fact the electrons are flowing from ground to pin 13.
See Conventional Versus Electron Flow. I quote:

When Benjamin Franklin made his conjecture regarding the direction of charge flow (from the smooth wax to the rough wool), he set a precedent for electrical notation that exists to this day, despite the fact that we know electrons are the constituent units of charge, and that they are displaced from the wool to the wax—not from the wax to the wool—when those two substances are rubbed together. This is why electrons are said to have a negative charge: because Franklin assumed electric charge moved in the opposite direction that it actually does, and so objects he called “negative” (representing a deficiency of charge) actually have a surplus of electrons.
By the time the true direction of electron flow was discovered, the nomenclature of “positive” and “negative” had already been so well established in the scientific community that no effort was made to change it, although calling electrons “positive” would make more sense in referring to “excess” charge. You see, the terms “positive” and “negative” are human inventions, and as such have no absolute meaning beyond our own conventions of language and scientific description. Franklin could have just as easily referred to a surplus of charge as “black” and a deficiency as “white,” in which case scientists would speak of electrons having a “white” charge (assuming the same incorrect conjecture of charge position between wax and wool).

Quote courtesy of Design Science under this license.

Would I connect Pin 13 (or say the 5V pin) to the + (the red line). Then I would connect the blue line (the -) to the ground on the arduino? Do I need to connect the blue line?

When using a breadboard I connect the 5V pin to the red line, the Gnd pin to the blue line, and other things (signals) to the internal (numbered) holes. The internal ones are connected cross-ways, so that is useful, for example, to put a series resistor for the LED there.
I trust you are using a resistor for the LED, if not you might damage both the LED and the Arduino. See The care and feeding of LEDs.

I am using a resistor yes. Right, so if I have the 13 signal connected to a lettered whole, does that not mean that the arduino is feeding electrons from the 13 pin TO the resistor, the resistor then feeds the electrons TO the LED and the LED then feeds the electrons to the Ground? Specifically, it is the Electrons leaving pin 13 yes? That is why the anode is connected next to pin 13 -- electrons flow to the positive end of the diode?

No, the electrons leave ground and head towards the positive side (pin 13). You don't really need to worry about which way the electrons move. In what way will that change what you are doing? I personally think of current leaving pin 13, going through the resistor, then the LED and then to ground. Strictly speaking though, the electrons are going the opposite way.


text:
atmega16 in Arduino Board
I had a very common question. Why a additional MEGA used in most of the Arduino Boards. Arduino board Mega2560 also have a MEGA16U2 controller on board which i think is used for programming via USB. Is there any other specific usage of atmega16 on arduino board.
Thanks

It's an ATmegaU2, which has USB hardware and handles the USB communication. It passes the hex file on to the bootloader in the main microcontroller. That is its only job.

as i can see its ATMEGA16U2. It handle USB communication means it simply convert a USB to serial?

That's what I said, in a different way.


text:
I2C Master send reset command to the slave counter
My name is Gianni, I live in Olbia Sardinia Italy and I have some experience in electronics.
For several years I have been passionate about Arduino.
They are now engaged in a project to counter with hall sensors.
The slave sends data to the master via I2C, for my project. I'm using the sketch of Gammon which uses a structure enum to send a request to the slave.
I have the need to send a reset command from master to slave.
I edited the sketch and I can see the command on the slave but will not let me use it to reset the counter.

Master code section
   void RstCounter()
  {

  Serial.println ("funzione azzera attivata");
   Serial.println (sensor);
  char key = keypad.getKey();
  if (key !='A')
  {

   char cmdrst = 'a';
   //set=key;

     if (sensor==11)
    {
    sendCommand (CMD_WRITE_D2, 1);

    Wire.beginTransmission(SLAVE_ADDRESS); // testiamo questa istruzione
    Wire.write(cmdrst);
    Wire.endTransmission();

    delay(100);
    Serial.println (cmdrst);
    }

   else
  {
  m=0;
  }

   azzera =true;
  }
   else if (key=='A')
    {
   Serial.println("");
   Serial.println("AZZERA close");
   azzera = false;
   }
     delay(100);
    }

SLAVE code section
#include <Wire.h>

const byte MY_ADDRESS = 42; // address in valore esadecimale

/************  VARIABILI SENSORI **********************/

#define Sensor11 2
int lastValueSensor11 =0;
int ValueSensor11=0;
int contatore11=0;
int counter11;

// various commands we might get
/************  VARIABILI ENUMERATORE **********************/
enum {
    CMD_ID = 1,
    CMD_READ_D2  = 2,
    CMD_READ_D3 = 3,
    CMD_READ_D4 = 4,
    CMD_WRITE_D2 = 5
    };

char command;
int sensor;
char cmdrst;

/************  SETUP **********************/
void setup()
  {
  command = 0;

  pinMode (Sensor11, INPUT);
  digitalWrite (Sensor11, HIGH);  // enable pull-up

  Serial.begin(9600);
  Wire.begin (MY_ADDRESS);
  Wire.onReceive (receiveEvent);  // interrupt handler for incoming messages
  Wire.onRequest (requestEvent);  // interrupt handler for when data is wanted

  }  // end of setup

/************  LOOP **********************/
void loop()
  {
        /************************ CONTATORE SENSOR 1 ***********************/
   ValueSensor11  = digitalRead(Sensor11);

            if ( ValueSensor11 != lastValueSensor11)
               { if ( ValueSensor11 == LOW)
                    {
                      contatore11 = contatore11 + 1;

                        }
                     }
   lastValueSensor11 = ValueSensor11;

/************  I2C RECEIVE **********************/
void receiveEvent (int howMany)
  {

  command = Wire.read ();  // remember command for when we get request
  //Serial.println(command);
  switch (command)
     {
     case CMD_WRITE_D2:
     Serial.println("comando 5 ricevuto");
     char cmdrst=Wire.read();
     delay(100);
     Serial.println (cmdrst);
     break;
    }
} // end of receiveEvent

void sendSensor1 (const byte which)
  {
  int val11 = contatore11;
  Serial.println(contatore11);
  byte buf11 [2];

    buf11 [0] = val11 >> 8;
    buf11 [1] = val11 & 0xFF;
    Wire.write (buf11, 2);
  }  // end of sendSensor

void requestEvent ()
  {
  switch (command)
     {
     case CMD_ID:
     Wire.write (0x55);
     break;   // send our ID

     case CMD_READ_D2:
     sendSensor1 (2);
     break;  // send A0 value

     case CMD_READ_D3:
     sendSensor2 (3);
     break;    // send D8 value

     case CMD_READ_D4:
     sendSensor3 (4);
     break;

     }  // end of switch

  }  // end of requestEvent

void receiveEvent (int howMany)
  {

  command = Wire.read ();  // remember command for when we get request
  //Serial.println(command);
  switch (command)
     {
     case CMD_WRITE_D2:
     Serial.println("comando 5 ricevuto");
     char cmdrst=Wire.read();
     delay(100);
     Serial.println (cmdrst);
     break;
    }
} // end of receiveEvent

Don't do serial prints inside an interrupt service routine (ISR). That is, not here.
Don't do delay inside an ISR.

  if (key !='A')
  {

I would be checking for NO_KEY first, otherwise you will assume that no key press is not 'A' and be doing that transmission to the slave a lot.

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:
Hardware to measure velocity via string/wire attatchment? beginner
This is a broad question but I want advice on what type of hardware I should look for to make a device that could measure the velocity of an object attached via a string/wire to some sort of rotary wheel.
The purpose of this is to attach it to a barbell and measure mean-velocity for weightlifting atheletes.
I'm a software engineer by trade but know nothing about hardware. I will obviously need to start with simple projects to learn, but I would like to know which hardware I should lean towards buying, so I don't have to re-buy anything?

Attach a optical rotary encoder. Similar to the one that can be found in mouse scroll-wheels. (Since direction isn't needed for you problem only a single photo-interrupter is needed.)

I wonder though how I would get the encoder to "rewind" back into position (between subsequent weight lifting repetitions) without affecting the velocity measurement, or causing undue asymmetrical stress on the athlete?

Some small spring would retract the wire without exerting any noticeable force for the athlete. Or have the wire loop around the "wheel" and attach a counterweight (just like a lot of fitness devices do).

You can use a dog lead (or replace it with a fishing line). I made one my self. I used a rotary encoder and a dog lead, an Arduino board Paralax, and Excel.
It will use interrupts. Once the wire is triggered, the Arduino will send to Excel time and distance traveled. Once the weight goes down distance and time will be printed too, however distance will run in a minus direction. Later just press one button in Excel and each set of lifts will appear on the desktop. I can see my lift speed, power generated, distance travelled and so on.

This is an example of the optical encoder.
You want to use interrupt detection, rather than polling.
Or maybe even an HW counter.
That's all you really need.
I am using 4 of them for a car.
I am in the process of refactoring the code, but you could already have a look at the driver & example I wrote for ChibiOS, here.

Second link appears empty

Ooops, sorry. Fixed.


text:
help with 7- segment display
I'm playing with a 7 segment display.
The following works on my breadboard:
5V -> 330 Ohm Resistor (same row, row 9)
330 Ohm Resistor -> Com Port (row 9 to row 15)
h led (the dot/row 17) -> ground rail

I get the dot to light up.
However, the following does not light up:
5V -> h led (the dot/row 17)
Com Port -> 330 Ohm Resistor (Row 15 -> row 38).
330 Ohm Resistor to negative rail (row 38 -> negative rail)

I realize that the row numbers are meaningless -- things just need to be on the same row. I've included them to make it easier to visualize.
So basically, if the circuit goes:
5V -> Resistor -> Com, then I can use the ground wire to light up any part I want.
If the circuit goes Com -> Resistor to Ground, I can't use the 5V to light up any part.
I'm not sure why given that all the stuff is in serial?

Because you have a common-anode display and you're trying to use it as a common-cathode display. LEDs, like all diodes, only conduct freely in one direction.

I was just stating to suspect that  -- as it wasn't labeled. Thanks! At least now I won't forget :-).


text:
Printing bitmap image from thermal printer using Serial input
I want to print Bitmap image from thermal printer, but image data is from Serial Input. But I am not getting valid print. What wrong i am doing ?
Here is code i wrote
#include "Adafruit_Thermal.h"
#include "SoftwareSerial.h"
// PIN 6 -> Yellow
// PIN 5 -> Green
// GND -> Black

#define TX_PIN 6
#define RX_PIN 5

SoftwareSerial mySerial(RX_PIN, TX_PIN);
Adafruit_Thermal printer(&mySerial);

int count =0;
void setup() {
  pinMode(7, OUTPUT);
  digitalWrite(7, LOW);
  mySerial.begin(9600);  // Initialize SoftwareSerial
  printer.begin();        // Init printer (same regardless of serial type)

  Serial.begin(9600);
  Serial.print("1");

  //printer.printBitmap(384, 5, image);

  //printer.feed(2);

  printer.sleep();      // Tell printer to sleep

  delay(3000L);         // Sleep for 3 seconds
  printer.wake();       // MUST wake() before printing again, even if reset
  printer.setDefault(); // Restore printer to defaults
}

void loop() {
    if(Serial.available()>48){
      uint8_t image[50];
      Serial.readBytes(image,48);
      printer.printBitmap(384, 1, image);
    }

}

Does the example sketch print a logo? Why do you put your printer to sleep? What printer model do you have? Also a single line bitmap is kind of easy to miss.

Yes i can print the logo, It was old code so i didn't bother to disable it,
I have https://www.adafruit.com/products/597. I tried printing 5 lines of bitmap so i have idea how small it would be that is why i sent multiple lines a complete 402px height image. i.e. 402 rows


text:
Just sanity-checking a concept... poor man's self-monitored alarm system
If I wanted to throw together a simple burglar-alarm system that had wireless sensors talking to an Arduino (which would then send me an SMS message via cellular shield as a silent alarm telling me which alarm sensor had changed state_)... what technology would you recommend for the sensor-to-arduino signalling?
It needs to be something that draws little or no power until the alarm is triggered, resistant to radio interference, and as always cheap is a huge plus.... but I haven't gotten much beyond that.
(Of course if anyone's already implemented something like this and there are descriptions/sketches I can adopt and adapt, feel free to point me in the right direction.)
EDIT: To provide more info,this is a wood-framed house, 2 storey plus basement, brick chimney possibly in the way. No straight-line distances greater than 60 feet. Wifi, wireless phone, usual electronics and a wood shop I'm still putting together. Shouldn't be difficult, I just want a robust solution in case a friend asks me to replicate it... and for purely aesthetic reasons.

What sort of range do you need from sensor to Arduino, and what sort of adventure will the transmission signals have - standard house with a few internal walls, big open-plan workshop with near line-of-sight to each sensor, or a shop that sells radio jamming devices that can never be switched off ?

NRF24L01+ for communication. Extreme low power if not sending. Detects packet loss, and automatically resend the packet.
You would however need a small arduino board at the sensor, to read the sensor, and signal to NRF24L01 to send a message.
You'll have to put the arduino in to low power sleep mode to get some good battery life. Either have the sensor wake the arduino up with an interrupt, of poll the sensor like every half second, and immediately go back to sleep.

That sounds good. See Power saving techniques for microprocessors. For extremely low power you would need switches to wake the Arduino (eg. reed switches on doors and windows).

extremely low power is only needed if you are running on a coincell or something. The overhead of running a watchdog timer, and waking up once or twice a second, to take a measurement, only means a few less weeks of battery life on e.g. AA batteries (with still more that a year of runtime). Use this tool to calculate battery life to give you an indication. Sometimes it just isn't worth the effort, just to get a few percent extra battery life.

It's more than a few percent. You can budget for a current draw of 100 nA with no watchdog timer in full sleep mode, and 6.5 µA with the watchdog timer enabled. So that is 65 times the current draw. Now I do indeed have a gadget lying around running from AA batteries that has lasted a couple of years, using the watchdog timer, but it would last even longer if it didn't need to use it.


text:
How do I connect Arduino directly to MySQL server using the URL?
I started a project with my Arduino Mega 2560 that gets some values from sensors. I'm using MySQL Connector, https://launchpad.net/mysql-arduino, and this library allows me to connect to a server using the IP address, and it worked on localhost.
This is the code:
/* Setup for all libraries */
#include <SPI.h>
#include <Ethernet.h>
#include <sha1.h>
#include <mysql.h>
#include <OneWire.h>

/* Setup for Ethernet Library */
byte mac_addr[] = { 0x90, 0xA2, 0xDA, 0x0E, 0xB3, 0x05 }; // MAC address must be unique; this is the Ethernet shield address
IPAddress server_addr( 177, 156, 122, 113 ); // Server addr

/* Setup for all others variables */
int DS18S20_Pin = 2; // Temperature sensor
float temperature;
float placasTensao;
float placasCorrente;
float geradorEolicoTensao;
float geradorEolicoCorrente;
float bateriaTensao;
float bateriaTemp;
float correnteSaidaControlador;
float correnteSaidaConsumo;

OneWire ds(DS18S20_Pin);  // On digital pin 2

/* Setup for the Connector/Arduino */
Connector my_conn; // The Connector/Arduino reference

/* Setup for connection and all variables of the database */
char user[] = "";
char password[] = "";
char INSERT_SQL[1000];
char temperature_convt[10], placasTensao_convt[10], placasCorrente_convt[10], geradorEolicoTensao_convt[10],
     geradorEolicoCorrente_convt[10], bateriaTensao_convt[10], bateriaTemp_convt[10], correnteSaidaControlador_convt[10],
     correnteSaidaConsumo_convt[10];

void setup(){
  Ethernet.begin(mac_addr);
  Serial.begin(9600);
  delay(1000);
}

void loop(){
  temperature = getTemp();
  convert(temperature, temperature_convt);
  snprintf(INSERT_SQL, "INSERT INTO data.data VALUES (%s, 1, 1, 1, 1, 1, 1, 1, NULL)", temperature_convt);
  sendData();
  delay(20000);
}

// Convert a float variable to string
void convert(float data, char *value){
  dtostrf(data, 7, 3, value);
}

// Saves all data on database
void sendData(){
  Serial.println("Connecting...");
  if (my_conn.mysql_connect(server_addr, 3306, user, password)){
    delay(500);
    Serial.println("Starting SQL!");
    Serial.println(INSERT_SQL);
    my_conn.cmd_query(INSERT_SQL);
    Serial.println("Query Success!");
    my_conn.disconnect();
    Serial.println("\n");
  } else {
    Serial.println("Connection failed!");
    Serial.println("Make sure all cables are properly connected!\nIf they are, restart the Arduino!\n");
  }
}

// Returns the temperature from one DS18S20 in degree Celsius
float getTemp(){
  byte data[12];
  byte addr[8];
  if (!ds.search(addr)) {
      // No more sensors on chain, reset search
      ds.reset_search();
      return -1000;
  }

  if ( OneWire::crc8( addr, 7) != addr[7]) {
      Serial.println("CRC is not valid!");
      return -1000;
  }

  if ( addr[0] != 0x10 && addr[0] != 0x28) {
      Serial.print("Device is not recognized");
      return -1000;
  }
  ds.reset();
  ds.select(addr);
  ds.write(0x44,1);
  // Start conversion, with parasite power on at the end
  byte present = ds.reset();
  ds.select(addr);
  ds.write(0xBE); // Read Scratchpad
  for (int i = 0; i < 9; i++) { // We need 9 bytes
    data[i] = ds.read();
  }
  ds.reset_search();
  byte MSB = data[1];
  byte LSB = data[0];
  float tempRead = ((MSB << 8) | LSB); // Using two's complement
  float TemperatureSum = tempRead / 16;
  return TemperatureSum;
}

Now, how can I connect to a server using the URL? Is there a library like MySQL Connector that allows me to use the URL instead of the IP address?
All I want is to do exactly the same thing that I'm doing with MySQL Connector, but using the URL of the server instead of the IP address.

The easiest, just git 'er done, way would be to do an nslookup on the domain, get the IP address and just hard code that into your source. It's not the most robust solution, as it's possible for the IP address to change over time. However, it's highly likely the IP address won't change frequently.
> nslookup google.ca
Server:     64.59.144.93
Address:    64.59.144.93#53

Non-authoritative answer:
Name:   google.ca
Address: 216.58.193.67

If you need it to be more robust, you would need the Arduino to perform the dns lookup to resolve the IP address. This looks like it would do the job:
https://github.com/esp8266/Arduino/blob/master/libraries/Ethernet/src/Dns.h

You are using DHCP, so this step might be optional.
Specify your network addresses (actually we want to specify DNS only but have to specify IP in 2nd argument, so likely have to specify gateway and subnet too):
IPAddress dns_addr( 8, 8, 8, 8); // GOOGLE DNS server, could be any DNS
IPAddress gateway_addr( , , , );   // put your gateway addr
IPAddress ip_addr( , , , );   // put your IP addr
IPAddress subnet( , , , );   // put your subnet mask

void setup(){
                  Ethernet.begin(mac_addr, ip_addr, dns_addr, gateway_addr, subnet);...

Now you could modify Connector::mysql_connect method (or create new method) as follows (only function declaration is changed, body is not):
boolean Connector::mysql_connect(/*IPAddress server*/const char *server, int port, char *user, char *password)
{
  int connected = 0;
  int i = -1;

  // Retry up to MAX_CONNECT_ATTEMPTS times 1 second apart.
  do {
    delay(1000);
    connected = client.connect(server, port);
    i++;
  } while (i < MAX_CONNECT_ATTEMPTS && !connected);

  if (connected) {
    read_packet();
    parse_handshake_packet();
    send_authentication_packet(user, password);
    read_packet();
    if (check_ok_packet() != 0) {
      parse_error_packet();
      return false;
    }
    print_message(CONNECTED);
    Serial.println(server_version);
    free(server_version); // don't need it anymore
    return true;
  }
  return false;
}

Modify the header file also:
boolean mysql_connect(/*IPAddress server*/const char *server, int port,
                                 char *user, char *password)

Now you can supply URL:
if (my_conn.mysql_connect("http:\\www.mysqlserver.com", 3306, user, password))...

I did everything. Modified the Connector::mysql_connect method and also the header. But it doesn't work @Flanker. Do you know what could be causing this? When the program call the my_conn.mysql_connect(), it just stop there, without any answer, appear just my message "Connecting...". Thank you for the answer.

Do you have "http://" protocol part in your URL? Please try without it, like "www.domain...". The Ethernet client have same connect function with URL parameter instead IP (and port), the idea is to use it. Also maybe DNS is not working, maybe test the network address configuration with another DNS sample sketch?


text:
How do you use SPI on an Arduino?
With reference to the Arduino Uno, Mega2560, Leonardo and similar boards:

How does SPI work?
How fast is SPI?
How do I connect between a master and a slave?
How do I make an SPI slave?

Please note: This is intended as a reference question.

Can you answer this related question https://arduino.stackexchange.com/questions/60703/can-serial-be-safely-used-in-an-spi-interrupt-routine

Introduction to SPI
The Serial Peripheral Interface Bus (SPI) interface is used for communication between multiple devices over short distances, and at high speed.
Typically there is a single "master" device, which initiates communications and supplies the clock which controls the data transfer rate. There can be one or more slaves. For more than one slave, each one has its own "slave select" signal, described later.

SPI signals
In a full-blown SPI system you will have four signal lines:

Master Out, Slave In (MOSI) - which is the data going from the master to the slave
Master In, Slave Out (MISO) - which is the data going from the slave to the master
Serial Clock (SCK) - when this toggles both the master and the slave sample the next bit
Slave Select (SS) - this tells a particular slave to go "active"

When multiple slaves are connected to the MISO signal they are expected to tri-state (keep at high impedance) that MISO line until they are selected by Slave Select being asserted. Normally Slave Select (SS) goes low to assert it. That is, it is active low. Once a particular slave is selected it should configure the MISO line as an output so it can send data to the master.
This image shows the way that data is exchanged as one byte is sent:

Note that three signals are outputs from the master (MOSI, SCK, SS) and one is an input (MISO).

Timing
The sequence of events is:

SS goes low to assert it and activate the slave
The SCK line toggles to indicate when the data lines should be sampled
The data is sampled by both master and slave on the leading edge of SCK (using the default clock phase)
Both master and slave prepare for the next bit on the trailing edge of SCK (using the default clock phase), by changing MISO / MOSI if necessary
Once the transmission is over (possibly after multiple bytes have been sent) then SS goes high to de-assert it

Note that:

The most significant bit is sent first (by default)
Data is sent and received at the same instant (full duplex)

Because data is sent and received on the same clock pulse it is not possible for the slave to respond to the master immediately. SPI protocols usually expect the master to request data on one transmission, and get a response on a subsequent one.
Using the SPI library on the Arduino, doing a single transfer looks like this in code:
 byte outgoing = 0xAB;
 byte incoming = SPI.transfer (outgoing);

Sample code
Example of sending only (ignoring any incoming data):
#include <SPI.h>

void setup (void)
  {
  digitalWrite(SS, HIGH);  // ensure SS stays high
  SPI.begin ();
  } // end of setup

void loop (void)
  {
  byte c;

  // enable Slave Select
  digitalWrite(SS, LOW);    // SS is pin 10

  // send test string
  for (const char * p = "Fab" ; c = *p; p++)
    SPI.transfer (c);

  // disable Slave Select
  digitalWrite(SS, HIGH);

  delay (100);
  } // end of loop

Wiring for output-only SPI
The above code (which sends only) might be used to drive an output serial shift register. These are output-only devices, so we don't need to worry about any incoming data. In their case the SS pin might be called the "store" or "latch" pin.

Examples of this are the 74HC595 serial shift register, and various LED strips, just to mention a couple. For example, this 64 pixel LED display driven by a MAX7219 chip:

In this case you can see that the board maker has used slightly different signal names:

DIN (Data In) is MOSI (Master Out, Slave In)
CS (Chip Select) is SS (Slave Select)
CLK (Clock) is SCK (Serial Clock)

Most boards will follow a similar pattern. Sometimes DIN is just DI (Data In).
Here is another example, this time a 7-segment LED display board (also based on the MAX7219 chip):

This uses exactly the same signal names as the other board. In both of these cases you can see that the board only needs 5 wires to it, the three for SPI, plus power and ground.

Clock phase and polarity
There are four way you can sample the SPI clock.
The SPI protocol allows for variations on the polarity of the clock pulses. CPOL is clock polarity, and CPHA is clock phase.

Mode 0 (the default) - clock is normally low (CPOL = 0), and the data is sampled on the transition from low to high (leading edge) (CPHA = 0)
Mode 1 - clock is normally low (CPOL = 0), and the data is sampled on the transition from high to low (trailing edge) (CPHA = 1)
Mode 2 - clock is normally high (CPOL = 1), and the data is sampled on the transition from high to low (leading edge) (CPHA = 0)
Mode 3 - clock is normally high (CPOL = 1), and the data is sampled on the transition from low to high (trailing edge) (CPHA = 1)

These are illustrated in this graphic:

You should refer to the datasheet for your device to get the phase and polarity correct. There will usually be a diagram which shows how to sample the clock. For example, from the datasheet for the 74HC595 chip:

As you can see the clock is normally low (CPOL = 0) and it is sampled on the leading edge (CPHA = 0) so this therefore is SPI mode 0.
You can change the clock polarity and phase in code like this (choose one only, of course):
SPI.setDataMode (SPI_MODE0);
SPI.setDataMode (SPI_MODE1);
SPI.setDataMode (SPI_MODE2);
SPI.setDataMode (SPI_MODE3);

This method is deprecated in versions 1.6.0 onwards of the Arduino IDE. For recent versions you change the clock mode in the SPI.beginTransaction call, like this:
SPI.beginTransaction (SPISettings (2000000, MSBFIRST, SPI_MODE0));  // 2 MHz clock, MSB first, mode 0

Data order
The default is most-significant bit first, however you can tell the hardware to process the least significant bit first like this:
SPI.setBitOrder (LSBFIRST);   // least significant bit first
SPI.setBitOrder (MSBFIRST);   // most significant bit first

Again, this is deprecated in versions 1.6.0 onwards of the Arduino IDE. For recent versions you change the bit order in the SPI.beginTransaction call, like this:
SPI.beginTransaction (SPISettings (1000000, LSBFIRST, SPI_MODE2));  // 1 MHz clock, LSB first, mode 2

Speed
The default setting for SPI is to use the system clock speed divided by four, that is, one SPI clock pulse every 250 ns, assuming a 16 MHz CPU clock. You can change the clock divider by using setClockDivider like this:
SPI.setClockDivider (divider);

Where "divider" is one of:

SPI_CLOCK_DIV2
SPI_CLOCK_DIV4
SPI_CLOCK_DIV8
SPI_CLOCK_DIV16
SPI_CLOCK_DIV32
SPI_CLOCK_DIV64
SPI_CLOCK_DIV128

The fastest rate is "divide by 2" or one SPI clock pulse every 125 ns, assuming a 16 MHz CPU clock. This would therefore take 8 * 125 ns or 1 µs to transmit one byte.
This method is deprecated in versions 1.6.0 onwards of the Arduino IDE. For recent versions you change the transfer speed in the SPI.beginTransaction call, like this:
SPI.beginTransaction (SPISettings (4000000, MSBFIRST, SPI_MODE0));  // 4 MHz clock, MSB first, mode 0

However empirical testing shows that it is necessary to have two clock pulses between bytes, so the maximum rate at which bytes can be clocked out is 1.125 µs each (with a clock divider of 2).
To summarize, each byte can be sent at a maximum rate of one per 1.125 µs (with a 16 MHz clock) giving a theoretical maximum transfer rate of 1/1.125 µs, or 888,888 bytes per second (excluding overhead like setting SS low and so on).

Connecting to Arduino
Arduino Uno
Connecting via digital pins 10 to 13:

Connecting via the ICSP header:

Arduino Atmega2560
Connecting via digital pins 50 to 52:

You can also use the ICSP header, similar to the Uno above.
Arduino Leonardo
The Leonardo and Micro do not expose the SPI pins on the digital pins, unlike the Uno and Mega. Your only option is to use the ICSP header pins, as illustrated above for the Uno. However the Leonardo and ProMicro don't expose the SS pin and thus cannot be used as an SPI slave.

Multiple slaves
A master can communicate with multiple slaves (however only one at a time). It does this by asserting SS for one slave and de-asserting it for all the others. The slave which has SS asserted (usually this means LOW) configures its MISO pin as an output so that slave, and that slave alone, can respond to the master. The other slaves ignore any incoming clock pulses if SS is not asserted. Thus you need one additional signal for each slave, like this:

In this graphic you can see that MISO, MOSI, SCK are shared between both slaves, however each slave has its own SS (slave select) signal.

Protocols
The SPI spec does not specify protocols as such, so it is up to individual master/slave pairings to agree on what the data means. Whilst you can send and receive bytes simultaneously, the received byte cannot be a direct response to the sent byte (as they are being assembled simultaneously).
So it would be more logical for one end to send a request (eg. 4 might mean "list the disk directory") and then do transfers (perhaps just sending zeros outwards) until it receives a complete response. The response might terminate with a newline, or 0x00 character.
Read the datasheet for your slave device to see what protocol sequences it expects.

How to make an SPI slave
The earlier example shows the Arduino as the master, sending data to a slave device. This example shows how the Arduino can be a slave.
Hardware setup
Connect two Arduino Unos together with the following pins connected to each other:

10 (SS)

11 (MOSI)

12 (MISO)

13 (SCK)

+5v (if required)

GND (for signal return)

On the Arduino Mega, the pins are 50 (MISO), 51 (MOSI), 52 (SCK), and 53 (SS).
In any case, MOSI at one end is connected to MOSI at the other, you don't swap them around (that is you do not have MOSI <-> MISO). The software configures one end of MOSI (master end) as an output, and the other end (slave end) as an input.
On some boards (like Leonardo, ProMicro — see above) the SS pin isn't exposed (rather it is connected to RX_LED). It is not possible to remap SS to another pin to be able to use those boards as an SPI slave as the AVR uses fixed SPI pins according to the datasheets (PB0-PB3 on 32U4).
Master example
#include <SPI.h>

void setup (void)
{

  digitalWrite(SS, HIGH);  // ensure SS stays high for now

  // Put SCK, MOSI, SS pins into output mode
  // also put SCK, MOSI into LOW state, and SS into HIGH state.
  // Then put SPI hardware into Master mode and turn SPI on
  SPI.begin ();

  // Slow down the master a bit
  SPI.setClockDivider(SPI_CLOCK_DIV8);

}  // end of setup

void loop (void)
{

  char c;

  // enable Slave Select
  digitalWrite(SS, LOW);    // SS is pin 10

  // send test string
  for (const char * p = "Hello, world!\n" ; c = *p; p++)
    SPI.transfer (c);

  // disable Slave Select
  digitalWrite(SS, HIGH);

  delay (1000);  // 1 seconds delay
}  // end of loop

Slave example
#include <SPI.h>

char buf [100];
volatile byte pos;
volatile bool process_it;

void setup (void)
{
  Serial.begin (115200);   // debugging

  // turn on SPI in slave mode
  SPCR |= bit (SPE);

  // have to send on master in, *slave out*
  pinMode (MISO, OUTPUT);

  // get ready for an interrupt
  pos = 0;   // buffer empty
  process_it = false;

  // now turn on interrupts
  SPI.attachInterrupt();

}  // end of setup

// SPI interrupt routine
ISR (SPI_STC_vect)
{
byte c = SPDR;  // grab byte from SPI Data Register

  // add to buffer if room
  if (pos < sizeof buf)
    {
    buf [pos++] = c;

    // example: newline means time to process buffer
    if (c == '\n')
      process_it = true;

    }  // end of room available
}  // end of interrupt routine SPI_STC_vect

// main loop - wait for flag set in interrupt routine
void loop (void)
{
  if (process_it)
    {
    buf [pos] = 0;
    Serial.println (buf);
    pos = 0;
    process_it = false;
    }  // end of flag set

}  // end of loop

The slave is entirely interrupt-driven, thus it can doing other stuff. The incoming SPI data is collected in a buffer, and a flag set when a "significant byte" (in this case a newline) arrives. This tells the slave to get on and start processing the data.
Example of connecting master to slave using SPI

How to get a response from a slave
Following on from the code above which sends data from an SPI master to a slave, the example below shows sending data to a slave, having it do something with it, and return a response.
The master is similar to the example above. However an important point is that we need to add a slight delay (something like 20 microseconds). Otherwise the slave doesn't have a chance to react to the incoming data and do something with it.
The example shows sending a "command". In this case "a" (add something) or "s" (subtract something). This is to show that the slave is actually doing something with the data.
After asserting slave-select (SS) to initiate the transaction, the master sends the command, followed by any number of bytes, and then raises SS to terminate the transaction.
A very important point is that the slave cannot respond to an incoming byte at the same moment. The response has to be in the next byte. This is because the bits which are being sent, and the bits which are being received, are being sent simultaneously. Thus to add something to four numbers we need five transfers, like this:
transferAndWait ('a');  // add command
transferAndWait (10);
a = transferAndWait (17);
b = transferAndWait (33);
c = transferAndWait (42);
d = transferAndWait (0);

First we request action on number 10. But we don't get a response until the next transfer (the one for 17). However "a" will be set to the reply to 10. Finally we end up sending a "dummy" number 0, to get the reply for 42.
Master (example)
  #include <SPI.h>

  void setup (void)
    {
    Serial.begin (115200);
    Serial.println ();

    digitalWrite(SS, HIGH);  // ensure SS stays high for now
    SPI.begin ();

    // Slow down the master a bit
    SPI.setClockDivider(SPI_CLOCK_DIV8);
    }  // end of setup

  byte transferAndWait (const byte what)
    {
    byte a = SPI.transfer (what);
    delayMicroseconds (20);
    return a;
    } // end of transferAndWait

  void loop (void)
    {

    byte a, b, c, d;

    // enable Slave Select
    digitalWrite(SS, LOW);

    transferAndWait ('a');  // add command
    transferAndWait (10);
    a = transferAndWait (17);
    b = transferAndWait (33);
    c = transferAndWait (42);
    d = transferAndWait (0);

    // disable Slave Select
    digitalWrite(SS, HIGH);

    Serial.println ("Adding results:");
    Serial.println (a, DEC);
    Serial.println (b, DEC);
    Serial.println (c, DEC);
    Serial.println (d, DEC);

    // enable Slave Select
    digitalWrite(SS, LOW);

    transferAndWait ('s');  // subtract command
    transferAndWait (10);
    a = transferAndWait (17);
    b = transferAndWait (33);
    c = transferAndWait (42);
    d = transferAndWait (0);

    // disable Slave Select
    digitalWrite(SS, HIGH);

    Serial.println ("Subtracting results:");
    Serial.println (a, DEC);
    Serial.println (b, DEC);
    Serial.println (c, DEC);
    Serial.println (d, DEC);

    delay (1000);  // 1 second delay
    }  // end of loop

The code for the slave basically does almost everything in the interrupt routine (called when incoming SPI data arrives). It takes the incoming byte, and adds or subtracts as per the remembered "command byte". Note that the response will be "collected" next time through the loop. This is why the master has to send one final "dummy" transfer to get the final reply.
In my example I am using the main loop to simply detect when SS goes high, and clear the saved command. That way, when SS is pulled low again for the next transaction, the first byte is considered the command byte.
More reliably, this would be done with an interrupt. That is, you would physically connect SS to one of the interrupt inputs (eg, on the Uno, connect pin 10 (SS) to pin 2 (an interrupt input), or use a pin-change interrupt on pin 10.
Then the interrupt could be used to notice when SS is being pulled low or high.
Slave (example)
// what to do with incoming data
volatile byte command = 0;

void setup (void)
  {

  // have to send on master in, *slave out*
  pinMode(MISO, OUTPUT);

  // turn on SPI in slave mode
  SPCR |= _BV(SPE);

  // turn on interrupts
  SPCR |= _BV(SPIE);

  }  // end of setup

// SPI interrupt routine
ISR (SPI_STC_vect)
  {
  byte c = SPDR;

  switch (command)
    {
    // no command? then this is the command
    case 0:
      command = c;
      SPDR = 0;
      break;

    // add to incoming byte, return result
    case 'a':
      SPDR = c + 15;  // add 15
      break;

    // subtract from incoming byte, return result
    case 's':
      SPDR = c - 8;  // subtract 8
      break;

    } // end of switch

  }  // end of interrupt service routine (ISR) SPI_STC_vect

void loop (void)
  {

  // if SPI not active, clear current command
  if (digitalRead (SS) == HIGH)
    command = 0;
  }  // end of loop

Example output
Adding results:
25
32
48
57
Subtracting results:
2
9
25
34
Adding results:
25
32
48
57
Subtracting results:
2
9
25
34

Logic analyzer output
This shows the timing between sending and receiving in the above code:

New functionality in IDE 1.6.0 onwards
Version 1.6.0 of the IDE has changed the way SPI works, to an extent. You still need to do SPI.begin() before using SPI. That sets up the SPI hardware. However now, when you are about to start communicating with a slave you also do SPI.beginTransaction() to set up SPI (for this slave) with the correct:

Clock speed
Bit order
Clock phase and polarity

When you are done communicating with the slave, you call SPI.endTransaction(). For example:
SPI.beginTransaction (SPISettings (2000000, MSBFIRST, SPI_MODE0));
digitalWrite (SS, LOW);        // assert Slave Select
byte foo = SPI.transfer (42);  // do a transfer
digitalWrite (SS, HIGH);       // de-assert Slave Select
SPI.endTransaction ();         // transaction over

Why use SPI?

I would add one preliminary question: when/why would you use SPI? A need for multi-master configuration or a very large number of slaves would tilt the scale toward I2C.

This is an excellent question. My answers are:

Some devices (quite a few) only support the SPI transfer method. For example the 74HC595 output shift register, the 74HC165 input shift register, the MAX7219 LED driver, and quite a few LED strips that I have seen. So, you might use it because the target device only supports it.
SPI is really the fastest method available on the Atmega328 (and similar) chips. The fastest rate quoted above is 888,888 bytes per second. Using I2C you can only get around 40,000 bytes per second. The overhead of the I2C is quite substantial, and if you are trying to interface really quickly, SPI is the preferred choice. Quite a few chip families (eg. MCP23017 and MCP23S17) actually support both I2C and SPI so you often can choose between speed, and the ability to have multiple devices on a single bus.
The SPI and I2C devices are both supported in hardware on the Atmega328 so you could conceivably be doing a transfer via SPI simultaneously with I2C which would give you a speed boost.

Both methods have their place. I2C lets you connect many devices to a single bus (two wires, plus ground) so it would be the preferred choice if you needed to interrogate a substantial number of devices, perhaps fairly infrequently. However the speed of SPI could be more relevant for situations where you need to output rapidly (eg. a LED strip) or input rapidly (eg. an ADC converter).

References

My page about SPI - also has details about bit-banged SPI, and using the USART to gain a second hardware SPI on the Atmega328 chip.

Serial Peripheral Interface Bus - Wikipedia

Arduino SPI library reference pages

SPI documentation at PJRC

SPI protocol - Sparkfun

Are you going to cover the weirdness that is the Due's SPI? Where the configuration of the SPI port is tied to the SS pin used, and there are (IIRC) 4 hardware SS pins assigned to the SPI port?

Other point about the selection: sometimes you really have no choice because the sensor you want/need to use is only available as I2C.

Are you going to cover the weirdness that is the Due's SPI? - I don't know anything about the Due's SPI (apart from presuming the overall protocol is the same). You are welcome to add a reply covering that aspect of it.

When is the audiobook of this answer coming out, and will you be reading it yourself ;)

@AMADANONInc. Perhaps a music video? Or an animation? I'm not sure if my Australian accent would be understandable. :P

@NickGammon, I live in NZ, and I've been learning from EEVBlog videos for some time, so I don't think I'll have any problems. A music video would be good, though - how's your circular breathing?

I think sub section "New functionality in IDE 1.6.0 onwards" should explicitly answer the question "What if I leave out SPI.beginTransaction?" (etc.). Similary, answer the question "Will old sketches work?" (backwards compatibility (with some fixed defaults?)) - I think they do; that is what I observed yesterday when trying with Arduino Uno, software version 1.6.5, and a DAC (MCP4901); but there could be caveats that I don't know of. "also" could maybe be "can also".

New SPI has SPI.transfer(buffer, size) https://www.arduino.cc/en/Reference/SPITransfer

@PeterMortensen using Arduino 1.8.8 setting SPI params the old way still works

Is the slave interupt function triggered by the clock leading edge?

No, it would be triggered by the complete transfer of one byte, as the ISR can immediately access that (SPDR), as in the code shown.

See my post https://www.fpaynter.com/2020/03/arduino-spi-data-exchange-between-two-arduinos-in-a-master-slave-configuration/ for a newbie's take on the problem

Someone tried to edit in a comment that the Leonardo and ProMicro don't expose the SS pin, so I have amended the answer to reflect that.

To the users that are rejecting edits about the SS pin, as the author I don't disagree with them.

I have amended the edit in question to remove the reference to "so people wondered" ... which people?

Thank you for the information.
Mr. Nick Gammon said

However the Leonardo and ProMicro don't expose the SS pin and thus cannot be used as an SPI slave.

but I could use ProMicro and Leonardo as SPI slave devides by wiring SS signal.
Reference: https://asukiaaa.blogspot.com/2023/05/atmega32u4-as-spi-slave.html

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


text:
Measure Vcc using 1.1V bandgap
For an battery driven application I want to measure the Vcc (using an Atmega 32u4). That is my code:
int readBandGap() {
  ADMUX = (B01 << REFS0)    // VCC
        | (0 << ADLAR)      // right-adjusted result
        | (B011110 << MUX0) // 1.1V
        ;
  // switch off any ADC conversion
  ADCSRA &= ~(1 << ADEN);
  // enable ADC
  ADCSRA |= 1 << ADEN;
  // start ADC
  ADCSRA |= 1 << ADSC;
  // wait until finished
  while (bit_is_set(ADCSRA, ADSC));
  // first read low, then high!
  uint8_t low = ADCL;
  uint8_t high = ADCH;
  // switch off any ADC conversion
  ADCSRA &= ~(1 << ADEN);
  return (high << 8) | low;
}

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

void loop() {
  int value = readBandGap();
  float vcc = 1.1 * 1023 / value;
  Serial.print(value);
  Serial.print("  ");
  Serial.println(vcc);

  delay(1000);
}

My Olimexino 32u4 board has the ability to switch the voltage between 5V and 3.3V. There are two strange things:

the first measurement is always significantly different than the later measurements
with 5V I'm getting 450, followed by ~367; with 3.3V I'm getting 422, followed by ~395. I would have expected a higher Vcc resulting in a lower measured value (bandgap should be measured compared to Vcc).

Any ideas what is wrong with my approach?

I have known good Vcc measuring code here: http://hacking.majenko.co.uk/making-accurate-adc-readings-on-arduino - You might like to compare it with your code - especially the bit that delays to allow Vref to settle.

I've tried that code now and readVcc always reports ~1100, no matter whether I'm using 3.3 or 5V. Maybe for the 32u4 some different flags have to be used.

Given that code was written for the 328P with fewer ADC inputs, yes, you probably need to adjust the MUX settings to get the right channel.

After tweaking a lot, I've now have found following code to work quite good.
float readVcc() {
  ADMUX = (B01 << REFS0)    // VCC
        | (0 << ADLAR)      // right-adjusted result
        | (B011110 << MUX0) // 1.1V
        ;
  // enable ADC
  ADCSRA |= (1 << ADEN);
  // seems necessary
  delay(2);
  // start ADC
  ADCSRA |= 1 << ADSC;
  // wait until finished
  while (bit_is_set(ADCSRA, ADSC));
  // first read low, then high!
  long value = ADCL;
  value |= ADCH << 8;
  return 1.1 / value * 1023;
}

The bandgap voltage reference needs some time to stabilize, after you enable it. See http://jeelabs.org/2012/05/12/improved-vcc-measurement/
Doing 3 dummy measurements, gives it enough time to do that.


text:
Dagu Mini Driver Board Issues
I have the Dagu Mini Driver board which is based on the atmega8 and I uploaded the code here. It uploaded perfectly and I wired 4x AA pack to the battery terminals making sure to observe polarity.
I then attached two DC motors to the ML and MR pins just like it said in the picture. I turned the board on, making sure the switch was set to on also.
The red light lighted up and the blue light flickered for a second. The motors did not move. I tried different motors. To check if it was a corrupt bootloader I tried to upload the hello world blink sketch. That worked perfectly.
I got my multi-meter out and tested the wires I was using...all good! Tested the battery...6.31v! That's within specs. I have the jumpers correctly inserted on the D7 - 10 pins. Here's my setup:

What in the world could be wrong? The code is supposed to make it turn in a rough square. I checked it over and over and it looks right. Any ideas?

What +V selector are you using? Battery or 5V. My guess is that you have it in the 5V setting and the regulator cannot driver the motors. The load is too high. http://www.generationrobots.com/media/RS027-mini-driver-instruction-manual.pdf

I had one too work perfectly ....I think you codE is wrong...

Switching the selector did not help. I received a new one which worked perfectly following the steps from before. Apparently the issue was hardware related, possibly a cold solder joint preventing the motor driver section to work while still letting everything else continue normally.

This is a generic debugging advice, but maybe it can still be of help:
have you tried driving the led from the loop, to check that it doesn't get stuck for some reason?
Other thing you could do is to get the datasheet of the motor driver, find out the inputs from the ATMega and see how they look like.
At least that would allow you to bisect the problem answering the question:
"Does the ATMega generate the expected signal?"

It looks to me like the "motor driver" is a pair of H bridges built out of discrete MOSFETs.  Hard to work out which one of the 14 MOSFETs is which.  Simpler to look at the digital IO pins that are documented as the control pins for the bridges.

If you mean the "hello world" blink sketch that blinks the D13 LED, I uploaded that and it works. I'll look at the data sheet.