text:
How to interface OV5640 to Arduino Mega using Embedded C?
I am trying to interface a OV5640 camera module to Arduino Mega 2560 in Eclipse IDE using C language . However I am not able to figure out the registers that need to be initialised , for the camera to start capturing pictures .
There are Arduino libraries to deal with setup and image transfer , however I do not wish to use them . I would like to code in C , without using any library . I just need to know which registers need to be accessed and modified to get the camera working .
For reference - I am trying to create a CCTV based system that will record picture based on intruder presence . The entire project is written in C language without any libraries .
Data sheet for OV5640 -https://cdn.sparkfun.com/datasheets/Sensors/LightImaging/OV5640_datasheet.pdf
Take a look in this link to get an idea about the kind of program it'll be.
How to get 38 Khz clock from Timer 0/2 in Arduino Mega 2560?

Tackling this kind of project usually requires learning how to read data sheets for yourself.  Failing that, study the libraries until you understand what they are doing well enough to make a simpler version in plain C and change whatever else you may not like about them.  Strictly speaking, the goal of plain C development without libraries is off topic here, because "Arduino" is primarily a library-centric approach to C++ development.

Arducam gives you all the info you need on the necessary register settings. The register values for each color space and resolution are defined in this header while the initialization sequence, image format selection and image capture process among other stuff, are implemented here and documented if you look closely at the variable names and compiler directives.
EDIT: More details
Lines 327 - 372 contain the relevant initialization sequence for this specific camera. For instance, assuming you want JPG images, line 335 marks the start of the needed settings:
delay(100);
wrSensorReg16_8(0x3103, 0x11);
wrSensorReg16_8(0x3008, 0x82); delay(100);
wrSensorRegs16_8(OV5640YUV_Sensor_Dvp_Init); delay(500);
wrSensorRegs16_8(OV5640_JPEG_QSXGA);
wrSensorRegs16_8(OV5640_QSXGA2QVGA);
wrSensorReg16_8(0x4407, 0x0C);  # assuming you arent using the Arducam shield or OV5640 5MP Plus

What wrSensorReg16_8 does is pretty obvious: write the 8-bit 2nd argument into the register specified in the 16-bit 1st argument. wrSensorRegs16_8 merely does the same thing for multiple register-value pairs passed into it. OV5640YUV_Sensor_Dvp_Init, OV5640_JPEG_QSXGA and OV5640_QSXGA2QVGA are all structs defined in the header I mentioned earlier; they contain the rest of the register-value pairs you need to know about. Ultimately, these settings should give you 320x240 JPEG, I think.
You can't use the start_capture method since you don't have the ArduCAM FIFO so you'll have to start grabbing frames yourself (and buffering them somewhere very quickly; transmitting the bytes as you read them is out of the question) by paying attention to VSYNC, HREF and PCLK. Look at the timing diagrams in the datasheet. I assume you'll only be taking frames occasionally since a Mega won't do for video. If you're very lucky, you'll get a nice image on your first try but on the whole, be ready to spend serious time studying the datasheet, ArduCAM code and other 0V5640-related code on the web or just go with the OV7670 which has more examples/tutorials.

@TisteAndil thank you for those links. I could gather some idea about the required registers .however it would be nice , if you can list them in order . I'm new to embedded programming and seeing the list of registers , I feel I am gonna miss out some important register settings. So it'll be helpful if you can make a list out of those entire register set that needs to be set  .   thanks

@BoudhayanDev Edited my answer.

thanks a lot . I guess you are right . Even with these setup configuration , clicking the image and getting the data will turn out to be seriously difficult . If you have solution for that please add it in your answer .  If not it's alright . Thanks for your answer.

@BoudhayanDev You just need more experience before working on a project of this complexity. You can either work with a ready-made solution like the ArduCAM or just go ahead with your current plan, no matter how long it takes.

Thanks . You are right. I'll need to know a bit more in detail before I can succeed with this project.  One last question - which camera do you suggest ? Should I go for the 2640 ,5640 or 7640 variant ? I will be also interfacing a SD card with it to store the captured image . Which camera module is relatively simpler to work with for a beginner?  @TisteAndii

@BoudhayanDev The OV7670 is the most commonly used with Arduinos. Max resolution is 0.3MP at 640x480. Buy the module that comes with an AL422 FIFO so it can buffer frames for you and then search for tutorials that show how to set up the camera and capture frames. Memory card is only useful if you intend to take pictures occasionally or get < 5 fps video (at VGA res).


text:
Multiple IDE instances
I recently moved all in for Linux and have no intentions of going back to Windows, but programming for Arduino is a little annoying as I cannot find a way to have multiple instances.
In Windows you create individual shortcuts for several Arduino IDE instances. When you launch these from the desktop they are autonomous, meaning you can set a board/port combination for each one.
I have yet to find a way to do that in Ubuntu. Is there some form of isolation I can use? I tried using workspaces but they all still see just the one setting.
I do not want to have a bunch of VMs and switch from one to the other unless that is the only option left.
Is there some way I can emulate the Windows autonomous shortcut approach in Ubuntu?

Use UECIDE. I specifically created it to address that problem amongst others.

How do we get that, @Majenko?

@SDsolar http://uecide.org/download.php

@Majenko Thanks, I will give that a try and report back.

@Majenko The .deb link returns a 404. I checked the downloads folder and the only.deb is for an earlier version. Should I be using that?

It should be in the preview folder. Same version pre14.

@Majenko Thanks, but it is just too difficult to get working. It cannot find my-own Libraries. I tried every Path and Folder combinations I could think of and it still keeps saying they do not exist.

There is nothing special about it, it just works.
I strongly suggest to remove everything that is Arduino related from the repositories and have a minimal Java environment installed.
It is no problem to have a gcc build environment together with Arduino though. Even a gcc-avr build environment from the repositories is no problem. But don't install any Arduino or Java-rxtx from the repositories.
You can download the linux version and unpack it in a folder.
Go to that folder where you unpacked the Arduino files and right-click on the 'arduino' file to create a shortcut. Move that shortcut to your Desktop.
Depending on the flavor of Ubuntu that you have, you can also create a starter and fill in the whole path of the 'arduino' file.
Then you can start the Arduino IDE, and just click/activate that shortcut or starter again for another instance of the Arduino IDE. They will work independent of each other. You have to set the right board for each instance of course. A third one or more is also possible.
If you have trouble with shortcuts or starters, then you can even open a terminal and go to the unpacked files, type "./arduino" to start it. Open an other terminal (or new 'tab' in the terminal) and do the same.
You don't have to makes copies of the Arduino files, you don't have to make multiple shortcuts or starters. Just start a new instance by activating the shortcut or starter once more.
I recommend to use only the newest version (at the moment 1.8.3). But if you need to run an older version then you can download and unpack older versions in seperate folders. Be careful that you can not run different versions of the IDE at the same time. The Arduino IDE before 1.6.x differs too much from 1.8.x. All of them share the same ~/.arduino15 folder with settings and downloaded files, which can cause trouble when running a new version, then an older version and then a newer version again.

Thanks, I will try UECIDE first then attempt your suggestions, but right now, they sound a little out of my current knowledge level with Ubuntu.

Thanks, I have that working for two version and that will do fine for now. The UECIDE thing is not working at all well and I can't be bothered trying to mess with it any longer.

The term 'version' could be confusing, I have added more explanation in my answer about 'version'.

I have to downvote your answer. While technically correct and to the point, is inappropiate, because OP stated that he is new to Linux and wants a simple solution. UECIDE solve the OP's problem, is better than Arduino IDE in every aspect, and doesn't requires any special installation.

@LookAlterno ha ha ha, that doesn't make sense at all. Starting a shortcut twice is all that is needed. The rest is explanation how to get the Arduino IDE working in linux properly.

Focus on the people and his needs.

Use UECIDE. It does everything Arduino IDE does, can have multiple instances running out of the box, and projects/libraries are 100% compatibles.
You get a nice standard interface, with a project, edit and output panes.

IDE can be extended with plugins:

Download it from the same site. You have versions for Windows, Mac and Linux:

Linux files
To run on 64-bit Linux you may need extra libraries installed. These
  are for the compilers, not for UECIDE, some of which only come in a
  32-bit flavour. Possible libraries include the i386 version of libc6.
uecide-0.8.9-pre17_all.deb
uecide-0.8.9-pre17-linux.zip

As UECIDE follow follow strictly the rules for project/directory organization as standard Arduino IDE, libraries and projects are compatibles. You can use Arduino IDE and UECIDE on the same project without harm.
I used Arduino IDE at first, and later slowly migrate to UECIDE, keping both for a while, but right now I keep Arduino IDE only as a backup.
@Majenko is the mantainer. Shy guy, doesn't promote himself.

It's not maintained anymore

source: Stack Exchange

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

sort: votes


text:
Turning on many (30) leds arduino mega
I´m new working with Arduino. Right now I have a project thar requires to turn on 30 LEDs at the same time with an Arduino Mega. The problem is that it would exceed the max current that the chip can tolerate.
It is possible to do this by turning on one LED at the time, very fast?
If it is, any clue on the code to achieve that will be apreciated.
Thank you very much
P.S.: I know there are components to expand the quantity of pins that work like that, but the idea is to avoid using one.

Do you need to run them at high brightness (=high current)?  Strobing them will have the effect of reducing the brightness, and if you don't need high brightness then you can use higher current-limiting resistors so save the effort of strobing them. If you need them to be bright, you'll need some sort of driver - the right transistor will probably be sufficient.

This page explains that the ATmega2560 could drive up to 800mA: Arduino Playground: Arduino Pin Current Limitations
There are limitations for groups of pins, so you have to be careful.
The 800mA is a lot in my opinion. I wonder how hot the chip will become.
What kind of leds do you use ? Normal 20mA leds ? Or is 10mA leds also possible ? 30*20mA = 600mA, but 30*10mA is only 300mA. The 300mA seems a lot safer to me.
With Charlieplexing the leds are not 'on' all the time. However, with the Arduino Mega 2560 you have enough pins, and you could just lower the current through the leds.
Turning them on for a short time (without Charlieplexing) is the same as turning them continuous on with a lower current.
The most common way to drive 30 leds is with a led strip. For example a led strip with neopixels. That led strip has to be powered seperately.
My advice is to lower the current for the leds to 10mA and hope that the ATmega2560 doesn't get too hot.
[ADDED] 300mA is still a lot. Start with 5mA per led for a total of 150mA when they all are on at the same time. Many modern and good quality leds are bright at 5mA.

Note that, if the LEDs are not blue nor white, and if the don't have to be individually addressed, they could be wired by pairs in series.

usually, 10ma is not much "dimmer" than 20ma, so if it's not for illumination nobody will notice.

Use external drivers, like a transistor.
If you have to tie them to the avr, use large or larger current limiting resistors. Or to multiplex so only some of them are on at a given time.

Use the MAX7919. It is a driver for multiples leds. It lets you output up to 64 leds at a high enough brightness.
https://playground.arduino.cc/Main/LEDMatrix
Its usually made to drive LED matrices or 7-segments LEDs.

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


text:
Using chipKIT WiFi Shield with an Arduino
I'm beginning with Arduino and I have to make two of them communicate via WiFi. I'm going to implement the examples for a WiFi Client and WiFi Server in their tutorials page.
The problem is I only have one Arduino WiFi Shield which is working fine. But I also have a chipKIT WiFi Shield.
My question is: Can I use this other shield to do what I want with one of my Arduinos (I have Uno, Mega and Due) and how? Because I've plugged the shield and I've uploaded the code but it didn't seem to work.

