text:
Saving sensor logs of unknown length
I have a sensor giving me values (ints) which I want to keep, and send to a computer via the WiFi shield when requested via HTTP. I have the HTTP thing working, however, I do not know how to have a String or whatever able to store what is basically an array of ints, when I do not know any maximum size.
I have read that using Strings on Arduino is not recommended because how RAM works and such things, so I translated all my String uses to C-style arrays (as it was recommended), this solved my memory issues, however, C-style strings are not resizable.
While browsing the forums, I found that for similar problems the recommended way of handling things would be to create an array of max size instead of dynamically growing the array, but I do not know the maximum size in this case.
Here are the requirements

A way of storing each values (in order) so they can be sent later after an HTTP request (but they can get requested multiple times so I can't delete them then),
Whatever storage way is fine by me (Strings, arrays of ints, ...), as long as it works.
A request to the data should take ~100ms (I don't think this will cause issues, but I'll mention it just in case).

I thought about printing the values to the SD card, since there I have far enough memory, but for some reason I can't get the WiFi and the SD card to work together (as soon as I init the SD library, the WiFi library doesn't work anymore - I asked an other question about this here).
PS.
I'm quite new to C++ and Arduino, but I'm not too bad at Java.
What would be the best (or at least a working one) way of achieving this ?

If this was an ordinary computer I would suggest using C++ vectors as you don't need to describe its size to the compiler.  But we are talking embedded and there may not be enough physical RAM for you to work with.  Have you consider using a much more powerful Arduino such as an ARM based Arduino?  Also, likely all libraries have never been tested with all other libraries for comparability.  Given the limited hardware resources of most Arduino processors, you are likely running into a conflict between the WIFI and SDCard libraries.

Also, considering the low cost of most Arduino platforms, it may be easer to split the tasks between two Arduinos.  The sensor sampling & SDCard logging can be accomplished on the 1st Arduino.  And the WIFI & web page serving can be accomplished on the 2nd Arduino.  It is certainly not the first time hardware has been used instead of software to solve a problem.

It would be a great solution, but I saddly can't do this (mostly because this is a project for school and I can't choose the hardware I'm working with, along with the fact that time is beginning to run out...)

Someone might have a direct solution for you (use the libraries as is and still run on a single Arduino).  Otherwise, start thinking "out of the box". Consider polling the Arduino on a periodic bases to avoid storing large amounts of data on the embedded processor.  Again, investigate alternative Arduino's with large amounts of built in RAM (such as the ARM based Ardiuno).  In this way you can set aside large amounts of RAM for data storage with little modifications to your existing WIFI only code (w/o the SDCard code).

This is basically two questions: how to get your SD card and WiFi working at the same time (in which case memory limitations are not an issue), and how to deal with the memory limitations if you choose in-memory storage of your data. I'll address the second one here; you should split out the WiFi/SD conflict into a separate question where you detail the exact hardware you're using and how it's connected.
You've got only 2 KB of RAM in an Uno and similar models, so you will have to discard data at some point, whether or not it was successfully sent in a reply to a web request. The key here is to use a fairly compact method of storing the data and to have an easy way to get rid of old values to free up space for new values.
One common way to deal with this is to use a ring buffer. This is a fixed size storage array with a pointer or index, which I'll call head, indicating the next storage location to use. You start with head = 0 (the beginning of the buffer) and every time you receive a new value you store it at head and then increment head by one. You also need to compare head to the end of the buffer and, when it would pass the end, reset it back to the beginning of the buffer. After the first pass through the buffer, storing at head will overwrite the oldest value previously stored.
Going back through the buffer to read out the old values is easy: you just start by reading the value at head - 1 (or the end of the buffer if head is 0) and work downwards, wrapping around when you hit 0, and stopping when you reach head.
You can handle the initial states where the buffer hasn't been filled yet in two ways: just fill the buffer with a value such as 0 that you don't mind returning as a "nothing stored here" value, or just set a flag at the start to say that the buffer hasn't been filled yet and you should stop at 0 when reading it out; this flag would be cleared the first time that head reaches the end of the buffer and wraps around.
Since you're getting data that are ints, storing them as (larger) strings would be silly; just create an array of ints of the smallest type that can store all possible values of your sensor, e.g., uint16_t if you're getting unsigned 16-bit values. With some experimentation and checking, you should be able to figure out how large a buffer you can use based on how much storage you have free after the RAM for other parts of the program has been allocated. I'd imagine that if you're careful and you're making sure you store strings in program memory you could make room for a buffer that would hold a couple of hundred entries.
Since this seems to be a student assignment, I won't provide sample code here; writing your ring buffer code will prove an excellent exercise in the details of programming.

Thanks ! I already heard about ring buffers in Java, this shouldn't be too hard to implement ; but I'm not sure if it'll be enough. Well, can't know without trying, if it's enough I'll mark the answer as accepted then.

What do you mean by "enough"? The problem with your question is that it doesn't have any clear criteria, such as the amount of data that must be stored. (If you must store more data than will fit in memory, clearly both this solution and the "Strings in memory" solution you originally used are both completely unacceptable and you should have asked two, separate, different questions: one specifically about how to get the SD Card working with WiFi (detailing your hardware precisely), and the other about other options for external storage.

What would be the best (or at least a working one) way of achieving this ?

none. Because the upper end of your possibilities (ie. infinite amount of data) is way beyond anything a computer can possibly handle now and into the distant future.
So unless you have some reasonable upper bound for the data in question, there isn't a whole lot you can do to satisfy your application.

authors: Вячеслав Сёменов


text:
TRT-25 and Arduino Uno
I am reaching out for help on a project I am working on. We are trying to integrate a reaction torque sensor and I am having a hard time deciding how to go about it. Previously I assumed that like my load cell I would be able to use the HX711 module to connect my Torque sensor to my Arduino. The Torque sensors uses a Wheatstone bridge configuration, which is great for this module. The problem I ran into is that the TRT-25 Torque sensor requires an excitation voltage of 10V and my Arduino is only supplying 5V. When I tried powering my sensor separately with 10V I quickly found out that these HX711 modules are not designed to handle 10V...
Needless to say that I am now wondering how I should be power my sensor, but also which A/D converter can be used to get this working. The same manufacturer sells all the components to get this working, but it is hundreds of dollars more and our budget doesnt allow for it. I am posting links here so you can see the sensor. What I am considering now is finding a 10V source and connecting the signal pins to my analog pins on my Arduino. I am hoping based on the raw value I can compute a torque measurement based upon this small piece of information their tech support gave me.  (X mv/v * EXCITATION v = TORQUE in/lbs).
FYI, I dont have much more information outside of what it is on the site for the sensor. My project uses a small enclosure and I have a arduino proto shield to power my other 3 sensors. I am limited on space but could probably incorporate a small supply and replace the current HX711 module.
HX711
https://www.transducertechniques.com/trt-torque-sensor.aspx

your question has nothing to do with the arduino ... it belongs at https://electronics.stackexchange.com/questions ... please delete the one here

"When I tried powering my sensor separately with 10V I quickly found out that these HX711 modules are not designed to handle 5V"  Did you mean not designed to handle 10V?  It would probably be better to link to exactly what you have.

It doesn't require 10V. 10V is just the voltage that they performed the calibration at. You can use anything up to the maximum - though at anything other than 10V your accuracy may vary slightly.

@Majenko I am finding that the mV reading seems to be too low. Less than 0.1mV it seems. I am planning on trying again with 9V battery.

source: Stack Exchange

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

sort: votes


text:
12V 28BYJ-40 motor is not generating enough torque
I am attempting to use a stepper motor to rotate one of my split-flap displays. However despite the thing the motor is rotating weighing probably half a pound, it struggles to do so. It really can rotate the module at all.
Why is my motor struggling so much?
My circuit is an Arduino powered by 5V from a wall outlet, connected to a ULN2003 driver that is powered by a 12V wall outlet. The driver is connected to the stepper motor.
This is my code, it uses the Accel stepper library:
#include <MultiStepper.h>
#include <AccelStepper.h>
#include <Stepper.h>

AccelStepper stepper2(AccelStepper::FULL4WIRE, 4, 5, 6, 7);

void setup()
{
    Serial.begin(9600);
    pinMode(0, OUTPUT);
    pinMode(1, OUTPUT);
    pinMode(A0, OUTPUT);
    pinMode(A1, OUTPUT);
    pinMode(A2, OUTPUT);
    pinMode(A3, OUTPUT);
    pinMode(A4, OUTPUT);
    pinMode(A5, OUTPUT);

    stepper2.setMaxSpeed(100);
    stepper2.setAcceleration(10);
    stepper2.moveTo(-24000000);

}
void loop()
{
    // Change direction at the limits
    //printletters();

    if (stepper2.distanceToGo() == 0)
        stepper2.moveTo(-stepper2.currentPosition());

    stepper2.run();
}

Edit: Here is the schematic, I'm sorry its terrible but I dont know how to make it better

simulate this circuit – Schematic created using CircuitLab

A stepper motor cannot start with the target speed if the torque is too high. You might need to accelerate it.

Could be lots of things. My first guess would be you're not sharing grounds, but with no circuit diagram, it's just a guess. It's also difficult to guess how much force is required to turn the thing you're turning; the weight doesn't describe the system.

Post a schematic, not a frizzy thing and calculate the required torque needed on the motor shaft. Note a schematic shows all power and ground connections. If you have a scope measure the voltage waveform at the motor connections. You are using a bipolar driver a lot of power is lost in that, about 1.4V per output pin.

@thebusybee i am accelerating it

@DaveNewton can you explain sharing grounds

The ground from the motor controller board needs to be connected to the ground of the Arduino--when dealing with potential electrical problems a schematic is a good idea.

@DaveNewton okay I added a schematic, Im sorry its not very good, I'm not very good

The grounds need to be shared.

@DaveNewton That totally fixed it thanks a ton man

Nice! Glad you worked it out.

The grounds needed to be shared. The driver board ground needed to be connected to the Arduino ground. Otherwise your putting 17V in and only taking 12V out. Thanks to DaveNewton for this answer. I made this change and the torque was immediately fixed!

The reason is because there's not a complete circuit between the Arduino output pin and the Arduino. You might be interested in https://forum.arduino.cc/t/common-ground-and-why-you-need-one/626215/5.

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


