text:
What is the logic behind Arduino inlining `HardwareSerial::_rx_complete_irq()` for receiving serial data (but NOT `_tx_udr_empty_irq()`)?
Q: What is the logic behind Arduino inlining HardwareSerial::_rx_complete_irq() for receiving serial data (but NOT _tx_udr_empty_irq()), and when is it advisable?
From the bottom of the HardwareSerial class in HardwareSerial.h:
// Interrupt handlers - Not intended to be called externally
inline void _rx_complete_irq(void);  // <======= inline!
void _tx_udr_empty_irq(void);        // <======= NOT inline! Why?

Furthermore, what is the design logic behind putting one of the serial ISR function definitions in a header file vs in a source file? Also, when is this good design and what are the tradeoffs, and when is it illegal or not permitted by the language, compiler or anything else?
Here is the exact scenario that made me think of this question:

See here for the HardwareSerial implementation files: https://github.com/arduino/ArduinoCore-avr/tree/master/cores/arduino
Here is the main header file. https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/HardwareSerial.h
The inline ISR _rx_complete_irq():

Line 138 of "HardwareSerial.h" declares the inline ISR for when serial data is received:
 inline void _rx_complete_irq(void);

This ISR is called whenever "there are unread data present in the receive buffer." (ATmega328 Datasheet 20.7.3 p190)

Line 40 and 48-50 of "HardwareSerial0.cpp" is where the ISR is set up:
   ISR(USART_RX_vect)  // line 40
   {                   // line 48
     Serial._rx_complete_irq();  // line 49
   }                   // line 50

Line 101-121 of "HardwareSerial_private.h" implements the inline _rx_complete_irq() function:
  void HardwareSerial::_rx_complete_irq(void)
  {
    if (bit_is_clear(*_ucsra, UPE0)) {
      // No Parity error, read byte and store it in the buffer if there is
      // room
      unsigned char c = *_udr;
      rx_buffer_index_t i = (unsigned int)(_rx_buffer_head + 1) % SERIAL_RX_BUFFER_SIZE;

      // if we should be storing the received character into the location
      // just before the tail (meaning that the head would advance to the
      // current location of the tail), we're about to overflow the buffer
      // and so we don't write the character or advance the head.
      if (i != _rx_buffer_tail) {
        _rx_buffer[_rx_buffer_head] = c;
        _rx_buffer_head = i;
      }
    } else {
      // Parity error, read byte but discard it
      *_udr;
    };
  }

The NON-inline ISR _tx_udr_empty_irq():

Line 139 of "HardwareSerial.h" declares the ISR for transmitting serial data: void _tx_udr_empty_irq(void);

This ISR is triggered by the "USART Data Register Empty" flag and is called whenever the transmit buffer has passed its value to the shift register and now is "ready to receive new data" (ATmega328 Datasheet 20.11.2 p200)

Its implementation is on lines 89-113 of "HardwareSerial.cpp"
   void HardwareSerial::_tx_udr_empty_irq(void)
   {
     // If interrupts are enabled, there must be more data in the output
     // buffer. Send the next byte
     unsigned char c = _tx_buffer[_tx_buffer_tail];
     _tx_buffer_tail = (_tx_buffer_tail + 1) % SERIAL_TX_BUFFER_SIZE;

     *_udr = c;

     // clear the TXC bit -- "can be cleared by writing a one to its bit
     // location". This makes sure flush() won't return until the bytes
     // actually got written. Other r/w bits are preserved, and zeroes
     // written to the rest.

   #ifdef MPCM0
     *_ucsra = ((*_ucsra) & ((1 << U2X0) | (1 << MPCM0))) | (1 << TXC0);
   #else
     *_ucsra = ((*_ucsra) & ((1 << U2X0) | (1 << TXC0)));
   #endif

     if (_tx_buffer_head == _tx_buffer_tail) {
       // Buffer empty, so disable interrupts
       cbi(*_ucsrb, UDRIE0);
     }
   }

Why the difference? Why inline one ISR and not the other?
Again, from the bottom of the HardwareSerial class in HardwareSerial.h:
// Interrupt handlers - Not intended to be called externally
inline void _rx_complete_irq(void);  // <======= inline!
void _tx_udr_empty_irq(void);        // <======= NOT inline! Why?

Why the somewhat complicated set of 3+ files?
Mainly:

HardwareSerial.h
HardwareSerial_private.h
HardwareSerial.cpp

I first documented this to myself and wondered about it on 31 Jan. 2018, while studying the Arduino source code. I'd like to hear some more insight on the topic from other developers.

What is the logic behind Arduino inlining HardwareSerial::_rx_complete_irq() for receiving serial data (but NOT _tx_udr_empty_irq()), and when is it advisable?

There's a couple of reasons which end up with this arrangement:

The RX interrupt has to be fast as we're reacting to an external stimulus. The TX interrupt doesn't have to be fast as it's only used to move data from the buffer to the UART.

We need to be able to respond rapidly to incoming data so we can store it away in the RX ring buffer in time to handle the next byte that arrives. Not really a problem at low baud rates, but when it comes to higher ones every cycle that can be shaved off that interrupt time is beneficial.  The TX interrupt, though, really doesn't matter. All it does is load the next byte into the outgoing UART buffer, and it doesn't matter if that takes a little longer, so there's no need to shave off the extra instruction cycles consumed by making a function call.

The TX interrupt is called from multiple places but the RX isn't.

The RX interrupt code is only ever called when the interrupt fires. That means it's only ever going to be called through one execution path.  However the TX interrupt code is not only called by the interrupt itself, but by other areas of the code. For example, if interrupts are disabled then the write function will manually poll the UART for the buffer state and manually call the interrupt function to send the data (see line 262 of HardwareSerial.cpp).
If the TX interrupt code were inlined then there would be lots of places throughout the code where that block would be duplicated causing code bloat. That's code bloat with no reason (See point 1) so it's something to be avoided.

Furthermore, what is the design logic behind putting one of the serial ISR function definitions in a header file vs in a source file?

Inlining can only be done within a single translation unit. If you want a function to be inlined in multiple translation units (HardwareSerial0.cpp, HardwareSerial1.cpp, etc) then you would have to have it within those translation units. And that means that you need it in the header1. Since the TX interrupt is not wanted to be inlined it can be put in a CPP file instead.

Why the somewhat complicated set of 3+ files?

Simple: management. It's easier to manage the (rather complex UART) code if it's broken down into different areas.  You have a common base object in HardwareSerial.cpp which is then used by the code for each individual UART in the HardwareSerial[0-3].cpp files.  You have a single header file that defines the class and all its methods and data (HardwareSerial.h). And then you have the "private" header with any inline functions in it that is included where it's needed.
True you could merge the HardwareSerial.h and the HardwareSerial_private.h into one, but this way the inline functions are excluded from translation units where they aren't needed. This way you don't get those chunks of code included in your sketch. True the linker will discard them as they're not used, but it's just tidier this way - the functions are only included in those translation units where those function are actually used.

Notes:

This code was written before the compiler had support for Link Time Optimization which allows inlining between translation units. The compiler may have moved on, but there is no point in changing code that works perfectly fine.

and that part was written before LTO was used

Indeed. I did think about mentioning LTO but thought it was probably outside the scope, since it didn't influence the coding style as it didn't exist in the compiler at that time.

the HardwareSerial[0-3].cpp files were an optimization without LTO.


text:
Help understanding Print::write()--it calls write()--where is write() defined? Help reading code
I'm writing a new serial library (eRCaGuy_Peer2Peer) to allow any 2 pins on an Arduino to be used for peer-to-peer type communication between Arduinos, withOUT interrupts or timers/counters.
Currently SPI, Serial, and I2C are pin-specific, and SoftwareSerial requires pin change interrupts. My implementation will solve these problems.
However, I first am trying to understand some things. As I study SoftwareSerial, I see it inherits from the Stream class, which inherits from the Print class.
I don't understand how Print's write is implemented. This is from Print.h:
virtual size_t write(uint8_t) = 0;
size_t write(const char *str) {
  if (str == NULL) return 0;
  return write((const uint8_t *)str, strlen(str));
}
virtual size_t write(const uint8_t *buffer, size_t size);
size_t write(const char *buffer, size_t size) {
  return write((const uint8_t *)buffer, size);
}