No, you can't. The only libraries available for the chipKIT WiFi Shield are written specifically for the chipKIT boards.
Also, how have you plugged the board into an Arduino? The chipKIT WiFi Shield has Digilent's own header layout with a double row of headers where the Arduino only has a single row. Half the pins won't be plugged into anything.

Thanks. I don't know much about chipKIT products. Only that I could use Arduino IDE also. And since I could plug it into a Uno I thought they could be compatible. The picture: https://www.dropbox.com/s/32pv2t0e0s1ptrh/2017-06-15%2007.19.04.jpg?dl=0

Look from the end - you'll see half the pins dangling in mid air.

You want something like an Uno32, uC32 or MAX32 to work with the WiFi Shield.

You're right, Majenko. But I thought that this was "normal". For some reason I thought the pins were like that so I could plug into different board sizes. My mistake. First time using shields.


text:
Diffrence between running once and infinite
const int ledPin = 12;

void setup(){
    pinMode(ledPin, OUTPUT);
    Serial.begin(9600);
}

void loop(){
    if (Serial.available()) {
        light(Serial.read() – '0');
    }
    delay(500);
}

void light(int n){
    for (int i = 0; i < n; i++) {
        digitalWrite(ledPin, HIGH);
        delay(100);
        digitalWrite(ledPin, LOW);
        delay(100);
    }
}

by Oscar Liang
awesome little piece of code which taught me how to setup connection by serial. yet one part I don't understand fully. Why does this line:

light(Serial.read() – '0');

make the code run once,
and this line an infinite times.

light(Serial.read());

has this something to do with binary? I don't get why subtracting the string 0 would run the code once.
Thanks in Advance!

Serial.read() -'0'
Such code is often used to convert a character to a digit (e.g. int).
Like if the character is '2', than '2' - '0' = ascii 50 - ascii 48 = 2
However, if you use
Serial.read()

the value will be 50 instead of 2.... maybe looping 50 times (or 48 to 58, for values 0 to 9) will give you the impression it runs infinite?

oh wow Thank you, so that is just a way to convert to a int. Never knew that!

Yes, it is a way to convert one digit (so a character from '0' to '9') to an integer. Nb if this answer is good, consider upvoting and accepting it as your answer.

cant upvote yet. I don't have enough rep, but you will get it in the end :)

Thanks for accepting. No problem (geen probleem). Enjoy programming!


text:
Optimizing ext. SPI ADC for speed and verify the speed
So I have a project where I will be using an Arduino Leonardo and an external ADC (AD7980) to run a 16-bit (18bit) conversion and transmit it to the Arduino and then out on USB as fast as possible.
The AD7980 can run up to 1 MSPS, and I know I cannot reach that with the ATmega32U4 - but I want to know how to optimize my code for running it as fast as possible and how to measure it.
Right now my code is:
#include <SPI.h>

int CNV= 11; //Convert on pin 11
int Slaveselect=8;
int adcValue;
byte highByte;
byte lowByte;

void setup() {
  Serial.begin(115200);
  SPI.begin();
  SPI.setClockDivider(SPI_CLOCK_DIV2 ); // 8 MHz rate
  SPI.setBitOrder(MSBFIRST);
  pinMode(Slaveselect, OUTPUT);
  pinMode(CNV, OUTPUT);
}

void loop() {
  digitalWrite(Slaveselect,HIGH);
  // SS always high to use 3 Wire mode without busy indicator
  digitalWrite(CNV,LOW);
  digitalWrite(13,LOW);
  digitalWrite(CNV,HIGH);//starts conversion
  digitalWrite(13, HIGH);
  digitalWrite(CNV,LOW); //starts to transmit MSB on data line
  digitalWrite(13,LOW);
  highByte = SPI.transfer(0x00);
  lowByte = SPI.transfer(0x00);
  adcValue = highByte << 8;
  adcValue = adcValue | lowByte;
  Serial.print("analog value =");
  Serial.println(adcValue);
  Serial.print('\n');
}

The datasheet for the ADC can be found here: Datasheet

Don't use digitalWrite().
Don't use delay().
Don't flood your Serial connection with useless junk ("analog value =")

You may also consider using lower level SPI operations instead of the SPI library, which is completely blocking and slows you down. At least consider the use of SPI.transfer16(...) which is more efficient than two SPI.transfer(...) calls.

"1. Don't use digitalWrite()" What should i use then?

@Martin.E Direct port manipulation. https://www.arduino.cc/en/Reference/PortManipulation

