text:
How to design and debug a custom I2C master-slave system?
How to proceed, when in need of a custom I2C master-slave system?
What are the design criteria to apply?
What are the debugging tools one can use to troubleshoot problems?

This is a reference question. I have deleted a couple of comments that made this less obvious. (The question is answered by the asker).

This tutorial I gave at the Embedded Linux Conference tries to answer the questions, providing links to more detailed description of the topics addressed and using the practical example of driving a 4WD drone, where an Arduino Mini Pro acts as slave and controls the 4 independent wheels.
The original document can be found here.
Note: This answer is currently work in progress, as I adapt the highlights from the link.

Typical Applications of the I2C bus

Interfacing with relatively slow peripherals. Ex: sensors, mechanical actuators.
Controlling “fast” peripherals, that use other channels for exchanging data. Ex: codecs.
In a PC, the Operating System usually interacts over I2C with:

temperature and battery voltage meters;
fan speed controllers;
audio codecs.

In case multiple bus controllers are available, peripherals are grouped by speed, so that fast ones are not penalized by slower ones.

A quick introduction to the I2C bus - key features

Serial bus.
Only 2 lines: Serial CLock and Serial DAta (plus ground).
4 speeds: 100kHz, 400kHz, 1MHz, 3.2MHz.
Typically, 1 master device and 1 or more slaves.
Communications are always initiated by a master device.
Multiple masters can co-exist on the same bus (multi-master).
Open-Drain: both SDA and SCL need pull-up resistors.
“Clock Stretching”

The master controls SCL, but a slave can hold it down (because open drain), if it needs to adjust the speed.
The master must check for this scenario.
A slave can get stuck and jam the bus: need for reset lines from the master to the slave.

Typically 7-bit addressing, but also 10 bit is supported.
Logical protocol: actual voltage levels are not specified and depend on individual implementations. Ex: 1.8V / 3.3V / 5.0V

Reference URLs:

http://www.i2c-bus.org
http://www.robot-electronics.co.uk/i2c-tutorial

Example of Bus Configuration

Characteristics of the Protocol (simplified)

2 message types: read and write
Start / Stop bit - represented as “[“ and “]” in the rest of the answer
Address: 7 or 10 bits
R/W bit: R = 1 / W = 0 Used to discriminate the type of message sent.
Data on the bus: (Address << 1 | R/W)
Registers as information handlers, within the selected device.

Example of Bus traffic

Custom Slaves
Why create a custom I2C slave?

Desired sensor/actuator unavailable with I2C interface.
Less unique addresses available than slaves needed.
Desired custom functionality on the slave:

Semi-autonomous reactions to stimuli.
Filtering/preprocessing input data.

Power optimization: custom “sensor hub” does the housekeeping while the main processor is idle.
Realtime response to inputs.
[your imagination here]

How to design a custom I2C slave?

Define requirements (see previous slide).
Choose microcontroller or microprocessor.
Choose Scheduler or Operating System (if any).
Define communication sub-protocol:

Define parameters and commands to be exchanged.
Organize them into “registers” and choose a free address.

Design of the I2C Master
Key design criteria:

Weight/Dimensions.
Required computational power and average latency.
PC-like device

Embedded device, typically headless.
Preferred programming language: interpreted vs compiled.

Availability of busses/gpios for driving the slave(s):

GPIOs only: bitbang the protocol
I2C: user-space application vs kernel driver.
No GPIOs/I2C interfaces available: USB to I2C adapter.

Debugging: Divide and Conquer
Take direct control of the bus with an ad-hoc device.
Examples:

Bus Pirate (useful also for other busses)
USB to I2C Master adapter, also based on the FTDI FT232R chip.
Custom device (could be a separate project).
Snoop the bus with a logic analyzer or a scope/advanced meter.
Examples:

sigrok/pulseview with compatible logic analyzer
2-channels standalone scope/meter
Use slave-specific In Circuit Debugger/In Circuit Emulator.
Example:
AVR Dragon for AVR chips (Arduino UNO, Nano, Mini, MiniPro)

BUS Pirate

Primarily for development purposes.
Can both sniff the bus and drive it.
Console interface over serial (ttyACM) port, including macros, or programmatic access for several programming languages.
Built-in pullup resistors and voltage sources (5V / 3.3V)
Supports many other protocols.
References: Wikipedia, main page

USB to I2C Adapter

Small footprint.
Suitable for permanent installations.
No need for special connections on the host: it can be used to interface with a typical PC.
Variant available that is also SPI-capable.
No console interface, only serial binary protocol.
Requires protocol wrapper.
Reference: protocol

sigrok and pulseview
sigrok(bakend component) logo

pulseview (visualizer) example

Example of low end logic Analyzer

De-facto standard for PC-driven measurements on linux (but available on other OSes too).
Support for vast range of logic analyzers, scopes and meters.
Various protocol decoders, including I2C.
Useful for visualizing the logical signals and debugging protocol errors.
Even very low end, inexpensive HW can provide a whole new dimension to debugging.
References: sigrok, pulseview, supported hardware

Example: steering a 4WD drone
Prototype built using 2 Arduino Mini Pro.

What does the slave do in the example?
The I2C slave:

Controls the amount of torque applied to each wheel.
Controls the direction each wheel spins.
Measures  the rotation speed of each wheel through an optical encoder (Odometer).
Exposes the parameters above to the I2C Master.

High level block diagram of the I2C Slave.

Selecting the Slave: Arduino Mini Pro

Enough pins/functions to provide for each wheel:

1 PWM output with independent configuration of the duty-cycle.
1 GPIO for registering odometer input as IRQ.
2 GPIOs for selecting:

Forward
Reverse
Idle
Lock

I2C HW block for interrupt-driven i2c exchanges.
Dedicated pins for SPI-based programming.
Small footprint.
Low Cost.
The board layout of the clone represented in the picture is optimized for mounting on a DIL socket.

Slave-specific ICD: AVR Dragon

Supports various programming modes, included SPI programming, through AVRDude.
Doesn’t interfere with normal AVR operations, so it can be left plugged into the system.
After enabling debugWire interface, it allows configuring HW/SW breakpoints, by a dedicated backend for gdb/ddd.

Selecting the OS: ChibiOS

RTOS: preemption, tasks, semaphores, dynamic system tic, etc.
Small footprint: link only used code/data.
Distinction between RTOS and BSP through HAL.
GPLv3 for non-commercial use.
Actively developed, but already mature.
Supports 8bit AVR.

However it had limited BSP support for AVR, lack of:
 - interrupts driver for AVR GPIOs (added).
 - I2C support for AVR slave mode (custom).
Which had to be developed separately as part of the Drone SW for the AVR.

Defining the Communication Parameters
For each wheel:

Duty Cycle of the PWM signal used to drive it - 1 byte.
0xFF = max torque / 0x00 = no torque.
Direction of rotation - 1 byte.

0x00 = idle
0x01 = reverse
0x02 = forward
0x03 = locked

Average period in between slots of the optical encoder - 2 bytes.

Writing anything resets the measurement.

Parameter Index - 1 nibble:

0 = Duty Cycle
1 = Direction
2 = Average Period

Wheel indexes - 1 nibble:

0 = Left Rear
1 = Right Rear
2 = Right Front
3 = Left Front
4 = All

Sub Protocol: Defining the Registers
Register format:   0xαβ
 - α = Parameter Index
 - β = Wheel Index
Address (chosen arbitrarily): 0x10
Bus Pirate format:
 - [ = start bit
 - ] = end bit
 - r = read byte
 - address times 2 (left shift 1), for R/W bit

Example - in Bus Pirate Format
[   i2c_addr   reg_addr=(parm,wheel)   reg_value  ]
[0x20 0x20 0x02]  Left Rear Forward
[0x20 0x21 0x01]  Right Rear Backward
[0x20 0x22 0x01]  Right Front Backward
[0x20 0x23 0x02]  Left Front Forward
[0x20 0x14 0xFF]  Wheels set to max torque

The car spins clockwise.


text:
Sending multiple channels with bluetooth
I have ordered my HC-05 BT modules.
My question is this:
Is it possible to send multiple channels over bluetooth. For example, stereo sound has two channels. I think i have seen people do this but i'm not sure.
If it is possible, could you please provide some more information on how its done?
Thanks!

The BT module will connect as a SPP (serial port) device, and then pass the serial data to and from the arduino and whatever you choose to connect to (that supports SPP).
There is only one channel, and in any case only one set of TX and RX wires that will be connected to your arduino, but this does not stop you from sending as much data of as many different types as you want. You are only limited by the BAUD rate and how much time the message will take to send.
For complicated data transfers you will need to write the code for a protocol so both sides can make sense of what the other says. You are free to do whatever you can think of here, although if you need to make a complicated protocol you might get some use out of the answers to this question:
Communication Protocol Best Practices and Patters

To add to BrettM answer, Bluetooth is the RF standard on which many protocols can stack up; each such protocol is called a 'Bluetooth Profile'.
The Bluetooth model you purchased comes only with the Serial Port Profile (SPP) profile implemented in the firmware. This mean that you can use it for establishing serial communication.
As serial protocol will probably be too slow for stereo Audio over Bluetooth, Audio usually use a different profile called Advanced Audio Distribution Profile (A2DP). Unfortunately, the HC-05 does not come with this protocol stack implemented in its firmware. If your primary goal is to send stereo Audio over Bluetooth, consider purchasing a dedicated chip, such as XS3868 or Sparkfun's RN-52. For beginners, it is recommended to get one with a breakout board for easy integration with Arduino projects.
For completeness, there are many other Bluetooth profiles, each is optimized for different task. See Wikipedia for the full list:
http://en.wikipedia.org/wiki/List_of_Bluetooth_profiles

source: Stack Exchange

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

sort: votes


text:
Assigning formatted value to variable
Look at this snippet of code (from TinyGPS++ library):
Serial.print(gps.location.lat(), 6);

It prints the latitude location with 6 decimal points.
I want, instead of printing that value, to have it assigned to a variable.
But i want it assigned just like above, with six decimal points. Is there a way to do this?

Sounds like you want dtostrf() - http://www.nongnu.org/avr-libc/user-manual/group__avr__stdlib.html#ga060c998e77fb5fc0d3168b3ce8771d42 It should do what you want (you have to preallocate the string, though).

To be clear, do you want to store the string with 6 decimal places, or a floating point value rounded to 6 decimal places?

Whatever will do, but i guess a string suits me better

What research have you done on this? @ConnorWolf gave you comment with a valid suggestion, have you looked into it?

Merely expanding on what ConnorWolf has said (which I saw yesterday), look at the link he gave you, it gives you a run down on the command you're after.