text:
Arduino UART (TX/RX) multidrop 1 master 50 slaves
I'm thinking to connect about 50 slave Arduinos on 1 master using TX/RX. I'm following recommendation of these links:

I'm looking for a way to serially communicate with a multi mesh Arduino slave network, and;
Tx/Rx UART communication between 2 MCU over 1 line

using the cathode of diode connected to slaves TX pins and pulling up this line, like this image:

In Arduino - Digital Pins, when pin is set to input (high impedance), it is "equivalent to a series resistor of 100 MΩ in front of the pin". Slave RX line has input (RX pin) in parallel, then, if this 'equivalent resistor' is true, we have a low resistance (duo parallel configuration) that burn the master TX. Is it make sense?
I have not found either in the Arduino or the ATmega documentation, if TX port have the internal pullup on. In ATmega documentation, TX pin is set as output and RX pin as input. The TTL logic is high on idle, then 5 V must be sourced from somewhere, correct?

Might want to use RS-485.

RS-485 is limited to 32 devices. For now, I need to use only TX/RX to communicate between master and slaves. It works for a master and 2 slaves. But, I'm worried when I connect 50 slaves and burn the master TX.

The number of devices depends on the bus driver. With "Fractional Unit-Load devices" you can have as many as 255 devices on a single bus segment. It is also possible to use multiple segments (repeater).

I checked RX (input) port in Arduino and it have 5 V and drain 0.14 mA. Then, RX is internal pulledup. But, ATmega 328P documentation say that internal pullup resistor is optional and USART section, at same documentation, have not mention about pullup TX.

nice project. Does it work so far? I'm going to do something similar.
which diodes do I have to select for this?

@Chris, I used the 1N4700. I used this to connect 72 arduinos, but I multiplexed the lines to have the max 18. I have some problems because of cables length (some with 10m), but worked with regards.

An input pin draws 1uA or less input current, so more like 1 Megohm resistor, not 100 Megohm.
In an Uno, the USB interface chip typically is what is pulling the Tx and Rx lines high with 5mA drive (high output thru a 1K resistor to D0 or D1).
What you have drawn should work. The pullup resistor will ensure the Rx into the 1st Arduino sees a nice crisp high when the other two stop pulling the line low as they send a message out, and the diodes will prevent the one driving the line high while the other pulls it low.

The Arduino - Digital Pins official documentation inform a 100 Megohms resistance to out the pin as input (high impedance). Reading Arduino Schematic, the RX and TX pins in ATmega 328 is connected to ATmeg82U. Maybe this CI can source 5 V to RX/TX. But I'm not using USB to power up Arduinos. I'm using UNO and Minipro powered up through 5 V Vin. Then, I do not know where come 5 V to pulling pins high.

There are other mistakes in Arduino documentation as well, 100 Megohm is just one of them.     The Atmega328P data sheet clearly says maximum input current is no more than 1uA. V=IR, or V/I = R. 1V/.000001A = 1,000,000 ohm resistor. Maybe 5 Megohm if you want to consider a 5V input and 1uA of current.

@CrossRoads, how does a 100MΩ resistor violate the "max 1μA" requirement?


text:
MH-Z19 with Arduino null output
I want to get CO2 value by using MH-Z19. I tried this code with Arduino uno R3 but I always get this result (CRC 0/0). I didn't understand where is the problem.
I linked A0 with TX of sensor and A1 with RX, I powered the card with 3.3V/Vin to visualize the result on PC via USB port.
 #include <SoftwareSerial.h>;

 SoftwareSerial mySerial(A0, A1); // A0 - к TX сенсора, A1 - к RX

 byte cmd[9] = {0xFF,0x01,0x86,0x00,0x00,0x00,0x00,0x00,0x79};
  unsigned char response[9];

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

 void loop()
{
mySerial.write(cmd, 9);
 memset(response, 0, 9);
 mySerial.readBytes(response, 9);

  int i;
byte crc = 0;
 for (i = 1; i < 8; i++) crc+=response[i];
 crc = 255 - crc;
 crc++;

  if ( !(response[0] == 0xFF && response[1] == 0x86 && response[8] == crc) )
 {
Serial.println("CRC error: " + String(crc) + " / "+ String(response[8]));
  } else {
unsigned int responseHigh = (unsigned int) response[2];
unsigned int responseLow = (unsigned int) response[3];
unsigned int ppm = (256*responseHigh) + responseLow;
Serial.println(ppm);
}

Start by modifying your sketch to print out the return value of readBytes() and the actual byte values in the receive buffer.  If you have a scope or logic analyzer you might try monitoring the command and response directly.  If SoftwareSerial has the same 1 second default timeout as hardware serial, it is probably never getting a response and timing out with an empty buffer still at the initialized zeroes.  Perhaps you should check that the return value of readBytes() indicates the expected number of characters have been received.

@ChrisStratton thank you for your response. I changed the softwareSerial pins to Digital one ( pin 0 Arduino (RX) linked to TX of sensor and pin 1 Arduino (TX) linked to RX of sensor), I get this as output: 32 - 30 - 20 - 2D - 20 - 33 - 33 - 20 - 2D - END                           I think it is not correct since according to the datasheet the first byte should always be 0xFF

From the datasheet, working voltage for MH-Z19 is 3.6V to 5.5V, so 3.3V is not enough. (Although the interface runs at 3.3V).

Also, the Uno might not run reliably at 16MHz and 3.3V.

Edited image from datasheet page 303.

thank you for your response. I have the same result (CRC 0/0) even with Wemos D1 powered with 5V.

@user3921905 -- You should probably add the details of all you have tested to the question. Also please post a pic of your setup with wiring, etc.

I updated my question.

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


text:
Can't get 4 digit 7 segment display to show different values
I'm an Arduino newbie having problems getting a 4 digit 7 segment display to work. The display is connected to a 74HC595 and the setup is from the elegoo tutorial 28 (I think it is download only).
I figured how to control which number to display, but all 4 digits always share the same number, so it is always like 1111, 5555, 9999 etc.
I've heard about something called multiplexing which might do the trick, but I can't adapt it to my project yet, missing too much experience.
This is the code that toggles between 2222 and 8888.
I want to be able to display any number like 1234 though.
Any help is very appreciated.
int latch=9;  //74HC595  pin 9 STCP
int clock=10; //74HC595  pin 10 SHCP
int data=8;   //74HC595  pin 8 DS

void setup()
{
  pinMode(latch,OUTPUT);
  pinMode(clock,OUTPUT);
  pinMode(data,OUTPUT);
}

void Display(unsigned int num)
{
  digitalWrite(latch,LOW);
  shiftOut(data,clock,MSBFIRST,num);
  digitalWrite(latch,HIGH);
}

void loop()
{
    Display(91);
    delay(1000);
    Display(127);
    delay(1000);
}

We have no clue what elegoo is. Show us your circuit.

Either you need multiplxing or you'll need to daisy chain 4 74HC595, one per digit. Otherwise, you won't get anything different than now. For multiplexing, I think there have been plenty of questions about this topic already. And a google search will show you what you need.

Hello my sevensegment have 14 pin can you send schematic map????

You have a common cathode display and all your cathodes are tied to ground through resistors. You have no way at all of separating out the different digits.
You cannot directly drive such a display with a shift register like that - you need a more direct connection to the Arduino (it needs to be high speed) and rapidly switch each cathode on and off in sequence to display each of the four numbers one after another.
Also the resistors should be in the 8 anodes, not the 4 cathodes.

Thank you Majenko for taking the time. I guess that means that this tutorial setup is not recommended nor feasible to be used to drive all digits separately then.
I will have to search for a different setup that I can take as the base then.

It is possible to use the shift register if you also connect the cathodes to the Arduino and select each one in turn. With the shift register though it may be flickery. The code is also much more complex than just shifting out a number.

https://playground.arduino.cc/Main/SevenSegmentLibrary

but all 4 digits always share the same number, so it is always like 1111, 5555, 9999 etc.

because that's how this particular circuit is designed for.

I've heard about something called multiplexing which might do the trick, but I can't adapt it to my project yet, missing too much experience.

multiplexing is no different than displaying each digit quickly (as you are doing now), and then display the next digit quickly, ....
what you are doing now will contribute to your learning multiplexing.

The problem with this setup is the circuit.
The Master Reset Pin 10 on the 595 is floating.
Use a 10K resistor to pull it up to VCC (+5V) and it will work.
I was getting all sorts of odd characters until I checked out the data sheet on the 595.

That circuit needs a 0.1uF cap from '595 VCC to Gnd for consistent operation. Ideally a resistor between each '595 output and the anode pin, and a transistor or other higher current device able to sink the current from 8 anodes being driven at once (i.e. ULN2003).  Once the cathodes can be driven seperately, to allow each digit to be selected individually, than an array can be used to map the digit to be displayed to the segments in a display:
// add before setup()
byte fontArray[] = {
0b00111111, // 0  where the bits represent dp-g-f-e-d-c-b-a
0b00000110, // 1  and 1 = segment turned on
0b01011011, // 2
// etc.
};

// and change this line in display() to display a number

shiftOut(data,clock,MSBFIRST,fontArray[num); // looks up mapping from above

// then turn on a cathode to display it for 2-3mS, then back off, and send
// out the info for the next digit

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


text:
Arduino Due not executing code after power on
My Arduino Due does not execute its code when powered on after being powered off for ten seconds or longer. I have to press the reset button for the code to execute.
I've read some older threads about a firmware issue and saw people doing solder jobs on their boards to fix it.
My question is, does this issue happen with all/any Arduino Due boards? Are just some clones (like mine) affected and the original works fine?
What's the best way to fix this problem? In this state the board serves no purpose anymore and I've downgraded to the Uno for now.
EDIT: Adding picture and link to the board used.
https://www.amazon.de/gp/product/B016D5KYF6/ref=oh_aui_detailpage_o00_s00?ie=UTF8&psc=1

you have posted inadequate information. what make of the board do you have? post a picture, maybe.

Nobody? It would help already to know if this issue is not "normal" for genuine Arduino Due boards.

It happens with UNOs as well. Have to press reset button to run any included program. Looking to fix this since the UNO has to start correctly when power is applied.

After some more research I found out that
a) the issue applies to some Due boards only, not all
b) newer boards seem to have fixed the issue
c) there's a software (firmware update) and hardware (10k resistor) solution
I went with the hardware fix shown here:
http://www.dimdim.gr/2016/03/fixing-startup-issues-with-arduino-dues/
I did not have an SMD resistor at hand, so mine looks ancient but does the job.
Hope that helps others, too.