Either write on GPIO registers directly (https://www.arduino.cc/en/Reference/PortManipulation, http://stackabuse.com/speeding-up-arduino/) or use at least https://github.com/NicksonYap/digitalWriteFast .

Also - changed my code to not use delay() and changed to SPI.transfer16 - now I have a sample periode of 44 micros - #Edit - With digital write fast, i am now down to 8 Micros

But by useing this, It looks like i lost some precision - Before this change, my max ADC value was 32000 - now its around 19000, and my minimum was 0 now it is 10000

You are probably violating some of the timing specifications (p.7f of the PDF). Conversion time is at least 500ns to at max 710ns, and the SPI.transfer might kick in before that. Time between conversions is at least 1000ns, acquisition time 290ns. FastDigitialWrite needs ~125ns on a 16MHz Uno. You should probably get an oscilloscope / logic analyzer to debug this thing now on these speeds. "Waiting" can also be done by burning cycles using the "NOP" instruction (https://forum.arduino.cc/index.php?topic=433372.0)

For fast possible speed, use spi transmission buffer and spi interrupt. The concept is that once there is at least free space in the buffer, it interrupts and you load the next byte into the buffer.
That's assuming that dma isn't available.
Short of that, don't use arduino GPIO functions - they are like 100x slower than that's possible. And use a usartt isr to  manage transmission.


text:
Trying to turn off fading RGB LED after 30 secs
I am trying to get something to work so that an RGB LED fades through the color spectrum, and when a button is pressed some music plays.
That is not the problem.
Assume I am using any loop that functions can be called at any time in.
I am trying to make it so that if the button is not pressed for a certain amount of time, say 30 seconds, the light stops fading through the color spectrum and when the button is pressed in this 'sleep mode', first the light starts fading, and then the next press plays the music.
I am aware this could be done somehow with millis();, but how would I approach this?
I am using an Arduino Uno.

If it is working now as you want it. Please consider accepting the answer that helped you in order to indicate to others that this issue has been resolved. Thank you for your cooperation to make this forum better.

Here is a little snippet of logic that you can implement in your code :
if(millis() - getOutOfSleepTime >= 30000) {
    activateSleepMode();
    while(!buttonPress);
    getOutOfSleepMode();
    getOutOfSleepTime = millis();
}

if(buttonPress)
    activateSleepMode();


text:
Issue with code for SDA/SCL TC9548A Multiplexer and HMC5883L sensors
This is my first time posting on this forum, so I hope my question is appropriate here. My team is working with the Adafruit TCA9548A 1-to-8 I2C Multiplexer Breakout board to try and read from six HMC5883L Breakout sensors, and I am in the process of trying to look at their code to solve a problem. For some reason, code does not run at all unless you comment out a certain line in the code. Once it is commented out, the code runs as expected.
Now, we have to initialize it in setup(), but the statement tcaselect(0) statement was commented out so it doesn't initialize the 0th sensor in setup(). We can keep the other part, the if(mag0.begin()) statement, and it works as expected. However, if we uncomment out tcaselect(0) in setup, the entire code crashes, and all we see are 'HM' in the display window. A very basic schematic is shown below:

simulate this circuit – Schematic created using CircuitLab
I ran some tests with my team, and when all six HMC5883Ls and the single TCA9548 multiplexer were connected on the same breadboard according to the schematic, they worked when tcaselect(0) in setup() was not commented out. Next, we had an apparatus to hold the six sensors, and we had it connected with long lengths of wire, the same as the schematic. We hooked it up to the same breadboard, and the code would not run unless tcaselect(0) in setup was commented out. This seems strange to me that they would work when connected on the breadboard, but when spread out and connected to the breadboard via long wires, they would not work unless that code was commented out.
https://learn.adafruit.com/adafruit-tca9548a-1-to-8-i2c-multiplexer-breakout?view=all
https://learn.adafruit.com/adafruit-hmc5883l-breakout-triple-axis-magnetometer-compass-sensor/overview
EDIT: Someone mentioned that wires might have problems with the SDA/SCL bus, so the wires that we're using are 4-pin ribbon cables, 2.54 mm pitch. A very rough schematic of the container that we're using is shown below:

simulate this circuit
Sorry for the roughness. It's the best I can do to show how the container is assembled. There's an 8x8 in. box where the components are stored, so the sensors go from various locations in the apparatus to the center box where the Pi, Arduino, and breadboard are placed. The nodes in the schematic represent the locations of the sensors. Given the rough dimensions, the longest distance for one of the sensors is around 56.8 inches (or approx. 1.45 meters) accounting for some extra wiring.
Code:
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_HMC5883_U.h>

#define TCAADDR 0x70

/* Assign a unique ID to this sensor at the same time */
Adafruit_HMC5883_Unified mag0 = Adafruit_HMC5883_Unified(0);
Adafruit_HMC5883_Unified mag1 = Adafruit_HMC5883_Unified(1);
Adafruit_HMC5883_Unified mag2 = Adafruit_HMC5883_Unified(2);
Adafruit_HMC5883_Unified mag3 = Adafruit_HMC5883_Unified(3);
Adafruit_HMC5883_Unified mag4 = Adafruit_HMC5883_Unified(4);
Adafruit_HMC5883_Unified mag5 = Adafruit_HMC5883_Unified(5);

//Display details of sensor here
void displaySensorDetails(Adafruit_HMC5883_Unified *mag){
  sensor_t sensor;
  mag->getSensor(&sensor);
  Serial.println("------------------------------------");
  Serial.print  ("Sensor:       "); Serial.println(sensor.name);
  Serial.print  ("Driver Ver:   "); Serial.println(sensor.version);
  Serial.print  ("Unique ID:    "); Serial.println(sensor.sensor_id);
  Serial.print  ("Max Value:    "); Serial.print(sensor.max_value);         Serial.println(" uT");
  Serial.print  ("Min Value:    "); Serial.print(sensor.min_value); Serial.println(" uT");
  Serial.print  ("Resolution:   "); Serial.print(sensor.resolution); Serial.println(" uT");
  Serial.println("------------------------------------");
  Serial.println("");
  delay(500);
}

//Given sensor i, select and write to it
void tcaselect(uint8_t i) {
  if (i > 7) return;
  Wire.beginTransmission(TCAADDR);
  Wire.write(1 << i);
  Wire.endTransmission();
}

    void setup() {
  Serial.begin(9600);
  /* Initialise the 0st sensor */
   //tcaselect(0);
   if(!mag0.begin())  {
    /* There was a problem detecting the HMC5883 ... check your connections */
    Serial.println("Ooops, no HMC5883 detected ... Check your wiring!");
   }

  /* Initialise Sensors 1-6 */
  tcaselect(1);  if(!mag1.begin())  {  Serial.println("Ooops, no HMC5883 detected ... Check your wiring!");  }
  tcaselect(2);  if(!mag2.begin())  {  Serial.println("Ooops, no HMC5883 detected ... Check your wiring!");  }
  tcaselect(3);  if(!mag3.begin())  {  Serial.println("Ooops, no HMC5883 detected ... Check your wiring!");  }
  tcaselect(4);  if(!mag4.begin())  {  Serial.println("Ooops, no HMC5883 detected ... Check your wiring!");  }
  tcaselect(5);  if(!mag5.begin())  {  Serial.println("Ooops, no HMC5883 detected ... Check your wiring!");  }

}

void loop() {
  /* Get a new sensor event */
  sensors_event_t event0;  sensors_event_t event1;
  sensors_event_t event2;  sensors_event_t event3;
  sensors_event_t event4;  sensors_event_t event5;

  tcaselect(0);  mag0.getEvent(&event0);  tcaselect(1);  mag1.getEvent(&event1);
  tcaselect(2);  mag2.getEvent(&event2);  tcaselect(3);  mag3.getEvent(&event3);
  tcaselect(4);  mag4.getEvent(&event4);  tcaselect(5);  mag5.getEvent(&event5);

  /* Display the results (magnetic vector values are in micro-Tesla (uT)) */
  Serial.print(event1.magnetic.x); Serial.print("  ");
  Serial.print(event1.magnetic.y); Serial.print("  ");
  Serial.print(event1.magnetic.z); Serial.print("  ");

  Serial.print(event2.magnetic.x);      Serial.print("  ");
  Serial.print(event2.magnetic.y);      Serial.print("  ");
  Serial.print(event2.magnetic.z + 37); Serial.print("  ");

  Serial.print(event3.magnetic.x); Serial.print("  ");
  Serial.print(event3.magnetic.y); Serial.print("  ");
  Serial.print(event3.magnetic.z); Serial.print("  ");

  Serial.print(event4.magnetic.x); Serial.print("  ");
  Serial.print(event4.magnetic.y); Serial.print("  ");
  Serial.print(event4.magnetic.z + 37); Serial.print("  ");

  Serial.print(event5.magnetic.x); Serial.print("  ");
  Serial.print(event5.magnetic.y); Serial.print("  ");
  Serial.print(event5.magnetic.z); Serial.print("  ");

  delay(500);
}

EDIT: Big news, I tried using only two sensors and 1.5m cables and adding 10k pullup resistors from VCC to SDL/SCA on the respective sensors; with these changes, they seem to work even with tcaselect(0) not commented out in setup, though I only used two sensors rather than six. The HMC5883L sensor breakout board contains 10k pullup resistors already, so with another 10k resistor per line, it would make it 5k. Would this value be too much, or is it fine? I looked at the datasheet of the sensor itself, but I can't find anything on what value the input impedance would be for SCL/SDA.
Also, on another related note, one of my sensors had wires crossed deliberately, so SCL and SDA are separated by GND and VCC in the cable. I'm still running tests to see if I need to do this, but is it recommended to do so even if it is not necessary for correct operation? Someone mentioned that having SCL/SDA next to each other would be bad if they cause problems with crosstalk/interference.

You could follow that tutorial from start to finish. There is a I2C scanner for each of the 8 channels. You could run that to see what it finds. How many pullup resistors did you add. I think that you need 2 pullup resistors that are on the multiplexer module, and 16 more pullup resistors. Did you read the note about the pullups in the "I2C Multiplexed-Side pins" paragraph ? Don't select a channel without pullups, when SDA or SCL is low, the Arduino I2C scanner stops working.

It stops at your dummy sensor ? What is a hardware dummy I2C sensor ? I have never heard of it before. Did you ask patent for it ? You might be the only one in the world that has one.

Thanks for your replies. Sorry, I use the term dummy sensor to denote a sensor that is attached to the setup, but we don't use it. It's just another HMC5883L, but we don't use it.

The HMC5883L breakout board has 10k pullup resistors from the SCL/SDA pins to VCC, so there's no problems there. For the multiplexer itself, we didn't add any pull up resistors. I saw the paragraph, but with the pull ups on the sensor, it should be fine, right?

Yes, pullup resistors on the HMC5883L module are fine. Select only the channels that have the pullup resistors. When nothing is running and Wire.begin() has been called, all SDA and SCL pins on both sides of the multiplexer should be high.

I apologize, but this doesn't exactly help with my problem. All of the sensors that we are using contain pullup resistors. It's just that something seems to happen when we don't have a sensor connected to SD/SC0 on the multiplexer, so we can't read from the other sensors as well. Looking at tcaselect, it seems to write an 8-bit signal to TCAADDR, but with a '1' bit depending on the device. If that's the case, then TCAADDR should be no problem.

@user101402 did you try with just one sensor?

Yes, I tried it with one sensor on a breadboard. Then I moved up to two, three, and then seven sensors. After that, I hooked up the sensors to sections of an apparatus and connected them to the breadboard with long wires. The wires were properly connected according to my new schematic, but it wouldn't work unless that line of code was not commented out.

How long are the wires ? what kind of wires ? Putting SDA and SCL in a ribbon cable is very bad for the signals. The Adafruit multiplexer has 10k pullup resistors for the signals to the Arduino. That means it might work up to 50 cm. Try to add pullup resistors at the Arduino, perhaps 3k3 or 4k7. They will be parallel the 10k and parallel the internal 50k pullup resistors of the Arduino board. You might want to try Wire.setClock(50000L) to lower the I2C clock.

Maybe your bus capacity is too big?

The bus capacity seems okay, as it handled 7 sensors when all on a breadboard. The wires are 4-pin ribbon cables, and length varies depending on the location. I'll edit my post once I get the measurements, but for the pullup resistors, would they be placed on the A4/A5 lines to +5V? I'm looking at the schematic (Uno Rev 3), but I don't see where the 50k/10k resistors are. The sensors and the multiplexer already have pull up resistors on them. Also, how would lowering the I2C clock help with tcaselect(0)? It doesn't explain how this line works with sensors on the breadboard but not with wires.

A flat ribbon cable with SDA and SCL next to each other is the worst possible wiring for a I2C bus. The SDA and SCL should have minimal capacitance to GND and VCC and they should not interfere with each other. If a pulse from SCL appears on SDA (or the other way around) that will make it impossible to make the I2C bus work. Capacitance to GND and VCC can be solved (for a part) by lowering the value of the pullup resistors and by lowering the I2C clock. But crosstalk between SDA and SCL can not be prevented that way. You have not told us yet how long the wires are.

I put down the distance from the center box to the farthest placed sensor, being around 1.45m, so that's approximately how long the wires are. The shortest distance is around 10 inches or so. I understand what you're saying about the I2C bus and the wire placements, but this is what I have to work with. I can add another resistor in parallel to reduce pull up value, Nevertheless, the strange issue still remains that with tcaselect(0) commented out in setup, all sensors were able to be read from. It's strange that this line of code is commented; kind of feels like it shouldn't be.

I'm sorry, but SDA and SCL next to each other in a flat ribbon cable is wrong, you should refuse to work with that. You can split the wires over the complete length of the ribbon cable, all of them. That will improve the signals. Did you forget the Wire.begin ? Perhaps some hardware needs time to power up. You could add a delay of 500ms before starting to use the I2C bus.

Jot, Thanks for your comment. I think that one of my issues is that I needed pull-up resistors. I used 10k resistors for the SDA/SCL lines on the sensors, so that worked with the cable. In regards to your comment on the cable, rather than having SDA and SCL next to each other, I moved the soldered wires around at the sensor so along the cable, SCL was on one side, SDA was on the other, with GND and VCC in between the two. That seems to work alongside the additional pull up resistors to get everything working, though I only tested it with two sensors.

I'm sure you have, but have you connected the grounds together?
Have you tried 1 sensor on SD/C0 and then moving it to SD/C1 it should stop working, so the fault has to be with SD/C0.
Looking at your code, is there a reason you haven't initialised sensor 0?
 /* Initialise Sensors 1-6 */

So it looks to me as the fault is caused by you not calling begin() on mag0

We connected the grounds together; they all lead to a node on the breadboard which feeds back to the Arduino. We tried your suggestion with SD/C0 and SD/C1, but the results were the same. I'll ask the team to try again since I can't exactly test it because I'm not on site with the device. The reason why we haven't initialized sensor 0 with tcaselect(0) was that it was causing our code to hang. Once we commented it out, the code continued, and we could read from all sensors. The guy in charge tested it, commented out stuff, and found that this was the issue, though we still don't know why.

Try bumping the empty to the last slot and changing your for loop to only iterate the first 7.
Serial prints along the way help debugging

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


text:
Unable to load programs onto Arduino Pro Mini Using FTDI?
I'm pretty new to this, so forgive me if I get some things wrong. I am working with a piece of equipment that uses an Arduino Pro Mini. When I first got to it, I realized that some of the code was incorrect and wanted to fix it. Unfortunately, my Pro Mini is soldered into the board with the labels and pins down, so the only accessible pins are the top six, and even those aren't labeled. The reset button is also upside down. I tried using a FT232H FTDI
hooked up (using a pinout because of the aforementioned no labels)
D0-> TX
D1-> RX
which I was told should work, but when I plug in the micro-usb into the FT232H and try to upload the sketch, it gives me the error
avrdude: stk500_getsync(): not in sync: resp=0x00

and also blinks green but has a constant red light (from what I can see from looking under the board). Because this Pro Mini controls my equipment, I'm wary of doing anything too intense. Any ideas of how to fix this without breaking my apparatus?
Update!
I changed the pinning, and the IDE told me that it uploaded, but it still won't run the program! Help!

An FTDI breakout should use more than two pins, check the Pro Mini datasheet for the correct pins to connect through a breakout. You might also benefit from looking up an Arduino FTDI tutorial on YouTube. Just make sure to check the simple things first :)

Please edit your question to include a list of exactly which pins you can connect to.  “The top six” is too vague.   Eg, are the ISP pins accessible? Also please edit your question to  make a list of unused pins

If you want to know which pins are which, Google search for "arduino pro mini pinout diagram". You will find lots of them.

"IDE told me that it uploaded, but it still won't run the program". It's likely the problem is with your code. Try uploading a minimal known-working sketch to see if it will run. The obvious choice would be File > Examples > 01.Basics > Blink but first you should make sure that the pin being blinked (13 by default) won't have any harmful effect on your equipment.

On some pro-minis, such as the one I got off Amazon, the FTDI header pins are mirrored. You may not be able to go by a downloaded pinout diagram without verifying the pins.

Same problem faced. Try out many times with proper connection but no success. After that, I found one unique and simple solution. I use Arduino Uno instead of FTDI. Follow below step, your problem will definitely solve.

First, remove Arduino Uno's IC means ATMEGA 328P-PU.
Now, do connection as shown in below figure.

Connections are like:
Arduino Uno(Without Chip)     Arduino Mini Pro

          RX                         RX
          TX                         TX
          +5V                        Vcc
          GND                        GND
         RESET                  RST(RESET PIN)

Now, plug your Arduino Uno to your computer and open your Arduino IDE.
Now, an open sketch which one you want to upload. Now, go to Tools and select board in which you want to upload code. Below, show in the figure.

Now, upload your program. It will definitely work.

I hope it will help you.

Could you possibly provide a reference link to some relevant documentation that explains this type of configuration please?

This should not be necessary.  Uploading via an FTDI does work.

@stevieb There is no proper documentation about this but I read out this thing in the forum. Prefer this link https://stackoverflow.com/questions/18362942/how-to-use-an-arduino-uno-as-an-ftdi-programmer

@ChrisStratton But FTDI not worked for me. That's why I found out this solution.

Then you did not use the FTDI correctly.  It will work for someone who does.  Postings here are not only for the benefit of the asker, but for that of future readers too.  Using an Arduino as a serial adapter is a possibility, but the traditional method of using an FTDI is a fine solution too, if that is what is on hand.

@ChrisStratton Hii buddy you  are right but if some alternatives are available and that  worked too so it is good to share and research is the field where you have to have different ways to find solution.


text:
Can't open "COM1" on Linux with Trinket Pro
At work, on a Ubuntu 14.04 system, I can access my Trinket Pro without any difficulty whatsoever.
At home, using either Linux Mint or Ubuntu across two laptops, I can not communicate with the device no matter what I try.
I have the correct board selected, the correct processor, and trying to use USBTiny ISP.
Currently, I'm getting:
avrdude: ser_open(): can't open device "COM1": No such file or directory
An error occurred while uploading the sketch

It's really getting frustrating having to take my devices to work just to upload a sketch, and I've been banging my head for over a week and a half. My UNO R3 boards work without issue on the same laptops.
Here's what dmesg says:
[  863.471315] usb 1-1.1: Product: USBtiny
[  863.471316] usb 1-1.1: Manufacturer: Adafruit
[  876.438778] usb 1-1.1: USB disconnect, device number 12
[  880.921492] usb 2-1: new low-speed USB device number 5 using xhci_hcd
[  881.092152] usb 2-1: New USB device found, idVendor=1781, idProduct=0c9f
[  881.092157] usb 2-1: New USB device strings: Mfr=1, Product=2, SerialNumber=0
[  881.092161] usb 2-1: Product: USBtiny
[  881.092163] usb 2-1: Manufacturer: Adafruit
[ 1004.305143] usb 2-1: USB disconnect, device number 5
[ 1019.935505] usb 2-1: new low-speed USB device number 6 using xhci_hcd
[ 1020.106524] usb 2-1: New USB device found, idVendor=1781, idProduct=0c9f
[ 1020.106530] usb 2-1: New USB device strings: Mfr=1, Product=2, SerialNumber=0
[ 1020.106533] usb 2-1: Product: USBtiny
[ 1020.106536] usb 2-1: Manufacturer: Adafruit

I am running IDE version 1.8.3, with sudo, the exact same way I'm doing at the office.
Can someone please advise on what I'm missing here? Windows is not an option; I haven't used it in many years. I'd just like to figure out what's wrong.
I do have an FTDI connector, but didn't have much luck with it either, and to be honest, don't want to use it as I just want to plug the Trinket in, and upload.
Update: I've tried both USB2 and USB3 ports repeatedly with the same results.

Linux doesn't have "COM1". Are you sure that's what you're supposed to be using?

I'm not using that. In "Port", I have /dev/ttyS4 and /dev/ttyS5. Selecting either one produces the same error. Technically, the serial port selection should be irrelevant with USBTiny, at least to my understanding.

heh. Upon changing the port from ttyS4 to ttyS5, I now get "programmer is not responding".

There's a clue that you are on the wrong one.  But that it exists.  One thing you know for sure is that unless it shows up in the IDE you can't reach it.  And now you know that tty55 is wrong.  For my systems it is usually something like /dev/ttyUSB0 (Nano) or /dev/ACM0 (Uno)

My point is that with the Trinket, the Port should not matter... ie. at the office, it can be ttyS4, ttyS5 whatever. There is no ttyUSBx at all.

Small update... I connected the Trinket to a Windows Virtualbox VM (guest), and ran into the exact same issue. However, I found somewhere online that said to try Sketch->Upload Using Programmer, and that actually worked. Will try this at home as well.

[  881.092161] usb 2-1: Product: USBtiny
[  881.092163] usb 2-1: Manufacturer: Adafruit
[ 1004.305143] usb 2-1: USB disconnect, device number 5
[ 1019.935505] usb 2-1: new low-speed USB device number 6 using xhci_hcd
[ 1020.106524] usb 2-1: New USB device found, idVendor=1781, idProduct=0c9f

The USB Tiny ISP device which this logs shows being connected to your system is not a USB serial device.  Therefore, it will not have any /dev/ttyXXX device associated with it.  Instead it should be used with the -c usbtiny argument to avrdude.
Adafruit documents their products fairly well, and this is no exception.  The Linux section of the user guide is at https://learn.adafruit.com/usbtinyisp/avrdude#for-linux
That guide goes on to explain that you will typically need to create a udev rule to allow an ordinary user account to access the device.  Depending on Linux installation, typical contents might be
SUBSYSTEM=="usb", SYSFS{idVendor}=="1781", SYSFS{idProduct}=="0c9f", GROUP="users", MODE="0666"

or
SUBSYSTEM=="usb", SYSFS{idVendor}=="1781", SYSFS{idProduct}=="0c9f", GROUP="adm", MODE="0666"

The above linked guide will more comprehensively explain how all of this works.
Note that the above pertains to the USB Tiny ISP programmer shown in your dmesg output.  According to the Adafruit page on the Trinket Pro, the Trinket Pro "bootloader looks just like a USBtinyISP" therefore, you would talk to it in the same way as the USB Tiny ISP that your system reports finding, ie, without using a /dev/ttyXXX device, but rather by specifying -c usbtiny in the avrdude command line, or using an Arduino IDE board configuration which does so.
Your error message suggests that avrdude is not being run with the correct command line options.  You may want to turn on verbose mode to see what is being run - it would especially helpful if you did that on both the working and the non-working Linux systems.

Thanks Chris. I will check what the avrdude upload command is on the home machine tonight. At work, it does get sent in with the -cusbtiny flag. What I meant by the serial port is that I'm aware it's irrelevant in this case, but on the work machine, the Port within the IDE can be set to any ttyS# and this doesn't affect the upload. The only thing I can think of is that at home, for some reason, the -c flag isn't being sent in. After some research, I've found how to upload via the command line, so I'll try that first, then troubleshoot the IDE if necessary.

Also, my understanding was that the udev rules are only necessary for running as a non-root user. That said, I did configure them on both machines in the same fashion already. I'll redo these steps if the steps in my above comment fail to produce positive results.

So, in the end, although Chris' answer didn't directly lead me to the solution, by delving through his links, I eventually ended up at a page that suggested using the Sketch->Upload Using Programmer feature.
That corrected the issue both as root and my normal Linux user account, without any other changes necessary. I find it odd that it isn't required on my work PC, but I digress. It works on both, so I'm pleased.

Sounds like you do not have a valid configuration for a Trinket Pro installed, or at least not selected as the board in use, on your home machine.

It works; I will completely review my setup, but I know for fact that things are the same on both machines IDE-config (UI) wise. There is no doubt. Again, I will review again, but I've been at this for a while. I may just redo everything from scratch to see if I did happen to go wrong somewhere.


text:
delay() runs super fast unless I remove a while loop that never runs
I'm working on a small game on arduino but I'm facing some really odd behavior. When I run this code all of my leds flash on and off in less than a second even though delay(10000); should stop them for 10 seconds. However if I remove the while(game_running) block they go back to flashing every 10 seconds even though that block of code never actually runs.
int yellow = 12;
int green = 10;
int red = 9;
int blue = 11;

int debug = 13;

int sequence[1000];
int level = 0;

int game_running = false;

void setup() {
  pinMode(yellow, OUTPUT);
  pinMode(blue, OUTPUT);
  pinMode(green, OUTPUT);
  pinMode(red, OUTPUT);

  pinMode(debug, OUTPUT);
}

void loop() {

  // Pre Game light flash
  digitalWrite(yellow, HIGH);
  digitalWrite(green, HIGH);
  digitalWrite(red, HIGH);
  digitalWrite(blue, HIGH);
  digitalWrite(debug,HIGH);
  delay(10000);
  digitalWrite(debug,LOW);
  digitalWrite(yellow, LOW);
  digitalWrite(green, LOW);
  digitalWrite(red, LOW);
  digitalWrite(blue, LOW);
  delay(10000);

  game_running = false;
  level = 0;

  while(game_running) {

    sequence[level] = random(4); // Select next color

    // Blink LEDs
    for (int i=0; i < level; i++) {

       if(sequence[i] == 0) {
         digitalWrite(yellow, HIGH);
         delay(1000);
         digitalWrite(yellow, LOW);
         delay(1000);
       } else if(sequence[i] == 1) {
         digitalWrite(green, HIGH);
         delay(1000);
         digitalWrite(green, LOW);
         delay(1000);
       } else if(sequence[i] == 2) {
         digitalWrite(red, HIGH);
         delay(1000);
         digitalWrite(red, LOW);
         delay(1000);
       } else {
         digitalWrite(blue, HIGH);
         delay(1000);
         digitalWrite(blue, LOW);
         delay(1000);
       }
    }
    level += 1;
  }
}

You're using the Uno? Your array sequence with 1000 entries eats up 2,000 bytes of RAM. (To say nothing of your other variables.) It might be causing some issues.

I have no problems running your code on my board, of course I changed the sequence array to have just 100 entries. Maybe that was a problem?

@lemontwistI changed the 1000 to 100 and now it runs as expected. Guess it run out of memory and removing the extra code freed some up?

Probably was the case. Memory management is very important. Microcontrollers have much more limited memory than PCs!

I will add an official answer just so that others can see it if they run into similar problems.
The issue is with the int sequence[1000] array, which eats up 2,000 bytes of data memory. The Uno only has 2,048 bytes of data memory so the instability is due to this memory hog of an array. Use a smaller number of array entries or switch to char (if you can) to use half the bytes of an int.

Compiler output:   Sketch uses 1724 bytes (5%) of program storage space. Maximum is 32256 bytes.
Global variables use 2017 bytes (98%) of dynamic memory, leaving 31 bytes for local variables. Maximum is 2048 bytes.
Low memory available, stability problems may occur.

offtopic (but cannot put it in a comment):
I do not see any problem with your code (maybe it's in the circuit?)
You can rewrite the 10 s pregame flash as:
// Pre Game light flash
setAllLights(HIGH);
setAllLights(LOW);

void setAllLight(int state)
{
  digitalWrite(yellow, state);
  digitalWrite(green, state);
  digitalWrite(red, state);
  digitalWrite(blue, state);
  digitalWrite(debug, state);
  delay(10000);
}

You can even optimize this further by creating an array:
int[] lights = { yellow, green, red, blue, debug}

void SetAllLights(int state)
{
   for (int color = 0; color < sizeof(lights) / sizeof(int); color++)
   {
       digitalWrite(lights[color], state);
   }
}

You can rewrite the inside of the loop like:
switch (sequence[i]):
   case 0:
      flash(yellow);
      break;

   case 1:
      flash(green);
      break;

   case 2:
      flash(red);
      break;

   default:
      flash(blue);
      break;
}

void flash(int colorPin)
{
   digitalWrite(colorPin, HIGH);
   delay(1000);
   digitalWrite(colorPin, LOW);
   delay(1000);
}


text:
Is there a microcontroller that can output hdmi?
Pretty simple question. Is there a microcontroller that can output hdmi? If not, what microcontrollers can output any type of video?

A Raspberry Pi can output HDMI. A Arduino Uno can output some kind of minimal VGA.

It depends on what you are looking for. There are lots o chips made to control and process hdmi frames. However, as Jot said, the arduino is not suitable for this. The arduino can output basic VGA, but it does not have enough "horsepower" to play with HDMI. The best and cheapest solution is to use a Raspberry Pi.

Arduino does have a board that can do HDMI (the MKR Vidor 4000), though it's cheating a bit by doing it on a FPGA rather than on the microcontroller itself.

RP2040 can output DVI which HDMI monitors can render.


text:
read CID of SD card with SD.h library
I would like to be able to read the serial numbers of SD cards using the SD.h library. Only reading the values is enough, I am not looking to modify the CID.
This should be possible but I do not have the programming skills to get it running.
I am using an esp8266 and already have the SD card running and working correctly. Only the chipselect needed to be modified for the SD library to work.
So far I have found this in Sd2Card.h
      /**
   * Read a cards CID register. The CID contains card identification
   * information such as Manufacturer ID, Product name, Product serial
   * number and Manufacturing date. */
  uint8_t readCID(cid_t* cid) {
    return readRegister(CMD10, cid);
  }
  /**

And in Sd2Card.cpp there is this:
/** read CID or CSR register */
uint8_t Sd2Card::readRegister(uint8_t cmd, void* buf) {
  uint8_t* dst = reinterpret_cast<uint8_t*>(buf);
  if (cardCommand(cmd, 0)) {
    error(SD_CARD_ERROR_READ_REG);
    goto fail;
  }
  if (!waitStartBlock()) goto fail;
  // transfer data
  for (uint16_t i = 0; i < 16; i++) dst[i] = spiRec();
  spiRec();  // get first crc byte
  spiRec();  // get second crc byte
  chipSelectHigh();
  return true;

 fail:
  chipSelectHigh();
  return false;
}

So it seems that the underlying code has been prepared in the library already, my question is how would I include it into a sketch like CardInfo.ino?

The method is visible from within your sketch. You just need to first create a cid_t struct like this in your sketch:
cid_t cid;  // at the top with the other globals

Then call readCID() anywhere in setup() after the card has been initialized.
card.readCID(&cid);
Serial.print("Serial number: "); Serial.println(cid.psn); // psn is the serial number field of the struct

Check out SdInfo.h for the other struct members.

Thank you, this is working for me and the explanation easy to follow. I tried additional information and can also read it. The SdInfo sketch is much better but it wouldn't run on my hardware, but I can see now how to use it as an example. Thanks again.


text:
Integrating an analog signal using Arduino Mega 2560
The sample code is this:
Sample code for Edgar Bonet
I have questions. I need to integrate the analog sine wave of 60 Hz, this signal described in the next picture, adding an offset near 2.5 V, because I can damage the Arduino board with the negative signal cycle. Internally on the Arduino board, I remove this offset, multiplying by 2, and subtracting 1.
V1=analogRead(A0)*2/1023.0-1.0;

The sampling period must be at least fs=300 Hz, T=1/fs and V1 is the signal I need integrate.
What modifications can I make to Edgar Bonet's code?

You are new, so consider the critique as constructive in intention. The title is not descriptive. The edit changed the circuit AND the nature of the question AFTER three people answered. One thorough response to the wrong question was deleted by its author. There is a conversion formula with the wrong denominator adjacent to text stating the translation to voltage is not needed. The purpose of integration is unclear without reading an IEEE document. Code indentation does not aid readability. Multiplication by 2 is unexplained. The correspondence between the block and the schematic is unclear.

you probably want to understand the essence of your goal vs. your approach. cosine modulation is a fancy way of saying that you control the firing angle non-linearly so the (power) output is linear - as linear control of phase angle will yield a non-linear output.

once you understand that you will come to a couple points: 1) you don't need to adc to get it to work; 2) you don't need to integrate to get it to work;