This is from Print.cpp:
/* default implementation: may be overridden */
size_t Print::write(const uint8_t *buffer, size_t size)
{
  size_t n = 0;
  while (size--) {
    if (write(*buffer++)) n++; //<--where is this write defined?
    else break;
  }
  return n;
}

My Questions:

What does this mean? I've never seen anything like this before: virtual size_t write(uint8_t) = 0; Why the = 0?
What does it mean/how does it work defining functions in .h files? I've never done this before: ex:
size_t write(const char *str) {
  if (str == NULL) return 0;
  return write((const uint8_t *)str, strlen(str));
}
Where is the write command I've marked above defined? Is Print::write() calling itself recursively?
Also, why does SoftwareSerial.h call using Print::write; (shown below) when it already re-implements the virtual write function just above that?

virtual size_t write(uint8_t byte);
    virtual int read();
    virtual int available();
    virtual void flush();
    operator bool() { return true; }
using Print::write;

I found the answer to my first question: the  = 0 means it is a "pure virtual function", which means derived classes MUST implement it: https://stackoverflow.com/questions/2652198/difference-between-a-virtual-function-and-a-pure-virtual-function

Will it work ? Do you have some explanation online to tell how you are going to make it ? When you are going to use micros or millis for synchronous data transfer, it might be limitied to 1 byter per 10 seconds. For example an Arduino with Ethernet shield that is retrieving a file from a SD card takes a while. When no timing will be used, you are going to need more pins for handshake signals.

Jot, follow my work live at my link above. I'm working on it as we speak. I have a clever plan. I believe I can make it happen. I don't expect it to be slow either. I'm expecting better than 115200 baud, and turning off interrupts for only a handful of microseconds at a time.

That might work. I like the idea and I like that the TX is always output and RX is always input. However, like the other software serial libraries, it has its own problems. The main problem is that the transmitter disables the interrupts for an unknown time, since the receiver might be very busy or it might execute interrupts while data is being transferred. I suppose it can be used as if it is full-duplex at a higher level using buffers just like the other serial libraries that inherit the Stream class. At a low level it is only half-duplex since RX is the acknowledge.

write is implemented in the class that inherits the Print class - such as HardwareSerial.
There are a number of write functions, and they are overloaded, which means that they are all distinct functions identified using their parameters as well as their name (write(uint8_t) and write(uint8_t *, size_t) are different functions).  The child class overrides the write(uint8_t) function that is pure virtual1 in the main Print class, but the other write functions with other parameter lists aren't overridden and are just "used".
The using Print::write tells it "the write functions to which I am referring are from the Print class."