The dtostrf() function returns the pointer to the converted string s.
char* dtostrf ( double          __val,
                signed char     __width,
                unsigned char   __prec,
                char *          __s
  )
  The dtostrf() function converts the double value passed in val into an ASCII representationthat will be stored under s. The caller is responsible for providing sufficient storage in s.
Conversion is done in the format "[-]d.ddd". The minimum field width of the output string (including the '.' and the possible sign for negative values) is given in width, and prec determines the number of digits after the decimal sign. width is signed value, negative for left adjustment.

From that, I wrote a short sketch that divides millis() by 1000 and saves this in a float, we then use this float as a source for dtostrf() to do it's work and store the result in a char array.
void setup(){
  Serial.begin(9600);
}

void loop(){
  char c[12];
  float f = millis()/1000.0;
  dtostrf(f,11,3,c);
  Serial.println(c);
  delay(111);
}

I have picked arbitrary values, you're going to have to do the calculations on the size of the array to create (don't forget the leading negative sign, the digits before the decimal, the decimal and your precision digits as well as the null terminator!

I had the same problem and I found answer
char latitude[20];
char longitude[20];

dtostrf(gps.location.lat(),8,6,latitude);
dtostrf(gps.location.lng(),8,6,longitude);

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

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


text:
arduino EM408 GPS problem
I have written this little snippet of code to interface with EM408 GPS.
#include <SoftwareSerial.h>
SoftwareSerial GPS = SoftwareSerial(2,3);  //rx,tx
void setup()
{
  GPS.begin(4800);
  Serial.begin(9600);
}

void loop()
{
  //Serial.print(GPS.read(), BYTE);
  Serial.write(byte(GPS.read()));  //as of Arduino 1.0
}

Hardware side i have these connections:
ENABLE: 3.3V
Vcc   : 3.3V
Ground: Ground
Rx, Tx correctly connected to arduino and correctly initialized with SoftwareSerial
However, the values i get are just junk data
ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ

I get these without ending...
I experimenting with changing the baud rate, still the same thing goes on.
Any ideas?
EDIT:
I used to get random junk data before with the EM406 gps module, but i solved it by casting everything to BYTE. I have tried both approaches here, but the results are the same...

The datasheet indicates that the communications port is "TTL Levels", which usually means that the data is inverted relative to normal RS-232 levels.  If you are connecting to a true RS-232 port on the Arduino, you will need to invert the signals to/from the GPS module.

What Arduino model do you use?

Duemilanove with 328

The problem you get is that read() does not wait for a byte to be available, it just returns -1 if there is no byte available; converted as an unsigned byte that becomes 255.
In ISO-8859-1, which I guess is the encoding that your serial monitor is using, 255 translates to ÿ, so this is exactly what you observe.
Fixing this problem is straightforward, just check that a byte is available on SoftwareSerial before reading it:
void loop()
{
    if (GPS.available()) {
        Serial.write(byte(GPS.read()));  //as of Arduino 1.0
    }
}

Thanks, but when i use this method, i receive nothing at all, with all baud rates combination and independent of time passed...

If you receive nothing, that may come from your wiring: voltage level, crossed connections, short-circuit...

Note that in your current code, you don't receive either, as I have explained, if ÿ is the only thing you get, it means your GPS stream never receives anything...


text:
Problem uploading big program to arduino
I have an arduino duemilanove with ATmega328.
Been doing several experiments with multiple peripherals
I had no problem uploading at all
But when i try to upload a big program (27,074 bytes (of a 30,720 byte maximum))
it compiles fine, then says uploading...
After some time passes i get this error
avrdude: stk500_getsync(): not in sync: resp=0x00

The board and serial port connections are fine.
Any ideas?
PS: Then i tried to upload the blink example, but i get the same error for some reason
Everything worked fine before i uploaded my "big" program

The sync error is a common issue that doesn't have one simple solution (as shown here)
It means that the computer can't communicate with the processor, but it recognizes that it's there (out of sync). This is probably due to something (a peripheral, stray wire) interfering with the transmission from computer to device.
Solutions that have worked in the past:

Unplugging the Arduino for 30 seconds, then plugging it back in.
Removing any wires connected to Rx and Tx pins during upload.
Soldering components connected to Rx or Tx to the board (in this case, I was using a shield that allowed me to do this)

There are lots of solutions available from different sources on the internet, but I have not come across one that names program size as the reason.

Removing any wires connected to Rx and Tx pins during upload. This was the issue after all. Thanks!


text:
Are DAC pins useful for anything besides working with audio?
Whenever I run into information about DAC, it seems to be related to audio processing. Are there any other use cases where DAC might be useful, or have any advantages over regular ADC PWM output on an Arduino?

DACs have many uses outside the realm of audio.
Basically a DAC is used any time you want to generate a specific voltage for whatever you need it for - that could be to generate a waveform for audio, or it could be for any other situation, such as:

Setting an offset point for an op-amp
Creating a comparison voltage for comparing another signal to
Controlling the bias voltage of a transistor
Generating a specific reference voltage for an external (or even the internal) ADC

The list goes on.  There are many places you would want to use a DAC.  And why a DAC above PWM? Well basically it boils down to:

Precision - the DAC can generate a more precise voltage than a filtered PWM signal
Noise - the DAC generates a much smoother voltage with better response than filtered PWM which either has switching noise and fast response or less switching noise and delays in voltage level changes.

Thanks. Out of curiosity, would there be any benefits to using DAC for dimming LED bulbs, instead of just using PWM outputs?

No. LEDs work best with PWM.

They are incredibly useful.  They are essentially how you deal with the analog world.
For example, I'm using two of them in a project here that uses a frequency generator and a couple of op-amps to create a VSWR bridge, allowing me to figure out the resonant frequencies of an antenna...  The parts with the arduino cost less than $20... Buying something that does the same thing is about $300!
So, yes, they are very useful. :)


text:
Can I increase the 10 event limit in Simon Monk's Timer library?
On Dr. Monk's library page here, he states: "You can attach up to 10 events to a timer." I am wondering if this is a hardware limit, or if it was an arbitrary number he chose for his library.
In Timer.h, he defines the maximum number of timed events like this:
#define MAX_NUMBER_OF_EVENTS (10)

Can you foresee any problems if I changed that to a higher number? My sketch is already approaching the limit of 10 timed events running at the same time, so it would help me if I was able to increase the maximum number of timed events to about 20.

I don't see anything that would cause any issue. Just don't exceed 255.

Thanks! I'll mark this as the answer if I don't notice any problems by tomorrow. I wonder why he would choose such a low arbitrary number. Even the forked updated versions on github keep the 10 limit.

This is due to memory. The library creates 10 Event objects and stores them in an array. That is at least 11 bytes per object.


text:
Whats the difference between RF options (wifi, xbee, NRF24L01)
When doing RF, you have many options.
Three of the most basic are in the title box

WiFi
Xbee
NRF24L01

What are the practical differences in using them. What is the purpose of each other and the pros and cons. What would you use depending on the application you had?
I do not have a project in mind, but i want to start learning about Rf. I searched ebay for wireless devices. but i couldnt understand the differences. My goal is simply learning

did it (nRF24L01 / RFM12B / RFM22B(SI4432)) work behind the walls because I want to use it inside the water tank

There are many different type of RF networks with various advantages and disadvantages. The main things I consider when choosing a wireless communication method are network topology, data rate and power consumption.
WiFi:
High data rate (54Mbit/s +) but also high power consumption. Used when you need to connect directly to the internet, such as an internet-of-things device, and have an external power source.
XBee:
Low data rate (250kbit/s) and low power consumption. Used to make mesh-type sensor networks; each XBee device can communication with each other, and through each other via the mesh to devices that are out of range. Used for networks of devices, particular home automation and sensors. link.
Bluetooth:
Medium data rate and medium power consumption. IEEE standard has different device profiles to enable interoperability between devices. 'Pairing' type network however, so not useful for sensor networks, but good for controlling devices using a laptop or phone which usually have Bluetooth on board. Communicates with Arduino via serial RX and TX pins. link.
Bluetooth Low Energy, ANT, etc:
Very low data rate and very low power. These RF chips can run for years on an AA battery and so are used for things like heart rate sensors. The data rate is quite low so only good for transferring a small amount of data such as sensor readings. Most devices are setup as peripherals and can only connect to one 'central' device, so no good for sensor networks. Bluetooth low energy is supported by the latest mobile phones and laptops however. Useful to enable control of a device using a phone or laptop, for example a LED lamp. (See redbearlab for some Arduino options)
GSM
Phone connection. TODO
nRF24L01 / RFM12B / RFM22B(SI4432)
Popular proprietary transceivers. They can connect via SPI and have a lot of fancy features like low power modes, multiple channels, channel hopping, frequency calibration, CRC, retransmit and so on. The nRF24L01 from Nordic Semiconductor link operates in the 2.4GHz band, others use the ISM band 433/470/868/915Mhz.
These are todays state of the art highly integrated and low cost hardware for  reliable telemetry and consumer applications. The range is between 10m and 150m. The SI4432/RFM22B has the range of about 1.5Km.
Other RF modules
Simple and cheap serial devices. Single transmitter/receiver or transceiver that operate in the ISM band link. Often used as garage door opener. Useful for sensor network where interoperability with other devices is not required and you can implement your own protocol. link

@bersch Yes, there is so much to put in. Feel like editing the answer with more info? :) This could become a community wiki. What would be the info? Data rate, power consumption, network topology, IEEE standard, interface, protocol, channels, difficulty? BTW do you know any commercial products that use nFR24L01?


text:
Library fails to compile
I want to try out this library:
https://github.com/connornishijima/arduino-volume3
I downloaded the zip file from github, renamed it, and included it as a library in the IDE.
So run one of the examples, A4_440HZ
This is its code:
#include "Volume3.h"
#define speakerPin 9

uint16_t frequency = 440;

void setup() {
  // Nothing neeeded here!
}

void loop() {
  for(uint16_t volume = 0; volume < 1023; volume++){
    vol.tone(speakerPin,frequency,volume);
    delay(1);
  }
  for(uint16_t volume = 1023; volume > 0; volume--){
    vol.tone(speakerPin,frequency,volume);
    delay(1);
  }
}