addendum:
The problem occurs only on some DUE boards and is due to some undocumented behaviour of the ATSAM3X8E processor combined with the behaviour of some MOSFETS installed on the DUE boards. So its occurence is largely a matter of luck.
The fix is simple: you just solder a 10K resistor across the top of this mosfet:
resistor about to be soldered on

resistor designated as R99

While the picture is great, it would be good if you could describe the fix in words so that it can still be applied by someone who might find your answer after the off-site link might have borken.


text:
Rotary encoder I2C LCD menu
I am trying to make a menu for a monitoring/control system.  I am not sure how to make this without interrupting my current code which needs to be monitoring my system at all times to shut off if it reads overload. It is mostly swtich () and case x: stuff. I have looked into attachInteruupt and rotary encoder examples, but none have really helped me figure out how to display a multiple layer menu where I can select to see the system readings as well as edit outputs.
There are a lot of posts here on rotary encoders with LCDs, but I can't seem to find a good skeleton menu code that works well and uses current libraries.  My biggest problem right now is making the menu layers without interrupting my monitoring code running in the background.

I don't think you should do both tasks on the same microprocessor.  Detach the UI an put it on a second processor that sends messages to the control processor over I2C or similar.  This way the user can 'accidentally' use the UI is a way the blocks the control processor.