Using-declaration introduces a member of a base class into the derived class definition, such as to expose a protected member of base as public member of derived. In this case, nested-name-specifier must name a base class of the one being defined. If the name is the name of an overloaded member function of the base class, all base class member functions with that name are introduced. If the derived class already has a member with the same name, parameter list, and qualifications, the derived class member hides or overrides (doesn't conflict with) the member that is introduced from the base class.

I'm not entirely sure why they feel they need to use it, since the write functon(s) in Print are public and thus exposed already.

What does it mean/how does it work defining functions in .h files? I've never done this before

Exactly the same as if you had defined the function in a .cpp file, but with a few minor differences, the most important one of which is that the compiler finds it easier to inline the function (or if you're really lucky eradicate the function altogether). It's great for simple functions such as setters and getters that just set or return the value of a variable. In such cases inlining is desirable, and the compiler may even be able to replace the entire function with just direct access to the variable (if it's clever enough).
Another important thing to note with functions in .h files is that you can only really do it with class member functions or static functions. Otherwise you end up with compilation errors complaining about multiple definitions if you use the header file in more than one place.

1: A Pure Virtual function (such as virtual size_t write(uint8_t) = 0;) is one which has to be implemented in the child class. Failure to implement it results in a compilation error. The pure virtual function defines part of the interface but doesn't implement the software for it - that is down to the child class to implement.

I think there's more to it than that. SoftwareSerial inherits Stream which inherits Print, so what other write could it possibly be referring to? ie: I think there's more to the using keyword here than what you stated.

This seems to shed some light: http://forum.arduino.cc/index.php?topic=302730.0

There is more to it, yes, but I was on my phone, so couldn't go into detail. Two terms you need to learn all about: overloading and polymorphism.

In the Print class the virtual size_t write (uint8_t)=0 DEFINES and names a function that accepts a byte and returns a size.  ANY "virtual" function in a base class CAN be over-ridden in a derived class; however, the =0 declares that there is NO actual function in the base class -- the compiler sticks a null function pointer there.  This is why pure virtual functions MUST be over-ridden in the derived (child) class.
The using Print::write; in the .h header file of your derived class tells the compiler that YOUR size_t DerCl::write (uint8_t val) {} should fill in that null pointer in the base class...this is why your write function must be declared exactly like the one in the base class.  If it were not, then when the base class calls it, it would push too many values onto the stack, it would pop too many values off the stack, or it would mix up the parameters sent to the function, etc.
This "polymorphism" allows the base class (Print) to define an interface (for printing in this case) and simultaneously allows the derived class to determine where the resulting byte stream will be sent.  Serial sends it to the USART's serial port.  SoftSerial sends it to any two port pins (one Tx and one Rx).  But you also can create classes to use SPI, TWI(i.e. CAN), a HDMC file, an LCD display, etc.  And you can leverage the uniformity and the functionality of all of the Write(), print(), and println() functions that you're already familiar with by writing a single, simple size_t write(uint8_t) function for your derived class.

source: Stack Exchange

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

sort: votes


text:
What Minimum Value Can I Measure With ACS712 30A Current Sensor?
I am making an Arduino multimeter for current measurement. I first thought about using a shunt but that fails to work since I need to measure current in the mA range.

That model has a sensitivity of 66mV/A which means for every 1A of current passing through it outputs 66mV.
The Arduino's ADC when running at 5V has a resolution of (5/1024) 4.88mV per LSB.
That means that 4.88/66 gives you 0.074 - or 74mA per LSB.
Since 1LSB is considered to be in the noise area of the signal you can expect the minimum usable value to be double that - 148mA
Which is pretty useless for measuring currents in the mA range.
You would get better results with the 5A variant, but still not great.

The datasheet for the ACS712 shows the following:

This means the 30A variant has a sensitivity of 66mV/A. This means a reading of 1A will show 66mV plus some bias voltage. The Arduino ADC is 10-bit, meaning it has 2^10 = 1024 increments across a default 5V voltage reference for the Uno, Nano, etc. This gives it a measuring resolution of 5V/1024 increments = 4.88mV voltage resolution. 4.88mV / 66mV/A = 0.074A, or 74mA.
So, the default resolution of an Arduino Uno, Nano, etc, is 74mA. Realistically it will bounce around this value, so your precision might be about 3~4x this, or around 300mA, and your accuracy is as good as you calibrate it, which could easily be around this value too if you calibrate it well.
74mA resolution isn't bad, but there are several tricks to improve this. Here are a few:
1. External hardware solutions:

Use the 20A or 5A version instead of the 30A version of the ACS712. The 5A version has a sensitivity of 185mV/A, which automatically improves your resolution to 4.88mV / 185mV/A = 0.026A, or 26mA, which is 74mA/26mA = 2.8x better.
Buy an external ADC with high-resolution. This Adafruit ADS1115 16-Bit ADC (datasheet) will improve your resolution on the 30A version of the ACS712 as follows. Minimum resolution of the ADC is now 5V/2^16 = 5V/65535 = 0.0763mV instead of 4.88mV, and 0.0763mV / 66mV/A = 0.001156A, or 1.156mA.

2. Software solutions (freebies!):

Change your voltage reference to use the internal 1.1V internal reference. This is easy: call analogReference(INTERNAL) in your setup() function. Done! See: https://www.arduino.cc/reference/en/language/functions/analog-io/analogreference/. If I recall correctly, this is a diode-based internal voltage reference (see the ATmega328 datasheet), and can be off by as much as 10% from part to part, so calibrate it for each individual Arduino you have and you will get good results! Now, your ADC resolution is 1.1V/1024 = 1.07mV instead of the Arduino's default 4.88mV, so your current resolution is 1.07mV / 66mV/A = 16.2mA, which is 74mA/16.2mA = 4.6x better.
Use oversampling to increase the Arduino's 10-bit ADC to up to ~16 bits or so. Atmel Application Note AVR121: Enhancing ADC resolution by oversampling explains this very well, albeit it requires some serious study. There are libraries which exist to do this for you which you can Google for. I wrote one of them. Here is a link to my website where I present one such library I wrote. The gist is this: to get an 11-bit reading (which is 1-bit better than your hardware ADC resolution of 10-bits) you need to take 4^1 = 4 10-bit readings, sum them, then divide by 2^1 = 2. Your max value will be 1023 x 2 = 2046. To get a 16-bit reading (which is 6-bits better than your hardware ADC resolution of 10-bits) you need to take 4^6 = 4096 10-bit readings, sum them, and divide by 2^6 = 64. Your max value will be 1023 x 64 = 65472. Your voltage resolution will be improved from 4.88mV to ~0.0764mV at best. It won't be as good as a true 16-bit ADC, like the Adafruit one above, but it's good enough for many uses. Keep in mind that 4096 10-bit readings takes some time, so I also recommend you speed up the ADC clock to improve reading rate at 10-bits from ~10kHz to ~50kHz. This is also where a library comes in handy to make this easy to do. Free and open source solutions already exist. Here's a table I made back when I first read the  AVR121 application note and practiced oversampling. Consider the resolution values beyond ~16-bits to be purely theoretical. Oversampling has its limits.

What would I do? I'd use the 1.1V internal voltage reference and oversampling with increased ADC clock speed on the ACS712 part which provides the minimum acceptable max current (ie: choose the 5A version not the 20A or 30A version if 5A is enough, or the 20A version not the 30A version if 20A is enough). Just be sure that your max voltage now at the analog pins will not exceed the 1.1V Vref value. If it will, use the standard 5V reference for the ADC, and just do oversampling alone. My current resolution would end up being a few mA in the end. If I can't sample at the desired frequency using oversampling (I don't know what dynamic effects you may be trying to measure), then I'd use an external high-resolution ADC which can sample faster than oversampling at high resolutions would allow.

And if that's not good enough, what would I do? I'd use a precision shunt, ie: "current resistor" with the right value such that I can measure values at the right range. If I need amplification I'd buy an external ADC and/or op-amp from Adafruit until I have everything sized just right. Remember, if your shunt (current resistor) is too small to measure the low currents you need, do the following:

Use a higher resistance value. V = IR (Voltage = Current x Resistance), so increase R to increase the V across it for a given current, I.
Use an op-amp to amplify the voltage drop across the resistor (go for an Adafruit one since Adafruit makes it easy and has the world's best examples).
Use a high-resolution ADC, and/or oversampling to increase your sensitivity to measure small voltage changes.

Thanks sir....  Thats actually helps

Glad to help! Don't forget to click the up-arrow at the top-left of answers to upvote answers that you find helpful, and click the check-mark if you'd like to mark an answer as the "best" or "correct" answer. It helps bring the best answers to the top to help others after you who have the same question.

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


text:
Dealing with a Signal Source
The following circuit is a simplified version of a more complex system. For testing purposes, the 555 Timer was added to serve as a test signal source with frequencies set by the resistors in series. Each arbitrary signal is indicated by a push button and the Arduino needs to be able to distinguish what button has been pushed. Unfortunately, there can only be 3 buttons and more cannot be added. This is where the problem occurs. How can you reliably indicate which push button has been pressed without interfering with the arbitrary waveform?
At first, my original thought was to have the Arduino sample the signal based on that sample the Arduino would be able to tell which button is pressed.
When button 1 in the pink is pushed the Arduino receives a takes the following
sample of the signal.

843
848
849
849
849
849
   // Time 0 when button is pushed
532
414
500
373
463
346
425
370
386
476
346
442
642
788

Moving the input

    // At t = 0 the Serial Monitor reads zero
    998
    998
    998
    998
    998
    0
    0
    0
    0
    0
    998
    0
    0
    0
    0
    0
    0
    0
    0
    0
    998
    0
    0
    0
    0
    998
    0
    0
    0
    998
    998
    998
    0
    998
    0
    0
    0
    998
    0
    0
    0
    0

Moving the analog input does not make it any easier to distinguish which button was being pushed. Which is why I decided to ask the community on how to deal with this. I have tried using a relay and simply hard coding all of the cases but the result is a system is not very robust and is vulnerable to easily break over time.

What is the role of the 555 chip in that circuit?

The 555 chip is being used to generate 3 waves.

Does this answer your question? Multiple Push buttons to one input

I need to apologize for the previous wording of my question I believe I made it difficult to understand. I am still relatively new to electronics in the future I will work to improve this.

After a day or two of working on this problem, I have found that it is best to avoid using the analog pins and stay away from directly interfacing with the 555 Timer. This is a simplified version of a more complex circuit and the 555 Timer represents some arbitrary signal source. For example, on mobile radio, you push a button to send out a certain frequency. That is the concept here only the frequencies cannot be adjusted yet. Now that it has been clarified that the 555 Timer has been placed in the circuit for debugging purposes here is the best solution I have found to this problem. First, I have found that it is doable to read in from the analog pin on the Arduino but not easy. This leaves a lot of room for error being that the waveform is arbitrary with some random frequency. Therefore, I have opted to use the digital pins on the Arduino.

by using the digital pins I have now only have to worry about whether the button is high or low. Then NPN transistors were used to act as switches once the button is pushed. The diodes then were added to maintain a steady voltage across the base of the transistor. For testing purposes, the LCD was removed and replaced by an LED. As far as the code is concerned it is nothing extraordinary or complex as shown below. Therefore, I believe this may be the best way to go about solving this problem.
const int D_pin10 = 10;
const int D_pin9 = 9;
const int D_pin8 = 8;
int led = 13;
void setup()
{
  pinMode(D_pin10 , INPUT); // pin 10 is an input
  pinMode(D_pin9 , INPUT); // pin 10 is an input
  pinMode(D_pin8, INPUT); // pin 10 is an input
  pinMode(led, OUTPUT);
}

void loop()
{
  int High_Low10 =0;
  int High_Low9 =0;
  int High_Low8 =0;

  High_Low10 = digitalRead(D_pin10);
  High_Low9 = digitalRead(D_pin9);
  High_Low8 = digitalRead(D_pin8);

  if(High_Low10 == HIGH)
  {
    digitalWrite(led, HIGH);
  }
  else if(High_Low9 == HIGH)
  {
    digitalWrite(led, HIGH);
  }
  else if(High_Low8 == HIGH)
  {
    digitalWrite(led, HIGH);
  }
  else
  {
    digitalWrite(led, LOW);
  }
  delay(1000);
}

If your aim is to detect button presses accurately, and use one pin per button, you don't need transistors, diodes or any other hardware apart from pushButtons. You can directly connect to pushbutton via an internal pull-up resistor and accurately read button states.

The goal is to control the astable 555 Timer with the pushbuttons. The diodes and transistors are functioning as a switch.

There's an easy way to achieve reading multiple pushbuttons using single analog input.
All you need to do is create some voltage dividers at different voltages which can be read using analogRead. The last resistor,R6, in the diagram below ensures that the pin reads 0 when no push-button is pressed (i.e pull-down resistor).
In the diagram below, connect Vcc to 5V on the Arduino.

Try it out, you should be able to get well spaced out values for different push buttons!

R1 ... R5 can have different values, which might spread the ranges per button more evenly

Re “1M”: Note that, on the Uno, the ADC is specified for a source output impedance no larger than 10 kΩ.

@EdgarBonet The 1M is just a float-prevention pulldown. By having it so high it prevents the input floating with no buttons pressed and at the same time has little effect on the readings. Worst case the output impedance with Button 1 pressed would be  799.36Ω. With nothing pressed there's no output to have an impedance. Just ground through a resistor. Yes, it may slow down the transition from a valid reading to nothing, but that's not a problem.

@Majenko: “nothing” is a valid reading.

Yes, but it's not an actively valid reading that is being driven by the rest of the circuit - just a "stop it floating" nothingness.

This is correct but utilizing the voltage divider is quite difficult in this scenario.

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


text:
What are the different types of high-speed serial data transfer protocols, and how do they work (ex: baudrate, synchronous vs asynchronous, etc)?
Otherwise worded: How do I resolve my understanding about baud rates and high speed serial data transfer?
From what I understand, serial communication is relatively slow.  By slow, I mean that the fastest common rate of transmission of data is 115.2 kBaud.
However, also from what I understand there are fast ways of transferring data serially.  I know that some serial configurations through Firewire or Ethernet can transfer data at speeds that are orders of magnitude higher than 115.2 kBaud.  These data streams are able to be read on simple computers that you can buy from Staples.  I don't know how these systems receive data at such a high speed if common baud rates are so low.
I know something is wrong with my understanding of it all.  I am new to electrical engineering and I am trying to teach myself some basic ideas for my research project - with much frustration.  I know that I need to have a system that can receive a pulse train at a minimum speed of 10MHz (hopefully up to 500MHz).  I will then program it to process this data.  The system that I currently have to receive the data is an Arduino certified product:
http://store.arduino.cc/product/E000052
Programming in the Arduino language is not a problem, I already know how to do this.  I just want to understand what I can do to receive this data stream.  Do I need something faster than this?  Or will this suffice?  I'm more interested in the theory than the device; it is more valuable for me to bolster my education than for me to solve my problem (though it needs to be solved).

Basically there are two kinds of serial: Asynchronous and Synchronous.
With asynchronous, which is what serial as in UART and RS-232 are, it's all down to how accurate a system's clock is.  Both ends of the line have to agree on the same speed (baud rate) and any deviation from that causes transmission errors.  The more accurately the two ends can agree on their baud rates the faster you can transfer data.
Note that on many systems (Arduino included) when you ask for one baud rate you actually get a slightly different baud rate.  That's due to the way that the internal UART hardware works - it divides the system clock into finer and finer bits to get as close to the requested baud rate as possible.  Lower baud rates are easer to get close to, but higher ones are much harder.  So it's "safer" to use a lower baud rate which gives more reliable communication to a greater variety of devices.

http://en.wikipedia.org/wiki/Universal_asynchronous_receiver/transmitter

The other kind of serial, synchronous, uses an extra wire for the transmitting (or master) end of the connection to send the clock to the receiving (slave) end.  The receiver uses the incoming clock to know precisely when it should look at the data line to receive a bit of data.  This is how things like SPI and I²C work, and very high baud rates can be achieved.  Speeds in the tens of megahertz are common.

http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus
http://en.wikipedia.org/wiki/I%C2%B2C

Some synchronous systems (such as Ethernet), instead of providing the clock as a discrete wire, encode the clock into the data stream.  This keeps the number of wires to a minimum yet allows high speed data transfer.  The down side is that this usually means the maximum speed you can run at is actually slightly lower since the effective size of the data being transmitted is increased.

http://en.wikipedia.org/wiki/Clock_recovery

The other answers have really good info in them, but I'd still like to expound a bit on the different types of serial protocols, and how they vary in speed. I'll also mention a few devices and show some comparisons. For synchronous vs asynchronous and what that means, see Majenko's really good answer.
Clarification:
Your phrasing of "receive a pulse train at a minimum speed of 10MHz" is quite confusing to me. Perhaps this is because when I hear "pulse train" I think you mean you want to read pulse widths in order to obtain data, ie: like the PPM pulse train used in Radio Control communication signals.
Is what you mean simply that you want 10Mbps (megabit per second) transmission rates? If so, the Arduino Intel Galileo can do SPI serial communication at a rate of up to 25MHz, or you can do Ethernet communication with this board up to 10 MHz or 100 MHz (see previous link as well). Note that some Ethernet devices can communicate up to 1000 MHz (like the Orange Pi Plus), but the Intel Galileo only goes up to 100 MHz, according to the link above.
USB3.1 serial communication, if a device supports it, however, can be done up to 10Gbps.
Standard RS-232 0-5V (TTL) Serial, and example:
Now, as for standard RS-232-type serial done with TTL logic levels (ie: signal voltage levels 0 to 5V), via a UART (piece of hardware that allows this type of asynchronous communication protocol), I have written C++ code on a PC and on a standard Arduino (ex: Nano, Uno, or Pro Mini--under $10 cost + $2 external UART) which communicates at 250kbaud (though 2Mbaud is possible on an Arduino Uno--see Connor Wolf's answer here).
When communicating via a serial UART type device, plugged into a PC via a USB plug, a Windows-based computer sees it as a "COM" port. The UART simply does USB to RS-232 TTL data conversion, so I can use this COM port as a serial port on the PC. Since pretty much every Arduino supports standard Serial communication, even the cheapest ones, this is very appealing to me to learn how to write C++ code to do this. I spent the last couple weeks working on my communication code.
At a serial communication speed of 250kbaud (250kbps in my case) I am able to transfer 25-byte binary data packets from my PC to my sub-$10 Arduino at a rate of up to 1000 packets/sec, while doing error checking on the Arduino receiving the data. In my case, each packet contains 8 commands, plus error checking bytes and a couple other things, to control an RC vehicle.

Here's a few key serial protocols, and their associated speeds, to be aware of.
All of these are different types of serial communication protocols:

I2C:
Normal Arduino (ex: Uno) default speed is 100kbps; it can be increased to 400kbps. Some non-Arduino devices can do 1Mbps or 3.4Mbps.
SPI:
Arduino default speed is 4Mbps. Normal Arduinos can go up to 8Mbps; Galileo can do 25Mbps. I have seen some devices (ex: Wiznet W5200 Ethernet chip), which can do SPI serial communication up to 80Mbps (source).
RS-232 TTL via UART:
This is what most people mean I think when they just use the word "serial" without specifying it further by saying "SPI," "I2C," etc. Whenever you see the term "baud" or "baudrate," this is the type of serial communication they are referring to too. Hardware (UART)-based serial communication is done via pins 0 and 1 on most Arduinos. Normally, the "high-end" speed is considered 115200bps, but I regularly use 250kbps on an Arduino. Up to 2 Mbps is theoretically possible under the right conditions for the Atmel AVR-based Arduinos, like the Uno. See Connor Wolf's answer here. Arduino also includes a software serial library for this type of serial communication on any of the Arduino's pins, and I have used it up to 250kbps. I haven't yet tested it beyond that speed, but being software-based, I'd expect it to become unreliable much beyond that.
USB:
USB Speeds (https://en.wikipedia.org/wiki/USB)
USB 1.0: Low Speed mode (1.5Mbps), Full Speed mode (12Mbps)
USB 2.0: High Speed (480Mbps)
USB 3.0: SuperSpeed (5Gbps)
USB 3.1: SuperSpeed+ (10Gbps)
Ethernet:
Standard rates are 10/100/1000 Mbps.

Conclusions:

If you must have a minimum of 10MHz (AKA mbps) communication rates, you can use the SPI, USB, or Ethernet protocols. I2C and RS-232 TTL serial are too slow.
If you really want the ~500MHz communication rate, you can use USB 2.0 or higher, or Ethernet 1000Mbps. All the rest are too slow.

Note that embedded boards and devices, microcontrollers, etc, can all do some type of serial communication, even if it's just slow bit-banged RS-232 TTL-type or SPI-type serial. Nevertheless, some high-end devices can do really high speed serial communication via USB, USB 3.0, high-speed Ethernet, high-speed SPI, etc. When it comes to really fast serial communication methods (~3Mbps and higher), synchronous techniques must generally be used rather than asynchronous techniques, as the errors in clock-rates caused by using separate clocks begin to be too pronounced.
You just need to look at your actual needs. For most of my needs, 250kbaud is plenty fast using the built-in UART inside every cheapo low-end AVR-based Arduino device. Your needs, however may be different.

Different serial communications protocols use different signal modulation methods to encode data; if you want to roll your own wire protocol, you'll want to learn about those.
Back in the day, low-rate UART serial systems were mostly used with modems that had to transmit long distances over voice telephone circuits. Those circuits were bandwidth-limited to the needs of voice communication, and were frequently "noisy", so phone line modems never evolved beyond 56Kbit/s rates. The UARTs themselves could go faster, so if you were doing a local serial connection you could get up to 115kbps. These UARTs were relatively cheap.
More advanced encoding schemes plus more expensive hardware (with a lower noise floor) allowed connections about 100 times faster -- 10mbps ethernet. That's a much more common standard now than RS-232 serial connections, and as it became widely adopted it got cheap, and so 100mbps and gigabit ethernets followed the same form factor and basic electrical characteristics because (under good conditions) all could work over the same wiring, so compatibility with existing systems was good; the endpoints for the most part can automatically downgrade to whatever speed is supported by both ends of a given wire.

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


text:
Convert comma-delimited Arduino String of hex values to array of bytes

My apologies if this is a naive question. How do I convert a String which has hex values to a byte array that has those hex values?
This:
String s = "0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff";

Needs to be converted to this:
char test[] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };

I used the following procedure. It does convert it, however, each character is saved as a character as opposed to hex value:
unsigned int str_len = s.length() + 1;
char charArray[str_len];
s.toCharArray(charArray, str_len);

Any help will be appreciated. Thank you!

there is no such thing as a hex byte ... it is simply an 8 bit number ... you could use 0xff or 255 because they are the same value

@jsotola This is just an example, I need this to be used for all hex values. How do I convert the string to byte array?

Related: How to convert a hex string to an array of bytes?

You only convert the String object to a char array. It need to further split the char array into substring, and then convert it to number.
To split the char array, you can use strtok() function in c++ to do the job.
There is no str conversion function that can convert "0xff" into uint8_t directly. However, as @rubemnobre mentioned strtol() can be used to convert a c string to a long (in Arduino, it is 4-byte number) and further cast into a uint8_t and store in a byte array.
String s = "0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff";

// Convert String object to char array
unsigned int str_len = s.length()+1;
char charArray[str_len];
s.toCharArray(charArray, str_len);

uint8_t byteArray[7];
int i=0;

// split charArray at each ',' and convert to uint8_t
char *p = strtok(charArray, ",");
while(p != NULL) {
  byteArray[i++] = strtoul(p, NULL, 16);
  p = strtok(NULL, ",");
}

// Print the byteArray
for (i=0; i<sizeof(byteArray)/sizeof(char); i++) {
  Serial.print(byteArray[i]);
  Serial.println(", ");
}
Serial.println();

If you're not strtol's using "endptr" (&ptr in your case) you can just replace it with NULL and the parameter will be ignored. Also if you're casting to uint8_t then strtoul would be a better choice.

@Majenko, thanks and upvoted for your comment, make the code cleaner and simpler. I updated my answer.

There are C functions that can convert text to number. For example, strtol() or atoi(). Here is a little snippet to get you started:
char *str = "FF";
char *ptr;
int result = strtol(str, &ptr, 16); //the 16 is the base the string is in (HEX -> base 16)

result will have 0xFF or 255 by the end. You can use this to achieve what you are trying to do. Take a look at this for functions you can use to manage your String.


text:
changing from long to bytes and vice versa
I want to converse data from long to bytes and vice versa. After searching around, I sticked together some code, which seems to work (the same code works for int and floats as well).
The long value LongVal changes to a byte array, and the four bytes construct LongVal2. Obviously LongVal = LongVal2.
long LongVal = -4080;
long LongVal2;

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

//byte* my_function(long LongVal){
//  byte *LongVal_byte = (byte *) & LongVal;
//  return & (LongVal_byte[0]);
//}

//long my_function2(byte & LongVal_byte){
//  long LongVal2;
//  memcpy(&LongVal2, LongVal_byte, sizeof(LongVal2));
//  return  LongVal2;
//}

void loop(){

  byte *LongVal_byte = (byte *) & LongVal;
  memcpy(&LongVal2, LongVal_byte, sizeof(LongVal2));
  Serial.println(LongVal2);
  Serial.println(" ");

//byte LongVal_byte = my_function(long LongVal);
//LongVal2 = my_function2(byte & LongVal_byte);

}

But should I try to wrap the two first lines of loop() in two individual functions, errors occur. The remarked lines are my attempts to create two functions.
How to wrap them up properly?
EDIT
This is what appears if I try to use the remarked functions:
 In function 'long int my_function2(byte&)':
15:51: error: invalid conversion from 'byte {aka unsigned char}' to 'const void*' [-fpermissive]
25:0,
1:
117:14: error:   initializing argument 2 of 'void* memcpy(void*, const void*, size_t)' [-fpermissive]

 In function 'void loop()':
26:33: error: expected primary-expression before 'long'
27:30: error: expected primary-expression before '&' token

And what do the "errors" say? Hint: they tell you what is wrong - they're not just printed for fun. Read them. They are generally self explanatory.

@ Majenko That is true, but due to my inexperience to C, I lack to interpreter  them.

But we can. Or we could if you told us what they were. By the way, I can already see some fundamental misunderstandings and mistakes in your code. I want to marry those up with the error messages you are getting so that you can understand the errors better in the future.

@ Majenko I just added the error comments.

So many problems here:
1) in function call there shouldn't be types, only arguments. byte LongVal_byte = my_function(LongVal);
2) & before variable means "get variable address". However in function prototype long my_function2(byte & LongVal_byte) it means reference to passed variable (and it must be byte), not a pointer.
3) pointer to local variable is returned from my_function. It might be working until pointed memory gets rewrited by something else (another function call or so)
And whole code might look like that:
long LongVal = -4080;
long LongVal2;

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

byte * my_function(long & LongVal) {
  return (byte*)&LongVal;
}

long my_function2(byte * LongVal_byte) {
  return *((long *)LongVal_byte);
}

void loop(){

  byte * LongVal_byte = my_function(LongVal);
  LongVal2 = my_function2(LongVal_byte);

  Serial.println(LongVal2);
  Serial.println(" ");
}

But it is basically exactly the same as before without functions (just no need for memcpy)

@ KIIV It works flawlessly, and even more, it works with every type of variables, (int, floats, even strings), providing that I set in the code the right type of variable.

15:51: error: invalid conversion from 'byte {aka unsigned char}' to 'const void*' [-fpermissive]

memcpy(&LongVal2, LongVal_byte, sizeof(LongVal2));

LongVal_byte is a single byte. It's not a pointer, and memcpy expects a pointer.

26:33: error: expected primary-expression before 'long'

byte LongVal_byte = my_function(long LongVal);

You do not specify the variable type when passing a variable to a function. The variable already knows what it is, and the function already knows what it wants.

27:30: error: expected primary-expression before '&' token

LongVal2 = my_function2(byte & LongVal_byte);

Same there.
You are showing a fundamental lack of understanding of some concepts of C.  Other errors you are making:
long LongVal2;
...
long my_function2(byte & LongVal_byte){
    long LongVal2;

You should never ever re-define a global variable inside a function. It's not actually syntactically incorrect, but from a reading perspective it becomes almost impossible to keep track of which LongVal2 variable is being used at any one time.
long my_function2(byte & LongVal_byte){

You are passing a reference to a single byte, not an array of bytes. For that you need a pointer.
You should re-write your functions to be like this:
byte* my_function(long LongVal) {
    return (byte *)&LongVal;
}

(although that is completely pointless, you just need to cast the value, you don't need a function to do it:
byte *byteval = (byte *)&LongVal;

)
long my_function2(byte *LongVal_byte){
    long LongVal2;
    memcpy(&LongVal2, LongVal_byte, sizeof(LongVal2));
    return LongVal2;
}

That is a long winded, but "safe" way of doing it. It is needed only on CPUs where alignment matters.  On an 8-bit CPU the alignment is 8-bit, and so a 32-bit word can be at any address.  On a 32-bit system a 32-bit word will be at a 4-byte alignment, so that method is needed.  On an 8-bit though you can just cast the array into a long:
long *LongValue = (long *)&LongVal_byte;

A better solution to the whole thing, though, is to use a union:
typedef union {
    byte byteval[4];
    long longval;
} LongBytes;

LongBytes myVal;

You can then access:
myVal.longval = 4893723284;

And also:
myVal.byteval[i];

where i is 0-3.

@ Majenko Your comments were quite thorough and useful. Thank you for your interest.


text:
RTC square wave
I have a DS3231 Real Time Clock module and I'd like to use the Square Wave output.
I wonder how can I set the frequency of the pulse?
How long is the (time) length of the pulse?
UPDATED QUESTION
In order to use the DS3231 as an 1PPS interrupt, I want to use the Square Wave output. Here's how I connected it to an Arduino.

I connected to the SQW output a 10kΩ pull-up resistor and an LED. After that I tested the code which shows the time and worked fine.
#include <Wire.h>
#include "RTClib.h"

RTC_DS1307 rtc;

void setup () {
   Serial.begin(9600);
   #ifdef AVR
      Wire.begin();
   #else
      Wire1.begin();
   #endif
   rtc.begin();

  if (! rtc.isrunning()) {
     Serial.println("RTC is NOT running!");
     rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
    }
  }

void loop () {

   DateTime now = rtc.now();
   Serial.print(now.year(), DEC);
   // etc
   }

(The DS3231 works fine with the DS1307 library)
In this case the LED was just flickering, so I thought that the default frequency of the SQW should be grater than 1Hz. I googled a bit and realized that I had to change some registers. So I found this piece of code which I called from the setup() function, but with no success, the LED is still flickering.
void set1Hz() {
   // Frequency is stored in register 0x0e in bit 3 and 4
   Wire.beginTransmission(0x68);
   Wire.write(0x0e);
   Wire.endTransmission();
   Wire.requestFrom(0x68, 1);
   uint8_t register0E = Wire.read();

   // clear bits 3 and 4 for 1Hz
   register0E &= ~(1 << 3);
   register0E &= ~(1 << 4);

   // put the value of the register back
   Wire.beginTransmission(0x68);
   Wire.write(0x0e);
   Wire.write(register0E);
   Wire.endTransmission();
 }

Since I'm now qualified for low level programming, any suggestions on how to change the registers would be appreciated.

What does the datasheet say?

datasheet page 13.

Even though it is unusual for someone to answer his/her own question, I did some more digging and managed to solve the problem. So, I'd like to mention one or two items in order to help someone who may encounter the same problem.

I used the Jack Christensen's library https://github.com/JChristensen/DS3232RTC, but I had to update the Time.h library.
In the setup() I add this line in order to enable the SQW output and set it to 1PPS.
RTC.squareWave(SQWAVE_1_HZ);

Other options are SQWAVE_1024_Hz, SQWAVE_4096_Hz, SQWAVE_8192_Hz and SQWAVE_NONE
Using the LED and resistor (390Ω) as shown in the figure above, it works as a voltage divider. In that case the voltage between SQW output and Ground didn't exceed 2.0V. Thus someone should be careful if wants to have an LED indicator and wants to use SQW output as interrupt.

Please remember to mark your answer as solution in 3 days ;)

SQWV output only pulls low, it is an open drain output.
Wire up like this: 5V to LED anode, LED cathode to current limit resistor, other leg of resistor to SQWV pin.
Check the current capability of the pin. 10K will make very dim (if seen at all) LED. Try 1K.

with DS1307 Tiny RTC library:
"rtc.writeSqwPinMode(0x10);" in the setup loop...
sets DS output to 1 Hertz, squarewave
Its not exactly 1PPS signal, which is typically a narrow pulse,
but this 50% duty cycle signal will do as a 1 second interrupt.


text:
How to connect gyro to Arduino Uno via I2C
parts

Three-axis rate gyro on breakout board: gyro datasheet, breakout board "datasheet"
Arduino Uno: pinout

goal: I want to periodically read a single axes' angular rate. As rvbarreto pointed out, Adafruit built an Arduino library for this sensor, so I'm playing around with its example file.
configuration:

I have a 5600 Ohm pull-up connected to the SDA and SCL pins each on the Arduino. The internal pull-ups of the Arduino are too weak according to this thread.
code: (Adafruit library's sensorapi example)
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_FXAS21002C.h>

/* Assign a unique ID to this sensor at the same time */
Adafruit_FXAS21002C gyro = Adafruit_FXAS21002C(0x0021002C);
//Adafruit_FXAS21002C gyro = Adafruit_FXAS21002C(0x21);

void displaySensorDetails(void)
{
  sensor_t sensor;
  gyro.getSensor(&sensor);
  Serial.println("------------------------------------");
  Serial.print  ("Sensor:       "); Serial.println(sensor.name);
  Serial.print  ("Driver Ver:   "); Serial.println(sensor.version);
  Serial.print  ("Unique ID:    0x"); Serial.println(sensor.sensor_id, HEX);
  Serial.print  ("Max Value:    "); Serial.print(sensor.max_value); Serial.println(" rad/s");
  Serial.print  ("Min Value:    "); Serial.print(sensor.min_value); Serial.println(" rad/s");
  Serial.print  ("Resolution:   "); Serial.print(sensor.resolution); Serial.println(" rad/s");
  Serial.println("------------------------------------");
  Serial.println("");
  delay(500);
}

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

  /* Wait for the Serial Monitor */
  while (!Serial) {
    delay(1);
  }

  Serial.println("Gyroscope Test"); Serial.println("");

  /* Initialise the sensor */
  if(!gyro.begin())
  {
    /* There was a problem detecting the FXAS21002C ... check your connections */
    Serial.println("Ooops, no FXAS21002C detected ... Check your wiring!");
    while(1);
  }

  /* Display some basic information on this sensor */
  displaySensorDetails();
}

void loop(void)
{
  /* Get a new sensor event */
  sensors_event_t event;
  gyro.getEvent(&event);

  /* Display the results (speed is measured in rad/s) */
  Serial.print("X: "); Serial.print(event.gyro.x); Serial.print("  ");
  Serial.print("Y: "); Serial.print(event.gyro.y); Serial.print("  ");
  Serial.print("Z: "); Serial.print(event.gyro.z); Serial.print("  ");
  Serial.println("rad/s ");
  delay(500);
}

NOTE: I noticed that Adafruit's Github had removed a line of code (line 67) in their library's main .cpp file. I edited my library code to reflect that change.
problem: I keep getting the "Ooops, no FXAS21002C detected ... Check your wiring!" error message.
questions:

Am I connecting my pull-up resistors correctly?
Should I not power VDD and VDD_IO on the same rail? Can they even be powered by the Uno?

I'm assuming that the gyro is on a breakout board of some sort? Linking the manual/schematic might be helpful.

Your I2C resistors are at least 10 times to large, and your code seemingly has nothing to do with this sensor, or at least not with it's "gyro-ness".  If you are new to this, you'd probably do best to pick a part for which others have already devised wiring and Arduino code, otherwise you'll need to make your own deep dive into I2C basics and data sheet fundamentals.

The arduino Wire library activates the 10k internal pull-up resistors of the TWI and SCK pins.

There is a library for this sensor made by Adafruit available at Arduino IDE. If you have an up-to-date version of Arduino IDE, go to Sketch > Include Library > Manage Library and then type "FXAS21002C" and you will see it. Just install it and you will have the library and examples to test, explore and get this working.

The 0x20 is the 7-bit address. Or 0x21 if you opt to configure it for that address. The full slave address byte is either 0x40 or 0x41 depending on if it's write or read. You should look at table 9 on page 12.

@ChrisStratton I can't find it at the moment, but another EE-SE post suggested 47k pull-ups because the Uno's internal pull-ups are too weak. Is a 5600k pull up better?

@rvbarreto oh wow, thanks. This will save me a lot of work.

I needed to connect the gyro's reset input to V_DD_IO. See gyro datasheet, table 1, pin 4. This corresponds to pin 7/RST_21002 on the breakout board. The gyro works like a charm now!


text:
Converting Arduino LCD Programs to Serial I2C LCD code
I just got a Serial LCD and wanted to test it out with a game. I found this site with game conversions and wanted to use this game.  However since my serial LCD use the LiquidCrystalic2 library the code in its current state won't work. Is there a simple method of converting or porting liquidcrystal to LiquidCrystalic2? Or if someone knows of a simple game in regards to hardware that uses a serial lcd and could direct me to a link that would be great.

i got my lcd working on I2C following the steps in this link http://forum.arduino.cc/index.php?topic=128635.0


text:
"variable must be const" fix for Arduino progrem
I am trying to upload to my nano the code attached. It is giving me an error saying variable must be const about something I am trying to put in progrem. I learned that installing a older version of the compiler worked. However I was wondering is there a way to just edit the code to make it work. I tried putting const before it but it didn't work. It is on line 78 and 79 of the first file.
const extern PGM_P *NApowerCodes[] PROGMEM;
const extern PGM_P *EUpowerCodes[] PROGMEM;

Could you please post the concerning lines of code. You can't expect us to go to a webpage, find and download a zip, open it, just to see the code.

Which version of the IDE are you using? I was able to compile to code on 1.0.5

I am using the latest version, I believe 1.0.06. I was able to compile it with your version but would like to know how to fix it.

Using the source from this link I got it to compile following these steps.

Before opening the sketch in the Arduino:

Rename TVB.pde to TVB.ino
Rename WORLDcodes.cpp to WORLDcodes.h

Open the sketch (TVB.ino) in the Arduino IDE

Edit main.h and change:
// The structure of compressed code entries
struct IrCode {
  uint8_t timer_val;
  uint8_t numpairs;
  uint8_t bitcompression;
  uint16_t const *times;
  uint8_t const*codes;
};

to:
// The structure of compressed code entries
struct IrCode {
  uint8_t timer_val;
  uint8_t numpairs;
  uint8_t bitcompression;
  uint16_t const *times;
  uint8_t const*codes PROGMEM;
};

That is, add PROGMEM to the codes line.

Edit TVB.ino and change:
extern PGM_P *NApowerCodes[] PROGMEM;
extern PGM_P *EUpowerCodes[] PROGMEM;
extern uint8_t num_NAcodes, num_EUcodes;

to:
#include "WORLDcodes.h"

This avoids some linker problems in the original code.

Edit WORLDcodes.h and delete the line:
 #include "main.h"

Continue editing WORLDcodes.h and change:
const struct IrCode *NApowerCodes[] PROGMEM = {

to:
const struct IrCode * const NApowerCodes[] PROGMEM = {

And also change:
const struct IrCode *EUpowerCodes[] PROGMEM = {

to:
const struct IrCode * const EUpowerCodes[] PROGMEM = {

It should now compile OK.


text:
Arduino IDE. How do I use labels in a macro?
It's the Arduino Uno. I've spent hours reading on the internet but found nothing yet. If you use a label in the macro, the 2nd time it's called you get a duplicate label error.

Please provide your code and the exact error message and describe what you are trying to achieve

I suggest only using local lables in assembly macros.

Its the aduino uno ... no it's not ... the problem you describe has nothing to do with the type of arduino

Many thanks Edgar Bonet. Local labels is exactly what I  was looking for.

Just to make the question clearer, let's take a simple example. Consider
the following assembly macro that implements a delay loop:
.macro short_delay
    clr  r0
repeat:
    dec  r0
    brne repeat
.endm

and use it in a program that repeatedly blinks the built-in LED of an
Arduino Uno (a faster version of “Blink”):
main:
    sbi  DDRB, PB5   ; set pin 13 = PB5 as output
loop:
    sbi  PORTB, PB5  ; turn PB5 HIGH
    short_delay
    cbi  PORTB, PB5  ; turn PB5 LOW
    short_delay
    rjmp loop

When the assembler expands the macro, it ends up with this:
main:
    sbi  DDRB, PB5   ; set PB5 as output
loop:
    sbi  PORTB, PB5  ; turn PB5 HIGH
    ; start of short_delay macro
    clr  r0
repeat:
    dec  r0
    brne repeat
    ; end of short_delay macro
    cbi  PORTB, PB5  ; turn PB5 LOW
    ; start of short_delay macro
    clr  r0
repeat:
    dec  r0
    brne repeat
    ; end of short_delay macro
    rjmp loop

and this fails with
Error: symbol `repeat' is already defined

The solution to this problem is to use, inside the macro, only local
labels. These labels are just numbers. When using them, one has to
append the suffix “b” (for backwards) or “f” (forwards) depending on
whether the label is defined before or after the point where it is being
referenced.
The nice thing about local labels is that they are... well... local, and
thus they can be safely reused many times. The assembler disambiguates
them by choosing the definition that is closer to the point of use,
along the specified direction. With a local label (I choose 0), the
delay macro becomes:
.macro short_delay
    clr  r0
0:  dec  r0
    brne 0b  ; the branch target is the preceding label `0'
.endm

When the macro is expanded, the main program becomes:
main:
    sbi  DDRB, PB5   ; set PB5 as output
loop:
    sbi  PORTB, PB5  ; turn PB5 HIGH
    clr  r0
0:  dec  r0
    brne 0b
    cbi  PORTB, PB5  ; turn PB5 LOW
    clr  r0
0:  dec  r0
    brne 0b
    rjmp loop

Although repeated, the label is not ambiguous, as brne 0b always
refers to the closest label 0 along the backwards direction.

Welcome, this is the same thing I had problems a few years back. Define the label in the macro (function) and it will be local and not available to the rest of the world. You can use the same label as many times as you want they just need to be inside a macro.
void macro(int label)
{
   Do something with label and then exit;
}

You can do whatever you want, say get the value of several pins to see if they are all on then use the return true or false. When you leave the macro all of the variables will be lost and the memory returned to the heap. This is done in several ways in many of the libraries.

The question is about the use of labels in assembly macros, not about the use of variables in C++ functions.


text:
Arduino IDE for ESP32: Compilation Error: Exist status 255
Problem:
I have a ESP32 and I've been trying to flash it with the Arduino IDE, however it's been giving me Python error messages :/ when I'm trying C/C++ code to flash the Arduino.
Question:
How can I setup the board below so I can flashi it with C/C++ from the Arduino IDE?
Error Message:
  [6909] Error loading Python lib '/var/folders/wm/_tds7_0s6_j9587rbm54nfv00000gn/T/_MEIli4AzL/libpython3.8.dylib': dlopen: dlopen(/var/folders/wm/_tds7_0s6_j9587rbm54nfv00000gn/T/_MEIli4AzL/libpython3.8.dylib, 10): Symbol not found: ____chkstk_darwin
  Referenced from: /var/folders/wm/_tds7_0s6_j9587rbm54nfv00000gn/T/_MEIli4AzL/libintl.8.dylib (which was built for Mac OS X 11.0)
  Expected in: /usr/lib/libSystem.B.dylib
  in /var/folders/wm/_tds7_0s6_j9587rbm54nfv00000gn/T/_MEIli4AzL/libintl.8.dylib

  exit status 255

  Compilation error: exit status 255

ESP32:

References Used/Due Diligence:

Installing the ESP32 Board in Arduino IDE (Windows, Mac OS X, Linux)
Getting Started with the ESP32 Development Board
ESP32 Bluetooth Classic with Arduino IDE – Getting Started

Version Numbers:

MAC OS Version: macOS High Sierra Version 10.13.6

Arduino Version: Version 2.0.4-nightly-20230119 CLI Version: 0.29.0

The error message says "...Mac OS X 11.0...". Is that the version of OS X you are using? Can you tell us what version of the IDE you are using?

Appended into the Question: macOS High Sierra Version 10.13.6; Arduino Version: Version 2.0.4-nightly-20230119 and CLI Version: 0.29.0

@VE7JRO I've updated the question with the version numbers.

And what do you conclude? The library was built for 11.0 but you have 10.13... Did you try to use a version of the Arduino IDE for your OS?

You might want to re-read the referenced tutorials. Disclaimer: I don't have a Mac and no ESP32 at hand, but know a bit about general computer science and used the Arduino IDE for different targets.

I don't have Mac but I am working on Linux and I also had issues with Arduino IDE v2 (in the past). Because of this I'm still using IDE v1 with no issues and that's my suggestion: try older version of the IDE on your mac, you can still download it. If it won't work you can turn to PlatformIO or VSCode IDEs.


text:
Powering a Tiny Arduino Project
I'm trying to build a tiny project. After I program the board, to power the dev board - how can I power it to run the code?
Question:

I was curious as to how I would be able to power the ATtiny85 USB Mini Dev Board by using a 90mAh 3.7V LiPo battery which is connected to a TP4056 5V micro USB Lipo battery charger? The power is regulated to 5V by a  3v to 5v 1a USB Charger DC-DC Converter feeding the 5V pin on the ATtiny85.
If now, how else can I power the ATtiny85 USB Mini Dev Board with a rechargeable battery?

New Circuit

Old Circuit

Final Circuit

The old circuit will not work as you expect. While the ATtiny85 can run happily with 2.7 to 5.5V in this setup it expects 5V. I assume this is due to the high CPU clock setting. To run stable at a high CPU clock it requires 4.5V.
The VIN pin is connected to a linear regulator that has a 2V drop-out. Thus the supplied voltage has to be at least 2V about the target voltage. That is why the shopping page states a 5V (direct) or 7-35V (regulated at VIN) power supply.
Your LiPo charger already has a boost converter built in that boosts the battery voltage (3.0 - 4.2V) to 5V. No need to use a separate DC-DC boost converter here.
Just connect OUT+ to 5V and you are done.

Thanks, so the final circuit would be correct? It would have enough power to light up standard 3mm leds  connectected to the pins?

Yes, this is the wiring one would expect.

@Kwasmisch I have one more question. Would you kindly be able to help me out please?


text:
How to power multiple LEDs with a microcontroller
I currently have a "tiny" setup and want to put a few (~20-30) 0402 LEDs on a 1:87 scale car. My current setup is an ATtiny85 USB Mini Dev Board powered by a 90mAh 3.7V LiPo battery which is connected to a TP4056 5V micro USB Lipo battery charger:
To my bitter disappointment one cannot connect the leds in series. I've read about charlieplexing which was a little mind boggling for me to comprehend.
I was going to break down the leds and pins as follows:

P0 - headlights (2x white 0402 LEDs) +  tail lights (2x red 0402 LEDs) - in series - in parrallel
P1 - blinkers (4x amber 0402 LEDs) - in series - in parrallel
P2 - siren (12x amber 0402 LEDs) - in series - in parrallel
P3 - beacon (2x blue 0402 LEDs) - in series - in parrallel
P4 - beacon (2x blue 0402 LEDs) - in series - in parrallel
P5 - beacon (2x blue 0402 LEDs) - in series - in parrallel

Question:

With space being limited inside the model car how would I be able to
drive 20-30 LEDs with the above set up?
I am in doubt that the models in the video use charlieplexing and use a similar microcontroller, how would they be doing this?
Would it be better for me use something like a Pro Micro ATmega32U4 5V 16MHz and spread the LEDs across the 16 pins (ie 2 LEDs per pin = total of 32 LEDs)?

No, you will never want to put the LEDs in series. You will have to put them in parallel. Some LEDs have a forward voltage of about 3V if you put them in series you will have to provide 6V to turn them on. You can't do that with just 5V.

I see no reason why you would not be able to light 30 LEDs.
ATtiny85 only has 5 pins for use (unless you want to use the reset pin as well in which case hell will cover you). So with charlieplexing you are going to be able to address 20 endpoints. (where each endpoint might consist of multiple LEDs)
But beware. You CAN address 20 endpoints but you CANNOT light every combination simultaneouly. You will have to work out if there is a constellation that allows you to light all lights you want in the same time or you will have to use one of the timers to toggle between different lights. I don't know how well it works thou.
I have managed to use a timer on an 8MHz device to drive 4 LEDs at 400Hz directly without charlieplexing and not using PWM. So I assume it will be possible but might be flickering.
It would definitively be easier. I always recommend to stick to things that are well known and widely used. That would fit your ATmega32U4.

Make sure you layout your LEDs and think how you want to address them and if it makes sense to join multiple LEDs to one pin and toggle them at once.

so 2x 0402 leds per pin on a Pro Micro ATmega32U4 5V 16MHz would work well? Would the Pro Micro be able to supply enough voltage & current for 2 0402 leds?

Yes, the pin will usually provide enough current for two LEDs in parallel. You will have to limit the current by using a current limiting resistor. BUT you will have to worry about the current of all pins together. From the datasheet p.383 states you can draw at most 40mA per pin and 200mA in total. Those are absolute maximum before it will blast. Usually you aim to never exceed half of it. You will have to look up the current of your LEDs to see if you can drive them directly or have to use a transistor.

half of 200mA is 100 mA; @ 20mA per 0402 LED I can only run 5 LEDs at any given instance?

@3kstc you probably don't want to run those leds at 20mA or your model car will be to bright to look at. Using transistors will bypass this issue. This could be a good option for the headlights, as you want to run those at max output. PS the red leds you might be able to run in series.

@Gerben - I can maybe PWM them so that they aren't too bright? Would the brightness of a LED and current drawn be in a linear relationship - (ie 20mA = 255PWM, 127PWM = 10mA?)

Yes, you can do that but this is the average power output. You still have periods of 20mA and 0mA. The peaks do count if it comes to the absolute limits. ATmega32u4 seems to have enough PWM channels.


text:
Problem Bootloading AVR328P-PU
I executed the following steps in order to burn a bootloader into an  AVR328P-PU chip I acquired on ebay.

I have set up AVR328P-PU on a breadboard as described here: http://arduino.cc/en/main/standalone
I have uploaded the ArduinoISP sketch into Arduion Uno.
Connected the wires in a way described here http://arduino.cc/en/Tutorial/ArduinoToBreadboard ( the setup with external clock)
Chose "Tools -> Programmer -> Arduion as ISP" in the IDE.
Chose "Burn Bootloader" from the IDE.
Got and error avrdude: Yikes!  Invalid device signature., noticed that I connected the wires in the wrong order.
Fixed the wired, but still got the error:

avrdude: Version 6.0.1
     System wide configuration file is "C:\Program Files\Arduino/hardware/tools/avr/etc/avrdude.conf"

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

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

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

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.06s

avrdude: Device signature = 0x000000 (retrying)

Reading | ################################################## | 100% 0.05s

avrdude: Device signature = 0x000000 (retrying)

Error while burning bootloader.
Reading | ################################################## | 100% 0.07s

avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.
     Double check connections and try again, or use -F to override
     this check.

avrdude done.  Thank you.

My questions

I understand that this can be caused by poor breadboard quality. How can I test this hypothesis before buying new breadboard?
Could the wrong wiring from step 5 ruin the chip?

Did you try setting up a crystal?

@Ignacio Yes, I set it up exactly like in step 1.

Direct link to how the setup looks like: http://arduino.cc/en/uploads/Main/arduinobb_08.jpg

Are +5v and Gnd carried across the breadboard to both sets of power rails?  * In the article you linked, the Arduino provides power to the chip you're trying to program - so why is there a regulator on the breadboard? * If the regulator is the chip's power supply, is its input voltage high enough for it to regulate, and are the grounds of both supplies (the Arduino and your breadboard) board connected to each other? * To your question 2, Maybe yes ... exactly what were the wrongly ordered connections?

@JRobert I have uploaded photos of the setup. The regulator is there, but for the bootloader burning, I power the breadboard from the Arduino.  The wrongly ordered connection was swapping of the blue and yellow wires (SCK <-> MOSI). Could this ruin the chip?

My guess is no - I'd be more concerned of one of the swapped wires was the Arduino's +5v or there'd been some cross connection of the two power supplies.

On the Arduino Uno, you'll need to connect a 10 uF capacitor between reset and ground (after uploading the ArduinoISP sketch)

@Gerben Same error. But can you explain the reasoning behind the suggestion?

http://arduino.cc/en/Tutorial/ArduinoISP . Wiring seems fine, but the programmer can't see the chip (sign. 0x0000). Try wiggling the pins in the breadboard, to make sure they make good connection. What leds do light up? (Left constant, and right flickering during programming?)

Being from eBay, I would assume the seller "bricked" the chip beyond his/her capability to fix.  Fortunately, you know about stack exchange!
My immediate suggestion is to find, borrow or build a high-voltage programmer.  This is a special programmer that can un-brick the chip no matter what's been done to it. The concept is easy, but you need to protect the programmer's pins from the 12v reset signal.
Googling "avr high voltage programmer" gives several useful links.
I'll get the actual links when I get back to a real computer.
Ok, so life got in the way, sorry about that.
This is the one I built which worked perfectly:
MightyOhm
However hooking up the AVR to a "high voltage programmer" is well documented in the data sheets.  These should be very much similar circuits on Google.

I had this exact same problem.  It turned out that my atmega328p had the wrong fuses.  I am not sure how to solve the problem using the default ardiuino ide, however I was able to plug my ArduinoISP into a linux machine (just plug in the usb) and correctly profram the fuses on a slave atmega328p to solve the problem:
The guide here gets you started, however it missing some of the fuses:
http://heliosoph.mit-links.info/arduinoisp-reading-writing-fuses-atmega328p/
The full command to set the default fuses is something like this:
avrdude -P /dev/ttyACM0 -b 19200 -c arduino -p m328p -U lfuse:w:0xFF:m -U hfuse:w:0xDE:m -U efuse:w:0x05:m