if you really want to go down this path, consider the use of of a hardware integrator;

if you have to do it with software, consider the use of a differential adc. that can be done via a mcu with a different adc, a hardware solution, or use two single-ended adc channels and calculate the difference. For example consider adc the opamp's output as well.

V1=analogRead(A0)*2/1023.0-1.0;

This will give you the voltage across R1 in units of 2.5 V. I do
not know whether you care or not about the units but, if you want the
voltage in volts, then:

the voltage at the Arduino input is analogRead(A0) * (5.0/1024)
to get the voltage across R1, you have to subtract 2.5 V
to get the voltage at the output of the transformer, you have to
multiply by 11.

This could be written as
float V = (analogRead(A0) * (5.0/1024) - 2.5) * 11;

but, in order to minimize the number of floating point operations, you
can simplify it to
float V = analogRead(A0) * (55.0/1024) - 27.5;

You could then integrate the voltage by running it through a function
like this:
static float integral(float x)
{
    static float y;                         // last filter output
    static uint32_t last_sample;            // last time sampled
    uint32_t now = micros();
    float dt = (now - last_sample) * 1e-6;  // step time in seconds
    last_sample = now;
    y += x * dt;
    return y;
}

Now, there is an issue with this approach: the average voltage at the
input of the Arduino is not going to be exactly 2.5 V, because
your resistors R3 and R4 will not have identical resistance. Then the
output of the integral will slowly drift and eventually become
unreasonably large.
One way to mitigate this drift problem is to measure this average using
the same Arduino running the same program: disconnect the mains, see how
the output of the program drifts, and measure the drift rate. Then you
subtract the drift rate from the 27.5 in the code, and fine tune until
there is no drift at all. There is, however, the risk that some time
later it will drift again, due to components changing behavior as the
temperature changes.
A better option would probably be to not integrate, but instead use a
first-order low-pass filter. Such a filter behaves like an integrator
for any signal faster than its cutoff frequency but, unlike a simple
integrator, it has a finite gain at zero frequency. You can turn the
integrator into a low-pass filter simply by changing the line
y += x * dt; into
y += (x - y/tau) * dt;