you might want to consider timed routines or interrupts.
For timers https://playground.arduino.cc/Code/Timer1 or similar can help.
When using interrupts be sure to be minimalistic because atmegas do not behave well when interrupts take too long to process.
About menus there are several, most of them dynamic and some requiring user display + nav code.
This open-source menu lib (https://github.com/neu-rah/ArduinoMenu) is static, that is good for bigger projects because it stores a lot on flash.

(-) you can not change menu at runtime (however it support value fields)
(+) requires no user code base
(-) setup involves several parts (inputs/output)
(+) non blocking polled mode. Just call the poll function on your code loop, the menu will just return if it has no input or output
(+) supports a lot of display devices, including i2c lcd
(+) supports encoder (interrupts (PCINT) or timed driver)
(-) atmega2560 interrupts (PCINT) only on 3 ports, PCINT might require pin mappings (not sure), but if needed the PCINT library examples can print one for you.


text:
How I can connect module GSM SIM800L?
I bought a GSM module, and I want to connect it with Arduino but I have a problem.
I linked GSM SIM800L with regular LM2596 12 V 2 VA I changed tension to 5 V, So far the GSM is working but if I connect TX_ARDUINO with RX_GSM the module enters in the loop of the restart.
The picture explains the montage.

How are you providing power to arduino?

I connect Arduino with my pc.

And your code...?  Also, you shouldn't be using GSM in modern designs. Many carriers are turning off GSM services. You should be using (at least) an LTE modem.

You should separate the ground of external power supply and GND of arduino.

@Vaibhav How is that going to help matters? All that will do is break things further.

@Vaibhav  how I can do it ??

@ÀbdóBougaà your module must have gnd terminal use it for supply as well.

@Majenko what I think Hardware connections are not right.

Follow this tutorial on how to connect your Sim800l with Arduino.


text:
ADS1115 : measuring 5v voltages and powering with 3.3v
I have a project where I need to measure 0 - 5 V. I’m using a ADS1115 to have a better precision, connected to a ESP12. Since the ESP is only 3.3 V tolerant and the ADS powered by 5 V (because it needs to be powered a the same voltage as the measured voltage), I put the two pull-up resistor of the I2C bus on 3.3 V.
Is it safe to operate like this?

I'd use a Bi-directional Logic Level Converter for I2C

esp8266 has no problem with 5 V I2C

Safe? Yes. Reliable? Not really. VIH is 3.5v at 5V VCC, and 3.3 is below that.

Is your arrangement safe? Yes, perfectly.
Is your arrangement a good idea? No, it is not.
When the ADS1115 is run at 5V it needs at least 3.5V on the I2C bus to properly register a HIGH.
However you can pull up to 5v instead and you won't have a problem.  Not only is the ESP8266 tolerant of 5v, but that 5v is severely limited in current by the pull-up resistors, so even non tolerant inputs would have a hard time complaining. Worst case scenario, the ESP8266 pulls the bus down to maybe 3.8v (3.3v plus an ESD diode drop) which is fine for a logic high on the ADS1115.
However, if you want to do things properly, you really should use a proper I2C level translator.

Ok thank you. I thought the ESP i2c bus was only 3.3 v tolerant. I don’t have enough space to put a logic converter (my pcb has be 4cm * 6cm)

So use a PCA9306 in DSBGA package then - 1.98 mm x 0.98 mm (can you even see that...?) I have used the X2SON version (1.40 mm x 1.00 mm) before, and that was, while tricky, actually possible to work with.


text:
Byte text file to array
I'm trying to display a bitmap on gLCD 128x64, I stored the bitmap into txt file 1.txt in a SD card this is a part of bit map  as following:
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x80, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0,
0xC0, 0xC0, 0x80, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00.......
I want to convert the content of this text into array:
Unsigned char logo[] with making a split on ",".
Any help please

The most efficient way is to read the file byte-by-byte into a small character array until you get a comma or the end of file - ignoring any characters that aren't of interest (line feeds, etc).
Then for each chunk that you read you then convert it to an integer.
For example (untested):
char temp[5] = {0}; // should be more than enough
int pos = 0;
int bno = 0;

const char *hexchars = "0123456789abcdefABCDEFx";

while ((int ch = myFile.read()) >= 0) {
    if (ch == ',') { // We found a comma
        logo[bno++] = strtoul(temp, NULL, 16); // Base 16 conversion
        pos = 0;
        temp[0] = 0;
    } else if (strchr(hexchars, ch) != NULL) {
        if (pos < 4) {
            temp[pos++] = ch;
            temp[pos] = 0;
        }
    }
}

Of course, you have to know how big the logo array has to be beforehand.
One does, though, have to ask "Why are you storing a graphical logo as a textual representation of binary data" in the first place?  It would be far easier to just store it as a simple binary file and read the data directly into the logo array with a single File::read(void *buf, size_t nbyte); function call.  Using text as an intermediate format is both wasteful and needlessly increases complexity massively.


text:
Transistor as switch for signal and high current buzzer
I'm a newbie in transistor switching.
I have PIR sensors with C and NC onboard. NC is 12 V signal that I need to switch transistor (bipolar?) to emit 3.3 V (collector connected to 3.3 V).

VCC equals 3.3 V. PIR is pin on ESP32.

Can you tell me if this circuit is okay or does it need additional edits?

Note: Q3, Q4 transistor number is random, if you can offer me suitable transistor I would be glad.
Next circuit:
ESP32 pin "ALARM" is connected to transistor (MOSFET N channel) base.

ALARM as device is connected to 12 V, required 300 mA to run and I need transistor to switch circuit. Relay is awful.

Is this circuit correct?
Do I need any additional edits?
Can you suggest me suitable transistor?
I don't know much about MOSFET shortcuts.

Third circuit I need is same as this but instead 12 V I need to switch 5 V.

I guess just to change MOSFET transistor?
Or use same as for 12 V?

Combined circuit schematic:

Your new schematic - have you posted that as an answer, or is that the circuit to which your questions apply? I notice that you have taken suggestions from Rp Rp's answers and made changes to the original circuit. That could end up confusing the question. If your original question was answered, then you should accept one of those answers. Thereafter if you have a new question then you should post a New Question. Sorry, I am just a bit confused as you asked for transistor suggestions, and then edit your answer to reflect those suggestions. Your new circuit should be posted as a answer maybe

Also, you should flag your question for migration to SE.Electrical Engineering as it would be a better fit, as your question isn't really about Arduino, but electronics in general.

@Greenonline my mistake, I thought if I was speaking about Arduino a little bit it could be posted here instead electrical stack exchange. I edited post because I can't add image to comment :)

I'll try to answer your post with "just words" and we will see how it goes. If it is not clear to you, i will post small schematic.
I do not recommend the first schematic that you posted.
You will likely reverse bias the BE (base emitter) junction with 12v. Most bipolar transistors have a maximum reverse BE bias of 5 v.
I do recommend using bipolar so that you dont have to study, understand the range of turn on voltages for a MOS transistor.
The bipolar is always 0.6v
and a Darlington bipolar is twice that.
Also, i dont know why you have the 100nF caps in there. They will guarantee a surge, everytime you turn the circuit on and hence put noise on your supply bus.
When I design a driver for a similar application i frequently use a TIP100 (https://www.digikey.com/product-detail/en/on-semiconductor/TIP100G/TIP100GOS-ND/1485300)
So use the basic design of your second circuit but use the TIP100.
ALWAYS have a resistor (10k ohms or so) to keep the leakage current (Icbo) from turning on the transistor when you dont want it on !
I would put all the loads into the Collector circuit in your second schematic, rather than make the uP drive your LED.
If your load is at all inductive (a coil) then ALWAYS put a reverse-biased diode across the load to catch any inductive kick back.
If this is all Greek to you, then just say so and I will draw a simple universal circuit that will work for 3.3v drive or 12v drive.
All the Best to you.
RP


text:
5V alternative to Due?
I've designed a circuit controlled by an Arduino Mega 2560 involving a number of external components all running on and sending out 5V signals. I'm now realizing that the 8Kb of SRAM on the Mega 2560 is insufficient, so I wanted to upgrade to an Arduino Due.  The Due, however, can't accept the 5V outputs from the rest of the components.
Is there an Arduino compatible 5V board with memory comparable to the 96Kb on the Due?
I know that level shifting is an option, but considering that almost every digital input on the board is being used, I'd rather not have to add so many level shifters to the circuit.  A voltage-compatible board is preferred.
I'm also not fixed on Arduino-compatibility.  If there is another convenient microcontroller development board available, I'd gladly consider it.
EDIT:
The Arduino is being used to read from a set of sensors that produce image data at a constant rate.  The data is recorded on the Arduino, then sent to a computer by USB.  The Arduino needs to store the whole image before sending it to the computer because performing a Serial write call delays the processor causing it to miss a data sample.  The ATMega2560 doesn't have enough SRAM to store the whole image at once.

please do some research ... come back with an actual question

What are you doing that requires so much memory?

If your code really gets to complex for the Mega, one option is also to move just the code away from the mega. Use the Due just for controlling the mega, over some serial protocol for instance. (In which case I'd even go for an ESP32, because it is much more powerful still than the due if the massive number of pins is not required)

Re “a Serial write call delays the processor”: if the input data rate is constant, and slower than what the output baud rate affords, you may consider foregoing the Serial object and just writing the incoming bytes straight to the serial port data register. That should take just a couple of CPU cycles.

@EdgarBonet I tried your suggestion to write to the serial register directly, and it is faster, but it still has to wait for the transmit buffer to be emptied before transmitting.  This variable delay causes the device to occasionally miss an incoming signal.

The Teensy 3.5 seems to be exactly what I was looking for.

It is an Arduino-IDE-compatible 5V tolerant microcontroller board with a whopping 256Kb of SRAM and 64 digital inputs.  It pretty much blows away the Due in every way.

The Arduino MKR Connector Carrier has input level conversion on analog inputs and logic level conversion on digital pins. It makes the 3.3 V MKR boards (SAMD21 MCU) compatible with 5 V sensors and actuators.
The SAMD21 on MKR boards has 256 KB internal flash memory and 32 KB SRAM.


text:
Problems connecting reliably using HC-05 (as bluetooth master)
I currently try to connect an Arduino Micro/Leonardo/32u4 to an ELM327 Bluetooth dongle using a HC-05 Bluetooth shield from iTeadStudio. I also have similar problems trying to connect to a bluetooth dongle (with added serial connection) on my PC.
The basic AT-command communication works, but I haven't found out yet why AT+PAIR or AT+LINK are failing and what should be done to avoid this (I've done dozens of Serial Monitor command iterations). Until now I haven't found a command sequence that reliably connects. What I've tried so far (from different documentation and example codes):
Check general AT command set:
AT
> OK

Reset to default values:
AT+ORGL
> OK

Set master mode and check it:
AT+ROLE=1
> OK
AT+ROLE?
> +ROLE:1
> OK

Connect only to the specified bluetooth address:
AT+CMODE=0
> OK

Reset and initialize:
AT+RESET
> OK
AT+INIT
> OK

Configure inquiring mode:
AT+INQM=1,9,48
> OK

Inquire:
AT+INQ
> +INQ:12:34:567890:1F1F,7FFF
> OK
AT+STATE?
> +STATE:INQUIRING

Try to stop inquiring:
AT+INQC
> OK
AT+STATE?
> +STATE:INQUIRING
> OK

Reset and initialize again (otherwise we can't leave the inquiring state):
AT+RESET
> OK
AT+INIT
> OK
AT+STATE?
> +STATE:INITIALIZED
> OK

Try to pair with the found device (my PC asks for the 1234-password and creates a serial port):
AT+PAIR=12,34,567890,20
> OK
AT+STATE?
> +STATE:PAIRED

Try to connect
AT+BIND=12,34,567890
> OK
AT+LINK=12,34,567890
> FAIL
...

Does someone have some hints for finding the right sequence?

I am using a "BIND" between the Pair and Link:
AT+PAIR=98D3,31,FC2D54,5
AT+BIND=98D3,31,FC2D54
AT+LINK=98D3,31,FC2D54

I can't even pair... I'm trying to connect a ds4 with a hc-05. It seems the password is used to pair, but the ds4 doesn't have any. Any idea?

I had same problem and searched for several helps to make it, however a couple of solution I found in the net could not directly solve the problem.
Now I finally found the real solution ,thank to GOd!

It looks like I now have a slight understanding of what happens and how to get the HC-05 working.
Be sure to have the CMD-DAT-switch set to CMD before turning on the HC-05.
Command mode (configuration)
Check general AT command set:
AT
> OK

Reset to default values (sets, among others, ROLE=0 and CMODE=1):
AT+ORGL
> OK

Set master mode and check it:
AT+ROLE=1
> OK
AT+ROLE?
> +ROLE:1
> OK

Reset and initialize (reset aborts, e.g. the inquiring state - quickly flashing LED; without initializing you would get ERROR(16)):
AT+RESET
> OK
AT+INIT
> OK

Now the LED should slowly flash.
Optionally: set password of the target device:
AT+PSWD=1234
> OK

Show count of all authenticated devices in pair list:
AT+ADCN?
> +ADCN:7
> OK

If the value is larger than 0, delete all authenticated devices in pair list:
AT+RMAAD
> OK

Now pair with the desired device (the last 20 mean 20s):
AT+PAIR=12,34,567890,20
> OK

The LED starts flashing one time with a longer pause.
Set the desired device:
AT+BIND=12,34,567890
> OK

Now link (e.g. when connecting to the ELM327; the PC will create another new port after having requested the password from the user):
AT+LINK=12,34,567890
> OK

The LED starts flashing two times with a longer pause. After linking, it might be that either the HC-05 switches to data-mode or continues in command-mode (haven't found out when it does one or the other).
Command mode (auto connect)
Now switch off the HC-05 and keep the CMD-DAT-switch to CMD. Switch it on again. It should automatically connect to the previously connected device. To switch to the data mode, first disconnect...
AT+DISC
> +DISC:SUCCESS
> OK

... and reconnect.
AT+LINK=12,34,567890
> OK

Now the connection seems to have switched to data mode.
Data Mode
Now switch off the HC-05 and move the CMD-DAT-switch to DAT. Turn on the HC-05. It automatically will try to connect to the previously connected device - the LED should flash two times with longer pause - and you don't have to mess with HC-05-AT commands any more.

I am using a "BIND" between the PAIR and LINK:
AT+PAIR=98D3,31,FC2D54,5
AT+BIND=98D3,31,FC2D54
AT+LINK=98D3,31,FC2D54

That seems to work for me.
See the docs here:
ftp://imall.iteadstudio.com/Modules/IM120723009/DS_IM120723009.pdf


text:
Problem activating HC-05 AT command mode with Arduino Uno Bluetooth shield
Please be gentle with me. I am attempting to modify the configurations of my HC-05 bluetooth module by using the AT command set. The method by which I'm trying to do this is by implementing the following connection:
HC-05 GND --> Arduino GND;
HC-05 3.3v --> Arduino 3.3V;
HC-05 TX --> Arduino Pin 10;
HC-05 RX --> Arduino Pin 11;
HC-05 KEY --> Arduino Pin 9

This is the code which I uploaded to my Arduino (btw my arduino uno is an SMD clone): (code's from http://www.instructables.com/id/Modify-The-HC-05-Bluetooth-Module-Defaults-Using-A/step2/The-Arduino-Code-for-HC-05-Command-Mode/)
#include <SoftwareSerial.h>

SoftwareSerial BTSerial(10, 11); // RX | TX

void setup() {
  pinMode(9, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
  digitalWrite(9, HIGH);
  Serial.begin(9600);
  Serial.println("Enter AT commands:");
  BTSerial.begin(38400);  // HC-05 default speed in AT command more

 }

void loop() {
  // Keep reading from HC-05 and send to Arduino Serial Monitor
  if (BTSerial.available())
    Serial.write(BTSerial.read());

  // Keep reading from Arduino Serial Monitor and send to HC-05
  if (Serial.available())
    BTSerial.write(Serial.read());

}

The problem is I can't seem to activate the AT mode. I don't get any response from the Serial Monitor whatever AT command I try. I double-checked the wiring and it's all good. I can't figure out what the problem is.

Yes it works fine. My HC05 is not experiencing any problems. Besides, the Rx pin is a serial pin and it is usually wired directly to the Tx pin of the arduino (which produces pulses of 5V) to make serial communications between the board and the hc05, so I don't think you should reduce it to 3.3V. The rx pin might not be able to read the serial data if the pulse level is reduced.

After 3 hours I magically solved my pretty simple problem myself. If you wired the HC-05 and arduino correctly, the module should indicate that it's in AT Mode by blinking the LED in an interval of 2 seconds. You should get response in the Serial Monitor by typing the AT commands by switching from "No line ending" to "Both NL and CR". That's about it.

In setup() put pin 9 to low, and delay it for about 1 second and then put it to high.

Can you explain how this solves the problem? As written it sounds like a "magic solution" with no explanation about why it works.


text:
Arduino and RF24 library: communication stops after short amount of time
I am using two Arduino Unos, NRF24L01+ transceivers, and a few components as per this site on which I am following the second tutorial on this page: Arduino Wireless Communication – NRF24L01 Tutorial.
I am using the exact code from the page as well - and have set everything up as per the diagrams, however everything stops working after a short amount of time. Usually between 15 and 30 seconds, everything stays powered but it seems like the transceivers stop communicating. A reset of the Transmitting board (the one with the potentiometer) will fix the problem until it again stops 15 or 30 seconds later.
Any idea what might be going on?

I can say that a lot of the problems with these modules can be avoided with hefty decoupling of power going in to the modules. So could you please solder a 5000uF-10000uF electrolytic and a smaller ceramic capacitor directly to the GND and VCC of the module. It would also help to know which nRFs you have, exact pictures if possible please.

There are few possible reasons:
First: If you soldered a capacitor it's capacity may bee too big , then if brownout appear radio module will not recover from it because of your big sized capacitor.
Second: it could be wrong config. use RF24_PA_LOW, RF24_PA_HIGH and RF24_PA_MAX but not MIN because it is not correctly supported by all RF24 modules.
Third: it could be brownout which is causing arduino board to fail (not the radio module). Then use alternative power source for radio module. But don't forget to leave ground cable of radio module connected to arduino (for data).

Your question does not provide much information to go on.  Setting up as given in the tutorial is a good start, but does not guarantee that there will be no problems.  It can still either be a problem due to hardware or firmware.
Firmware problems:

The radio data may be getting corrupted after some time, which shows up as a failed radio transaction
You inadvertently change the register settings of the radio

Hardware problems:

There is noise interference on the radio channel you are using due to the urban environment (wifi, etc).  Does the system work any better on a different channel?
The radio drains too much power and browns out, then will revert to default settings on the IC rather than the ones set by your Arduino sketch.

I had the same problem and so far I have not been able to find the reason why this happens.
Anyways my temporary solution was to make arduino go to sleep and wake up. The moment the board goes to sleep and reboots everything works great again.
Execute this code every now and then
#include <avr/wdt.h>

....

// enable the watchdog timer. This will wake up the board after 120ms
wdt_enable(WDTO_120MS);

// go to deep sleep
if (true)
{
  SMCR |= (1 << 2); // power down mode
  SMCR |= 1;        // enable sleep;
  __asm__ __volatile__("sleep");
}

I know this is not a solution but it is better than nothing like in my case.
Edit (Solution that worked for me)
For some reason if I remove the millis() function the code keeps working.
    unsigned int end = millis() + 2500;
    for(int i=0; i<2000; i++) // New code
    // while (millis() < end)  // Old code stops working after 2 minutes ....
    {

I perform a task for 2.5 seconds that is why I was using the millis function...

I had a similar issue. I got my NRF24L01+ working for an entire day, but then it suddenly broke and I could not fix it. From my online research, there seem to be a lot of reliability issues with NRF24L01+. Eventually, I implemented my plan Z: switch NRF24L01+ for a HC-05 bluetooth module (which is really easy!!), check out:
https://www.instructables.com/How-to-Connect-HC-05-to-Windows-1011-Mac-Apple-Com/
If you continue to trouble, I suggest just use HC-05, which would save you a lot headache and time.
However, the UART on HC-05 transmits data a lot slower than the SPI on NRF24L01, but I did not need the speed, so the switch was a great decision for me.


text:
SerialPort Node.js stuck in 'Error'
I am trying to get my Arduino to send data to my computer using Node.js Serial port. Everything compiles, my Arduino is working well and sending data in the serial monitor, but the program always goes into myPort.on('close'), and I can't figure out why.
//import serial port js package
const SerialPort = require('serialport');

//opening a port
var myPort = new SerialPort("/dev/ttyS2", {
  baudRate: 9600,
  //parser: SerialPort.parsers.raw
});

//how to pass the readline
const Readline = SerialPort.parsers.Readline;
const parser = new Readline();
myPort.pipe(parser);

myPort.on("open", onPortOpen);
myPort.on("data" , onData);
myPort.on("close" , onClose);
myPort.on("error" , onError);

function onPortOpen(){
    console.log("Port open");
}

function onData(data){
    console.log("data transfer completed..");
    console.log(data);
}
function onError(){
    console.log("Error. something went wrong..")
}
function onClose(){
    console.log("Port is closed. Communication terminated");
}

Would anyone know what are the potential reasons? I double checked my port and it really is COM3, therefore, /dev/ttyS2 for Windows 10.

I see two issues in your code. I cannot say for sure they are related to
the problem you experience, but anyway:

The Readline parser's line terminator defaults to "\n", whereas
Arduino's Serial.println() uses "\r\n". In order to get the line
terminators match, you should invoke the Readline constructor with
{ delimiter: "\r\n" } as an argument.
Piping the flow through the parser returns a new stream. You should
watch for data events on that stream rather the original port.

Thus I suggest you try:
const parser = new Readline({ delimiter: "\r\n" });
const parsedStream = myPort.pipe(parser);

myPort.on("open", onPortOpen);
parsedStream.on("data" , onData);
...

Thanks for the help! Still same issue but appreciated nonetheless.

When I run the file, if the data is not transfered at this very moment, then node receives nothing. Could this be the issue? I would need a continuous loop listening?

@J.C: It works for me with serialport 5.0.0 / nodejs 4.2.6 / Ubuntu 16.04, a Serial.println() on te Arduino side, and /dev/ttyACM0 as the port name.

And just making sure: running it in your console with simple:    node yourFile.js  ?

@J.C: Actually nodejs the_file.js, as the executable is called “nodejs”.


text:
Power RFID module using GPIO
I am building an ESP8266 device that uses RFID but need to conserve battery power.
The ESP is a Wemos D1 Mini and the RFID module is a RC522 (still waiting for it to arrive), which needs 3.3 V. I'm powering the ESP with a battery shield and 3.3 V.
But I don't want to connect the RFID module directly to the battery shield because it will be sucking voltage constantly. Instead, I want to be able to control its power using the ESP.
So I thought the easiest would be simply to connect the RC522's 3v3 line to one of the ESP's available GPIO pins, set it to output, and when I need  RFID, set the GPIO pin high, to turn on the RFID module.
Is this an acceptable solution, or do I need to wire in a transistor and capacitor somewhere?

the RC522 has a power-down pin that you can use to shut down the module .... it also has a software controlled power-down

you used an incorrect term .... it will be sucking voltage constantly  .... not voltage .... current or power

No, this is not an acceptable solution.  The RC522 needs in excess of 100mA to operate, and an ESP8266's GPIO pin can only supply 12mA maximum.  You will damage the ESP8266.
You need to use a P-channel MOSFET with the gate pulled HIGH as a high side switch.

simulate this circuit – Schematic created using CircuitLab
Set the GPIO to LOW to turn on the MOSFET. Set it HIGH or to INPUT to turn off the MOSFET.

Note 1: Set the communication IO pins to INPUT before powering off otherwise they could back-power the target device through the ESD diodes in the IO pins.

Thanks. I don't have a mosfet lying around. Can't I achieve the same with a transistor (seeing I can make the GPIO pin HIGH to turn it on, and LOW to turn it off again?
eg: http://groovy.globi.ca/img/20180718-7714e8d6873173aa18bb3a91390ed0e6.png

@AndreasHuttenrauch Only if the RC522 is OK running at (say) 2.6V. The PNP will impose a voltage drop that the MOSFET would minimise.

And yes, it must be a PNP not an NPN transistor. You can't use an NPN as a high side switch like that.

So I just need to move the NPN to the low side? (sorry - code veteran but arduino n00b :-) - eg: http://groovy.globi.ca/img/20180718-83709a0ae4eee0a5fee0e8caefeee93f.png

No, that would be almost as bad - the ground would then be offset and communication may fail. It really wants to be a MOSFET.

It may be simpler to just buy a module that does it for you. Here's one: https://www.robotshop.com/uk/gravity-mosfet-power-controller.html - maybe overkill :)


text:
How to set cables to connect CP2102 to Pro Mini?
How to connect the cables in order to program the pro mini with the CP2102 usb interface ?
The TX RX and GND is easy, but I am not sure about the RST, DTR, DST, etc

When I try cables like this:
TX  ... RX
RX  ... TX
5V  ... VCC // my pro mini is 5V version
GND ... GND
RST ... RST

The board lits up and green starts blinking, this should be the default blinker program.
I click Upload, I get this error, and I assume the cables are not properly connected:
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x89
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x89

I know some people mentioned it works by adding some resistor and capacitor, but I was hoping that is an error and it should work without that complication.

I think the connections are alright, to upload the code you dont need to connect  other than tx rx rst and power pins. Looking at your issue, I think it may be the on the software side. Please check if you have right drivers installed.
avrdude: stk500_recv(): programmer is not responding

Also, the issue can be resolved by changing the processor in Arduino software by going to tools->processor and then changing it to the one with the old bootloader.
Attaching a screenshot for reference:

Here's what works for me:
Pro Mini  ---------   CP2102

  DTR     ---------    DTR
  RST     ---------    RST   (optional if you wish to press some buttons)

  GND     ---------    GND
  RX      ---------    TX
  TX      ---------    RX
  VCC     ---------    VCC

Tap on the image to see the HD image

Pretty sure RST is Reset input to the CP2102, that will not work.
DTR to DTR (BLK on the Promini) will work, the DTR Low level goes thru the Promini's 0.1uF cap and 10K Reset pullup resistor to make a Reset pulse. That's how the FTDI Basic works when connected.
RTS (Request To Send output) might also work, that is supposedly a pulsed level.

same errors, I tried the DTR and RTS pins from USB to pins from pro mini (RST, BLK) in all combinations.

You meant to add a 10K resistor ?

The Promini's I've used http://store.yahoo.com/yhst-27389313707334/arpromi5v.html have the 0.1uF cap and 10K pullup resistor on board. All that was needed for programming was to connect an FTDI Basic directly to it, pin to pin.   http://www.tinyosshop.com/download/Pro-Mini.sch.pdf

Are you positive your Promini has a bootloader installed?

I have no ideea, it seems to have blinker program installed, does it mean the bootloader is already there ?

OK, I heard enough times about the 0.1uF cap and 10K pullup resistor [https://forum.arduino.cc/index.php?topic=231863.0], I am going to the store now :)

RST to RST. Ignore the others, they are irrelevant.

Doesn't seem to work, I updated my questions with error details.


text:
How to determine the source of constants in libraries?
Preamble:
I am trying to figure out how to program and use the timers in the Feather M0 using the Arduino IDE. I have seen a number of examples published, but I'm not one to just blindly copy some code and expect it to work. The issue that I'm having (and it seems to be ubiquitous in Arduino) is that there does not seem to be a concept of dependencies. In order to reference constants, they have to be defined somewhere.
Question:
How can I find the source of the definition of the constants that people keep referring to in their code? For example, in this code a Arduino Zero, M0 timer example, reference is made to TC_CTRLA_PRESCALER_DIV1 among other constants. Where is this constant defined?
Efforts:
I've searched generally and specifically for these constants. But, as you would imagine in C, it's difficult to find the actual source versus a simple reference to the constant.
I've also tried a search in the installed Arduino IDE with SAMD and Adafruit SAMD libraries installed. For example
~/Arduino$ grep -r --include=*.h --include=*.cpp "TC.*_PRESCALER_DIV"

Did not yield anything. I apologize if this is a naive question, but I haven't been able to find a simple, obvious answer. Actually, I haven't been able to find any answer.

in Eclipse I use 'go to definition' with F3 key

The name TC_CTRLA_PRESCALER_DIV1 indicates this is a macro. A trick for quickly finding the exact location of a macro definition is:

File > Preferences > Compiler Warnings > All > OK
In your sketch, add a #define directive for the macro name that definitely changes the definition:

#define TC_CTRLA_PRESCALER_DIV1 foobar

Sketch > Verify/Compile
After the compilation finishes, examine the compiler output in the black console window at the bottom of the Arduino IDE window (you will need to scroll up to see it all) for a "redefined" warning. The warning will state the path of the original definition:

    C:\Users\per\AppData\Local\Temp\arduino_modified_sketch_804921\sketch_aug05a.ino:1:0: warning: "TC_CTRLA_PRESCALER_DIV1" redefined [enabled by default]

   #define TC_CTRLA_PRESCALER_DIV1 foobar

   ^

  In file included from C:\Users\per\AppData\Local\Arduino15\packages\arduino\tools\CMSIS-Atmel\1.1.0/CMSIS/Device/ATMEL/samd21/include/samd21g18a.h:268:0,

                   from C:\Users\per\AppData\Local\Arduino15\packages\arduino\tools\CMSIS-Atmel\1.1.0/CMSIS/Device/ATMEL/samd21/include/samd21.h:69,

                   from C:\Users\per\AppData\Local\Arduino15\packages\arduino\tools\CMSIS-Atmel\1.1.0/CMSIS/Device/ATMEL/samd.h:105,

                   from C:\Users\per\AppData\Local\Arduino15\packages\arduino\tools\CMSIS-Atmel\1.1.0/CMSIS/Device/ATMEL/sam.h:470,

                   from C:\Users\per\AppData\Local\Arduino15\packages\arduino\hardware\samd\1.6.19\cores\arduino/Arduino.h:48,

                   from C:\Users\per\AppData\Local\Temp\arduino_build_309126\sketch\sketch_aug05a.ino.cpp:1:

  C:\Users\per\AppData\Local\Arduino15\packages\arduino\tools\CMSIS-Atmel\1.1.0/CMSIS/Device/ATMEL/samd21/include/component/tc.h:113:0: note: this is the location of the previous definition

   #define TC_CTRLA_PRESCALER_DIV1     (TC_CTRLA_PRESCALER_DIV1_Val   << TC_CTRLA_PRESCALER_Pos)

   ^

in Eclipse F3 shortcut key opens the definition source code on the value. end if it is a redefinition of some lower level macro, I drill down with next F3. And the value of a macro is displayed in tooltip bubble too. And same for functions.

First of all, the definitions of these constants won't tell you very much. They just represent the registers and bits used in the datasheet of the microcontroller.
If you do want to find their definitions, try looking in ~/.arduino15/.


text:
Formula creation
I was creating a scoring formula for a game.
The formula in question is
millis() * 1.1 ^ (millis()/10000);

However, I'm having trouble understanding the different error messages that the Arduino IDE is projecting to me

invalid operands of type to binary operator

I have declared the score as an unsigned long.

^ is the binary exclusive-or operation. You are probably trying to raise it to the power of. Use pow(base, exponent) instead.

Creating two declarations, score = millis() * 1.1 and divisor = millis()/10000 and then creating a new unsigned long machinescore = pow(score, divisor) outputs consistent 1's. does it have anything to do with it being integer math? as such it wont display anything until something is greater than another?

add a .0 for the divisor: 'millis()/10000.0'. Hopefully you've also declared both score and divisor as floating point numbers. Also the result will be a floating point number. This is basic C programming language stuff. You can try it on your local machine instead of uploading it to the board every time you try to figure out something.

Thank you so much, ive been working on other projects hence the arduino IDE. cant wrap my head around basic principals at the moment.

I would avoid calling millis() twice within the same expression. Not
really a big deal in your case, but the two calls can very well return
different values, which would make your formula slightly inconsistent.
Then, using the proper syntax for the power function, as explained by
Kwasmich:
uint32_t t = millis();
float score = t * pow(1.1, t/1e4);

Note that 1e4 is the scientific notation for 10000.0. I personally
find the former more readable, as you don't have to count the zeros.
Now, it is worth noting that the pow() function is very expensive to
compute on this kind of 8-bit FPU-less processor. It involves both a
logarithm and an exponential. The second line is essentially equivalent
to
float score = t * exp(t/1e4 * log(1.1));

The floating point division is also quite expensive. You could save
something like half the processing cycles by pre-computing
log(1.1)/1e4 and using the result in your expression:
float score = t * exp(t * 9.53e-6);

Thanks for that, i added it in and it works as the graph shows.
I do have another question if you could help. I'm preparing the score to send via UART so i need to convert the score in 4 8bit packets, my way of thinking is using modulus 256 and storing the frames in a respective variable to send, but i can only think of how to do it once, leaving me with 24 more bits to shift and send.
cheers for any help.

@ReidPilkington: To send numeric data through the serial port, use Serial.println(score). This will format the number in ASCII. If that can't work for you, open another question, explain why ASCII won't do it, and provide a complete specification of the binary format you want (IEEE 754 v.s. integer, endianness...).


text:
Difference in pinout (types?) Uno/Mega
As a hands-on guy, I've started my first ever Arduino project 5 hours ago with no prior knowledge about Arduinos (I have coding experience tho. included this in case I am missing something obvious to the veterans around here). So far I have been able to hook-up 3 SSD1306 SPI OLED displays to my Uno, and created a script that allows me to control each display separately. Because my goal is to have 5 displays work off one Arduino, I figured to pin everything over to my Mega since it has more outputs (not sure yet about the differences between DIGITAL PWM on the Uno, and the 53 additional DIGITAL pins on the Mega).
First problem I encountered is that I couldn't find where the clock pulse was specified in the demo script. It's pinned on the Uno on pin 13, but this is not specified somewhere in that script, and I think once I understand the differences in pins from both boards, I might be able to help myself a few more steps into the future.
So to sum up my questions.

How or where is the ClockPulse being specified.
Can I use the 53 DIGITAL pins on the Mega, instead of the 13 DIGITAL PMW that I have on my Uno, and if yes, do I need to change some settings?

Here is my current script that works on my Uno, but not on my Mega, even if I use the same DIGITAL PMW pins on my Mega.
#include "HCuOLED.h"
#include "SPI.h"

//#define CS_DI 10
//#define DC_DI 9
//#define RST_DI 8

//HCuOLED HCuOLED_1(SSD1307, CS_DI, DC_DI, RST_DI); // For SSD1307 displays (HCMODU0050 & HCMODU0052)
HCuOLED HCuOLED_1(SSD1307, 10, 9, 8); // For SSD1307 displays (HCMODU0050 & HCMODU0052)
HCuOLED HCuOLED_2(SSD1307, 7, 6, 5); // For SSD1307 displays (HCMODU0050 & HCMODU0052)
HCuOLED HCuOLED_3(SSD1307, 4, 3, 2); // For SSD1307 displays (HCMODU0050 & HCMODU0052)

void setup()
{
  HCuOLED_1.Reset();
  HCuOLED_2.Reset();
  HCuOLED_3.Reset();
}

void loop()
{
  //display 1
  HCuOLED_1.SetFont(Terminal_8pt);
  HCuOLED_1.Cursor(44,0);
  HCuOLED_1.Print("Cpt");
  HCuOLED_1.Cursor(20,10);
  HCuOLED_1.Print("Fastlane");

  HCuOLED_1.Cursor(14,24);
  HCuOLED_1.SetFont(LCDLarge_24pt);
  HCuOLED_1.Print("KM/H");
  HCuOLED_1.Refresh();

  HCuOLED_1.ClearBuffer();

  //display 2
  HCuOLED_2.SetFont(Terminal_8pt);
  HCuOLED_2.Cursor(44,0);
  HCuOLED_2.Print("Cpt");
  HCuOLED_2.Cursor(20,10);
  HCuOLED_2.Print("Fastlane");

  HCuOLED_2.Cursor(14,24);
  HCuOLED_2.SetFont(LCDLarge_24pt);
  HCuOLED_2.Print("RPM");
  HCuOLED_2.Refresh();

  HCuOLED_2.ClearBuffer();

  //display 3
  HCuOLED_3.SetFont(Terminal_8pt);
  HCuOLED_3.Cursor(44,0);
  HCuOLED_3.Print("Cpt");
  HCuOLED_3.Cursor(20,10);
  HCuOLED_3.Print("Fastlane");

  HCuOLED_3.Cursor(14,24);
  HCuOLED_3.SetFont(LCDLarge_24pt);
  HCuOLED_3.Print("Info");
  HCuOLED_3.Refresh();

  HCuOLED_3.ClearBuffer();
}

And here is the original script:
#include "HCuOLED.h"
#include "SPI.h"

/* Example bitmap */
const PROGMEM byte Tiny_Logo_Resistor[] =
{
  0xC0, 0xE0, 0x30, 0x30, 0xF0, 0xE0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x80, 0xE0, 0x38, 0x0E, 0x07, 0x1E, 0x78, 0xE0, 0x80, 0x00, 0x00, 0x00, 0x00, 0xC0, 0x70, 0x1C, 0x07, 0x0F, 0x3C, 0xF0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x80, 0xF0, 0x3C, 0x0F, 0x07, 0x1C, 0x70, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x80, 0xE0, 0x78, 0x1E, 0x07, 0x0E, 0x38, 0xE0, 0x80, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xE0, 0xF0, 0x30, 0x30, 0xE0, 0xC0,
  0x00, 0x01, 0x03, 0x03, 0x03, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x0F, 0x3C, 0x38, 0x0E, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x07, 0x1E, 0x38, 0x1C, 0x07, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x0E, 0x38, 0x38, 0x0E, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x07, 0x1C, 0x38, 0x1E, 0x07, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x0E, 0x38, 0x3C, 0x0F, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x03, 0x03, 0x03, 0x01, 0x00,
};

/* Digital pin number for the displays chip select pin */
#define CS_DI 10
/* Digital pin number for the displays data/command pin */
#define DC_DI 9
/* Digital pin number for the displays reset pin */
#define RST_DI 8

/* Array indexes for the X and Y coordinates */
#define X1 0
#define Y1 1
#define X2 2
#define Y2 3

/* Arrays to store coordinates and direction for the line, rectangle and bitmap */
byte Box[4] = {1,1,20,20};
byte BoxDir[4] = {1,1,1,1};
byte Line[4] = {100,25,120,55};
byte LineDir[4] = {-1,-1,-1,-1};
byte Bitmap[2] = {40,40};
byte BitmapDir[2] = {-1,-1};

/* Create an instance of the library (uncomment one of the lines below) */
//HCuOLED HCuOLED(SSD1307, SS_DI, DC_DI, RST_DI); // For SSD1307 displays (HCMODU0050 & HCMODU0052)
HCuOLED HCuOLED(SH1106, CS_DI, DC_DI, RST_DI); // For SH1106 displays (HCMODU0058 & HCMODU0059)

void setup()
{

  /* Reset the display */
  HCuOLED.Reset();
}

void loop()
{
  /* Display some text using a small 8x8 fixed width font */
  HCuOLED.SetFont(Terminal_8pt);
  HCuOLED.Cursor(44,0);
  HCuOLED.Print("HOBBY");
  HCuOLED.Cursor(20,10);
  HCuOLED.Print("COMPONENTS");

  /* Display a number using a large 4 line LCD style font */
  HCuOLED.Cursor(20,24);
  HCuOLED.SetFont(LCDLarge_24pt);
  HCuOLED.Print("HCuOLED");

  /* Change the draw mode from NORMAL to INVERT */
  HCuOLED.DrawMode(INVERT);
  while(1)
  {
    /* Move the positions of the 3 objects */
    MoveRect();
    MoveLine();
    MoveBitmap();

    /* Draw the objects to the display buffer */
    HCuOLED.Rect(Box[X1],Box[Y1],Box[X2],Box[Y2], SOLID);
    HCuOLED.Line(Line[X1],Line[Y1],Line[X2],Line[Y2]);

    HCuOLED.Cursor(Bitmap[X1],Bitmap[Y1]);
    HCuOLED.Bitmap(84, 2, Tiny_Logo_Resistor);

    /* Write the display buffer to the screen */
    HCuOLED.Refresh();

    /* Draw the objects again. As we are in INVERT mode this will remove them */
    HCuOLED.Rect(Box[X1],Box[Y1],Box[X2],Box[Y2], SOLID);
    HCuOLED.Line(Line[X1],Line[Y1],Line[X2],Line[Y2]);

    HCuOLED.Cursor(Bitmap[X1],Bitmap[Y1]);
    HCuOLED.Bitmap(84, 2, Tiny_Logo_Resistor);
  }
}

/* Update the X and Y coordinates for the box */
void MoveRect(void)
{
  if(Box[X1] == 0 || Box[X1] == 127)
    BoxDir[X1] *= -1;
  Box[X1] += BoxDir[X1];

  if(Box[Y1] == 0 || Box[Y1] == 63)
    BoxDir[Y1] *= -1;
  Box[Y1] += BoxDir[Y1];

  if(Box[X2] == 0 || Box[X2] == 127)
    BoxDir[X2] *= -1;
  Box[X2] += BoxDir[X2];

  if(Box[Y2] == 0 || Box[Y2] == 63)
    BoxDir[Y2] *= -1;
  Box[Y2] += BoxDir[Y2];
}

/* Update the X and Y coordinates for the Line */
void MoveLine(void)
{
  if(Line[X1] == 0 || Line[X1] == 127)
    LineDir[X1] *= -1;
  Line[X1] += LineDir[X1];

  if(Line[Y1] == 0 || Line[Y1] == 63)
    LineDir[Y1] *= -1;
  Line[Y1] += LineDir[Y1];

  if(Line[X2] == 0 || Line[X2] == 127)
    LineDir[X2] *= -1;
  Line[X2] += LineDir[X2];

  if(Line[Y2] == 0 || Line[Y2] == 63)
    LineDir[Y2] *= -1;
  Line[Y2] += LineDir[Y2];
}

/* Update the X and Y coordinates for the bitmap */
void MoveBitmap(void)
{
  if(Bitmap[X1] == 0 || Bitmap[X1] == 43)
    BitmapDir[X1] *= -1;
  Bitmap[X1] += BitmapDir[X1];

  if(Bitmap[Y1] == 0 || Bitmap[Y1] == 47)
    BitmapDir[Y1] *= -1;
  Bitmap[Y1] += BitmapDir[Y1];
}

You are communicating with your OLED displays using SPI - Serial Peripheral Interface.  This is a special hardware peripheral built in to the MCU, and the outputs of it are physically connected inside the MCU to what become pins 11-13 on the Arduino UNO.
This, and other things like the UART, PWM and the analog inputs, are known as alternate functions of the pins.
On small MCUs like the Arduino uses these functions are fixed in hardware (more advanced MCUs employ a system to allow you to map the functions to different pins).
When you use SPI on the UNO it always uses pins 11-13 (MOSI, MISO and SCK in that order).  When you use SPI on the Mega it always uses pins 51, 50 and 52 (in that order for the same functions). You can't change it. Pin 10 on the UNO is the Slave Select pin, and that again is an alternate function which is hard wired. On the mega that function is pin 53.
For SPI to work as a master (which is what you want) then pin 10 on the UNO or pin 53 on the Mega must be set to OUTPUT. It doesn't matter if you actually use it, but it has to be set to OUTPUT as that defines the direction the SPI peripheral operates in.
So for the Mega you would wire your OLED displays to pins 51, 50 and 52 instead of pins 11, 12 and 13. You could use pin 53 as one of your chip select pins (though you don't have to, just as long as you set it to OUTPUT).
Incidentally, you can save pins on your setup by sharing some of them.  The only pin that need to be unique for each OLED is the Chip Select pin. That is the pin that tells the OLED that it is being spoken to. Only when that pin is active will the OLED listen to any of the other pins.
The only other one you may need to connect separately is the reset pins, since you reset the displays in turn - resetting the second would reset the first and undo the configuration. TBH I'd connect the RESET pins of the OLEDs to a single pin, and specify another (unused, or non-existent) pin in the constructors for RESET - then manually reset all the OLEDs together through the one LOW pulse of the RESET pin, and then call the reset functions for each display, which should configure them all.
That way you are then using just (example UNO pins numbers shown):

MOSI  (11)
MISO  (12)
SCK   (13)
DC    (7)
RESET (6)
CS1   (10)
CS2   (9)
CS3   (8)

Amazing stuff! Ill probably have to read it a couple of times before I can fully wrap my head around it. I dont fully understand the RESET part, because the way I see it, it seems that I cannot get arround having to use one pin on the board per display, be it via the regular way, or manually. Could you elaborate? By sharing the DC pins I do free up 3 more pins that allows me to add 2 screens, and have one more pin that will eventually control my rev bar (havent figured that bit out yet, but it will be a bar of LEDs that will take in RPM data).

Also, when i've connected pin 50 and 52 (not using pin 10 on the UNO now), can I assign DC, RESET and CS to any of the other 49 digital pins on the MEGA?
(post became to long)

Yep, DC, CS and RESET can be any pin you like (even Analog pins). When you share pins (like DC) all the displays get sent the DC setting (HIGH or LOW), but only one does anything with it - the display that currently has the CS pin LOW.

Ohh i see now (I think haha). So I can combine all pins except CS, and instead of doing the regular .display () command, I first manually set the output for whatever pin is CS for the display I wanna update to LOW, and then use the .display() function (after updating the data to display that is)?

The library is doing that for you. Just repeat the same numbers in the constructors.

Ahh right. Again, this was already a HUGE help understanding how these boards work. I am a game developer by trade so I'm used to having to do everything myself haha.

I'm getting back at this for a second. Is there a way to calculate wether a UNO or MEGA would have enough cpu/memory power to handle whatever i want? Right now I'm about to use 5 OLED screens, 4 will be text only in white, the fifth will be a coloured one for bitmaps warning lights. Beside those I am going to add a rev bar with approx 30 RGB LEDs.

@sdieters That's pretty impossible to know. It's not so much what you connect, as what you do with them. And that very much depends on how the libraries you use work, etc. The Mega2560 has more memory (both flash and RAM) than the Uno, but still a tiny amount compared to more modern MCUs. Be sure to read up on using PROGMEM to save RAM - that will be your most critical area.

Will do! What do you mean with the more modern MCUs? I always thought the mega was the flagship among DIY hobbyist MCUs.

@sdieters There are many far more powerful MCUs around now than the old 8-bitters. Plenty of 32-bit ones using ARM or MIPS cores. Much faster, much more memory, much more flash, more powerful peripheral interfaces, etc.

Oehh, ill have to look into that once I start designing some more powerful digital dashboard. Hopefully they are as easy to work with as the Arduino

Well, generally they use the same API - often adding more functions as well. Sometimes even the same footprint.  I work almost exclusively with chipKIT. Teensy is very popular.

Alright, it seems I cannot get it to work when sharing the other pins. I currently have shared all pins except the CS pin, and I'm using the following pins: VCC=3.3v, GND=GND, SCK=13, SDA=11, DC=10, RST=9 CS(display1)=8, CS(display2)=7, CS(display3)=6. The odd thing is that I currently only get display 3 to work, the other 2 do nothing. When adding the other 2 displays on pin 5 and 4 without using them in my code, they just flicker (sorta expected that since they get no data, nor are they being reset.) I havent changed any of the script, other then reassigning the Defined Vars and CS pins

Nevermind, got it working now! Forgot to remove the extra RESET commands. I figured by calling those RESET 3 times during the same cycle now they are all connected, only the 3th display would remain working, while the other 2 keeps getting resetted... I only have one HCuOLED_1.Reset() command in the setup instead of 3 for each display.

I am now also able to effortlessly add 2 more displays by just hooking them up to my remaining pins. Thanks again for all your support! Not sure if it is allowed, but if you wanna follow what I am working on, look for my page on FBdotCOMslashCPTfastlane =)

after some time off my project I went back at it to make it work with my MEGA. However, even without setting pin 53 to OUTPUT in the setup function, it still works. Why is this? You can find the details about what I did in here:
https://arduino.stackexchange.com/questions/56301/getting-spi-ssd1307-to-work-on-arduino-mega/56314#56314


text:
Compilation issues on Arduino Due
I wrote an code on Arduino and I getting compilation errors. I am using Arduino Due . I wrote the following code :
void setup() {
  Serial.begin(9600);
  analogWriteResolution(12);  // set the analog output resolution to 12 bit (4096 levels)
  analogReadResolution(12);   // set the analog input resolution to 12 bit

}

void loop() {

  // code
}

But compiler gave me the following errors :
'analogReadResolution’ was not declared in this scope
‘analogWriteResolution’ was not declared in this scope
‘DAC0’ was not declared in this scope

I'm using Arduino 2:1.0.5 (on Linux). The board list doesn't show Arduino Due (USB programmable).And I don't have Board Manager option. How do I install Arduino SAM Board to compile the program ?

Did you try to update the Arduino library/IDE? Afaik the analogRead/WriteResolution functions should be known.

I installed it today itself and it v2:1.0.5. If I have to update the it through terminal how do i go about it ?

In case you installed it, it is not needed to update.

According to the Arduino - ReleaseNotes,

ARDUINO 1.5 BETA - 2012.10.22

First release for the unified IDE for both AVR 8-bit and ARM 32-bit   (SAM3 CPUs) architectures.
This release include the SAM Arduino Core used in the Arduino Due   Board.

So your 1.0.5 version does not allow for Due compilation. Download the most up-to-date version and you will be fine (you will be able to install SAM support).
Then you will be able to at least compile. If you have other problems with your code, please open another question here (in order to keep the one-question-per-post behavior of this website).
Don't install arduino from the debian repository, since that version is not updated regularly. Use the website version

I updated it to the latest version but I still can't find the Arduino Due board. When I select the board manager option it throws an error saying Error downloading http://downloads.arduino.cc/packages/package_index.json

@SamThornton did you try google? Most of the times other users report this is 1) a spyware, 2) a connection issue, 3) a JAVA misconfiguration. I think 1 is not applicable to linux. Try accessing the file from a browser (if you can't it is an internet issue). Or verify if you are behind a proxy. As a last resource, purge the old arduino install, clean the new one and then reinstall, reboot and try again

I finally found the error. It was due to the fact that the Linux was set on Automatic Proxy.

@SamThornton good to know ;) Glad you managed to fix it


text:
Reducing noise and finding sampling rate
I have Arduino Due R3 (84MHz) and I am trying to find the mean of value from AnalogRead. I have to set the sampling rate of 8000 samples/second with 4 channels. I tried using for loop for this purpose.
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

int i = 0;
int sensorPin = A0;
int sensorValue = 0;
int highest=0;
int lowest=0;
float mean=0;

void setup()
{
  Serial.begin(9600);
  analogWriteResolution(12);  // set the analog output resolution to 12 bit (4096 levels)
  analogReadResolution(12);   // set the analog input resolution to 12 bit
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);

  lcd.print("Hello");

}

void loop()
{

  for(;;)
  {
    mean=0;
    for(i=0;i<8000;i++)
    {
       sensorValue = analogRead(sensorPin);
     highest=max(highest,sensorValue);
     lowest=min(lowest,sensorValue);
     mean = mean + (highest-lowest);
    }
    mean = mean/8000;
    delay(10);
    lcd.setCursor(0, 1);
    lcd.print(mean);
  }

Will this set sampling rate to 8000 samples/sec ?
Also I was receiving  a lot of noise at A0 which often led to the lowest value to be 0. In the image : The  red wave is a constant dc voltage of 2.7 V from power supply.

How do I overcome this noise so that mean value is accurate and precise ?

Just to as a complement to Majenko's answer (which I second), there are
a couple of flaws in your program that may be related to your problem:

lowest is always zero, as it is initialized to 0 and cannot increase
your computation of the mean is incorrect: the mean is the sum of the
readings divided by their number
you fail to reset lowest and highest between consecutive runs of
8000 samples
there is no point in putting all of loop() inside an infinite loop.

Assuming you really intend to print summary statistics on runs of
8000 samples, as your code suggests, I would write it like this:
const int SENSOR_PIN = A0;
const int SAMPLE_COUNT = 8000;
const uint32_t SAMPLE_PERIOD = 125;  // 125 us

void loop()
{
    long sum = 0;
    int lowest = INT_MAX, highest = 0;

    uint32_t lastTime = micros();
    for (int i = 0; i < SAMPLE_COUNT; i++) {

        // Wait until it's time.
        while (micros() - lastTime < SAMPLE_PERIOD) ;
        lastTime += SAMPLE_PERIOD;

        // Take and process the sample.
        int sensorValue = analogRead(SENSOR_PIN);
        sum += sensorValue;
        highest = max(highest, sensorValue);
        lowest = min(lowest, sensorValue);
    }
    float mean = (float) sum / SAMPLE_COUNT;
    Serial.print("mean: "); Serial.print(mean);
    Serial.print(", minimum: "); Serial.print(lowest);
    Serial.print(", maximum: "); Serial.println(highest);
    Serial.flush();
}

Edit: I changed the code in order to keep a roughly constant
sampling rate of 8000 samp/s. The main change is that, before
taking a reading, we wait until it's time to do so (until
micros() - lastTime >= SAMPLE_PERIOD).
Note that lastTime could be updated with lastTime = micros(), in
which case it would have hold the time we last took a sample. By
updating it with lastTime += SAMPLE_PERIOD it instead holds the time
we shoud have taken the last sample. This is the right choice for
enforcing a given average sampling rate.
Running on an Uno: I have no experience with the Due, but here are
some remarks that would apply to an Uno, or any other AVR-based Arduino:

analogRead() takes about 110 µs, which means we cannot sample
more than one channel, and we only have about 15 µs to process
the sample. Here the processing is simple enough that the Arduino can
do it in this limited time.
There is some jitter in the sampling, because micros() has a limited
resolution of 4 µs, because of the timer interrupt kicking in
from time to time, and because the while loop takes a finite amount
of time.

If I were to do something similar on an Uno, I would forgo
analogRead(), configure the ADC to be triggered by a timer, and set
the timer to trigger the DC every 125 µs. Not only would this get
rid of the jitter, it would also allow the CPU to do its job in parallel
with the ADC, instead of just sitting idle and waiting until the ADC is
done. This would allow for more complex per-sample processing.
About the Due: As I said, I have no experience with this board. It
has a more capable processor, but this tells you nothing about the speed
of its ADC. I would expect to face the same issues as with the Uno,
though maybe to a lesser degree. I guess it should be possible to
trigger the ADC from a timer, but I have no idea how to do so.

Thanks for the corrections. Actually I wanted to calculate maximum and minimum per cycle and then calculate the mean of their difference for the given number of samples. I have updated my code also. Sorry for Incovenience.Also how do I set the sampling rate to around 8000 samples/sec if I'm using 4 channels with Arduino Due R3 (84 MHz) ?

@SamThornton: About the sampling rate, see the expanded answer.

Thanks !! Just there is 1 doubt ? Why can't I use mutiple channels ? What if use nested loop like for(int i=0;i<4;i++) { for(int j=0;j<8000;j++) //take input and process }

@SamThornton: Yes, you can read one waveform on one channel, then another one on the other channel and so on. What you cannot do, at least with this scheme, is sample the four channels simultaneously at 8 kS/s. Unless your ADC is way faster than the ones on the AVRs.

Oh I see. Thanks ! BTW Is there a way to do it simultaneously ?

Will this set sampling rate to 8000 samples/sec ?

No, that will make it perform a block of 8000 samples as fast as it can. There's absolutely nothing in there that has anything to do with time, so how can "seconds" be included in the description of it?

How do I overcome this noise so that mean value is accurate and precise ?

That depends on where the noise is coming from. Maybe if you slowed down your sampling you wouldn't get the noise. Maybe if you made a better connection to whatever it is you're sampling you'd get less noise. Maybe if you added some external filtering you'd get less noise. Maybe if you used a different mathematical model for determining what your average value is you'd not care about the noise.

Can you tell me the way to calculate the mean such that I don't have to care about the noise ?


text:
Arduino Mega, PWM analogWite doesn't work with Timer interrupt
Can anybody explain me, why the PWM doesn't work in such a simple example?
Generally, Timer interrupt is being called once per 100 ms and then in the interrupt function the bool flag (state ) is being set. Then in the main loop the flag is checked and when it is 1 (true) several instructions are being executed. Next, PWM is generated and measured via ADC and also displayed on the LCD.
The problem is that the PWM is generated as 0 or sligthly over the 0, even when the value put to the  analogWrite is 255 (max of 8 bit). Variable counter is incremented without problems and this value is being put to the analogWrite and despite it the PWM doesn't work.
I don't know, totally, what can be wrong.
Can anybody help me?
 #include<LiquidCrystal.h>
 #include<TimerOne.h>

  LiquidCrystal lcd(52, 50, 48, 46, 44, 42, 40);

  int out = 12;
  int in = A7;
  volatile bool state;

  int counter = 0;
  volatile int y;

  void setup()
  {
    lcd.begin(16, 2);
    lcd.clear();
    pinMode(out, OUTPUT);
    pinMode(in, INPUT);

    analogReference(DEFAULT);
    Timer1.initialize(100000);
    Timer1.attachInterrupt(functionInterrupt);

     state = 0;
      y = 0;
   }

   void loop()
   {
     y = analogRead(in);
     y = y / 4;
     y = y - 128;

    if (state == 1)
    {
      state = 0;

      counter++;
      if (counter > 255)
      //counter = 0;
      counter = 200;

      //state = 0;
     }

      analogWrite(out,counter);

      lcd.home();
      lcd.setCursor(0, 1);
      lcd.print(counter);
      lcd.setCursor(12,1);
      lcd.print(y);
     }

    void functionInterrupt()
    {
      state = 1;

     }

When you use a timer to generate an Interrupt Service Routine (as you do with the TimerOne library) you change the configuration of that timer (in your case timer1). The timer is used by the TimerOne library to provide an interrupt, but also by the microcontroller itself to produce a PWM signal on some pins depending on the timer: in your case (Arduino Mega, timer 1) on the 11 and 12. If you use one of these pins as "analog" output while controlling an ISR with the same timer you won't get the expected output, because the timer isn't any more configured as needed by the PWM generation mechanism but as needed by you (you changed the configuration of the timer in the Timer1.initialize(100000); function call).

So, either you use another PWM pin as output either you use a timer library which uses another timer (or you implement it by yourself).

I just edited my own answer because as I wrote it I didn't notice you (the OP) were using an Arduino Mega board (you only wrote it in the title, and I didn't pay much attention to it... sorry)

noearchimede, I'm really thank you. You're right. I didn't consider it and have wasted much time trying to solve it. Thanks.

if (state = 1)

This is setting state to 1, not testing if it is equal to 1. In other words, it will always be true.

Nick Gammom, you're right but this is not that. It was just my typo mistake when I was translating variable's names from my native language to english. In my real code I had "if(state == 1)". But anyway, thank you for your respond.

Can you correct your question then? As it is, it is misleading. It is also misleading to post code which is not the problem code in the first place.