And i get this error:
Error Compiling
A4_440Hz.cpp.o: In function `loop':
/usr/share/arduino/A4_440Hz.ino:12: undefined reference to `vol'
/usr/share/arduino/A4_440Hz.ino:12: undefined reference to `vol'
/usr/share/arduino/A4_440Hz.ino:16: undefined reference to `vol'
/usr/share/arduino/A4_440Hz.ino:16: undefined reference to `vol'
collect2: error: ld returned 1 exit status

I have no idea what is to blame, or how to mitigate it.
This is the first time that an included example from a library does not play out of the box.

It compiles here. What IDE version are you running?

You could have just installed the library from the library manager in the Arduino IDE.

They are using extern Volume vol; in header file, but there is no definition in cpp, nor in the sketch. The Volume vol; will be needed in your code, I suppose

The second part of that library, the TimerOne uses the same pattern, but it has both the declaration in header file and the definition in cpp file line 41 TimerOne.cpp

@timemage It is 2:1.0.5. It does not have a library manager. Perhaps it is an old version? But i installed it recently. I am using Ubuntu Linux.

@user1584421 Very old and a common problem. In case you're wondering, the 2: is not part of the IDE version. That is part of a Debian style package versioning scheme. What you're looking at is IDE version 1.0.5 from 2013. Debian and Ubuntu could do everyone a favour by removing these packages, but they don't. Unpack (optionally install) from the tarball instead.

This is kind of a weird situation. The library declares the object
vol, but fails to define it. On the ancient version of the Arduino IDE
you are using, compilation fails, understandably, because vol has
never been defined. What is weird is that, on a more recent version
(1.8.15 on Ubuntu here), compilation succeeds.
It is worth noting that vol belongs to the class Volume, which is an
empty class. As such, it only plays the role of a namespace for the
functions vol.tone() and vol.noTone(). Strictly speaking, as vol
has no data (its size is zero), the compiler should never need to access
it. My guess is that the newer Arduino manages to compile this only
because it uses different optimization settings than the ancient 1.0.5.
Anyhow, you have two options:

upgrade your installation of the Arduino IDE

declare Volume vol; near the top of the sketch.

Edit: I did some tests and it appears that, as I suspected, this is
related to link-time optimization (LTO). Since version 1.5.7, the
Arduino IDE enables LTO, and when this is the case, the linker doesn't
complain about missing empty objects.
The library could be fixed by defining vol in Volume3.cpp, although
this would create a weird empty object in the BSS. Another option would
be to declare both methods as static within Volume3.h. This would make
the compiler know it doesn't actually need to reference the vol object
when one of its methods is called.
Would you submit a pull request with one of those fixes?

Thank you! I tried both! The library compiles but no sound is heard. I guess it is an old library.

Same regarding optimizer. To be clear, the code was always incorrect. It is only a question of whether the problem manifests from that.

So if i do your suggestions, will the lib work? Did you manage to make it run? BTW, the last sentence is this targeted to me?

@user1584421: It should work, although I tested only on example code with my host compiler. And yes, the last sentence was a suggestion for you.

Thank you. But inside Volume3.cpp i defined Volume vol;. I then used one of the examples.The library compiled/uploaded but nothing is heard from the speakers.

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


text:
Programming barebones ATMega328 with external programmer and no bootloader
I have created a circuit with a barebones ATMega328.
I also have an external programmer (Sparkfun's Pocket AVR Programmer)...
Now I want to program a particular sketch... When uploading a sketch, do i also have to flash the bootloader beforehand?
Or is it possible to upload the sketch directly to the microcontroller without a bootloader?

The Pocket AVR Programmer is just a standard ISP programmer, meaning it uses the ISP protocol built into the hardware of the microcontroller to write data to flash and EEPROM. That is also the way, that the bootloader got onto the microcontroller in the first place.
The bootloader of the Arduino on the other hand is a small program to communicate over Serial (or USB depending on the Arduino board) and then write the data to flash and EEPROM.
So: No, you don't need the bootloader, if you want to use the ISP programmer. Select your programmer in the corresponding menu of the Arduino IDE to use it.
Though keep in mind, that you won't be able to upload a new sketch via Serial/USB without the bootloader. You can always use the ISP programmer to again write the bootloader to the microcontroller.


text:
OLED on Hardware SPI, on DUE
I want to use an OLED with DUE.
I plan to connect it via hardware SPI.
The Due has a 3X2 pin connector labeled SPI. Is it here where i connect the SCK and MOSI?
If indeed, i connect it here, then which one is SCK and which one is MOSI?
Most importantly, i saw somewhere that in the DUE, hardware digital pin 13 is SCK and pin 11 is MOSI?
Is this true? Because if it is, i can simply hook it up to these pins and get rid of the confusing 3X2 pin connector.

It doesn't look like it's true. There is only one SPI module and it has fixed pins which are not duplicated anywhere.
However there are three instances of USART which can be used in synchronous mode as SPI:

USART0: RXD0(PA10) / TXD0(PA11) / SCK0(PA17)
USART1: RXD1(PA12) / TXD1(PA13) / SCK1(PA16)
USART2: RXD2(PB21) / TXD2(PB20) / SCK2(PB24)

Whole table from SAM3X datasheet:

But I'm not sure if the Arduino IDE supports this mode, or you'll have to do it from scratch by yourself.
You can even use RTS as select slave signal:


text:
Cannot upload to Due
I cannot upload my sketch to my arduino DUE.
I get this error:
Send auto-baud
No device found on COM8
Set binary mode
An error occurred while uploading the sketch

The IDE recognizes thought that port 8 is the DUE programming port. Also i get a response when i press "Get Board Info".
After searching online, i found out it has to do with my baud rate.
So i use the "mode" command in windows and the baud rate is 115200.
So i use this command:
mode com8:1200,n,8,1

When i retype mode, then indeed, COM8 is at 1200 baud.
Then i try to reupload and it fails yet again!
So i retype "mode" and COM8 is back to 115200.
So i think the IDE resets the baud rate to that value.
Any clue on what to do?

1200 baud is only used as a reset trigger when using the native USB port. 115200 baud is correct for uploading. Do you have anything plugged into the board? Did you have anything plugged into the board when it stopped working? Have you tried a manual erase procedure?

My god... Yeah, i had an OLED display. When i removed it it worked!!! I dont know why? This is the pinout i used
#define OLED_MOSI  11   //D1
#define OLED_CLK   12   //D0
#define OLED_DC    9
#define OLED_CS    8
#define OLED_RESET 10
Also another pin to 3.3V and another pin to GND.
Thanks a lot!


text:
How does Arduino IDE for mac deal with functions in other files
I'm a longtime C programmer. I've also done a little C++, a little Java, and a LOT of Objective-C, but am fairly new to the Arduino platform and it's IDE.
So far all my sketches have had a single source file.
I see how you copy libraries into the libraries sub-folder of your Arduino source folder, either from the Mac finder or from the IDE.
I'm trying to understand somebody else's project (The "Camera Axe" device for high speed photography.) in that project there is a folder for the entire sketch, "cameraAxe". In that folder there's a file called "cameraAxe.ino", which follows the usual convention that the sketch's main source file needs to be inside a folder with the same name.
However, for this project there are 17 other source ".ino" files. Looking at the main "cameraAxe.ino" file, it only #includes 2 files, "EEPROM.h" and "DogmCA.h", both using the convention of enclosing the filename in angle brackets so the compiler knows to look in it's libraries directory. That makes perfect sense to me, and works like any other C compiler I've ever seen.
What I DON'T understand is how the compiler knows where to find the code for the many functions that are defined in other files in the same folder. There a function projectileMenu() which handles the menu for configuring a projectile sensor. That function is defined in the file menu01_projectile.ino, but it doesn't have a header, and there's no #include anywhere.
Does the compiler treat all the ".ino" files in your sketch folder as part of your source and compile them all together and as if they are one large file? I see tabs in the IDE for each of the files, which suggests that it does.
What if there are dependencies among the files? What defines the order in which they are compiled? Or is it a 2 pass compiler where the order of function definitions doesn't matter?
::wanders off, muttering in confusion::

arduino has its own little .ino preprocessor that generates forward declarations (like in a header file) for all function in the project's .ino files. Most of the time this just makes things less confusing for new users.
I'm not familiar with the entire process, but the effect is that any function in any .ino is known to all other .ino code.
Anything with .h or .cpp in a library or in the project file is treated as normal c++ code and not subject to arduino's manipulations. It will need "#include"s.
If you are interested, there is a hack to make arduino not mess with a function in a .ino file: add an empty "throw()" like this:
void foo() throw() {
}

Interesting. What about #defines, global variables, typdefs, and things like that that are in secondary .ino files? And can you use .c as well as .cpp as a suffix?

@DuncanC Basically any code that is in another .ino file is as though it was appended to the main .ino file.

In what order though?

I've done a bit of digging and it would appear the order is whatever java's File.list() gives, which is not guaranteed to be anything in particular.

OMG, that's awful. So it is a typical single-pass C compiler where functions and variables have to be declared first before they can be referenced, but the order in which the files are parsed is not defined? It sounds like it handles function declarations through some kind of magic, but what about #defines, global variables, etc?

I know, it does lead to a few weird errors now and then. What I take away is that you cannot guarantee that any #define or global from one ".ino" will or will not be defined in another, just that they all know each-others functions. I usually only use 1 ".ino" file. It is all sent to avr-gcc by the way.


text:
Arduino IDE - Start Serial Monitor once upload is complete
When using the Arduino IDE on Windows (10) is there a way to get it to start the serial monitor automatically when the upload to the board completes?
I know this is a long shot, but pressing those extra 3 keys (CTRL-SHIFT-M) is really bugging me.

You could set up a macro triggered by the completion of the upload that automatically sends ctrl+shift+m. This could be done by watching for the exit of the upload application(AVRDUDE for example) or by calling a wrapper batch file from platform.txt's upload.pattern/program.pattern that runs the upload application and then triggers the Serial Monitor keyboard shortcut. There are a variety of Windows software options for doing this. EventGhost is the one I'm most familiar with but AutoHotkey could likely do it also.
To do it with EventGhost you would either:

Install the Process Watcher plugin and use, for example, the Process.Destroyed.avrdude event to trigger the Serial Monitor keyboard shortcut using the Send Keystrokes action. This will cause false triggers on Burn Bootloader but you can get around that issue by identifying uploads by the compilation application events(such as Process.Destroyed.arduino-builder) that will not occur with Burn Bootloader.
Run EventGhost.exe from the wrapper batch file with the -e command line option to generate the trigger event.

I think the first option is the best because it doesn't require modifying platform.txt, which will need to be redone on every update of any hardware core.
Not exactly what you're asking for, but a much more simple solution is to use Arduino IDE 1.6.5 or newer, which leaves the Serial Monitor open(but disabled) during uploads. This means you only need to load Serial Monitor once. You could have both the Arduino IDE window and the Serial Monitor window tiled on your screen so that you don't need to switch screens to go from editing/uploading your sketch and using Serial Monitor.

thats more complicated then clicking CTRL+SHIFT+M

@canadiancyborg of course it's more complicated. Any solution will be more complicated to initially set up than pressing three keys. Maybe there's a better answer but this is the one I know and have used to automate similar processes related to Arduino development.

OK Three keys doesn't seem so bad now.  I'll keep this because I'm sure I'll find a use for it on another binge of laziness.


text:
Arduino webserver: faster alternative to "indexof" for parsing GET requests?
I have a webserver successfully running on an Arduino Mega, but I'm trying to make sure it's parsing the GET requests in the fastest way possible. This is what the relevant code for the GET requests looks like:
String readString;
EthernetClient client = server.available();
if (client) {
  while (client.connected()) {
    if (client.available()) {
      char c = client.read();

    if (readString.length() < 20) {
      readString += c;
    }
    ...
    ...
      if (readString.indexOf("?a1o") >0){
        mySwitch.send(a1o, 24);
      }
      if (readString.indexOf("?a1c") >0){
        mySwitch.send(a1c, 24);
      }

The sketch checks for 40 possible GET variables. I'm running it as a local webserver with the address: http://192.168.0.180.
-Is there a command faster than "indexOf" that I could be using?
-I saw some information suggesting that sometimes "parseInt" can be faster. Is there any way for me to make that work even though my local base URL is already full of integers? I would be willing to convert the commands into integers (like "11" instead of "a1o") if there was a way to use parseInt or another faster command with it.
Thanks!

Can you post an example of the sort of input you are processing? Is it, perhaps: http://192.168.0.180?a1o or http://192.168.0.180?a1c, or might you have multiple of them on the GET line?

Maybe state what these 40 GET variables are. Is there a pattern? Eg. a1o, a1c, a2o, a2c, a3o, a3c ... ?

yes, that's exactly how it looks: 192.168.0.180?a1o

There's a pattern, but it doesn't have to be that way. Currently it goes: a1o, a1c, a2o, a2c, etc until a5o, a5c. Then it starts: b1o, b1c, etc. ('o' stands for 'open' and 'c' stands for 'close', it's opening and closing different wireless outlets). I would have no problem though renaming them all, like just giving them all numbers or a clear pattern, if there was a way to make it parse faster.

Extract the query string once, and store it in a variable. Next test whether this variable is 'a1o' or 'a1c', etc. Using switch-case would be faster than a whole list of if statements.

Thanks Gerben! I will try using Gammon's code below, but with the addition of using your advice about the switch-case.

I know it is very old post but can you please show how to parse POST method with your code?
It should be very useful for beginners like me :-)
Thank you so much!
PPT

Well, for fast parsing I wouldn't use String for a start. I've written an example (below) which does away with the String class, and also demonstrates parsing the line once.
#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address and IP address for your controller below.
byte mac[] = {  0xB3, 0x8D, 0x72, 0x1D, 0xCE, 0x91 };

// Our IP address
IPAddress ip(10,0,0,241);

// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(80);

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

  // start the Ethernet connection and the server:
  Ethernet.begin(mac, ip);
  server.begin();
  Serial.print(F("Server is at "));
  Serial.println(Ethernet.localIP());
  }  // end of setup

// how much serial data we expect before a newline
const unsigned int MAX_INPUT = 100;
// the maximum length of paramters we accept
const int MAX_PARAM = 10;

// Example GET line: GET /?foo=bar HTTP/1.1
void processGet (const char * data)
  {
  // find where the parameters start
  const char * paramsPos = strchr (data, '?');
  if (paramsPos == NULL)
    return;  // no parameters
  // find the trailing space
  const char * spacePos = strchr (paramsPos, ' ');
  if (spacePos == NULL)
    return;  // no space found
  // work out how long the parameters are
  int paramLength = spacePos - paramsPos - 1;
  // see if too long
  if (paramLength >= MAX_PARAM)
    return;  // too long for us
  // copy parameters into a buffer
  char param [MAX_PARAM];
  memcpy (param, paramsPos + 1, paramLength);  // skip the "?"
  param [paramLength] = 0;  // null terminator

  // do things depending on argument (GET parameters)

  if (strcmp (param, "foo") == 0)
    Serial.println (F("Activating foo"));
  else if (strcmp (param, "bar") == 0)
    Serial.println (F("Activating bar"));

  }  // end of processGet

// here to process incoming serial data after a terminator received
void processData (const char * data)
  {
  Serial.println (data);
  if (strlen (data) < 4)
    return;

  if (memcmp (data, "GET ", 4) == 0)
    processGet (&data [4]);
  }  // end of processData

bool processIncomingByte (const byte inByte)
  {
  static char input_line [MAX_INPUT];
  static unsigned int input_pos = 0;
  switch (inByte)
    {
    case '\n':   // end of text
      input_line [input_pos] = 0;  // terminating null byte
      if (input_pos == 0)
        return true;   // got blank line
      // terminator reached! process input_line here ...
      processData (input_line);
      // reset buffer for next time
      input_pos = 0;
      break;

    case '\r':   // discard carriage return
      break;

    default:
      // keep adding if not full ... allow for terminating null byte
      if (input_pos < (MAX_INPUT - 1))
        input_line [input_pos++] = inByte;
      break;
    }  // end of switch
  return false;    // don't have a blank line yet
  } // end of processIncomingByte

void loop()
  {
  // listen for incoming clients
  EthernetClient client = server.available();
  if (client)
    {
    Serial.println(F("Client connected"));
    // an http request ends with a blank line
    boolean done = false;
    while (client.connected() && !done)
      {
      while (client.available () > 0 && !done)
        done = processIncomingByte (client.read ());
      }  // end of while client connected

    // send a standard http response header
    client.println(F("HTTP/1.1 200 OK"));
    client.println(F("Content-Type: text/html"));
    client.println(F("Connection: close"));  // close after completion of the response
    client.println();   // end of HTTP header
    client.println(F("<!DOCTYPE HTML>"));
    client.println(F(""));
    client.println(F(""));
    client.println(F("<title>Test page</title>"));
    client.println(F(""));
    client.println(F(""));
    client.println(F("
My web page
"));
    client.println(F("
Requested actions performed"));
    client.println(F(""));
    client.println(F(""));

    // give the web browser time to receive the data
    delay(10);
    // close the connection:
    client.stop();
    Serial.println(F("Client disconnected"));
  }  // end of got a new client
}  // end of loop

The incoming lines from the client are captured in a static buffer. This eliminates issues with memory fragmentation (caused by using String).
processIncomingByte is called for each byte from the client. Once an entire line is assembled it calls processData. If that finds a "GET " line it calls processGet. That looks for the parameters on the GET line. The GET line looks like this:
GET /?bar HTTP/1.1

So we need to get between the "?" and the next space, to get the parameter ("bar" in this case). This can be accomplished by finding their positions with strchr.
Finally (as a simple example) I tested with strcmp for a direct match on various words. You could probably make that more efficient but I doubt it would matter much.

I just implemented these changes, and it's noticeably a TON faster!!!!! I'm so happy with this! Thanks a lot for the help!

I converted all my GET parameters into integers so that I could use a switch-case. I converted "param" into an integer like this:   param2 = atoi(param); and then I did "switch(param2);". Can you please tell me if this is a bad way of doing things? Thanks.

That's fine, it will give you a slight speed increase. If you liked my answer please "accept" it by clicking the tick mark next to it. This lets other users know that the answer was helpful. Thanks!

Thanks! JSYK how much faster your code was: beforehand it took 2-3 seconds after clicking the web link before the wireless switches would get activated. Now it only takes 200-300 ms. This is very useful to me.


text:
Arduino Mega PWM pins stop working for LEDs once servo is attached?
I can get LEDs to fade properly using PWM on pins 44-46 on the Mega2560 when I don't have a servo attached, but once I "attach" the servo in the code, then PWM pins 44-46 don't work for PWM. They can still work with digitalWrite, but not with analogWrite.
This is the code:
#include <Servo.h>
Servo myservo;
int led = 46;

void setup()  {
  myservo.attach(3);
  pinMode(led, OUTPUT);
  analogWrite(led, 60);
}

void loop()  {}

If I comment out the "myservo.attach(3);" line, then PWM works for the LED pin. Otherwise the LED stays off. Why would PWM on pins 44-46 stop working once the servo is attached?

Wanted to add: I just tested it on an earlier PWM pin (12), and the PWM worked fine even when the servo was attached. It seems that only 44-46 are having problems.

Looks like the mega has some clever servo handling features. Servo control always uses a timer of some sort and can conflict with the pwm timer. The first 12 servos knock out pins 44,45,46 ...

For Arduino Mega it is a bit more difficult. The timer needed depends on the number of servos. Each timer can handle 12 servos. For the first 12 servos timer 5 will be used (losing PWM on Pin 44,45,46). For 24 Servos timer 5 and 1 will be used (losing PWM on Pin 11,12,44,45,46).. For 36 servos timer 5, 1 and 3 will be used (losing PWM on Pin 2,3,5,11,12,44,45,46).. For 48 servos all 16bit timers 5,1,3 and 4 will be used (losing all PWM pins).

Wow, great find!! Thanks so much for the help! I already had switched to using pins 11-13 for the PWM, but I was still interested in learning the answer.


text:
Append Text to Variable Names: Please Help Me Shorten This Code
I'm trying to shorten the code under "setup" below, where I have over 120 variables that are being read from an external EEPROM. There is a pattern where the variable that stores the position of the EEPROM address is the name of the variable being populated, plus the word "Pos".
byte fanSpeed, nl1Toggle, ledsToggle;
byte fanSpeedPos = 12, nl1TogglePos = 95, ledsTogglePos = 7;

void setup() {
  fanSpeed = readEE(fanSpeedPos);
  nl1Toggle = readEE(nl1TogglePos);
  ledsToggle = readEE(ledsTogglePos);
  //there are over 120 of the above readEE statements in the actual code.
}

uint8_t readEE(uint8_t entry) {
  readEEPROM(AT24C32_ADDRESS, 1, entry);
}

Ideally I would like it to work like this (I'm using pseudo code because I don't know how to do this):
char* variableNames [] = { "fanSpeed", "nl1Toggle", "ledsToggle" };
byte fanSpeedPos = 12, nl1TogglePos = 95, ledsTogglePos = 7;

void setup() {
  for (int i = 1; i < 120; i++;) {
    variableNames[i] = readEE(variableNames[i] + 'Pos');
  }

Is this possible using C++ / Arduino?

Copy the EEPROM variable into RAM (ie. into a character array). Then use strcat to append your word to the end of it. Allow enough room for the finished words, and the terminating 0x00 byte.

This can be achieved with a simple preprocessor macro:
#define readEE(VAR) VAR = readEEPROM(AT24C32_ADDRESS, 1, VAR ## Pos)

You can then use:
readEE(foo);

and it will be expanded out to:
foo = readEEPROM(AT24C32_ADDRESS, 1, fooPos);

The ## operator in macros expands out both sides (VAR and Pos) and then concatenates the results together. Since VAR itself is a macro (whatever you pass when you call the macro) it gets replaced with that value, but Pos, because it isn't a macro, just stays as Pos. So you end up with your variable name concatenated with the word Pos.
Note that you can't use that in a loop with variable names in an array - simply because variable names only exist in the source code, not in the compiled code, so you can't do anything with those variable names once the code is compiled.  Hence you have to use the preprocessor to do the job.
Yes, it means you still have to write 120 lines of code for all 120 variables, but they are just shortened to readEE(varname);.
However a better solution is to either use Mikael's struct method, or to just use an array and think differently about the concept of names:
uint8_t data[120];
for (int i = 0; i < 120; i++) {
    data[i] = readEEPROM(AT24C32_ADDRESS, 1, i);
);

So now all your variable values are in the data[] array, and you just need to know, in your program, which value is which - and you can do that by defining names for each position as preprocessor macros:
#define FAN_SPEED 12
#define N1_TOGGLE 95
#define LEDS_TOGGLE 7

Then use those macros in place of the numbers:
Serial.println(data[FAN_SPEED]);

Alternatively you could use the macros to "mask" variable names:
#define fanSpeed data[12]
#define n1Toggle data[95]
#define ledsToggle data[7]

There is one thing you might have noticed though: Nothing here shortens your code, it just moves things around a bit. Let's face it - you have 120 variables stored in 120 locations. Whatever you do you're still going to have to have 120 pointers of some form to those variables and their locations. All you can really do is choose the method that provides the most readability so that someone else looking at your code can understand what is going on. Whatever you do you have a long list of variables or variable names to define or set up, which means a lot of typing.

The preprocessor solution is really nice - did not think of that :).

Thanks so much for the concise "big picture" overview. I loved learning about all of the methods. I think my first try will be with the preprocessor macro, since that shortens/simplifies the code (which was my main purpose), without changing the way the variables are written to or named. I would have to modify hundreds of lines of code if I changed the way the variables are stored, which I might experiment with if I have time/ambition in the future.

I just added the preprocessor solution to my code, and it worked beautifully without a hitch. It was really a very ideal solution to the problem. Thanks.

variableNames[i] = readEE(variableNames[i] + 'Pos');

Is this possible using C++ / Arduino?

No! Very few programming languages allow that as it requires a lot of run-time information.
Let us instead revisit you issue; Load a large set of variables from EEPROM. What mechanisms do we have in C/C++ and AVR library that could help with this?
Here is a really simple solution that results in a "one-liner"; eeprom_read_block().
struct var_t {
  byte fanSpeed, nl1Toggle, ledsToggle;
};
var_t var;
const void* pos = ...;
eeprom_read_block(&var, pos, sizeof(var));

Obviously var_t and var are not very good names (and you will have to come up with something better) and this is for the internal EEPROM but the same technique can be used for the I2C EEPROM.
Cheers!
BW: What AT24CXXX library are you using? Because this looks strange.
 uint8_t readEE(uint8_t entry) {
   readEEPROM(AT24C32_ADDRESS, 1, entry);
 }

No return statement, etc.

Thanks for the answer! This stuff is a little too complex for me, so I have some studying to do before it becomes more clear (same for @Nick Gammon's comment too, which I have to study more about). The AT24CXXX is on a DS3231 RTC board, and I think I had to look through some of the less common DS3231 libraries to find one that would work with the Due (it was easy to find ones that worked with the ATmegas). The code I used is located here: https://github.com/kriswiner/DS3231RTC. I think I still had to make some modifications to get it to work on the Due, but I don't remember exactly.


text:
Signal sampling: losing data every 103 points when it is recorded in SD
I'm working on a system of acquisition and ECG datalogging with the Arduino, and I'm having the following problem:
I'm losing data every 103 points (just 103). No matter the sampling frequency to use, every 103 points, some points are lost, damaging the signal sampling.
It could be the recording time on the SD card, but even when the SD.close () command is run only once, the data is lost.
Here is a simple test algorithm with a 100 Hz sine wave at the entrance.

#include <SD.h>
#include <SPI.h>

int CS = 4;
int ECG_PIN = 1;
int voltage;

int index = 0;
const int bufferSize = 5;
int vetor[bufferSize];
int RECORD_TIME = 20000;
File logFile;

void setup(){
  pinMode(CS, OUTPUT);
  pinMode(ECG_PIN,INPUT);

  if(!SD.begin(CS)){
    return;
  }
  logFile = SD.open("ECG_log.txt", O_CREAT | O_WRITE);

}

void loop(){
  while(millis() <= RECORD_TIME){

      voltage = analogRead(ECG_PIN);
    if(logFile){

       logFile.println(voltage);

       delay(0.5);
    }
  }
  logFile.close();
}

What could it be? Speed analogRead ()? Problem on the SD card?
Sorry if the question is very basic, I am beginner, in a way, the Arduino platform. Any help will be very welcome.
Thanks!...

It's all to do with writing to the SD card.
You have a buffer of 512 bytes which is one "block" of the SD card.  When you have written to the card enough to fill that buffer up it has to write that buffer to the SD card and empty the buffer so you can start filling it again.
That writing to the SD card takes time - lots and lots of time (relatively), and it can't be doing anything else at the same time as writing to the SD card.
The only way you can get around that is to have your sampling performed within an interrupt - maybe a timer interrupt - so that it can interrupt the writing to the SD card.  However, that's not a simple task.
You would need to implement a system known as ping-pong buffers.  You have a pair of buffers for storing incoming samples within your interrupt routine.  When one buffer is filled up you switch to the other buffer and signal to your main loop() routine that you have filled the buffer.  It's then the job of loop() to save that buffer to the SD card and empty it ready for when the second buffer has been filled up.  The name ping-pong comes from the game of table tennis (also known as ping-pong) as you are switching from one buffer to the other and back again in a constant backwards-and-forwards motion like the ball in a game of table tennis.
Getting the right size of buffers is also critical.  You have to ensure that the time taken to fill one buffer is always going to be longer than the longest amount of time it takes to write a buffer to the SD card, including any flushing of the internal SD card buffer.  The best size is probably going to be to match that internal SD card buffer so every ping or pong you will be doing an entire SD card block's worth of data - so 512 bytes.
That means you have 3 buffers of 512 bytes - your two ping-pong buffers and the SD card's buffer, which is 1536 bytes - not far off the limit of an Uno, so you may struggle with that.  For this kind of thing it is better to use one of the boards with a more meaty chip, like the Mega2560.
Also the line:
delay(0.5);

is meaningless.  delay() takes an integer value, so 0.anything is actually truncated to 0.  To delay for less than a millisecond you should use delayMicroseconds().

Thank you for quick and didatic response, @Majenko.
I've been having insufficient memory problems with the Uno from the start of the project. I will purchase a Mega as soon as possible.
I got the idea of ping pong buffer, but still can not understand how to put it in the form of code. Could you point me some material or program as a reference?
Thank you very much.

I don't have any examples online at the moment. It's simple enough - 2 buffers, 2 flags. One flag says which buffer is being filled at the moment, the other flag is used to indicate that a buffer is ready for writing. When the writing flag is set loop() notices it, writes out the non-filling buffer by checking the first flag, and clears the second flag. When you have filled a buffer you set or clear the filling flag and set the writing (ready-to-empty) flag.

512 bytes divided by 5 bytes per datapoint (three digits + carriage return + newline) = 102.4 (rounds up to 103)

@Gerben What a coincidence ;)


text:
Arduino LCD Simple Problem
Hi my lcd doesnt display that i was expected. Can anyone help me???
RS-->22
RW-->GROUND
E-->23
D4-->24
D5-->25
D6-->26
D7-->27
    #include <LiquidCrystal.h>

LiquidCrystal lcd(22, 23, 24, 25, 26, 27);
void setup() {

lcd.begin(16,2);

lcd.setCursor(0,1);
lcd.print("Hello!");
delay(1000);
}
void loop() {
lcd.setCursor(0,1);
lcd.print(millis()/1000);
}

Have you tried turning the trim pot? It could be a contrast issue

yes. i add lcd clear commant and shakes the cables and the problem is solved!

I Had a similar problem with a different display, It looks like you are printing the value without clearing the display so all the numbers print on top of each other creating those squares. try adding lcd.clear() in the loop to clear the display before it prints another value.


text:
Arduino timers. How they work
Explain this line in simple words.
TCCR0B=TCCR0B&0b11111000|0x01;

As the variuos arduinos have different chips. They also have different timers and different pins which use them.
Lately i want to rewrite a code(Arduino Uno) to make it work on a Arduino Micro.
I need to understand how this works in simple words. I normally write web based code(javascript,php...). Just lately i started writing in c++ or a "simplified" c++ in the arduino ide. It's not that hard. But some specific parameters are hard to understand for me.
Shortcuts like the following.
TCCR0B=TCCR0B&0b11111000|0x01;

What does that?
TCCR0B

TCCR = Prefix for timers. Correct?
0 = Timer1 or 0 call it however you want.
B = What is A,B,C and sometimes D for? What does this?why in that code is the programmer using B and not A,C or D
TCCR0B= Timer 0 B is equal to:
TCCR0B& if Timer 0 B return True .. exists "&" ?
0b11111000 What is this? i already asked this and the answer was something like "clears the low-order 3 bits". Like i said, i'm not very familiar with c++, bits and other stuff regarding the arduino. I now less about the various chips and also about how they implemented the various parameters from arduino ide to work with those chips. I know that i have here 8 values that i can change from 0 to 1. What does those values change relative to the timer. Please think of me as a 6 year old.
|0x01; I got this... it sets the prescaler... 1,8,32.. some timers have differnet values... no problem. I need it at 1.

Related question: http://arduino.stackexchange.com/questions/14298/arduino-uno-vs-arduino-micro-timers-pins/

i already asked this and the answer was something like "clears the low-order 3 bits". Like i said, i'm not very familiar with c++, bits and other stuff regarding the arduino. - OK, you don't understand what "clear the low-order 3 bits" does. Then in another comment you say: This part is actually easy to understand for me as i work alot with coding language. also you can find easely online hex to decimal converters and so on. It isn't clear what you are asking. First you say you aren't familiar with C++ bits, then you say that's not what you are asking.

i needed a simple explaination about what those 3 bits and the other 7 bit change. I also didn't know what ABCD's that are appended to the TCCR0 are for. Those are different registers of 8 bit each. On probably all arduino to change the prescaler you only need the register B. the last 3 bits. those change the multipler. "TCCR0B=TCCR0B&0b11111000|0x01;" this line: timer 0 register B is reset and newly set to 1.Appropriate timers for the arduino micro vs the uno are pin 9,10,12 ... all use timer4 register b...and i need to change the last bits

in your really nice, but to complex answer for me, i cant read that. You don't explain that those 0b11111000 last 3 bits are to reset the timer. you also don't explain what abcd means. then as i asked you more you told me to write a new question.. i did. you got the +1 and the correct answer.

Both Majenko and I posted an excerpt from the datasheet showing what each of the 8 bits in TCCR0B mean. If i don't know what i'm looking for i can't properly consult a 438 pages datasheet. - you look at the part for Timer 1 (or Timer 2 etc.) which is only a few pages. Then you look at the page describing TCCR0B. That describes each of those 8 bits. Each bit has a name (eg. WGMC13, CS10). Underneath the text in the datasheets explains what those bits do. The libraries on the Arduino are to help people write code without reading datasheets. If you want to go further, you have to read them.

i looked the datasheet various times , it's like looking at hyroglyphs. so showing me a part of the hyroglyphs does not the solve problem. i have already dificulties writing and reading everything in english. I need Simple explainations. @Majenko , as he saw that i did not undertsand opened a chat and explained me that those 3 bits are the same bits that change the prescaler... those 3 bits are probably always in the register B of the timer N.those 3 bits needed to be reset than you can change them to whatever you want again.

Let us continue this discussion in chat.

chat!chat!chat!

i tought those... 3 bits change something different somewhere and that A B C & D is some sort of subset of the timer... now it's clear... ABCD is the "memory" of each timer that contains all the various settings... only the 3 bits in memory B change the prescaler. now that i know that also your answer is alot clearer.much clearer than the actual datasheet... they should rewrite the datasheet...

TCCR0B=TCCR0B&0b11111000|0x01; is inscrutable w/o datasheet.  Searching the UNO's ATmega328P datasheet at  https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf for "TCCR0B" has 8 matches, one for section "14.9.2 TCCR0B – Timer/Counter Control Register B" that explains each of the bits, similar to TCCR0B on Micro's ATmega32U https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7766-8-bit-AVR-ATmega16U4-32U4_Datasheet.pdf . I'd write the clear/set TCCR0B=(TCCR0B & 0b11111000) | 0b001; There's TCCR0A and TCCR0B controlling Timer 0.

First I'll tackle what
TCCR0B=TCCR0B&0b11111000|0x01;

means from a pure programming perspective:
Let's break it down into parts:
TCCR0B = TCCR0B & 0b11111000 | 0x01;

TCCR0B is a register. It could be any variable really - it's just "a value" in this context. Just because it happens to control one of the timers is besides the point.
0b11111000 is a binary representation of a value.  It's the same as the hexadecimal number 0xF8.  F is 15.  15 in binary is 1111.  8 is 8 in both hexadecimal and decimal.  8 in binary is 1000.  Put the two together and you have 11111000.  Incidentally, in decimal that is 248.
0x01 is hexadecimal for 1 in decimal - it's also 1 in binary.
Between them are bitwise operators - & is a bitwise AND operation, and | is a bitwise OR operation.  AND calculates which bits in a pair of binary numbers are both on, and OR calculates which bits in a pair of binary numbers are on in either of the numbers.
So take the first one first.  Say the TCCR0B register contains the value 0x6F, which is 157 in decimal, or 01101111 in binary.  The first operation is to AND that with 11111000:
01101111
11111000 AND
--------
01101000

You can see that the last three bits of the value have been cleared because they aren't 1 in both the left and right operands to the & operator.
Ok, so the next operation is to OR it with 0x01:
01101000
00000001 OR
--------
01101001

Effectively the two operands have been overlaid on each other and any bits that are set in either operand will be reflected in the result.
So finally the value is then stored in TCCR0B.
In summary that specific operation clears the lower three bits then sets the lowest bit of TCCR0B.
Now what that actually means with respect to what the TCCR0B register does can be gleaned from the datasheet for the chip.  For instance, take the ATMega328P chip from the Arduino UNO board.  Section 14.9.2 "TCCR0B – Timer/Counter Control Register B" of the datasheet describes that register in detail.  The bit-wise overview looks like this:

Those bits all correspond 1:1 to the binary bits from above in the same order.  So the first stage, clearing of the lowest three bits, sets CS02, CS01 and CS00 to 0.  The second stage, ORing 0x01, then sets CS00 to 1.
The datasheet goes on to tell you what those mean:

Bits 2:0 – CS02:0: Clock Select

The three Clock Select bits select the clock source to be used by the Timer/Counter.

And a table to show the different meanings of the possible values:

The value that has been masked and created for those three bits is, of course, 001, which in that table is "CLK I/O / (No prescaling)", which is the timer running at the frequency of the IO clock.  If you were to set those bits to 010, you'd get "CLK I/O / 8 (From prescaler)".  So your masking would change to:
TCCR0B = TCCR0B & 0b11111000 | 0x02;

Or more explicitly so you can see the bits easier:
TCCR0B = TCCR0B & 0b11111000 | 0b010;

As to what the "A" and "B" mean (TCCR0A and TCCR0B), there are two registers that are used to control the timer.  They each serve a different purpose.  TCCR0A has bits that control PWM, and TCCR0B has bits that control the timer itself.
Not to be confused with OCR0A and OCR0B which are two separate numeric values that are compared to the timer's counter value TCNT0 to provide two separate PWM outputs (OC0A as Uno pin D6, and OC0B as Uno pin D5) synchronised from the same timebase. (See sections 14.9.4 OCR0A – Output Compare Register A and 14.9.4 OCR0B – Output Compare Register B in the datasheet)

Actually i'm trying to get exactly not that as an answer.I need the part you skipped. This part is actually easy to understand for me as i work alot with coding language. also you can find easely online hex to decimal converters and so on. My question is what that line actually does in simple words. If i don't know what i'm looking for i can't properly consult a 438 pages datasheet. All i know is i need to set a timer to a prescaler of 1. Understanding whats the difference between TCCR1A,TCCR1B,TCCR1C or what those 8bit (0b11111000) represent.

Consider this.. i know nothing. i can code. "TCCR is just a value" you said. Why can't i just write: "Timer1 setPrescaler 1". Why do i need to write "Timer1b dosomething or set to 1"

If i knew where to look in the datasheet i would not be here. All i know is i need to change the prescaler of various pins of various timers of various chips of various boards. And now they are all different.

At the other side. if i would like an answer like this i would ask in stackoverflow and not here. It's an Arduino specific question.

In the datasheet, select "8-bit Timer/Counter0 with PWM" or whatever it's called for your chip.  Then select "Register Description", then "TCCR0B" and it tells you what each bit means.  In the 328p datasheet that's section 14.9.2 on page 109. Indexes are wonderful things.

@cocco On the other-other side, since this has nothing specific to do with Arduino, and is in fact about the ATMega chips that are on them, you would really ask this question on Electronics.SE.  Most people who land here lack the basic programming skills to understand the bitwise operations, hence that is the answer given here - it is an answer for Arduino users, whereas you sound more like you may be looking for an EE answer.

Sorry i didnt mean to be bad... but: those sites are made to simplify the life of people. i'm registered on various stack sites, i answered more questions that i asked. i write code since alot of years now. not c++ in simple javascript php and others... understanding this language is easy for me as it uses almost the same syntax as javascript or php... at the end they are almost the same. i know the bitwise oerators even if they are slightly different in js/php. Each language has it's own function reference. The arduino reference is limited and does not properly describe each function

The quesiton is very specific. It talks about Arduinos. the point is each individual arduino has differences, depends on the chip. I can't find the "Register Description".

The Arduino site only really talks about the Arduino specific API functions, not the underlying language, which is C++.  For anything that isn't specific to the Arduino standard C and C++ tutorials and references should be used (though they don't mention that).  Things like the bitwise operators are standard C so don't get explained properly on the Arduino site.

but also i don't get the difference between TCCR0A,TCCR0B,TCCR0C you said it... they are all the same timer.. so why is there a difference between those values.?

TCCR0A = not arduino specific? not c++?

So basically your saying that TCCR0A is not arduino specific but more Atmel specific? if so tell me where to go to ask this question.

Let us continue this discussion in chat.

i'm in chat if you want

It's specific to the chip that is on the Arduino. Arduino don't make the chip, they just buy them from Atmel.  It's Atmel that defines the registers and what they do.  I have expanded the answer with information about the registers from the datasheet and how to interpret it.

To add to Majenko's very thorough and excellent answer (which I can't yet upvote because I'm very newbie):
Let's try to hone in on the line of code you need:
TCCR0B=TCCR0B&0b11111000|0x01;

On that particular Ardiuno, TCCR0B is the register that controls the rate of that particular timer. More specifically, the lowest 3 bits (the last in the 8-bit value) control the prescaler. The manufacturer labels those as CS02, CS01, and CS00. The combination of 1s and 0s in those three bits determines if the clock time is scaled or not, and by how much (or even if there is an external clock source). The reproduced table 14-9 will tell you how much the clock is "slowed down". This lets you create a 1Hz (1-second) timer, for example, rather than the 16Mhz (or whatever your particular board runs at) by scaling down how fast the timer "ticks".
If you google "Arduino hardware timer calculator" or similar, you can find very helpful tools to help you set the clock frequency you want. Do that, since there are dangers to setting the wrong values, and your compiler may not catch what can be a serious error.
I only learned about hardware timers after exploring Arduino for a few years. Turns out they are very, very useful!

The answer, at high level, is: each bit (or group of bits) in a register is, in practice, like a knob that can configure certain parts of the HW.
For each peripheral you want to control, you have to understand the block diagrams, the related knobs and in which registers those knobs are located.
Sometimes there are multiple (almost) identical instances of a certain HW block and in the ATMega case these instances are often addressed with letters.
So registers that have almost identical names, apart from A, B, C, are basically identical, but each of them will affect a separate instance of a certain peripheral.
Depending on which pins or interrupt you want to use, you can choose the specific instance of a certain peripheral.
You should check the ATMega328p programmer's manual (it's 2k pages, but it's easy to find the desired section.)

I understand your question is not about c++ and bit manipulation.
It's not about "Arduino" neither, because your code line does only make sense for a certain avr microcontroller with a register named TCCR0B.
Sure, some arduinos are based on such microcontrollers and the c++ compiler used in the arduino toolchain allows access to those hardware registers via their names used in the datasheets.
Details however are beyond "Arduino" and should be looked up in the corresponding controller datasheet.


text:
Using an arduino to emulate keyboard inputs
I have a shapeoko 2, and have been wanting to create a jogging pendant for it for a while.  Currently GRBL (the G code interpreter for arduino) doesn't support jogging the machine with a pendant.  I was wondering if it was possible to emulate arrow key inputs on the keyboard through an arduino.

Pretend, for a moment, that we don't know what a "shapeoko 2" is, or even what jogging a machine with a pendant entails.  Instead focus on exactly what you want to achieve from the Arduino in a more generic form.

Your answers might lie in the Arduino reference pages: https://www.arduino.cc/en/Reference/MouseKeyboard https://www.arduino.cc/en/Reference/KeyboardModifiers

Every arduino with programmable USB chip like Arduino Uno or Arduino Mega is capable of emulating any USB device.


text:
How to use the additional SPIs on Arduino Due
According to the following image it is possible to use a second SPI bus on the Arduino Due by using Serial1 and SCL1 as SCK0 for SPI (or Serial2 and SCK1).

source
However I did not find the code necessary to set up the additional SPI interfaces. I would prefer using these SPI interfaces as they are accessible on the stacking headers in contrast to the default SPI.
Additionally can a SD-Card be accessed using these SPI buses while still using the corresponding Arduino Library?

Have you quantified how harder it would be to not use the library?

I think the information you are looking for can be found at https://www.arduino.cc/en/Reference/DueExtendedSPI
There are two other alternatives that I can see: if your device supports slave select (which I think they are supposed to), then you can use a different pin to select either device 1 or device 2 (or 3...).
The other options is that if you can connect the clock to only one slave at a time (again, with another pin), you should get the same result - you should be able to use a MOSFET between the Arduino's clock-out and the slave's clock-in, and hook the MOSFET's gate to a spare pin; repeat the procedure, using a separate MOSFET, connected to a different spare pin, to the second slave; then bring one or the other "spare pin" high, to select which way the clock goes. If a slave does not receive a clock, it will not listen for incoming signal. This last one I dreamed up; I don't know if it will work.


text:
How to differentiate between 2 Micros on Linux
I have 2 Arduino Micro based devices that I want to use on my Ubuntu Linux machine.  I need them to have unique serial ports.  Unfortunately, both have the same serial number which makes identification through udev rules difficult (if not impossible).
This is the serial number that I get for both:
$ udevadm info -a -p  $(udevadm info -q path -n /dev/ttyACM0) | grep -i serial
  ATTRS{serial}=="0000:00:14.0"

Is there any way to manually set the serial number on an Arduino Micro?  Or is there any other unique identifying properties I can use for udev rules?
Typically, I do something like this in my /etc/udev/rules.d/99-usb-serial.rules file:
SUBSYSTEM=="tty", ATTRS{product}=="Arduino Uno", ATTRS{serial}=="64936333936351911191", SYMLINK+="MyDevice"

Side note: I also have a Due, that has the same serial number as the Micros, but since ATTRS{product} is different, I can differentiate it.

The USB VID, PID and Serial Number are all programmed into the chip when you upload your sketch.  The VID and PID are tied to the board, and the serial number is always the same regardless of which board.
So no matter which board you program it will get the same details as any other board of the same kind.
There's no option to change the serial number (there is, IIRC, actually no serial number defined) but the VID and PID are provided as a pair of macros on the compilation command line: USB_VID and USB_PID.
So you could (cheakily) create a new board definition (based on the existing Micro one) that is "The other Micro" and provide a different (unofficial) PID to that board.  You can then differentiate the two boards in udev using the VID/PID combination.
Of course, you have to then ensure that you have the right board selected when you program them, and the act of entering the bootloader on the "other" board would revert back to the old PID which is programmed into the bootloader, but I'm sure you can cope with that.

That "0000:00:14.0" isn't the serial number for the Arduino: udevadm is printing info for more than one device, and that's for the USB controller chip.
Arduinos built on the ATMEGA32U4 don't get a serial number: I have some Leonardos giving me the same problem you're having. When the bootloader was originally designed, the programmer didn't have it report one. I found a modified bootloader that does, but I haven't tried it yet: http://forum.arduino.cc/index.php?topic=503703.0
Genuine Arduinos with an FTDI chip report unique serial numbers. Some of the knock-offs either don't set it in the chip, or may set it to some non-unique number(skipping that step to save a  few cents of manufacturing cost). Ones that use a 16U2 chip for the USB interface (like the Uno R3) are supposed to get a unique serial number. The Chinese ones I just bought did, but it's possible that other makers of them are cutting corners like some users of FTDI chips do.
Arduinos that use the Chinese CH340 USB chip also don't report a serial number: the chip doesn't support it. I think that's also true for the CP2102, but I'm not certain.
You may be able to fix the problem with that modified bootloader (I hope so: I have half-a-dozen Leonardos, and it's a hassle anytime I have more than one connected simultaneously. Fortunately, I don't normally use them as "PC peripherals"). Or you could buy another of the "tiny" Arduinos with a 328P that uses a USB-to-serial chip, and base the udev rules on VID and PID to distinguish them.


text:
Unable to program with AVR ISP mkII under Linux
I just got an AVR ASP mkII external programmer and I am unsuccessfully trying to program my arduino with it.
All the settings in the IDE are correct. This is the error message that I am getting:
avrdude: usbdev_open(): cannot open device: Permission denied
Typing lsusb in a terminal, I am able to see the programmer.
Bus 001 Device 007: ID 03eb:2104 Atmel Corp. AVR ISP mkII

Do you have a udev rules for it (for example from platformio)? Is it working under root?

@KIIV I just opened the Arduino IDE from the Gnome GUI. Therefore I am guessing it is not root. As for udev.... I don't know much about it and I haven't touched it.

Does this answer your question? Arduino IDE Permision Denied For Upload, Ubuntu

@thebusybee the AVRISPmkII does not create tty device. So closing as a duplicate of that question won't help.

Please [edit] your question and add the command used for avrdude. You might need to enable the verbose output of the upload process in the preferences.

@thebusybee I am not explicitly using avrdude. I am using the AVR IDE, and I select "upload using external programmer".


text:
Perform Volume Control on arduino speaker
I am following this guide to produce tones with the arduino:
https://www.arduino.cc/en/Tutorial/BuiltInExamples/toneMelody
This uses the tone() builtin function. The connections is that one pin of the speaker got to one digital pin of the arduino, while the other goes to ground.
Is there a way to perform volume control (perhaps with a potentiometer) on this setup?
What worries me is that this is digital information (PWM) that goes to the speaker, and not an analog signal that can be adjusted.

one option: https://github.com/teckel12/arduino-toneac/blob/master/README.creole

@Juraj Thanks! I used this but unfortunately the sound quality is not as good as the original tone() function. In addition to that, when the sound was at the lowest, i could hear i clicking sound when every not was heard. However, i went back to the original tone() function and that clicking sound existed, however it was not as easily identified because the tone() is louder that the toneAC.

@Juraj I asked a new question about it here: https://arduino.stackexchange.com/questions/89993/clicking-sound-at-the-beggining-of-each-note

There is a library from LixieLabs that implements an audio-based PWM at super high frequencies that allows you to change the tone volume without additional hardware.

Thanks. I have tried this library, but i was not able to make it work in the past. See here: https://arduino.stackexchange.com/questions/90002/library-fails-to-compile

The tone() function generates a 50% duty cycle square wave using a timer and interrupts. 50% duty cycle is basically full volume.
It's possible to reduce the volume by reducing the duty cycle, but the tone() function does not support it. It is of course possible to change the software PWM generation to change the duty cycle (I wouldn't know how, so don't ask me), but I'll leave that as an academic exersize for you to experiment with should you wish.
An alternative is to do it in hardware. You can use an op-amp as buffer (or speaker driver) and a couple of resistors (or a potentiometer) as an "attenuator" before it to change the voltate of the signal going to the op-amp.
You need the op-amp as a buffer because the speaker will mess with the potentiometer otherwise.

Thank you! So is it possible to fix this with hardware alone? I will definately try this. I have another question that maybe you may know. At the beggining of each note, a clicking sound is heard and i don't know why, or if it is possible to mitigate it. Perhaps with an analog filter? I created a question here: https://arduino.stackexchange.com/questions/89993/clicking-sound-at-the-beggining-of-each-note. Thank you so much!

Is this how the connections to the system should be? https://imgur.com/a/tgK0hZ2 Did i understand your advice correctly?


text:
Send a 2d PROGMEM array over SoftwareSerial
I have a 2d array:
const byte messages_for_measurement[2][8] PROGMEM =
{
  { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 },
  { 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10 },
};

I want to send one of these sub-array over software serial.
Initially, this produced junk data:
swSerial.write( messages_for_measurement[0], sizeof(messages_for_energy_meter[0]) );

Then I learned about pgm_read_byte_near() and pgm_read_word(). I tried every combination but I did not get this to work:
swSerial.write(pgm_read_byte_near(pgm_read_word(messages_for_measurement[0]))), sizeof(pgm_read_byte_near(pgm_read_word(messages_for_measurement[0])));

and
swSerial.write(pgm_read_byte_near(&pgm_read_word(messages_for_measurement[0]))), sizeof(pgm_read_byte_near(pgm_read_word(&messages_for_measurement[0])));

and
swSerial.write(char(pgm_read_byte_near(pgm_read_word(messages_for_measurement[0])))), sizeof(char(pgm_read_byte_near(pgm_read_word(messages_for_measurement[0]))));

and
swSerial.write(char(pgm_read_byte_near(pgm_read_word(&messages_for_measurement[0])))), sizeof(char(pgm_read_byte_near(pgm_read_word(&messages_for_measurement[0]))));

How can I send the sub-array over serial, when the 2d array is in PROGMEM?

The write() method from SoftwareSerial (which is inherited from the
abstract Print class) does not support printing PROGMEM-based binary
buffers. The print() method does have some PROGMEM support, but it is
limited to printing NUL-terminated character strings, and is meant to be
used with the F() macro. You could coerce this method into printing
your data, but this would require you to add a null byte at the end of
each inner array, and the trick would break if you ever have to send a
null byte.
Also, the pgm_read_stuff() macros cannot read an array at a time. You
could do achieve this with memcpy_P(), but that would require
allocating an array in RAM. I think the simplest solution here is to get
the bytes from the flash one by one with pgm_read_byte():
const byte *message = messages_for_measurement[0];
size_t size = sizeof messages_for_measurement[0];
for (size_t i = 0; i < size; i++) {
    swSerial.write(pgm_read_byte(&message[i]));
}

Note that the first line does not attempt to access the array data: it
only copies into message the address of the first byte: this is the
decay-to-pointer semantics.


text:
Setting pinmode() in header file
I am trying to have a header file to handle all my pin definitions and pinmodes.
This is the header:
#ifndef __HEADER_TESTER__
#define __HEADER_TESTER__

#include <SoftwareSerial.h>
const byte rxPin = 2;
const byte txPin = 3;
SoftwareSerial mySerial(rxPin, txPin);

pinMode(LED_BUILTIN, OUTPUT);

#endif

However, when I compile this, I get an error on the pinMode(LED_BUILTIN, OUTPUT); line:
expected constructor, destructor, or type conversion before '(' token

try including the header file from inside setup()

@jsotola I got the same error...

Except for the preprocessor directives, none of this belongs to a header.

The pinMode() statement is executable code and can not be executed outside of a function - setup(), loop(), or some other function defined by you. One could imagine defining a function in your header (.h) file to set your pin modes but defining code in a header will cause a different kind of problem (multiple definitions) if you ever add another code module, a .cpp file, for instance, that also includes this same .h file.
Pin modes are usually set in the setup() function, once per execution of the sketch. There really isn't much value to having them in the .h file. If it is for documentation purposes, you could #define in the .h file, a symbol that expands to all of the pinMode() calls you need, then write that symbol at the appropriate place in your setup() function where it's expansion will be syntactically correct. This would accomplish the documentation, but at the cost of a reader of your code having to search for the definition of that symbol to find out what code is being executed there. That's pretty roundabout for what seems like little to no gain.


text:
Copy one SD card to another
I want to copy an SD card to another.
What is the best way to attack this problem?
Should i get two sd card shields?
If yes, is it possible to stack two together, or will there be problems with the interface protocols (SPI/I2C)?

Why would you want to do this with an Arduino when you can do it on a PC so easily?

Because sometimes, a pc just isn't available.

Fair enough then.

It should be perfectly possible to do it. As long as the SD cards and shields play ball then there should be no problem from a hardware perspective.
From a hardware perspective you should be able to share the MOSI, MISO and SCK lines and just have separate CS pins per card.
However some SD card shields employ level translation that doesn't properly release the SPI bus when idle, and some cheap SD cards don't release the bus in a timely manner too.
From a software perspective though it may be a different matter. I am not sure how well you can run two instances of the SD classes at once on an Arduino.  You may be better off looking at FatFS instead which is far more flexible.
You have two strategies when copying cards, each of which has a different way of programming it.

Block copy the entire card: this involves reading a 512 byte block from one card and writing it to the other one.  This would be the most efficient from a resource perspective (you don't need to care about the contents of the card, so don't need any filesystem code), but if the card is not close to full it will be very inefficient from a runtime perspective. Also the two cards have to be the same size for it to work well.
File copy. For this you need much more complex code, but it you only copy each file from one card to the other. It's much better though if the cards don't have much data on them - also the cards can be different sizes.

The time it takes to block-copy a complete "small" 16 GB SD-card via SPI is probably longer than finding a PC around  :)

Maybe, if two arduinos - where each has an SD card shield, and they communicate somehow? Maybe this is a better choice?


text:
Connecting high sampling rate DAC and ADC to arduino DUE, timer consideration
I'm in the echopen association, our goal is to create a low cost, open source echographic probe. In order to do that, we use an arduino due for the first step. For doing acoustic imaging, we use ultrasonic transducer wich works at high frequency, typically 5 MHz. So, for our purpose we need to send and receive analogic signal at high frequencies.
We want to connect a 80 Msps DAC and a 80 Msps ADC to the arduino due so we can generate and mesure analog signal up to 42 MHz. I have found here (http://www.instructables.com/id/Arduino-Timer-Interrupts/#step0) how to use arduino timer interrupts in order to send and receive data at 84 MHz. I haven't connect my converters for the moment, but I have preliminary questions.
First, is the definition of the timer is the same for the arduino due (i.e. timer1 is a 16 bits timer) ? Morever, my ADC and DAC are 14 bits converters, can I tell to the arduino to sent only 14 bits digital signal ?
Secondly, as we work at high frequencies we will have to send a lot of data from the microcontroller to a computer via the serial port. I have make a test and at 250000 bauds it takes nearly 0.5 second to transfer 4300*8 bits datas. It is to slow for our purpose, how can I do it faster ?

If I'm interpreting the datasheet correctly, you might be able to use the Static Memory Controller (SMC) capability of the Cortex M3 Sam3X to attach some 128K x 8 SRAM devices to your Due.  If your ADC and DAC support tri-state outputs then they could be attached the same way as memories (but ignoring address lines as irrelevant), allowing memory-to-memory DMA transfers.  Ie one could either input and store batches of ADC results at 42 MSPS, or could output batches of data to DAC at 42 MSPS, or could do simultaneous I/O at 21 MSPS.  I haven't read the DMA section closely enough to verify that this will work with the M3.
See Figure 25-2 in Section 25.6.2 of the datasheet regarding memory controllers, and Section 26, “Peripheral DMA Controller (PDC)”, regarding DMA.  Also see the eevblog.com page, “Looking for Cortex M3 or M4 with DMA to GPIO capability”.

I'm sorry, but by your description you are doomed to failure from the start.
The Arduino Due runs at 84MHz.  That doesn't mean that it can communicate at 84MHz, only that it can process its instructions at around 84 million per second.
In order for you to transmit or receive 80 million samples per second you have to be able to a) transmit sample words (14 bits) 80 million times per second, and b) process the information between each sample.
That means you are going to require a processor that operates considerably faster than 84MHz.
For instance, assuming you are using high speed synchronous serial communication (say, SPI) to transfer the data.  For 16 bits of data (you won't get it to do just 14 bits using hardware and software would be way too slow) would require a transmission clock of (80000000 * 16) 1.28GHz.
If you're using a 16-bit parallel interface then you would only need an 80MHz communication clock to move the data around, but receiving that data and storing it somewhere and also processing it would require many many more instructions between each clock.  Far more than the Due could perform.  Certainly it's way way outside the scope of a timer interrupt.
I would suggest instead investigating systems that run in the high hundreds of Megahertz or even Gigahertz range.  Maybe one of the newer "version 2" Raspberry Pi embedded computers may be suitable.

I thought the arduino due can send digital data at each time clock... I have to find another way.
Thank you for your answer

The Due uses an ARM core.  The ARM core is RISC.  To, for example, get a byte from memory and place it on a port register takes minimum 4 instructions (load address, load data from address, load address, write data to address) and each instruction (load or store instruction) takes 1 clock cycle. That's in assembly. In C it becomes more, and as soon as you start looping you get even longer - condition tests, branches, incrementing values, etc - it may take upwards of 10 instructions with maybe 15 clock cycles for each access of the port. That would make about 5.6MHz maximum output.

DMA might be able to do a bit better than the ARM core, but still the design seems farfetched.  This is territory for an FPGA, or a very, very carefully chosen MCU.  The pi is probably not a fit - the core may be fast, but that does not mean there is necessarily a suitable fast I/O interface.

May I suggest you decorrelate the acoustic frequency with the sampling frequency ?
While you need the high frequencies to get spatial resolution, what you are interested in is only the signal return amplitude (not the exact waveform), which you could sample at a much lower rate using appropriate analog front end.

Right, it is possible to have lower sampling rate by using the envelope of the signal (few Msps is enougth).
We are doing both actually, we sample only the envelope or the complete signal to compare. But we don't use an arduino anymore.


text:
Datasheet of arduino power jack
Can we find out about the parts that the arduino uses?
I want to make a shield, and i bought the same power jacks.
And i thought that there would be two pins, one for power, one for GND.
However, it has three pins.
The supplier did not have a datasheet, and right now i do not have a continuity beeper either, so could i see its datasheet somewhere, or does anyone know why it has three pins?

The third pin is connected to the sleeve pin, if there is no jack plugged in. It disconnects when a jack is plugged in. You can use it to detect if a jack is plugged in. You can even use it have you project run on batteries, and automatically switch if a power-jack is plugged in. Though in almost all cases you leave it disconnected, or connect it to the sleeve pin. PS this third pin also makes it so the plug is more solidly connected to the PCB.

@Gerben Thank you! But which is the center pin, and which is the third pin?
Plus, i suppose that the polarity of these two pins is GND right? I mean the extra pin (whatever it is), is not connected to the center of the power connector (the power), but to the side (the GND). Am i correct?

@timemage. Hello. What do you mean?

Just me venting.  I had written an answer.  It's gone now.  I find it extremely frustrating that no one pays attention to the thing that is literally written right on the box that I am typing into now, which says "Use comments to ask for more information or suggest improvements. Avoid answering questions in comments."

@timemage Why did you delete your answer?

Partly out of frustration, partly out of the experience that when a comment contains an answer, the actual answers go ignored.  With the answer gone, I can make a point about this without driving traffic to the answer I gave.

@timemage I understand your frustation. Answer it again, if you'd like and i will upvote and mark as accepted.

Credit for it is something I gave up to avoid a conflict of interest when venting about it.  If you just want to view it for yourself, it'll be at https://timemage.wereclam.net/tmp/da.png for a few minutes.  It's nothing to write home about, but it is(was) an answer.  If you like it, vote up jwh20's answer if you haven't already.

@timemage I did upvote his answer. But almost everything i wanted is contained in your answer. So please, answer again, don't type anything, just add the image if you want (if you are bored). Come on you deserve it! Plus i got just one question about this. I will ask you in the comments ;)

@Gerben "This one on connected the the sleeve pin, if there is no jack inserted (so yes, you were correct). " Sorry i didn't get this, you have a typo.

The center pin is connected to the back. The sleeve in on the bottom. The switched contact is the one on the side. This one is connected the the sleeve pin, if there is no jack inserted (so yes, you were correct). In most power jacks the sleeve in ground, but this isn't always the case. (corrected misspellings)

This is an image from a typical power jack:

The specific ones you bought may differ.  The vendor should be able to supply you with a manufacturer and P/N or an actual data sheet.
Image copied from: https://www.we-online.de/katalog/datasheet/6941xx301002.pdf