where tau is the time constant of the filter.

Now I understand why SE experts overlook opportunities to gain a few rep points by gathering more requirements in the question's comments section. I wasted quite a bit of time answering a question that has completely changed, and I'm shell shocked now. Thanks for the discussion however. That was the only thing of interest that came out of my answering in this case. :)

Thanks Edgar Bonet, the low pass filter worked very well.
I could already integrate the signal. Happy week.

Brief Electrical Comment First
The circuit as depicted seems sound, but it may be wise to measure the max and min peaks with an oscilloscope or multi-meter to ensure you are within the voltage range of the Atmel chip on the Mega 2560, which is zero Volts to Vcc [1] per Atmel processor's spec sheet [1].
Since Vcc is 5V per the Mega's schematic [2], the safe range you depicted is correct, however you cannot trust the voltage on the mains to stay within IEEE specifications, the p-p secondary Voltage of the adapter to be dead on in proportional relation to the primary, or the resistors to be in the center of their 5% or 10% range of precision.  You may wish to add some potentiometers to your circuit to make adjustments.
Now the Math and Software Implementation
Continue to take the i,t (integer, time) sample vector as in the example you referenced.  I changed the variable names to be more descriptive from a systems engineering point of view.
int s_in = analogRead(input_pin);
unsigned long microsecs = micros();

The algebraic (not code) relation of the sample to the instantaneous voltage is as follows.

v_in = 5V X s_in / 1024
v_no_offset = v_in - v_offsreallyreallyet
v_offset = 2.5
v_secondary = v_no_offset X (110 KOhms / 10KOhms)

Keep in mind here that the sample is not a p-p measurement.  It is an integer representing a Voltage measurement over a very small time range relative to the period of an approximate [3] 60 Hertz sine wave.  There is no reason to multiply samples or corresponding Voltages by two for this circuit.
The period of a 60 Hertz sine wave is 16,667 usec, so the difference between your max value and min value for any given 16,667 usec period's worth of samples is your p-p Voltage for that period.  You can average those over time to get a less instantaneous p-p Voltage.  Before considering p-p or RMS calculations, you must first computing the secondary Voltage corresponding to the integer sample acquired in the analogRead.
Substitution and calculation in mV instead of Volts yields this.
mv_secondary = (5000 X s_in / 1024 - 2500) X (110000 / 10000)

Translating into C, which will be interpreted correctly within an Ino sketch, and using a simplified expression and long integers to achieve reasonable computational speed and accuracy [4] you get this.
int s_in = analogRead(input_pin);
unsigned long microsecs = micros();
unsigned long mv_secondary = 53711L * s_in / 1000 - 27500;

The v,t (secondary Voltage, time) vector is now in the variables mv_secondary and microsecs respectively.  Then calculate the delta time and find the product to sum.
unsigned long nano_volt_second = mv_secondary * u_sec_delta;

System Design Considerations
In designing the system, it is often better to delegate the conversion to physical units and the Gaussian approximation of an integral to another part of the system (as in the case of when the embedded program is doing data acquisition but not control) or not do it at all (as in the case when control is in the same board as the data acquisition and the PID parameters superseded the need to translate the integers from readAnalog to physical units altogether).
To achieve the higher loop speed when using USB transfer of the values, one can USB transfer the return values of the analogRead more directly as two byte pairs and perform calculations on the USB peer computer (workstation or other computing hardware).  Conversion of integers of any type to strings slows a data acquisition loop down considerably, and should be avoided.
Hardware triggering of the ADC subsystem of the Atmel chip can also increase speed, especially if the analogRead function is bypassed by a lower level implementation of the register reading.  At sampling speeds above 200KHz, completely within the capability of the Arduino Due, every usec counts.
Ambiguous Intent Reference to Integration
The summing of products isn't actually integration, which is a symbolic operation, not a calculation.  The example reference given does a Gaussian discrete approximation of an integral.  The reason for seeking that approximation is not given.
The result of such a calculation would be the product of the time over which the approximation is made and the offset, which would naturally be zero except for any calibration error and low frequency noise in the secondary winding's circuit.
If the intention is to calculate Voltage RMS, there is another real time methodology for that.  If you want the average p-p Voltage, there's another (partly described above) for that.  If you want to track spikes on the line, then you probably want a circuit with over-Voltage protection and a different algorithm.
Usefulness of Optimized Math
The use of unsigned long for optimization may not be necessary for low frequency applications [5], but any system that needs to meet the Nyquist criterion for audio will require a sample rate where the fixed point simulation may cause a statistically significant number of delays over the time of sampling.
Even if the speed is not needed, exceeding the Niquest criteria permits gaining extra bits of accuracy if windowing is used during data reduction.
References
[1] Atmel 2560 cpu spec sheet @ http://www.atmel.com/Images/Atmel-2549-8-bit-AVR-Microcontroller-ATmega640-1280-1281-2560-2561_datasheet.pdf
[2] Mega 2560 schematic @ https://www.arduino.cc/en/uploads/Main/arduino-mega2560-schematic.pdf
[3] A Voltage waveform from a power grid is rarely if ever a perfect sine wave.
[4] Arduino use of long integer constants as in C/C++ discussion @ https://www.arduino.cc/en/Reference/IntegerConstants
[5] The maximum Δt before the unsigned long product overflows is given by `floor ((2^32 - 1) / (53,711 x 1023 / 1000 - 27,500)) = 156,485 usec, corresponding to a 6.39 Hz sample rate.

I timed yous computation of the integral at 49 µs, v.s. 50 µs for my floating point version. Worth the trouble? Your avoidance of floats looks to me like premature optimization. If you do have a performance issue, then fixed-point is definitively a worthwhile optimization technique, but doing it right is trickier than you may think. I would not recommend fixed-point to a newbie, unless it is a requirement or clearly worthwhile for his project.

@EdgarBonet, more than worth the trouble ... necessary in many if not most cases. The sample rate of 20KHz is far below the Due's capability. Perhaps the test code is string USB transfers instead of packed byte arrays. Optimization to avoid delays in faster loops is require to meet the Nyquist criterion for full spectrum audio & faster control apps. ... Reducing s/n ratios for weak signals requires multiples of the Nyquist. ... In sampling 60 Hertz, the code above does not require floats, fixed point libraries, or testing overflow . See [5] and the other material added to the answer.

The signal will saturate.
You should increase the attenuation if you want to be able to add the full cycle.  Or add half cycle and make assumptions about the other half.
As to the code you simply needs to convert the ADC readings to a DC reading and subtract the center offset from it  . Much better to do that in the ADC reading domain. Like this
Y = analogread(AIN) - 2.5 * 1023 / Vref;

Why would it saturate? The attenuation appears to be excessive, leading to unnecessarily loss of bits of accuracy. ... Also, your formula is incorrect in that you are missing the parentheses around the subtraction.


text:
Read from analog then cast not showing the correct value
I'm trying to read the analog value of the light sensor and print its percentage but for unknown reasons I'm getting negative values when I'm printing the value.
void setup() {
  Serial.begin(9600);
}

void loop() {

  // Let's say 1002 is the analogValue
  int analogValue = (int) analogRead(0);

  // get the percentage
  int value = 100 * analogValue / 1023;

  Serial.println("~~~~~~~~~~~~~~~~~~~~~~~~~");
  Serial.println(analogValue); // print the analog value 0...1023
  Serial.println(100 * analogValue); // just for test
  Serial.println(value); // The percentage
  Serial.println("~~~~~~~~~~~~~~~~~~~~~~~~~");

  delay(500);
}

I don't know what's going in background, but I'm getting negative values when I try to print the percentage:
~~~~~~~~~~~~~~~~~~~~~~~~~
1002
-30772
-30
~~~~~~~~~~~~~~~~~~~~~~~~~

Max value for int is 32,767. But 100 * 1002 = 100,200. You are overflowing the int. Use unsigned long. Or float and cast to int when printing.

Simplest would be to replace 100 by 100L.

Yes, but OP would have to be sure to do that on both lines - the original calculation as well as the Serial.println line (even though it's "just for test").  Either way works, though.


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

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

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

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

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


text:
Is it possible to use Arduino PWM for audio within a PAM8493 amplifier?
I've seen some projects using PWM for playing audio files, and it seems like it needs an amplifier, otherwise the sound is very low.
I already made a project using a DFPlayer and PAM8403, but now I need more control over the files in the SD Card which is not supported by the DFPlayer library, so it seems like I need to use PWM and a SD Card module, instead of a separate audio module.
My questions are, can I simply connect the PWM output to the amplifier (PAM8403) and I will be able to control volume (using the programming language) and have a good quality sound?

Are you using a basic Arduino board (not I2S) and a sampling frequency of 8 kHz or 16 kHz? That could interfere with the default switching frequency of 260 kHz.
My suggestion is to use a low pass RC filter.
You might have to lower the signal level from the Arduino.
The PAM8403 requires a series capacitor and resistor at the input (those are probably already on the amplifier module).
In the end you probably need a voltage divider with a capacitor to ground for each channel.
I don't know if your PWM library has volume control. The TMRh20 has a function to set the volume.
The overall quality will be reasonable, but not very good. There are MP3 shields that can play mp3 files from a SD memory card. Those have better quality.
[ADDED]
I think I have misunderstood your question. Sorry. I'm still not sure that I understand your question now.
Wiki of DFPlayer Mini: DFRobot:DFPlayer Mini
Code on Github for DFPlayer Mini: Github:DFPlayer Mini
The PAM8403 has no volume control, you need to adjust the audio signal that is going to the PAM8403 module.
The DFPlayer Mini code has functions for volume, volumeUp, volumeDown and readVolume. However, it does not seem to have a function to select a specific file.
The Adafruit Music Maker shield is in two versions, one has an amplifier onboard: Adafruit:Music Maker MP3 Shield for Arduino w/3W Stereo Amp - v1.0. With that shield, you can play a file by its name. It can also set the volume. I suppose that is what you want ?

I already have a project running with DFPlayer, but now I need to have control over the fles in the SDCard and it seems like none of the mp3 modules provides that. I can chose any board. Currently the DFPlayer project was made with a nodemcu

@Valdir, I have added a [ADDED] section. In my opinion, every "normal" mp3 player module can select a file, only the very cheap ones can only play the next one, but not a specific file.

Note that if using the TMRh20 library, which uses raw PWM to generate audio, the correct "audio amplifier" to use to drive the speaker is a DC motor driver (H bridge), such as one from Pololu.


text:
error: espcomm_upload_mem failed ESP8266
So, I downloaded tools for my ESP8266 using this link:
http://arduino.esp8266.com/stable/package_esp8266com_index.json
I installed the last version in my motherboard manager (2.3.0) and tried to execute my first example ("Blink"), but here is what I get :

What can I do to prevent this?
P.S My ESP8266 is connected to an Arduino Mega

And how exactly is it connected, and what are you running on the mega?

@Majenko I used the scheme from that article : http://www.teomaragakis.com/hardware/electronics/how-to-connect-an-esp8266-to-an-arduino-uno/

@Majenko Nothing except the ESP is connected to my Arduino

The reason why this error comes up is because the programmer cannot communicate with the bootloader of the ESP.
The link you mentioned in the comments misses a very important step, which is to remove the ATmega chip already on the Uno board. Otherwise the programmer will see corrupt data due to 2 bootloaders on the same UART lines.
Remember that only one device can communicate on the UART lines.
The Mega board has the ATmega chip soldered to the board, so you don't have much hopes of isolating the UART lines.
Another thing to remember is to always reset the ESP into flash mode (reset the ESP with GPIO_0 pulled low).
If you still want to use the ESP with the Mega board, go through the Multi Serial examples given in the IDE. The concept requires making two GPIO lines communicate with the ESP, while the original Serial lines to the programmer (the computer).
All data sent via ESP is routed to Mega's serial lines and vice versa.


text:
Arduino Zero D0/D1 set output high
I am trying to use D0/D1 as normal IO pins but DigitalWrite does not work as on an Arduino UNO.
I know the SAMD21G has SERCOM but I can't seem to find an example of not using D0/D1 as an UART port.
EDIT ** Code I have tried:
#define MYMASK 0x00000C00
void setup() {
  REG_PORT_DIRSET0 = MYMASK; // Direction set to OUTPUT
  REG_PORT_OUTSET0 = MYMASK; // set state of pin(s) to TRUE (HIGH)
  delay(1000);
  REG_PORT_OUTCLR0 = MYMASK; // set state of pin(s) to FALSE (LOW)
}

void loop() {
}

You can do this by simply calling the right registers:
Example 1, using a MASK
D0/D1 are mapped to to PA10 & PA11 on the M0
/* The following ports where selected
    PORT_PA11
    PORT_PA10
    */
#define MYMASK 0x00000C00

int main (void)
{
    system_init();

    REG_PORT_DIRSET0 = MYMASK; // Direction set to OUTPUT
    REG_PORT_OUTSET0 = MYMASK; // set state of pin(s) to TRUE (HIGH)
    //REG_PORT_OUTCLR0 = MYMASK; // set state of pin(s) to FALSE (LOW)

    while(1){

    }
}

Here is another simple example:
/* The following ports where selected
    PORT_PA11
    PORT_PA10
    */
#define MYMASK 0x00000C00
#define LED1 PORT_PA10
#define LED2 PORT_PA11
int main (void)
{
    system_init();

    REG_PORT_DIRSET0 = LED1 | LED2; // Direction set to OUTPUT
    REG_PORT_OUTSET0 = LED1 | LED2; // set state of pin(s) to TRUE (HIGH)
    //REG_PORT_OUTCLR0 = LED1 | LED2; // set state of pin(s) to FALSE (LOW)
    while(1){

    }
}

In the Arduino IDE you can do something like:
#define MYMASK 0x00000C00
void setup() {
  REG_PORT_DIRSET0 = MYMASK; // Direction set to OUTPUT
}

void loop() {
   REG_PORT_OUTSET0 = MYMASK; // set state of pin(s) to TRUE (HIGH)
   delay(1000);
   REG_PORT_OUTCLR0 = MYMASK; // set state of pin(s) to FALSE (LOW)
   delay(1000);
}

Thanks for the quick reply... I tried the the above trough Arduino but without any luck. I wonder if Arduino overwrites the registers in the background.

Can't tell unless you post your code.

Have added the Arduino Code...

@BertusKruger - I just tried the code on my Arduino M0 which has D0/D1 mapped to PA11 & PA12. You have set the ports to low before the loop. See my revised code.

edit - D0/D1 are mapped to PA10 & PA11

Thanks @PhillyNJ . I can confirm that that worked for me. How did you derive the mask and where can I read more about the registers? I would like to do the same with the SPI and I2C pins...

@BertusKruger HTH - please don't forget to mark as answered :) - You can read all about the GPIO registers in the Datasheet or my tutorial which  I posted here https://community.atmel.com/forum/samd21samr21-xplained-pro-gpio-tutorial for peer review. Let me know how it goes.

Thanks. I figured out the mask but could not see any mention of REG_PORT_DIRSET0 in the datasheet. I now noticed the DS talks about DIRSET. Still need to find the link... I am building a SAMD21 board from scratch and is now busy on a test jig testing each pin... :)

Thanks for the tutorial link. Haha I found my answer... :)  https://github.com/arduino/ArduinoCore-samd/blob/master/bootloaders/sofia/Bootloader_D21_Sofia_V2.1/src/ASF/sam0/utils/cmsis/samd21/include/instance/port.h


text:
Passing serial data to Processing using something other than ln to trigger Processing
I have a Uno program and I can transfer data to Processing using println. In Processing bufferUntil('\n') interprets the ln  as \n, stops buffering, and reads the string until the next '\n'. I would like to use something other than ln to trigger Processing. That way I can use Serial Monitor in the Uno to see serial data when Processing is not running at the same time.
I have searched the net but have not found the technique to use something other than ln. Thanks.

ln? You mean \n aka new line character?

Sounds like you want 2 programs monitoring the same serial port on the PC. What OS are you using? The question is not very clear.

If I understand your question (which is not certain):

Pick a different "trigger" byte that you won't be sending in your messages.  Maybe TAB?
In your "Processing" program, use: port.bufferUntil(TRIGGER);
In your Arduino sketch, rather than println, use print to send both your data and the trigger byte:  Serial.print(your_message); Serial.print(TRIGGER);

Note that sending binary data will cause this to fail when the data uses the trigger byte.
From: https://www.arduino.cc/en/Serial/Println The println()
   method sends your output then a CR and NL.  And it seems bufferUntil() takes a character on which to trigger:
https://processing.org/reference/libraries/serial/Serial_bufferUntil_.html


text:
How to read resistive buttons with Arduino Pro Micro?
I am trying to read some resistive buttons presses on a PCB like this:

This is the full sketch I am using:
#include <Keyboard.h>

byte ZbuttonPin = 3;

void setup() {
 // initialize the button-reading pins
  pinMode(ZbuttonPin, INPUT_PULLUP);
}

void loop() {
  if (digitalRead(ZbuttonPin) == 0) {
    // if the button goes low
    Keyboard.write('z'); // send a 'z' to the computer via Keyboard HID
    delay(100); // delay so there aren't a kajillion z's
  }
}

If I short the Arduino pin 3 and GND directly it outputs the "z" letter correctly.
But when I connect M16 and GND on the PCB it outputs "z" continuously even if the button if not pressed with the rubber pad.

I would suppose that showing the circuit would help others help you. Shorting this or shorting may mean a lot to you hurt exactly zero to those who may be of help to you. Help others help you.

Use a multimeter to test the resistance when the button is pressed and when it is not pressed. Perhaps adjusting the voltage level with a pullup resistor is enough to make it work.

the resistance is about 1.5M ohms when not pressed and 170ohms when pressed... should i change the read logic?

Those values seem okay. It should work. Perhaps you can try with an extra pullup resistor of about 1k to 10k from pin 3 to 5V.

i've tried adding a 10K resistor in series with the pin 3, but still not working as expected. do you think using the 5v pin and wiring like this may solve the problem?

The button at GND and the pullup at 5V or vice versa, that is the same for an Arduino Uno, and almost the same for an Arduino Pro Micro. The Arduino Pro Micro has lower voltage levels for HIGH and LOW for a digital input. You can get the same result by adjusting the value of the pullup resistor. Do you have more resistors to try ? Do you use a breadboard or something else with bad contacts ? If nothing works, you could try an analog input and check at which analog value a pressed button is.

I am using crocodile clips and no breadboard. I've also tried connecting to a momentary pushbutton and it worked fine. Probably i am going to try with analogRead and see what happens...


text:
Incorrect data being received on RX of NRF24L01P
I am running a setup of two NRF24L01P's on homemade code where the TX sends an analog signal fed through a standard pot, and the RX simply prints out the signal. But the RX seems to be getting incorrect data, meaning that where the centre value on TX side is 670, the centre value on RX side is 180. Why is this happening? I have auto acknowledgement, and dynamic payload enabled. I also tried setting 250KBPS and 2000KBPS with the max power setting, and still the results dont change. Is this because of loss of power in the wireless communication? Will a voltage follower be needed?
Function definitions in code:
/* CONNECTIONS
 * NRF    ARDUINO
 * GND    GND
 * VCC    VCC
 * CE     D7
 * CSN    D8
 * MOSI   D11
 * SCK    D13
 * MISO ``D12
 * IRQ    D2*/

 #include <SPI.h>
 #define CE_PIN 7
 #define CSN_PIN 8
 #define MOSI_PIN 11
 #define SCK_PIN 13
 #define MISO_PIN 12
 #define W_REGISTER B00100000
 #define R_RX_PAYLOAD B01100001
 #define W_TX_PAYLOAD B10100000
 #define FLUSH_TX B11100001
 #define FLUSH_RX B11100010
 #define RF_SETUP 0x06
 #define RF_DR_LOW 5
 #define RF_DR_HIGH 3
 #define RF_CH 0x05
 #define EN_RXADDR 0x02
 #define ERX_P0 0
 #define SETUP_AW 0x03
 #define RX_ADDR_P0 0x0A
 #define FEATURE 0x1D
 #define EN_DPL 2
 #define EN_AA 0x01
 #define CONFIG 0x00
 #define PWR_UP 1
 #define PRIM_RX 0
 #define MASK_RX_DR 6
 #define MASK_TX_DS 5
 #define MASK_MAX_RT 4
 #define EN_CRC 3
 #define CRCO 2
 #define STATUS 0x07
 #define RX_DR 6
 #define TX_DS 5
 #define MAX_RT 4
 #define NOP B11111111
 #define TX_ADDR 0x10
 #define DYNPD 0x1C

 byte data_buff;
 int address = 123;
 byte data_recieve;

//******************************** write a byte to a regster *******************************
void writeRegister(byte reg_address, byte data)
{
  bitClear(PORTB, 0);
  SPI.transfer(W_REGISTER | reg_address);
  SPI.transfer(data);
  bitSet(PORTB, 0);
}

//******************************* set the air data rate *******************************
void setAirDataRate(int air_data_rate)
{
  switch(air_data_rate)
  {

    case 250:
     setRegisterBit(RF_SETUP, RF_DR_LOW, 1);
     setRegisterBit(RF_SETUP, RF_DR_HIGH, 0);
     break;

    case 1000:
     setRegisterBit(RF_SETUP, RF_DR_LOW, 0);
     setRegisterBit(RF_SETUP, RF_DR_HIGH, 0);
     break;

    case 2000:
      setRegisterBit(RF_SETUP, RF_DR_LOW, 0);
      setRegisterBit(RF_SETUP, RF_DR_HIGH, 1);
      break;

    default:
      Serial.println("WRONG AIR DATA RATE ENTERED!");
      break;
  }
}

void setRegisterBit(byte reg_address, byte bit_add, byte bit_val)
{
  getRegisterStat(reg_address);

  if(bit_val == 1)
  {
    bitSet(data_buff, bit_add);
  }

  else
  {
    bitClear(data_buff, bit_add);
  }

  bitClear(PORTB, 0);
  SPI.transfer(W_REGISTER | reg_address);
  SPI.transfer(data_buff);
  bitSet(PORTB, 0);

  Serial.print(bit_add);
  Serial.print(" bit set to ");
  Serial.print(bit_val);
  Serial.print(" in register ");
  Serial.println(reg_address);
}

void getRegisterStat(byte reg_address)
{
  bitClear(PORTB, 0);
  SPI.transfer(reg_address);
  data_buff = SPI.transfer(0);
  bitSet(PORTB, 0);
}

void enableDPL( int pipe_number)
{
  setRegisterBit(FEATURE, EN_DPL, 1); //enable dpl by EN_DPL = 1
  setRegisterBit(DYNPD, pipe_number, 1); //DPL_Px = 1
}

void openReadingPipe()
{
  setRegisterBit(EN_RXADDR, 0, 1); //ERX_P0 = 1
  writeRegister(RX_ADDR_P0, address);//set address for datapipe
  Serial.print("Data Pipe open with address:  ");
  Serial.println(address);
}

void openWritingPipe()
{
  setRegisterBit(EN_RXADDR, 0, 1); //ERX_Px = 1
  writeRegister(TX_ADDR, address);//set address for datapipe
  writeRegister(RX_ADDR_P0, address);
}

//******************************* set the frequency *******************************
void setChannelFreq(int frequency)
{
  int  frequency_val = frequency - 2400;
  if(frequency_val <= 125 && frequency_val > 0)
  {
    writeRegister(RF_CH, frequency_val);
  }

  else
    Serial.println("WRONG FREQUENCY VALUE ENTERED!");
}

//******************************* print the status of the register *******************************
void printRegStatus(byte reg_address)
{
  getRegisterStat(reg_address);

  switch(reg_address)
  {
    case RF_SETUP:
    bitRead(data_buff, 3) ? Serial.println("AIR DATA RATE SET TO 2000KBPS") : bitRead(data_buff, 5) ? Serial.println("AIR DATA RATE SET TO 250KBPS") : Serial.println("AIR DATA RATE SET TO 1000KBPS");
    break;

    case EN_RXADDR:
    bitRead(data_buff, 0) ? Serial.print("Data Pipe 0 open with address:  ") : Serial.print("Data Pipe 0 not open with address:  ");
    Serial.println(address);
    break;

    case RF_CH:
    Serial.print("The set frequency is:");
    Serial.println(2400 + data_buff);
    break;

    case CONFIG:
    bitRead(data_buff, MASK_RX_DR) ? Serial.println("RX_DR interrupt not reflected on IRQ") : Serial.println("RX_DR interrupt is active low on IRQ");
    bitRead(data_buff, MASK_TX_DS) ? Serial.println("TX_DS interrupt not reflected on IRQ") : Serial.println("TX_DS interrupt is active low on IRQ");
    bitRead(data_buff, MASK_MAX_RT) ? Serial.println("MAX_RT interrupt not reflected on IRQ") : Serial.println("MAX_RT interrupt is active low on IRQ");
    bitRead(data_buff, EN_CRC) ? Serial.println("CRC is Enabled!") : Serial.println("CRC is diabled!");
    bitRead(data_buff, CRCO) ? Serial.println("CRC is 2 bytes.") : Serial.println("CRC is 1 byte.");
    break;

     case EN_AA:
    bitRead(data_buff, 0) ? Serial.println("ENABLE AUTO ACK ON PIPE 0") : Serial.println("AUTO ACK NOT ENABLED");
    break;

    case FEATURE:
    bitRead(data_buff, EN_DPL) ? Serial.println("DYNAMIC PAYLOAD LENGTH ENABLED") : Serial.println("DYNAMIC PAYLOAD LENGTH NOT ENABLED!");
    break;

    case DYNPD:
    bitRead(data_buff, 0) ? Serial.println("DYNAMIC PAYLOAD ON DATA PIPE 0 ENABLED!") : Serial.println("DYNAMIC PAYLOAD NOT ENABLED IN DATA PIPE!");
    break;

    case TX_ADDR:
    Serial.print("ADDRESS: ");Serial.println(data_buff);
    break;

    case RX_ADDR_P0:
    Serial.print("ADDRESS: ");Serial.println(data_buff);
    break;

    case SETUP_AW:
    if(bitRead(data_buff, 1) == 0 && bitRead(data_buff, 0 == 1))
    Serial.println("ADDRESS WIDTH 3 BYTES!");
    break;

  }
}

//******************************* set the address width *******************************
void setAddressWidth(byte address_width)
{
  switch(address_width)
  {
    //addres width is 3 bytes
    case 3:
    setRegisterBit(SETUP_AW, 0, 1);
    setRegisterBit(SETUP_AW, 1, 0);
    break;

    //address width is 4 bytes
    case 4:
    setRegisterBit(SETUP_AW, 0, 0);
    setRegisterBit(SETUP_AW, 1, 1);
    break;

    //address width is 5 bytes
    case 5:
    setRegisterBit(SETUP_AW, 0, 1);
    setRegisterBit(SETUP_AW, 1, 1);
    break;

    default:
    Serial.println("WRONG ADDRESS WIDTH ENTERED!");
    break;
  }
}

//******************************** enable auto acknowledgment *******************************
void enableAutoACK()
{
  setRegisterBit(EN_AA, 0, 1);
}

//******************************** enable auto acknowledgment *******************************
void clearInterrupts()
{
  setRegisterBit(STATUS, RX_DR, 1);
  setRegisterBit(STATUS, TX_DS, 1);
  setRegisterBit(STATUS, MAX_RT, 1);
}

void confirmTransmit()
{
  Serial.print("PACKET SENT SUCCESSFULLY!!");
  setRegisterBit(STATUS, TX_DS, 1);

}

void setupRadio(int air_data_rate, int frequency, byte address_width)  //air data rate in kbps, frequency in MHz, address width in bytes
{

  DDRB = B00101001;
  DDRD = B10000000;
  Serial.begin(115200);
  SPI.begin();
  //set air data rate
  setAirDataRate(air_data_rate);

  //set frequency
  setChannelFreq(frequency);

  //set address width
  setAddressWidth(address_width);

  //flush the rx and tx fifo
  bitClear(PORTB, 0);
  SPI.transfer(FLUSH_RX);
  bitSet(PORTB, 0);

  bitClear(PORTB, 0);
  SPI.transfer(FLUSH_TX);
  bitSet(PORTB, 0);

  //enable dpl
  enableDPL(0);

  //enable CRC
  setRegisterBit(CONFIG, EN_CRC, 1);
  setRegisterBit(CONFIG, CRCO, 0);

  bitClear(PORTD, 7); //set CE low
  bitSet(PORTB, 0);// keep CSN high
}

//******************************** setup the RX *******************************
void setupRX()
{
    //open up the pipe for transmission
    openReadingPipe();

    //mask tx and max rt IRQ
    setRegisterBit(CONFIG, MASK_MAX_RT, 1);
    setRegisterBit(CONFIG, MASK_TX_DS, 1);

    //power up module
    setRegisterBit(CONFIG, PWR_UP, 1);

    //Tpd2stby delay
    delay(5);

    attachInterrupt(digitalPinToInterrupt(2), recieveData, FALLING);

    //clear any interrupt flag
    clearInterrupts();

    //set PRIM_RX bit
    setRegisterBit(CONFIG, PRIM_RX, 1);
    bitSet(PORTD, 7); //set CE high
    delay(1);
}

//******************************** setup the TX *******************************
void setupTX()
{
  openWritingPipe();
  setRegisterBit(CONFIG, PRIM_RX, 0);

  //mask rx and max rt interrupt
  setRegisterBit(CONFIG, MASK_RX_DR, 1);
  setRegisterBit(CONFIG, MASK_MAX_RT, 1);

  //enable autoACK
  enableAutoACK();

  setRegisterBit(RF_SETUP, 2, 1);
  setRegisterBit(RF_SETUP, 1, 1);
  setRegisterBit(CONFIG, PWR_UP, 1);

  delay(5);

  attachInterrupt(digitalPinToInterrupt(3), confirmTransmit, FALLING);

  clearInterrupts();
  delay(1);
}

//******************************** read data from RX FIFO *******************************
void recieveData()
{
  Serial.println("RECIEVE ISR BEGUN");

  bitClear(PORTD, 7); //set CE_PIN low
  delayMicroseconds(100);

  bitClear(PORTB, 0);
  SPI.transfer(R_RX_PAYLOAD);
  data_recieve = SPI.transfer(NOP);
  bitSet(PORTB, 0);

  bitClear(PORTB, 0);
  SPI.transfer(RPD);
  data_buff = SPI.transfer(NOP);
  delay(1);
  bitSet(PORTB, 1);

  bitRead(data_buff, 0) ? Serial.println("THERE IS ENOUGH POWER!") :
  Serial.println("THERE IS NOT ENOUGH POWER!");

  delayMicroseconds(15000);
  setRegisterBit(STATUS, RX_DR, 1);

  bitSet(PORTD, 7);
  delayMicroseconds(100);

  Serial.print("THROTTLE :");
  Serial.println(data_recieve);
 }
//******************************** write data to be transmitted *******************************
void transmitData(byte data)
{
  bitClear(PORTB, 0);
  SPI.transfer(FLUSH_TX);
  bitSet(PORTB, 0);

  bitClear(PORTB, 0);
  SPI.transfer(W_TX_PAYLOAD);
  SPI.transfer(data);
  bitSet(PORTB, 0);

  bitSet(PORTD, 7);
  delayMicroseconds(1000);
  bitClear(PORTD, 7);

  delayMicroseconds(130);

  /*bitClear(PORTB, 0);
  SPI.transfer(0x17);
  data_buff = SPI.transfer(NOP);
  bitSet(PORTB, 0);
  bitRead(data_buff, 4) ? Serial.println("TX FIFO EMPTY!") :
  Serial.println("DATA IN TX FIFO");*/
}

The RX code (all function definitions are same obviously):
void setup(){
  setupRadio(1000, 2515, 3);
  setupRX();
 /*printRegStatus(CONFIG);
 printRegStatus(TX_ADDR);
 printRegStatus(RX_ADDR_P0);
 printRegStatus(EN_AA);
 printRegStatus(RF_CH);
 printRegStatus(FEATURE);
 printRegStatus(RF_SETUP);
 printRegStatus(SETUP_AW);*/

}

void loop(){

 delay(1000);
}

The TX code (all function definitions are same obviously):
void setup(){
      setupRadio(1000, 2515, 3);
      setupTX();
     /*printRegStatus(CONFIG);
     printRegStatus(TX_ADDR);
     printRegStatus(RX_ADDR_P0);
     printRegStatus(EN_AA);
     printRegStatus(RF_CH);
     printRegStatus(FEATURE);
     printRegStatus(RF_SETUP);
     printRegStatus(SETUP_AW);
     printRegStatus(DYNPD);*/

    }

    void loop(){
     int throttle_raw = sqrt(pow(analogRead(A2), 2) + pow(analogRead(A3), 2));
      transmitData(throttle_raw);
      Serial.println(throttle_raw);
      delay(1000);
    }

Probably has to do with the fact that you're passing an int-sized parameter to a function that takes a byte. Your transmitData() doesn't take multi-byte values into account. Why not use existing libraries?

Your new TX function:
void transmitData(byte * data, byte len)
{
  bitClear(PORTB, 0);
  SPI.transfer(FLUSH_TX);
  bitSet(PORTB, 0);

  bitClear(PORTB, 0);
  SPI.transfer(W_TX_PAYLOAD);

  len = min(len, 32); // since 32 is max size
  for (int i = 0; i < len; i++)
    SPI.transfer(*data++);
  bitSet(PORTB, 0);

  bitSet(PORTD, 7);
  delayMicroseconds(1000);
  bitClear(PORTD, 7);

  delayMicroseconds(130);

  /*bitClear(PORTB, 0);
  SPI.transfer(0x17);
  data_buff = SPI.transfer(NOP);
  bitSet(PORTB, 0);
  bitRead(data_buff, 4) ? Serial.println("TX FIFO EMPTY!") :
  Serial.println("DATA IN TX FIFO");*/
}

To receive data with dynamic payloads enabled, you need to know the size of the incoming payload before you read. Study getDynamicPayloadSize() in the RF24 library and pass the value returned as the second argument to the RX function below. Your new RX function should look like this:
void recieveData(byte * data, byte len)
{
  Serial.println("RECIEVE ISR BEGUN");

  bitClear(PORTD, 7); //set CE_PIN low
  delayMicroseconds(100);

  bitClear(PORTB, 0);
  SPI.transfer(R_RX_PAYLOAD);
  for (int i = 0; i < len; i++){
    *data = SPI.transfer(0xff); data++;
  }
  bitSet(PORTB, 0);

  bitClear(PORTB, 0);
  SPI.transfer(RPD);
  data_buff = SPI.transfer(NOP);
  delay(1);
  bitSet(PORTB, 1);

  bitRead(data_buff, 0) ? Serial.println("THERE IS ENOUGH POWER!") :
  Serial.println("THERE IS NOT ENOUGH POWER!");

  delayMicroseconds(15000);
  setRegisterBit(STATUS, RX_DR, 1);

  bitSet(PORTD, 7);
  delayMicroseconds(100);
 }

In both functions, you pass in buffers to hold the data you want to send or receive. In your case, since you're sending ints, a call like this transmitData(&throttle, 2) should do. Since you already know the size of what you're sending, you can simply pass 2 as length to receiveData() and skip querying the payload size like this receiveData(&throttle, 2). Casting will be done implicitly.
If, in fact, receiveData is an ISR like your comments say (maybe you're using some IRQ pin), you'll have to split it in two; one part to handle the interrupt quickly by setting an available flag or something (obviously taking no arguments) to be polled in loop() and another to actually read the data. Or you can just setup the buffer as a global thing and hard-code a 2-byte read in the ISR. Though I have to say your maybe-ISR is terrible, what with huge delays and prints everywhere and I don't know how it manages to work at all.
Basically, if you want to understand the chip, it doesn't hurt to look at existing code to understand the 'right' way to do stuff.

In RF24, why does he define the parameter for the buffer in write_payload as a void* ?

@BabaYaga So that you can pass a pointer to any sort of data type without needing to cast it first. Casting is done within write_payload().


text:
ESP8266 + NeoPixel - Cannot set pixel color, I got "Exception 29: StoreProhibited"
I'm trying to use NeoPixel on the ESP8266.
I made simple test put all required code into setup() and loop() methods. Then, to keep everything in order I create a class LedModule which handle the led strip state, changes, etc.
Here some parts of my class
LedModule::LedModule(unsigned int numOfPixels, uint8_t dataPin)
{
    // When we setup the NeoPixel library, we tell it how many pixels, and which pin to use to send signals.
    // Note that for older NeoPixel strips you might need to change the third parameter--see the strandtest
    // example for more information on possible values.
    pixels = Adafruit_NeoPixel(numOfPixels, dataPin, NEO_GRB + NEO_KHZ800);

    mState = LED_MODULE_STATE_IDLE;
    mIsLedStripOn = false;
}

...

// The method to set all leds of the strip to the same color
void LedModule::turnAllNeoPixelsTo(uint8_t red, uint8_t green, uint8_t blue)
{
    for (uint16_t i = 0; i < getLedCount(); i++)
    {
        // Avoid to light up the middle leds
        if (i < 5 || i > 9)
        {
            pixels.setPixelColor(i, red, green, blue);
        }
        else{
            pixels.setPixelColor(i, 0,0,0); // off
        }
    }
    pixels.show(); // This sends the updated pixel color to the hardware.
    mIsLedStripOn = true;
}

After this changes, when I call the method above, I got the exception:
Exception 29: StoreProhibited: A store referenced a page mapped with an attribute that does not permit stores
Decoding 15 results
0x4020ddbd: ieee80211_send_mgmt at ?? line ?
0x4020db5f: ieee80211_send_mgmt at ?? line ?
0x40102864: trc_NeedRTS at ?? line ?
0x4020fe6d: ieee80211_sta_new_state at ?? line ?
0x402101ab: ieee80211_sta_new_state at ?? line ?
0x4021060f: sta_input at ?? line ?
0x402109cb: ieee80211_parse_wmeparams at ?? line ?
0x402103ab: sta_input at ?? line ?
0x40204ce3: pp_tx_idle_timeout at ?? line ?
0x40204607: ppPeocessRxPktHdr at ?? line ?

It seems to crash during the pixels.setPixelColor(i, red, green, blue); method.

What is pixels?

instance of Adafruit_NeoPixel library object. I updated the class code above.

I don't like your method of constructing. I think you need a new in there and make it a pointer

I used the sample coming from the library. You can find it here: https://learn.adafruit.com/adafruit-neopixel-uberguide/arduino-library

That is completely different, sorry.

pixels = Adafruit_NeoPixel(...) creates a local variable (an rvalue) then copies it to the class member. If Adafruit_NeoPixel does not have a proper operator= problems may arise.

Your "constructor" isn't doing what you think.
In the example you point to you have, efectively:
Class object = Class(parameters);

Whereas in your code you have:
Class object;

object = Class(parameters);

In the first form it results in a new object constructed at declaration time. In the second it first creates a new "empty" object and then at a later date tries to copy a newly constructed object into it - which may be failing if the class doesn't support copying.
Instead you should be working with new and pointers.
In your class definition you create a pointer to your Adafruit class:
private:
    Adafruit_NeoPixel *pixels;

Then you create a new object pointing to it:
pixels = new Adafruit_NeoPixel(numOfPixels, dataPin, NEO_GRB + NEO_KHZ800);

Accessing it is then done with -> instead of .:
pixels->setPixelColor(i, red, green, blue);

Another option (to avoid new) would be to use the initializer list: LedModule::LedModule(unsigned int numOfPixels, uint8_t dataPin) : pixels(numOfPixels, dataPin, NEO_GRB + NEO_KHZ800) {...}

Yeah, I thought of suggesting that, but it can get a bit awkward with the Arduino API and the order things get initialized. I find it's best in general to do things in begin() rather than with constructors. Besides, there's no harm in using new in this situation.

Another option would be to extend the NeoPixel class creating a child class that adds more functions to it.