text:
Library to set internal analog gain of the Arduino?
My original question was if there is a library that covers the internal comparator and differential and gain modes for the Arduino Uno, Mega 2560, Leonardo, Due, Zero, M0.
The answer is obvious: "No". To my surprise there is not even a start to make it and neither a collaboration to gather usefull code.
If you know pieces of code (Arduino compatible and documentation for which pins) for the analog comparator and gain, then please tell me about it, and I put them in this list.

analogComp, a library to manage the analog comparator.
To use the analog comparator for the ATmega8, Arduino Uno, Leonardo, Mega 2560, ATtiny85, and others. A routine is called with an interrupt every time a particolar condition happens.
Arduino Differential ADC and Gain ADC
A file "wiring_differential.c" should be added to the Arduino files. Functions "analogReadDiff" and "analogReadGain" will be added. For the Arduino Leonardo and the Arduino Mega 2560.
Nick Gammon: Using the Arduino Analog Comparator
A simple example of a comparator mode for the ATmega328.
Application Note AT11480: Analog Comparator Application Examples
Using the Analog Comparator for SAM D (that includes the ATSAMD21 of the Arduino Zero and M0) processors.

Please pick a board, as the all have wildly differing processors. Or tell us what you want to achieve if you are actually asking which board to buy.

@Gerben, But I don't want to pick a board. I don't want to have a single solution for one specific project, I would like to know that there is something that I might use when needed. Next time I have a project with Arduino with one of the more common AVR or SAM boards then I would like to use a library to use the comparator or gain features. If I try really hard, then I could get some of the ATmega32U4 extra analog features working, but then I would have to do it all over again when using a Zero. For example the EnableInterrupt library is there and ready to be used when needed.

For one, the UNOs processor doesn't have the option to set a gain. So that board is already incompatible. The different processors have different gain values that you can select. I'm not sure about any other incompatibilities, as I've never used the comparator. It's very hard to create a library that bridges these incompatibilities, without loosing functionality (lowest common denominator).

My intention is to find a way to use every possible extra analog feature. Not to find the common denominator and end up with nothing.

Then you need to use the datasheets. You can have library to use simple abstractions, or you can have every possible features, but they are different for every processor and hypotetical library covering that all would be much more complicated, than those datasheets, as it would need to doo everything in each datasheet and also translation to some API and solve all cases, when user tries feature A from uP AA on uP BB, which does not have mentioned feature. And solving all those cases would cost a lot of cycles, so it would not be able use the uP to full extend anyway (for being too slow)

@gilhad That's what I'm afraid of. It would be a nice feature to use in many situations, but I can't even find a proper guide about the possibilities for the different Arduino boards. I posted my question because searching for "arduino gain" does not help. As far as I know there is not even a website where the information is gathered and something is being made. Even https://www.pjrc.com/teensy/adc.html has not filled in the "Differential Inputs & Amplifier" section.

Arduino way is common denominator and easy to use. Your needs are get as much as possible at any cost, which is opposite to Arduino way. You should look for Atmel datasheets for their processors, is you want to squeeze max from them. Not for libraries targeted at Arduino, which tries make easy and "same for all" access to "some basic electronics" and accidentally used (only) some of Atmels processors and then other people expanded it to few other cheap processors too (at least the basics). If you want racing bike, it is not good start from childgarten one with ballance wheels and built on that

@gilhead, I mentioned the "EnableInterrupt" library. That is something that just works. It took a few years, but it is very useful. Since the ATmega2560 and ATmega32U4 have similarities and also the M0+ (Zero) and M3 (Due), there are two main paths, and a number of differences for each chip. I would be nice if someone at least made a start, but beside those two pieces mentioned in my question, I can't find anything.

@gilhad, I have lowered my goal in my question drastically. Now I'm just looking for pieces of code that use the comparator and gain.

I would recommend you to check Nick Gammon's example on using the analog comparator by means of configuring the relevant flag bits of registers in the ATmega328. Sample code from the link, by Nick:
volatile boolean triggered;

ISR (ANALOG_COMP_vect)
  {
  triggered = true;
  }

void setup ()
  {
  Serial.begin (115200);
  Serial.println ("Started.");
  ADCSRB = 0;           // (Disable) ACME: Analog Comparator Multiplexer Enable
  ACSR =  bit (ACI)     // (Clear) Analog Comparator Interrupt Flag
        | bit (ACIE)    // Analog Comparator Interrupt Enable
        | bit (ACIS1);  // ACIS1, ACIS0: Analog Comparator Interrupt Mode Select (trigger on falling edge)
   }  // end of setup

void loop ()
  {
  if (triggered)
    {
    Serial.println ("Triggered!");
    triggered = false;
    }

  }  // end of loop

That was already in the analogComp library. But I didn't know that Nick Gammon wrote a page about it. Therefor you get the +200 bounty. At this moment I'm looking at the Atmel Studio 7 API for the ATSAMD21.

You seem to be interested mainly in ATSAMD21. There is an application note from Atmel, AT11480: Analog Comparator Application Examples, which may be of interest for you.
From the Getting started section (3.1, page 8):

The AC [Analog Comparator] example project has to be opened from New
  Example Project option in Atmel Studio. Using the option Atmel Studio
  → File → New → Example Project will open the New Example Project from
  ASF or Extensions window. The project named Analog Comparator Examples
  – SAM D21 Xplained Pro has to be opened.

There you'll find example code that might be useful for you, as it will show how to configure and manage the registers involved in using the analog comparator of the ATSAMD21. Namely, the example code is related to the following example applications:

Level crossing detector.
Window mode operation.
Preventing false spike detection.
Gray signal frequency measurement.
SleepWalking with analog comparator.

If you look into the first case (level crossing detector) for guidelines for where to start from, you can see that the application example goes through the following steps:

Enable alternate function H (AC/CMP[0]) for pin PA12 so that the comparator 0 output is directly routed to the pin.
Select GCLK Generator 0 as GCLK source for AC module. The GCLK Generator 0 is clocked from internal OSC8M oscillator whose output is set to 8MHz.
Select AIN[0] pin (PA04) as positive input and internal voltage scaler output as negative input for comparator 0. The voltage scaler register is set to a value of 9 corresponding to a voltage output of 0.5156V.
Set comparator 0 in continuous comparison mode with hysteresis and filter mode disabled.
Enable comparator 0 output to be routed to I/O pin and select interrupt mode as toggle so that comparator output toggles when positive input crosses the negative input (both during rising and falling).
Enable comparator 0 and then enable the AC module.

You could get from that example code some ideas about the registers to be configured and managed, and then try to use that knowledge for creating (or even reusing) some code within the Arduino IDE.
Hope it helps...

Thank you. That is the comparator. What about the differential mode with gain (and offset). I would like to keep using the Arduino, therefor I would like to be able to use the Arduino definitions instead of the Atmel Studio API calls.

What you are trying to do can be easily done via simple programming of the channels bits in the ADV module - the datasheet is your best friend here.
So if you want to take this one, take a look at the datasheet and that's all there is to it.
Happy to provide a sample piece to get you going.

A "common" problem is with a simple pressure sensor that has a wheatstone output with a offset. I would need a differential input, preferably with offset compensation and a lot of gain. For example the M0+ (ATSAM21G18) in the Arduino M0 or Zero can probably not do all of that, but should be able to get a reasonable resolution, but I don't know where to start http://www.microchip.com/wwwproducts/en/ATSAMD21G18 and I don't understand this: https://electronics.stackexchange.com/questions/275940/understanding-differential-adcs-and-refrence-voltages

Yes. A differential acc would be the way to go. In ave, the channel selection buts control the inputs as well as gains. So the best place to start would be to look at the datasheet and write your own analog Read() or to customize the stock analog read.

but I don't know where to start. the device datasheet is generally a great place to start. in the case of certain avrs, the adc can be configured to have gain and different inputs by selecting the channel bits. You can also use an external instrumentation amplifier to convert different inputs into single-ended input for your mcu that doesn't have different adc capabilities.

For that approach, you can check out an experiement I did using the differential input on ATtiny85 to build a simple milliohm meter here: https://wordpress.com/post/dannyelectronics.wordpress.com/262

another alternative is to use external adc with differential inputs. I also built a millieohm meter with the super cheap HX711. You may find it helpful as well: https://wordpress.com/post/dannyelectronics.wordpress.com/219

I can not open those links.

here is the first link: https://dannyelectronics.wordpress.com/2015/11/08/a-mcu-based-milliohm-meter-version-2/

the link for the hx711: https://dannyelectronics.wordpress.com/2015/10/25/a-hx711-based-milliohm-meter/

Thanks, but I'm looking or Arduino compatible code, preferably for the official AVR and M0+ and Due boards.

not all AVRs have differential inputs, and when they do, not all of them have PGAs. of the AVRs used in popular Arduinos, ATtinyx5 and ATmega32U4 chips offer such capabilities - the ATmega32U4 is an exceptional chip actually.

Unfortunately, many 32U4-based Arduino boards don't route ADC0/1. Bone headed move.

another chip to consider is the less popular AT90USB128x/teensy.

I don't use Due but the datasheet would be your starting point. A quick scan suggests that gain control is done via CGR. But in a very limited range.

I tried to find further information that would help you about the ATSAMD21, but I only managed to find the source code for the definitions of the Analog Comparator Controller (ACC), the Power Management Controller (PMC), and some example code as well. The example code follows, to avoid this being a link-only answer:
 #include "asf.h"
 #include "stdio_serial.h"
 #include "conf_board.h"
 #include "conf_clock.h"

 #define VOLT_REF   (3300)

 #define MAX_DIGITAL (4095)

 #define DACC_CHANNEL_0 0

 #define DACC_ANALOG_CONTROL (DACC_ACR_IBCTLCH0(0x02) \
                           | DACC_ACR_IBCTLCH1(0x02) \
                           | DACC_ACR_IBCTLDACCORE(0x01))

 #define ADC_CLOCK 6400000

 #define ADC_STARTUP_TIME_SETTING 0x8u

 #define ADC_TRACK_SETTING 0x0u

 #define ADC_TRANSFER_SETTING 0x1u

 #define ACC_SELPLUS_AD5  0x5u
 #define ACC_SELMINUS_DAC0  0x2u
 #define ACC_EDGETYP_ANY  0x2u
 #define ACC_INVERT_NO 0x0u

 #define STRING_EOL    "\r"
 #define STRING_HEADER "-- ACC IRQ Example  --\r\n" \
         "-- "BOARD_NAME" --\r\n" \
         "-- Compiled: "__DATE__" "__TIME__" --"STRING_EOL

 void ACC_Handler(void)
 {
     uint32_t ul_status;

     ul_status = acc_get_interrupt_status(ACC);

     /* Compare Output Interrupt */
     if ((ul_status & ACC_ISR_CE) == ACC_ISR_CE) {

         if (acc_get_comparison_result(ACC)) {
             puts("-ISR- Voltage Comparison Result: AD5 > DAC0\r");
         } else {
             puts("-ISR- Voltage Comparison Result: AD5 < DAC0\r");
         }
     }
 }

 static void configure_console(void)
 {
     const usart_serial_options_t uart_serial_options = {
         .baudrate = CONF_UART_BAUDRATE,
         .paritytype = CONF_UART_PARITY
     };

     /* Configure console UART. */
     sysclk_enable_peripheral_clock(CONSOLE_UART_ID);
     stdio_serial_init(CONF_UART, &uart_serial_options);
 }

 static void dsplay_menu(void)
 {
     puts("-- Menu Choices for this example--\n\r"
             "  s: Set new DAC0 output voltage.\n\r"
             "  v: Get voltage on potentiometer.\n\r"
             "  m: Display this menu again.\r");
 }

 static int16_t get_input_voltage(void)
 {
     uint8_t i = 0, uc_key;
     int16_t us_value = 0;
     int8_t c_length = 0;
     int8_t ac_str_temp[5] = { 0 };

     while (1) {
         while (uart_read(CONSOLE_UART, &uc_key)) {
         }
         if (uc_key == '\n' || uc_key == '\r') {
             puts("\r");
             break;
         }

         if ('0' <= uc_key && '9' >= uc_key) {
             printf("%c", uc_key);
             ac_str_temp[i++] = uc_key;

             if (i >= 4)
                 break;
         }
     }

     ac_str_temp[i] = '\0';
     /* Input string length */
     c_length = i;
     us_value = 0;

     /* Convert string to integer */
     for (i = 0; i < 4; i++) {
         if (ac_str_temp[i] != '0') {
             switch (c_length - i - 1) {
             case 0:
                 us_value += (ac_str_temp[i] - '0');
                 break;
             case 1:
                 us_value += (ac_str_temp[i] - '0') * 10;
                 break;
             case 2:
                 us_value += (ac_str_temp[i] - '0') * 100;
                 break;
             case 3:
                 us_value += (ac_str_temp[i] - '0') * 1000;
                 break;
             }
         }
     }

     if (us_value > (5 * VOLT_REF / 6) || us_value < (1 * VOLT_REF / 6)) {
         return -1;
     }

     return us_value;
 }

 int main(void)
 {
     uint8_t uc_key;
     int16_t s_volt = 0;
     uint32_t ul_value = 0;
     volatile uint32_t ul_status = 0x0;
     int32_t l_volt_dac0 = 0;

     /* Initialize the system */
     sysclk_init();
     board_init();

     /* Initialize debug console */
     configure_console();

     /* Output example information */
     puts(STRING_HEADER);

     /* Initialize DACC */
     /* Enable clock for DACC */
     pmc_enable_periph_clk(ID_DACC);
     /* Reset DACC registers */
     dacc_reset(DACC);
     /* External trigger mode disabled. DACC in free running mode. */
     dacc_disable_trigger(DACC);
     /* Half word transfer mode */
     dacc_set_transfer_mode(DACC, 0);
     /* Power save:
      * sleep mode  - 0 (disabled)
      * fast wakeup - 0 (disabled)
      */
     dacc_set_power_save(DACC, 0, 0);
     /* Timing:
      * refresh        - 0x08 (1024*8 dacc clocks)
      * max speed mode -    0 (disabled)
      * startup time   - 0xf (960 dacc clocks)
      */
     dacc_set_timing(DACC, 0x08, 0, 0xf);
     /* Disable TAG and select output channel DACC_CHANNEL */
     dacc_set_channel_selection(DACC, DACC_CHANNEL_0);
     /* Enable output channel DACC_CHANNEL */
     dacc_enable_channel(DACC, DACC_CHANNEL_0);
     /* Setup analog current */
     dacc_set_analog_control(DACC, DACC_ANALOG_CONTROL);

     /* Set DAC0 output at ADVREF/2. The DAC formula is:
      *
      * (5/6 * VOLT_REF) - (1/6 * VOLT_REF)     volt - (1/6 * VOLT_REF)
      * ----------------------------------- = --------------------------
      *              MAX_DIGITAL                       digit
      *
      * Here, digit = MAX_DIGITAL/2
      */
     dacc_write_conversion_data(DACC, MAX_DIGITAL / 2);
     l_volt_dac0 = (MAX_DIGITAL / 2) * (2 * VOLT_REF / 3) / MAX_DIGITAL +
             VOLT_REF / 6;

     /* Initialize ADC */
     /* Enable clock for ADC */
     pmc_enable_periph_clk(ID_ADC);
     /*
      * Formula: ADCClock = MCK / ( (PRESCAL+1) * 2 )
      * For example, MCK = 64MHZ, PRESCAL = 4, then:
      *     ADCClock = 64 / ((4+1) * 2) = 6.4MHz;
      */
     adc_init(ADC, sysclk_get_cpu_hz(), ADC_CLOCK, ADC_STARTUP_TIME_SETTING);

     /* Formula:
      *     Startup  Time = startup value / ADCClock
      *     Transfer Time = (TRANSFER * 2 + 3) / ADCClock
      *     Tracking Time = (TRACKTIM + 1) / ADCClock
      *     Settling Time = settling value / ADCClock
      * For example, ADC clock = 6MHz (166.7 ns)
      *     Startup time = 512 / 6MHz = 85.3 us
      *     Transfer Time = (1 * 2 + 3) / 6MHz = 833.3 ns
      *     Tracking Time = (0 + 1) / 6MHz = 166.7 ns
      *     Settling Time = 3 / 6MHz = 500 ns
      */
     /* Set ADC timing */
     adc_configure_timing(ADC, ADC_TRACK_SETTING, ADC_SETTLING_TIME_3,
             ADC_TRANSFER_SETTING);

     /* Channel 5 has to be compared */
     adc_enable_channel(ADC, ADC_CHANNEL_5);

     /* Enable clock for ACC */
     pmc_enable_periph_clk(ID_ACC);
     /* Initialize ACC */
     acc_init(ACC, ACC_SELPLUS_AD5, ACC_SELMINUS_DAC0,
             ACC_EDGETYP_ANY, ACC_INVERT_NO);

     /* Enable ACC interrupt */
     NVIC_EnableIRQ(ACC_IRQn);

     /* Enable */
     acc_enable_interrupt(ACC);

     dsplay_menu();

     while (1) {
         while (uart_read(CONSOLE_UART, &uc_key)) {
         }

         printf("input: %c\r\n", uc_key);

         switch (uc_key) {
         case 's':
         case 'S':
             printf("Input DAC0 output voltage (%d~%d mv): ",
                     (VOLT_REF / 6), (VOLT_REF * 5 / 6));
             s_volt = get_input_voltage();
             puts("\r");

             if (s_volt > 0) {
                 l_volt_dac0 = s_volt;
                 /* The DAC formula is:
                  *
                  * (5/6 * VOLT_REF) - (1/6 * VOLT_REF)     volt - (1/6 * VOLT_REF)
                  * ----------------------------------- = --------------------------
                  *              MAX_DIGITAL                       digit
                  *
                  */
                 ul_value = ((s_volt - (VOLT_REF / 6))
                     * (MAX_DIGITAL * 6) / 4) / VOLT_REF;
                 dacc_write_conversion_data(DACC, ul_value);
                 puts("-I- Set ok\r");
             } else {
                 puts("-I- Input voltage is invalid\r");
             }
             break;
         case 'v':
         case 'V':
             /* Start conversion */
             adc_start(ADC);
             ul_status = adc_get_status(ADC);
             while ((ul_status & ADC_ISR_EOC5) != ADC_ISR_EOC5) {
                 ul_status = adc_get_status(ADC);
             }
             /* Conversion is done */
             ul_value = adc_get_channel_value(ADC, ADC_CHANNEL_5);

             /*
              * Convert ADC sample data to voltage value:
              * voltage value = (sample data / max. resolution) * reference voltage
              */
             s_volt = (ul_value * VOLT_REF) / MAX_DIGITAL;
             printf("-I- Voltage on potentiometer(AD5) is %d mv\n\r", s_volt);
             printf("-I- Voltage on DAC0 is %ld mv \n\r", (long)l_volt_dac0);
             break;

         case 'm':
         case 'M':
             dsplay_menu();
             break;
         }
     }
 }

I'm afraid you'll have to study how to configure the registers, taking the datasheet and, as a guideline, the ACC and PMC definitions linked above.

Thanks, but that is the ASF framework, and not how most Arduino code is (but I'm not sure). The Arduino has already all the bits defined for the differential and gain modes, for example "ADC_INPUTCTRL_GAIN_16X", but that might be the ASF framework as well (or not). I'm still like a rabbit staring into headlights.

I can feel and understand your frustration. I've searched but haven't been able to find exactly what you need. At this point I can only recommended that you take Nick Gammon's example code and modify it to configure instead the specific registers of the ATSAMD21 as per the linked ASF examples and definitions. Sorry...


text:
Transistor switching problem
With my team we constructed a circuit using Arduino. The circuit works on the Proteus simulator. It worked fine with LEDs connected directly to Arduino outputs.
However, when I used Arduino output to trigger a BC 337 transistor to try and actuate a 12 V DC coiled relay, it wouldn't trigger. I measured voltage across transistor collector and emitter, it reads 12 V, just like the source I gave... (The transistor is not switched on I guess).
Supply for the Arduino is a constant 5 V DC.
Where have I gone wrong? Picture as uploaded.

Furthermore, we are trying to build a controller for an ice making machine. The power circuit (12 V) is to be controlled by Arduino through the transistors.
I am uploading the codes we used and the full circuit diagram.
const int start = 13;
const int comp= 2;
const int cond=3;
const int hGas=4;
const int wbut=12;
const int watersol=5;
const int dumper=6;
const int iced=11;

int startButton=0;
int waterButton=0;
int dumperlimswitch=0;

void setup() {

  pinMode(start, INPUT);
  pinMode(comp, OUTPUT);
  pinMode(cond, OUTPUT);
  pinMode(hGas, OUTPUT);
  pinMode(wbut,INPUT);
  pinMode(watersol, OUTPUT);
  pinMode(dumper, OUTPUT);
  pinMode(iced, INPUT);
}

void loop() {

startButton = digitalRead(start);
waterButton = digitalRead(wbut);

 if (startButton == HIGH) {

    digitalWrite(comp, HIGH);
    digitalWrite(cond, HIGH);

    waterButton = digitalRead(wbut);
    if (waterButton == HIGH){
      digitalWrite(watersol,HIGH);
      }
    else{
      digitalWrite(watersol,LOW);
      }
     delay(800);
    digitalWrite(hGas,HIGH);
    digitalWrite(cond, LOW);

    waterButton = digitalRead(wbut);
    if (waterButton == HIGH){
      digitalWrite(watersol,HIGH);
      }
    else{
      digitalWrite(watersol,LOW);
      }
    delay(500);
    digitalWrite(hGas, LOW);
    digitalWrite(dumper, HIGH);
    digitalWrite(cond, HIGH);

    waterButton = digitalRead(wbut);
    if (waterButton == HIGH){
      digitalWrite(watersol,HIGH);
      }
    else{
      digitalWrite(watersol,LOW);
      }
    delay(800);
    digitalWrite(dumper, LOW);
  }
else {
    digitalWrite(comp, LOW);
    digitalWrite(cond, LOW);
  }
}

Circuit...? Code...?

What's an ardinho?

@gre_gor It's what you get after you use a "Harduino".

What is pin 13 doing?  Are you putting 12V into p13?  Can you take the Arduino out of the equation, just supply 5V out into the wire that would have been pin 2?  I don't think your problem is an Arduino one, it would have been nice to see the code, but if its working with LEDs then it looks like an electronics issue and would be better on Electronics Exchange.  But if you include Arduino in it they will send it back here :)

Where is your second image? I can't find the URL of the second image in any of the previous edits. I have reinstated the first image for you already.

i have now uploaded the correct one. thanks.

Why are there still two dead links to the second image in the middle of the question? Please tidy up your question, and place the image in a suitable location, rather than right at the top (I would suggest placing it just beneath Where have I gone wrong? Picture as uploaded.. Two people have attempted to tidy the question for you. Please take the time to see how they did it, and try to follow their example. A well presented question will get [better quality] answers. Oh, and welcome to SE Arduino, BTW! :-)

Thanks, your question looks much better now, and is on its way to being reopened :-). BTW, if you are addressing your comment to someone, as you did to me in your last comment, you need to add @, (i.e. @greenonline) in order for that person to receive notification that you have messaged them, otherwise they may never see that comment. I only saw your comment because I was reviewing the question at the time that the comment was posted.

thanks @Greenonline, i am not so conversant with online protocols. but alas, it seems my question may still not be good enough.

@Greenonline - I broke the image links not the OP.  Sorry :(

Yes, I saw that, but that was the first image, that is not the problem, it was the second image that  disappeared. Anyway, not to worry :-)

@Majenko , now circuit and code posted, does it make sense now?

Why are there no resistors on your LEDs?

@majenko , arduino output is capable of upto 50ma current , the LEDs draw so much less, so we supposed, no need of resistors for the current limiting purpose.

Wrong on both counts. Learn basic electronics and how to count.

Arduino IO is 40mA absolute maximum and 25mA recommended maximum sustained.

An ideal LED will draw an infinite amount of current.

Maybe this will help: https://hackingmajenkoblog.wordpress.com/2017/03/20/what-exactly-is-a-gpio-pin/

Remove the LEDs or add resistors to them (1k is all you need for indicator LEDs like that) and watch the circuit spring to life.

TL/DR: Your LEDs without resistors are diverting all the current away from the transistors so they are unable to switch.
In detail:
Let's take a quick look at just one small portion of your circuit in more detail:

simulate this circuit – Schematic created using CircuitLab
I have added an extra resistor into the circuit - Rw - which represents the resistance of the wires and pins of the LED, and I have given it a nominal 0.1Ω value.
Now, let's say you set the GPIO HIGH, so it outputs 5V. The LED, D1, is a typical red LED with a forward voltage of, say, 2V.  Let's calculate the current through the LED.

I = (VCC - VF)/R = (5 - 2) / 0.1 = 3 / 0.1 = 30A

30A?! But the GPIO can't provide more than 40mA absolute maximum. So all that can come from the GPIO is being sent straight through the LED leaving nothing (much) for the transistor.
Oh and yes, all that current demand is doing unspeakable damage to the Arduino's GPIO pin.
The transistor's Base-Emitter junction has about a 0.7V drop across it, and, if it weren't for the LED, with the 1kΩ resistor that gives (5-0.7)/1000 = 4.3mA. Which with a hFE of around 100, would give a collector current of around 430mA. And that should be fine for most small relays.
But with all the current being dumped through the LED what can get through to the transistor won't be enough to turn on the relay.
So increasing the resistance of the wire to the LED will decrease the current demands of the LED. And of course you do that by adding a resistor. So let's make that 1kΩ - a decent enough value for a simple indicator LED:

simulate this circuit
Now let's do the calculation for the LED's current:

I = (VCC - VF) / R = (5 - 2) / 1000 = 3 / 1000 = 3mA

Add that to the 4.3mA that wants to go through the transistor, and we have 7.3mA in total.
Now that is way below what the Arduino's GPIO can provide, so the IO pin is happy, the LED is happy and, most importantly, the transistor is happy.

This is not an answer but its too big to be a comment.  I can't solve your problem, but hopefully I can point you in the right direction.
I think the first problem you have is you have talked this problem in one chunk.  I think even some of the more experienced users would have a problem hitting this in one go.  You need to break it down into simple units (Functional decomposition if you want to be posh).
The problem you are asking about is why your transistor doesn't work.  You have used an LED and you think the correct signals are being sent.
So Phase one, take the transistor and test it in isolation, then you know its working.  Secondly does it still work when the Uno is controlling it rather than just a battery?
Does the object you are powering via the transistor work on its own?
Does it work when you add it to the uno and transistor?
You get the idea.  To be honest I suspect it might be an issue with lack of power.

thanks @code Gorilla , yes, i guess, i'll have to break it down. somehow, i thought of giving a full picture.

The either the transistor is broken or its not getting enough current from the uno.

and:the uno is giving the output signals alright. correctly as per the program. however, the uno output signal is not firing up the transistor. the battery is a secondary circuit. the transistor was supposed to close that secondary circuit .    secondly, yes the object i am trying to power through the transistor works fine.   yes you may be right, the voltage reaching the base of the transistor is 0.7v (due to the 1k ohm resistor, ) i am lowering that value. but somewher i also read that even if the transistor fires, it shall limit the voltage to 4.3 volts . he suggests to use mosfet.

source: Stack Exchange

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

sort: votes


text:
Using tinyGPS++ with millis errors
Hi I am trying to make search GPS (using tinGPSplus) every x time. The problem is when I do compile the code:
void loop()
{
    read=BP_mnger.pressedButton();
    navigateMenus(read);
    dealWithUsedEvents(getmenuUsed());
    setmenuUsed(0);

    if (isStarted && (GPSSearchPeriod<=millis()-oldMillisVallue)) {

        oldMillisVallue=millis();// if i comment this line it works
        Serial.print(F("oldMillisVallue: "));
        Serial.println(oldMillisVallue);
        while (ss.available() > 0){
            if (gps.encode(ss.read()))
                if (gps.location.isUpdated() || gps.date.isUpdated() || gps.time.isUpdated() || gps.altitude.isUpdated() || gps.satellites.isUpdated() || gps.hdop.isUpdated())
                    GPSSentence=makeGPSSentence( );
        }

    }

I get this:
oldMillisVallue: 22355
oldMillisVallue: 24356
oldMillisVallue: 26357
oldMillisVallue: 28358
oldMillisVallue: 30359

When I comment out:
oldMillisVallue=millis();// if i comment this line it works

I get this :
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0
2000,0,0,4294967295,15,43,3,36,5,41,4.066298,48.269157,77,0.12,90,380,98,2,1,3
2000,0,0,4294967295,15,43,3,39,5,43,4.066298,48.269157,79,0.122200,92,380,98,2,1,3
------------------------
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0

oldMillisVallue: 0
oldMillisVallue: 0
2000,0,0,4294967295,15,43,4,39,5,43,4.066265,48.269126,80,0.12,94,380,101,3,2,5
2000,0,0,4294967295,15,43,4,41,5,45,4.066265,48.269127,82,0.121900,94,380,103,3,2,5
------------------------
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0

You're only reading from the serial port every GPSSearchPeriod milliseconds. That gives plenty of time for the small serial read buffer to overflow and lose the data.
Instead you should be reading all the time regardless of your desire to only do things periodically. Sure, report the data periodically, but you must read all the time as well.

Just to be sure you are talking about the Serial buffer ?
"reading all the time" wouldn't that drain the battery ? my goal was like to make one GPS search each 2 seconde to save battery

The SoftwareSerial buffer, yes. Unless you are sleeping the MCU reading all the time will make no difference. You are just looking at the content of the serial buffer.

thank you very much, now i can read properly the data.
last question i tried putting the while (ss.available() > 0) with declaration of the gps in a function that i call every time as u said to save sram (the SoftwareSerial is still global) i had no output is it because the decalring the gps as local variable ?

Yes. You need the gps instance to either be global or local and static - the effect is the same (just the scope is different).

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


text:
Lighting up LED lights on Arduino tank using Arduino transmitter
I am making an Arduino tank using the motor shield, more of a recon tank as it has no gun. And I'm using one Arduino board as the receiver and controller of the tank and the other as the transmitter. I'm thinking of adding lights to the build and want to remotely operated them. I don't know where to look at or start. Can someone help me?

I'm voting to close this question as off-topic because we are not a free code writing service.

I am very sorry gre_gor I didn't know that you would take this the wrong way. I am just new to this Arduino thing and wanted since guidance. If you wish, I will delete this question

You said, "Can someone just send me the code".  So I don't think he took that wrongly.  We are not a free code writing service.

@Ronitbal - Change the last line of you question to "I don't know how to start, please can some one tell what I need to look at?" and people should be OK with it.

Well, Im going to see your question with good eyes and help you out giving you the properly guidance. With no sarcasm.
First of all you just would do some google searchs using the correct words.
To achieve the correct words you need to enumerate important things just doing the following quastions.
What do I have?
Arduino, Led

What do I want?
Controlling Led Remotely

So with these couple of question I could achieve the following sentence:
controlling led arduino remotely

This gave me the following good and usefull link with source code:
http://www.instructables.com/id/Arduino-Control-LEDs-with-a-Remote-Control/
Now you can improve your serach and come back here, bringing us what you have done so far with a far more accurated techinical question like:
What is the best way to controlling LED remotely in the given situation?

And go on.
The most important thing to know is how to separate requirements from impediments. I think now you are fair well introduced about how to use this very good resource.

Before you can operate LEDs remotely, do you know how to write a program to make a switch turn on a LED on the same board?  Then the next step is make the switch on board 1 turn on the light on board two.


text:
Source code for Arduino “firmware”?
I am wondering if anyone here knows where the source code for the Arduino "firmware" is available for reading? I think it must be more than the 'boot loader' but I am not sure. Thanks!
p.s. I assume this kind of question is ok here, even though it's not ok on StackOverflow?

The “firmware” is whatever program a microcontroller runs. On an
Arduino, it is typically the program you write and upload into the
microcontroller's flash memory.
If by “firmware” you mean the core library (the source code of
pinMode(), digitalRead() and so on), it is here:
https://github.com/arduino/ArduinoCore-avr
If by “firmware” you mean the bootloader (the small program that runs at
reset and will accept the upload of your firmware), is is here:
https://github.com/arduino/Arduino/tree/master/hardware/arduino/avr/bootloaders/optiboot
Note that this is valid for the AVR-based Arduinos.
The cores and bootloaders used in other architectures are stored is
separate repositories, e.g.
https://github.com/arduino/ArduinoCore-sam

If you are looking for the Flash Firmware, I think the github project documentation is pretty well developed, here:
https://github.com/arduino/Arduino
This is a good introduction to build and flash your Arduino UNO:
http://angryelectron.com/arduino-firmware/
And here a good start to build you own Arduino on a breadboard:
https://www.arduino.cc/en/main/standalone

Thanks. The arduino/arduino github repo looks like java so I think it's for their IDE. Thanks for the other links, I will followup.

@pitosalas: that GitHub repo also has the source of the AVR core and a few extra libraries.

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


text:
Understanding the ESP8266
I've received my ESP8266-01 and playing with it I discovered that with a baudrate of 74880 I can get the boot modes and `hy version, etc:
 ets Jan  8 2013,rst cause:1, boot mode:(3,0)
load 0x40100000, len 1856, room 16
tail 0
chksum 0x63
load 0x3ffe8000, len 776, room 8
tail 0
chksum 0x02
load 0x3ffe8310, len 552, room 8
tail 0
chksum 0x79
csum 0x79

2nd boot version : 1.5
  SPI Speed      : 40MHz
  SPI Mode       : DIO
  SPI Flash Size & Map: 8Mbit(512KB+512KB)
jump to run user1 @ 1000

rf cal sector: 249
rf[112] : 00
rf[113] : 00
rf[114] : 01

SDK ver: 1.5.4.1(39cb9a32) compiled @ Jul  1 2016 20:04:35
phy ver: 972, pp ver: 10.1

With this baudrate I'm not able to check the AT commands. Then, when I switch to a baudrate of 115200 I am able to communicate with the ESP:
Ai-Thinker Technology Co. Ltd.
ready
AT
OK
AT+CWL
ERROR
AT+CWJAP?
No AP
OK
AT+CWLAP?
ERROR
AT+CWLAP
+CWLAP:(4,"bbox2-7f0d",-88,"00:1 ",1,-46,0)
+CWLAP:(0,"PROXIMUS_FON",-94,"06: ec:6b",1,-47,0)
+CWLAP:(5,"PROXIMUS_AUTO_FON",-88,"0a: :ec:6b",1,-44,0)
+CWLAP:(3,"WiFi-2.4-BB3D-ext",-51,"00: 9a:38",1,-12,0)
+CWLAP:(3,"NGUYEN",-79,"e0:b ",11,-2,0)
+CWLAP:(0,"PROXIMUS_FON",-81,"42:6 ",11,0,0)
+CWLAP:(5,"PROXIMUS_AUTO_FON",-79,"42 ",11,0,0)
+CWLAP:(4,"WiFi-2.4-6858",-75,"4 e",11,1,0)
+CWLAP:(0,"PROXIMUS_FON",-89," ",11,-6,0)
OK

How is that possible that it has two different baudrates?
Thanks in advance,

How is that possible that it has two different baudrates?

Very simple. Exactly the same as the Arduino.
If you put:
Serial.begin(9600);

in your program then your sketch runs with the serial port at 9600 baud. However, just before then, the bootloader runs at 115200 baud for a few seconds listening for instructions from the PC.
There's no magic there.
You can even do it yourself:
Serial.begin(9600);
Serial.println("Hello at 9600 baud");
Serial.flush();
Serial.end();
Serial.begin(115200);
Serial.println("Hello at 115200 baud");
Serial.flush();
Serial.end();

The baud rate isn't fixed. It's whatever the firmware that is running at that precise moment deems it to be - whether that is the bootloader, the AT firmware, or your own custom sketch.


text:
Write data on the computer with Arduino
I wonder if in Arduino you can modify the computer eg create a text file inside the computer using Arduino. Is there any way you can do this or something like that?
Because you can use the library #include <stdio.h>, which is a C++ language library to handle file on the computer.
In Arduino maybe you can create files on the computer using pointers or a library? Because using the library "Keyboard.h" you can handle the computer. The Keyboard library can interact with the computer by typing on the computer
I'm in doubt, I need your knowledge.

You can do it with a Serial.print if there is a program on the computer ready to accept the input from the serial port.

But to be clear, that requires writing a program on the computer to listen for the signal from the Arduino and actually do the work.  The Arduino cannot command the computer by itself.  All it could do would be to send a signal to let the computer know it was time to do it.

The arduino can't directly modify the contents of the PC hard drive, the ability for a peripheral device to do this would be considered a massive security flaw in the PC operating system.
Having said that there are a few ways to do it:
To save a text file without anything special on the PC:
Have the Arduino act as a keyboard. Send (windows key + R) (pause) notepad < enter > (pause) [ The text you wish to save to the PC ] (alt-f) s < file name > < enter>
This does require the PC to be unlocked (or you send the unlock key sequence first) and setting the directory to save to or overwriting a file could get tricky but should be possible if you work out the correct key sequence. The (windows key + r) combination is very powerful and also very dangerous. It makes it trivial to wipe the entire computer so use it with care.
To save a binary file to the PC:
Set up the arduino to act as a serial port. Start the terminal program of your choice and set it to log to a file. Send the data from the arduino. On the PC wait until the transfer is complete and then save the log file.
To read/save/modify any file without user interaction:
Set up the arduino to act as a serial port. Write a desktop PC application that takes the data from the Arduino. Define a protocol that allows the arduino to to specify the filename and what to do with it. The arduino doesn't directly access any files, instead it sends the commands to an application running on the PC, that application then performs the required file operations.
Alternative way to read/save/modify any file without user interaction:
Connect the arduino to the PC using USB. Exploit a flaw in the PC operating system to install a virus on the PC that gives you full control over the computer.

The keyboard library just sends key presses to the computer like a keyboard.  From the PCs point of view it's no different from you banging on the keyboard in front of it.  The Arduino can't control anything on the computer and it can't run any code on the computer.  Now if you can do what you want completely from the keyboard then arduino could send those same keypresses.  But the Arduino has no access to the PCs operating system or file system.

There are a number of serial-terminal programs that run on your PC (and pretty much any OS) that will copy the data they receive to a file. I use CoolTerm on MacOS. I think Windows HyperTerminal offers that capability as well on Windows. You have to start the terminal program on the PC, set it to capture, and open the capture file yourself - the Arduino can't cause the PC to do that - but once you've done it, the terminal program will copy all output from the Arduino to the capture-file. You might also have to set the PC to not sleep, if you need it to capture data without you being present.


text:
Button not working - Arduino Due project (MiniEngine v2)
I am building Arduino Due based project called MiniEngine v2 (an open-source motion control software for timelapse photography).
The project is not very active anymore but there are still all the documentation at github. Project owner had webshop where he sold MiniEngine shields for arduino but they are not available anymore. There was gerber files available at project github page so I orderer PCB's form seeed.com.
Project's Github page is at:
https://github.com/airiclenz/miniEngine2
Everything seems to work ok but one of the buttons is not working. There is only 2 buttons and one rotary encoder.
I think the reason why the button is not working is that the output voltage for button from 74HC14N (hex smith trigger) is too low (I am not very good at electronic so I might be totally wrong.
I tried to measure values with voltage meter and here is the result what I got for those two buttons:
Here are the values in written format ( I took measurement from SN74HC14N )

btn_2 (pin9 input, pin8 output)
btn_1 (pin11 input, pin10 output)

SETTINGS BUTTON (btn_2) -> this one works fine

1) button up  - metering from input pin 11 => 3.26
2) button down -metering from input pin 11 => 0
3) button up - metering from output pin 10 => 0.6
4) button down - metering from output pin 10 => 2.38

START/BACK BUTTON (btn_1) -> this one does not work

1) button up  - metering from input pin 9 => 3.26
2) button down - metering from input pin 9 => 0
3) button up - metering from output pin 8 => 1.43
4) button down - metering from output pin 8 => 1.53

Here is how the buttons are initialized:
    void input_init() {

  // set pin modes
  pinMode(PIN_ROTARY_PRESS, INPUT);
  pinMode(PIN_KEY_1, INPUT);
  pinMode(PIN_KEY_2, INPUT);

  // attach interrupts for the keys
  attachInterrupt(PIN_ROTARY_PRESS, input_interrupt_keyRotary_press,  RISING);
  attachInterrupt(PIN_KEY_1,        input_interrupt_key1,             RISING);
  attachInterrupt(PIN_KEY_2,        input_interrupt_key2_press,       RISING);

  // attach interrupts to both encoder pins for every state change
  attachInterrupt(PIN_ROTARY_A,     input_interrupt_rotary,           CHANGE);
  attachInterrupt(PIN_ROTARY_B,     input_interrupt_rotary,           CHANGE);

  // set the initial rotary values & configurations
  rotary.setPosition(0);
  rotary.setKeyMode(true);
  rotary_old_pos = 0;
}

And here is function for btn_1 press that is never called (except once in powering the shield/arduino due)
void input_interrupt_key1() {

  if ((key_1_time + DEF_INPUT_DEBOUNCE) < millis()) {

    key_1_time = millis();
    setBit(input_status, BIT_2);

  }
}

I can only use 2 links in posts (I do not have 10 reputation) so you can find the code for inputs at Github (link above). (folder MiniEngine2/Software/miniEngine2/mE2_input.ino)
All code files are at Sotfware at folder: MiniEngine2/Software/miniEngine2
I have put Serial.println command in code and nothing is printed when btn_1 is pressed. When I plug power on then the btn_1 is triggered once...
Here is link to the the schematic for that shield ( it is quite big so that's why I did not embed the photo):
Schematic for shield is at Github folder : Hardware/miniE shield v2 revB BED board - schematic.pdf
Here is also link to the video where you can see how I took the measurements:
https://youtu.be/wFR7P65qMGA
Please ask if I need to provide more information...

First thing to try - power the board without the arduino connected and verify that you see the same results. That would eliminate the possibility or an arduino or software related issue. My best guess is a soldering issue on the output pin or the connector to the arduino. A digital output pin that's stuck halfway between high and low normally means either a design fault or a short somewhere.

I forgot to mention that I soldered two similar shields and both have the same problem. So I do not believe that it is soldering issue (but of course it still might be it). Now I try without arduino connected...

It was the Arduino Due issue. Arduino digital pin 43 was faulty or something. I managed to change 43 to 53 and now the button works...

You should accept this answer as the solution so that the question no longer shows up as open.


text:
ATTiny85 and DHT11 - Sensor always returning 0
Good day.
I am making a small weather station using ATTiny85, DHT11, and an OLED display.
There are many, many tutorials that explain how this works, and various libraries that show you how to get the DHT11 to work with the ATTiny85 and others that are dedicated to the SSD1306 Oled displays, some even show you how to combine them together. Well, for the better part of 2 days nothing worked for me.
My schematics is as follows:

And here is a picture of the actual thing, working with a CR2032 Coin Cell:

The Libraries I am using are:

OLED Libraries for ATTiny85 - Source: http://www.14core.com/wiring-digispark-attiny85-with-096-oled-screen-display/
Rob Tillaart DHT Library - Source: https://github.com/RobTillaart/Arduino/tree/master/libraries

My Code is as follows:
    //OLED Libraries for ATTiny85 - Source: http://www.14core.com/wiring-digispark-attiny85-with-096-oled-screen-display/

#include <font6x8.h>
#include <font8x16.h>
#include <num2str.h>
#include <ssd1306xled.h>
#include <ssd1306xled8x16.h>
#include <SSD1306_minimal.h>
#include <TinyWireM.h>
#include <USI_TWI_Master.h>

#define DEG "\xa7" "C"

SSD1306_Mini oled;

char strHum[4];
char strTemp[4];

#include <dht.h>
dht DHT;
#define DHT11_PIN 1

void setup()
{

  TinyWireM.begin(); // initialize I2C lib - comment this out to use with standard arduinos
  oled.init(0x3c);
  oled.clear();

}

void loop()
{

  //            DHT Code goes here                              //

  DHT.read11(DHT11_PIN); //Calling the read function

  float hu  = (DHT.humidity, 1);
  float te  = (DHT.temperature, 1);

  //            OLED Start -- DO NOT CHANGE ANYTHING            //

  //oled.clear();

  oled.startScreen();
  oled.cursorTo(10, 0);
  oled.printString("ATTiny85 & DHT11");

  oled.startScreen();
  oled.cursorTo(12, 9);
  oled.printString("Temp & Humidity");

  oled.startScreen();
  oled.cursorTo(10, 18);
  oled.printString("www.MDChaara.com");

  oled.startScreen();
  oled.cursorTo(0, 27);
  oled.printString("mdchaara@gmail.com");

  oled.startScreen();
  oled.cursorTo(0, 45);
  oled.printString("Humidity(%): ");

  oled.startScreen();
  oled.cursorTo(110, 45);
  oled.printString( itoa(int(hu), strHum, 10));

  oled.startScreen();
  oled.cursorTo(0, 55);
  oled.printString("Temperature(c): ");

  oled.startScreen();
  oled.cursorTo(110, 55);
  oled.printString( itoa(int(te), strTemp, 10));

  //            OLED End          //

  delay(5000);
}

Now I know that the OLED code works, and it was a very interesting round or research to get it to work. The DHT code is another story. I have tried 6 different libraries and none of them worked. They all either return 0, 1, or blank readings on the screen.
I have checked if the sensor is working with an Uno and a Nano, works well! I checked the connections, and the soldered parts and did continuity tests, but the issue still remains.
I am asking because I am hoping a fresh set of eyes can pin-point the issue that I am facing. Any help will be highly appreciated.

Arduino IDE: 1.8.2
OS: Windows 7 64 bits
Micro controller: ATTiny85-20PU

Sketch is uploaded to the micro controller using Arduino Uno as a programmer.
Sketch is uploaded at Internal 8MHz clock setting.
Thank You.

Is that second pin of the DHT, the one that goes to the ATTiny pin, supposed to also be connected to +3V like that?  Pretty sure there was supposed to be a resistor there.  You should probably also include some decoupling caps on the power lines.  0.1uF as close as you can get to the power pins of the ATTiny.

@Delta_G - Thank you for your comment. I have a 10K resistor connected to the data pin of the DHT11 sensor. My understanding is that the pull-up resistor is needed because the data line to the sensor is bidirectional. I have tested the sensor itself with an UNO and it worked well (with and without the resistor, powered with 5v and 3v3 volts) which yielded different results of course but that is expected. I think my issue could be in the software itself.

Why is the line DHT.read11(DHT11_PIN); commented? You have to perform a read before accessing the variables...

itoa()  is for converting an integer to ascii, but you are giving it a float.  It works on a PC (Visual Studio), but you might want to check it works under GCC.  Also what happens if itoa returns more than 4 characters?  You might want to consider putting the strings in flash?  I think you prefix them with T?? (Please someone help!!)

@frarugi87 - That is commented because it's from another library. I will actually remove it from the code. Thank you for highlighting this.

@CodeGorilla - You are right, but changing the type does not help. I did try to read it from DHT as an int (didn't work), pass it to itoa() as an int (didn't work), and as a float (also didn't work). itoa() would never pass more than 4 characters, but I have non the less changed a few things in the code. Please have a look and check if you can spot something. Thank you for the comment, and the call for help.

@MDChaara you said that you are using Rob Tillaart's library. This library (actually there are two, but they work the same) REQUIRES you to call the read function before getting the results from the object. See this example

@frarugi87 - Thanks for the example. The function is called but the result remains the same. I have updated the code. Thanks for your help. I appreciate it.

@MDChaara Have you tried printing a literal string rather than iota output (which should be a perfectly good string, but...).  i.e. try printing the temp as "42" and make sure it appears where you expect it to.  All the other strings work so this should too.  I appreciate its probably pointless, but...

@MDChaara the pinmode on the dht pin input is useless (the library manages that for you). Try checking also the return value of the read11 function (like they do in the example)

@CodeGorilla : You might actually be onto something :) When I print a number it comes in binary. I tried 30 and it printed 11110 on the screen :)

@frarugi87 Thanks. I will remove it and try the code.

Ok i tried something like that for myself and thanks to this and ..many other posts and forums/videos i could make myself something that works but with a little other setting like in the start post (other libs ect)
in my case the main reason for the "1" output on the oled was this:
  float hu  = (DHT.humidity, 1);    //original

  hu  = (DHT.humidity);       //what worked for me

Maybe you can figure out more Problems, my code is shure not perfekt! But maybe it helps someone for a vew steps
#include <dht.h>
#include <U8x8lib.h>
#define DHT11_PIN 1
dht DHT;
int temp = 0;
int humi = 0;
char strTemp[4];
char strHumi[4];

U8X8_SSD1306_128X64_NONAME_SW_I2C u8x8(/* clock=*/ 2, /* data=*/ 0, /* reset=*/ U8X8_PIN_NONE);         // Digispark ATTiny85 Pin 0 Data, Pin 2 clock

void setup(void)
{

  u8x8.begin();
  u8x8.setPowerSave(0); //enegergiesparen 0 aus

}

void loop(void)
{

  int chk = DHT.read11(DHT11_PIN);

  temp = (DHT.temperature);
  humi = (DHT.humidity);

  u8x8.setFont(u8x8_font_chroma48medium8_r);
  u8x8.drawString(0,0,"~~~~~~~~~~~~~~~~");
  u8x8.drawString(0,1,"Temperatur");
  u8x8.drawString(1,2,( itoa(int(temp), strTemp, 10)));
  u8x8.drawString(4,2,"Grad Celsius");
  u8x8.drawString(1,3,"--------------");
  u8x8.drawString(0,4,"Luftfeuchtigkeit");
  u8x8.drawString(1,5,( itoa(int(humi), strHumi, 10)));
  u8x8.drawString(4,5,"Prozent");
  u8x8.drawString(0,6,"~~~~~~~~~~~~~~~~");
  delay(200);
}

The DHT11 is notoriously slow to respond and often returns null for readings sporadically.
I notice in your second circuit you have resistors by the sensor but I cant see what pins they are connected to.
You will need pullup for the sensor data line 4K7 usually does the trick.

The DHT works, by specification, with a 3.5V minimally. I think you can expect anything if you don't provide the appropriate voltage, which seems to be only 3V from the picture you show.
source:
https://components101.com/dht11-temperature-sensor


text:
A1 was not declared in the scope
I'm trying to put all my settings in a config.h file and then #include it in the Arduino sketch.
Here's what my config.h looks like:
RobotConfig.h
#ifdef BOT
    //hardware pins
    int motor1Pin = 9; //s0
    int motor2Pin = 10; //s1

    //pins for light
    int light2 = A4;
    int light3 = A2; //right
    int light1 = A1; //left

And here's what .ino sketch looks like:
#define BOT
#include "RobotConfig.h"

void setup() {
  //Light INIT
  pinMode(light1, OUTPUT); //left light with motor1/s1 in front
  pinMode(light2, OUTPUT); //middle light with motor1/s1 in front
  pinMode(light3, OUTPUT); //right light with motor1/s1 in front
  ...
}

This compiles fine on my Mac but I'm trying to compile this on Raspberry Pi (Pi3 with new Jessie install with sudo apt-get install arduino) and get an error while doing so. The error says:

A1 was not declared in the scope etc.

What am I missing?

Do you have an #endif in RobotConfig.h ?  If so, please edit your question to show it

RobotConfig.h needs to include Arduino.h in order to have those constants.


text:
Humidity sensor for wet environment
I've had a bit of experience with DHT11/DHT22 sensors in a greenhouse environment, and believe that when they get wet they stop working altogether.
Are there any low cost humidity sensors that I can hook up to an Arduino that don't suffer from this problem, or is there a way to protect these sensors from damage when near water? (I'm not talking about immersing them in water - but do expect condensation to get sprayed with water and/or get condensation on them from time-to-time).
Am I correct that the SHTxx sensors are able to withstand this kind of abuse, and that these sensors are about 5-10 times the cost of DHT sensors?  (I did not want to spend that much, but if it's the only possibility I might consider it).

use two temps to calc humidity (wet bulb and dry bulb). that would let a pair of cheap but tough thermocouples measure humidity. a neodymium magnet on an analog dial can also be used with a hall-effect sensor.

Get a proper enclosure for it.

Adafruit has those sinter metal mesh enclosed humidity sensors: https://www.adafruit.com/product/1298 There is a big difference between (near) 100% humidity and water condensation or sprayed with water. A capacitive soil moisture sensor can be submersed, but it can not measure the air humidity: https://wemakethings.net/chirp/ I suggest to protect humidity sensors with an enclosure as @Gerben wrote (an 'open' enclosure of course) and also use those sinter metal mesh enclosed sensors, and perhaps use a few different types of sensors so hopefully they will not all fail.

This HTU21D has a PTFE filter on top of the sensor. Not sure how good they work for water mists. Try checking the data sheet for it.

@dandavis interesting solution Ive not thought of - thank you. Unfortunately I don't think I have the knowledge to pull that off, particularly in my environment with limited airflow (And I don't want to add a fan)

@gerben - can you shed light on what I am looking for with respect if an enclosure? I have not been able find anything for the DHT, and wonder how fine a mesh I would need and how it will impact accuracy.

2022 UPDATE: After ~5 years since I wrote this answer, I'd like to mention that I don't like BME280 anymore, because of its (1) inaccuracy and (2) requirement to make some non-trivial computations to get real values from sensor's data. If you already got a BME280 and your project requires only approximate values of temperature/humidity, it will work, go ahead. Otherwise, consider using SHT3x!
See also this, this, and especially this one.
Original answer:

I'd consider using Bosch BME280 digital sensor. Although it's a bit expensive, it has very good sensitivity, precision and amazingly fast response for humidity changes (for ex. in my project it detects dry human hand lying in 2" away within a 1-2 seconds).
So its features make possible to put it into an enclosure to avoid direct water contact with water spays and it'll still be very responsive for greenhouse needs, I suppose.
Datasheet warns:

Liquids shall not come into direct contact with the device.

Also, I'd use electronic-friendly protective acrylic lacquer (Plasticote 70 for instance) and put two layers to sensor's PCB, avoiding small black tiny vent hole on the chip itself:

UPD: Here's DHT11 with cover removed:

It might be the easiest and cheapest solution to cover all internal contacts and IC (avoiding humidity sensor's stripes) of DHT11 with Plasticote 70.


text:
Arduino Esplora
So I'm trying to turn my Arduino Esplora into a controller, and my first step is to understand how the controller works. I've copied and pasted this code into the Arduino 1.8.2 IDE.
Esplora.writeRGB(255, 255, 255); // sets red, green and blue all to full brightness

But I get an error saying,
exit status 1
'Esplora' does not name a type
Please explain why it's doing this.

Please edit your question to include a Minimal, Complete, and Verifiable example of code, not just a snippet.   Make sure all the library names are shown, all the variable declarations, and all the function definitions – so people don't have to waste time guessing what you did or what you meant.  Also make it verifiable, ie so it can be compiled and tested, allowing other people to test their theories about the problem.

Please also take the tour at http://arduino.stackexchange.com/Tour to get the most out of this site.

You probably forgot:

To include Esplora.h in your sketch.
To select "Esplora" for the board.


text:
Control a 5 volt water pump with an Arduino
I want to control (only on/off) a small water pump (5 V, 200 mA max.) with my Arduino.
I read something about NPN transistor, because the output pins of the Arduino can't supply enough current to the pump. However, I don't know how to choose the right transistor and how to connect it with my Arduino and my water pump.

i would use an n-channel logic-level mosfet; 1w is going to be pushing it for signal BJTs.

@dandavis: Note that 1 W is the power of the load. The switching transistor is not going to dissipate anywhere near that power.

@EdgarBonet: at least 0.6/5th of it will, and that can get little TO92s quite hot...

@dandavis: What does “0.6/5th” mean?

(0.6v / 5v) * 1w = 120mw to dissipate. that's actually probably fine now that i run the math. toasty, but not pushing it. cheers

To use an NPN, connect a power rail of 5V to the pump's positive terminal, and from its negative terminal wire it to the transistor's collector pin. Wire emitter to GND, and place a >=220 ohms resistor between your arduino control pin and the transistor base.
If instead using an N-channel MOSFET, wire load to drain, source to GND, and use a 4K7 pull-down on gate.
Also add a diode, with its anode at the pump's negative terminal, and cathode (white ring) at the positive terminal.

why do you need a resistor on the mosfet's gate? The MCU grounds the pin when deactivated, so is there an advantage to using an external resistor?

@dandavis yes, there is an advantage in that. The switching works best when the MOSFET is absolutely OFF when not absolutely ON. A transient could turn the MOSFET on, or the gate may not discharge quickly enough to allow for fast switching. I had problems with the latter, even on small MOSFETs, like 2N7000.

@dandavis No. The signal from the MCU would just go directly to ground, and the gate would never be charged.

Connect the output from the MCU directly to the gate. Connect the gate to a 4K7 resistor. Connect the other side of the resistor to ground. Optionally, if the gate has enough capacitance to surge the output, add a 220 ohms resistor in series from MCU output to gate.

@dandavis Why are your replies deleted?

i don't want to detract from the answer. was hoping you would edit... i thought you had meant to connect the gate via a resistor to the mcu...

I would only do this for large power MOSFETs to prevent surging. Regardless, it seems OP has flown away.

@dandavis: The pulldown on the MOSFET gate ensures it will be off even before your sketch starts, while the Arduino is running the bootloader. Otherwise it would float, as the Arduino pins are in the high-impedance state until you issue pinMode(pin, OUTPUT).


text:
Arduino Uno alarm interrupt
I am trying to create a temperature-humidity monitor using Arduino and I want to power it using a battery. So, power efficiency is of interest. I am trying to put the Arduino to sleep for x-time (10sec for testing now). I am using a DS3231 alarm as an interrupt on pin 2 to wake-up. I am using the tutorial here along with its associated RTClibExtended library. Here is the code I am using:
#include "DHT.h"
#include <RTClibExtended.h>
#include <Wire.h>
#include <LowPower.h>
#include <stdlib.h>
#include <avr/interrupt.h>      // library for interrupts handling
#include <avr/sleep.h>          // library for sleep
#include <avr/power.h>          // library for power control

#define DHTPIN 7     // what pin we're connected to
#define DHTTYPE DHT22   // DHT 22  (AM2302)
#define wakePin 2    //use interrupt 0 (pin 2) and run function wakeUp when pin 2 gets LOW

RTC_DS3231 rtc;
char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
int interval_sec=10; //An alarm every 10 sec
DHT dht(DHTPIN, DHTTYPE);

void setup () {

  Serial.begin(9600);

  delay(3000); // wait for console opening

  /**RTC**/
  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }
  rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));

  /**INTERRUPT**/
  //Set pin D2 as INPUT for accepting the interrupt signal from DS3231
  pinMode(wakePin, INPUT);
  Wire.begin();
  //clear any pending alarms
  rtc.armAlarm(1, false);
  rtc.clearAlarm(1);
  rtc.alarmInterrupt(1, false);
  rtc.armAlarm(2, false);
  rtc.clearAlarm(2);
  rtc.alarmInterrupt(2, false);

  //Set SQW pin to OFF (in my case it was set by default to 1Hz)
  //The output of the DS3231 INT pin is connected to this pin
  //It must be connected to arduino D2 pin for wake-up
  rtc.writeSqwPinMode(DS3231_OFF);

  Serial.println("Initialisation complete.");
  delay(100); //Allow for serial print to complete.
}

void loop () {
    DateTime now = rtc.now();

    Serial.print(now.year(), DEC);
    Serial.print('/');
    Serial.print(now.month(), DEC);
    Serial.print('/');
    Serial.print(now.day(), DEC);
    Serial.print(" (");
    Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
    Serial.print(") ");
    Serial.print(now.hour(), DEC);
    Serial.print(':');
    Serial.print(now.minute(), DEC);
    Serial.print(':');
    Serial.print(now.second(), DEC);
    Serial.println();

    /**Temperature and Humidity**/
    // Reading temperature or humidity takes about 250 milliseconds!
    // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
    float h = dht.readHumidity();
    // Read temperature as Celsius
    float t = dht.readTemperature();
    // Read temperature as Fahrenheit
    //float f = dht.readTemperature(true);

    // Check if any reads failed and exit early (to try again).
    //if (isnan(h) || isnan(t) || isnan(f)) {
    if (isnan(h) || isnan(t)) {
      Serial.println("Failed to read from DHT sensor!");
      return;
    }

    Serial.print("Humidity: ");
    Serial.print(h);
    Serial.print(" %\t");
    Serial.print("Temperature: ");
    Serial.print(t);
    Serial.println(" *C\t");

    delay(3000); // wait for console

    /**INTURRUPT**/
    DateTime nextAlarm = now + TimeSpan(0, 0, 0, 10);
    Serial.print("Alarm at:");
    Serial.println(nextAlarm.hour());
    Serial.println(nextAlarm.minute());
    Serial.println(nextAlarm.second());
    rtc.setAlarm(ALM1_MATCH_HOURS, nextAlarm.minute(), nextAlarm.hour(), nextAlarm.second());   //set your wake-up time here
    rtc.alarmInterrupt(1, true);
    delay(3000); // wait for console
    attachInterrupt(0, wakeUp, LOW);       //use interrupt 0 (pin 2) and run function wakeUp when pin 2 gets LOW
    LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF);   //arduino enters sleep mode here
    detachInterrupt(0);                                    //execution resumes from here after wake-up
    //When exiting the sleep mode we clear the alarm
    rtc.armAlarm(1, false);
    rtc.clearAlarm(1);
    rtc.alarmInterrupt(1, false);

    Serial.println();
    delay(3000);
}

void wakeUp()        // here the interrupt is handled after wakeup
{
}

The Arduino is going to sleep as expected, but not waking up. Where am I going wrong?
Here is the output:

Initialisation complete. 2017/6/7 (Wednesday) 12:42:49 Humidity: 36.90
  % Temperature: 25.60 *C
  Alarm at:12
  42
  59

After trying for a few hours, I was able to figure it out.
The change required is:
rtc.setAlarm(ALM1_MATCH_HOURS, nextAlarm.second(), nextAlarm.minute(), nextAlarm.hour (), 1);   //set wake-up time here

So, in the original code, the order of arguments as well as the number of arguments passed to rtc.setAlarm() was wrong. Even though we are not interested in the "day" part (last argument) for setting the alarm, it requires a value. Using ALM1_MATCH_HOURS ensures that we match the alarm time to seconds, minutes, and hours ignoring the day part.
Improvement
Instead of hardcoding the alarm interval, the global variable called interval_sec can be set at the top and used to set the alarm time:
DateTime nextAlarm = now + TimeSpan(0, 0, 0, interval_sec);

In RTClibExtended.h it is important to always include all arguments: seconds, minutes, hours, daydate. If 0 value is used then this means "always" for that argument.
Example:
RTC.setAlarm(ALM1_MATCH_SECONDS, 30, 00, 0, 0); // activate every minute at 30 seconds
RTC.setAlarm(ALM2_MATCH_MINUTES, 0, 01, 0, 0); // activate every hour at 01 minutes
RTC.setAlarm(ALM1_MATCH_HOURS, 33, 18, 0); // activate every day at 18:33

(note: this example is copied from RTClibExtended.h examples, author does not adhere to his own rule to include seconds, even in ALM2. But it works).
Any suggestions or corrections are welcomed!


text:
ESP8266 proper power circuit for avoid reset issue
I am using an ESP8266 in a project which will be on for at least 18 hours a day. I'm using an Arduino 3.3V power supply to feed the ESP8266.
The issue I'm facing is a reset issue. It sometimes disconnects from the hotspot automatically.  I have heard this could be because the ESP8266 draws more power than the Arduino's regulator is able to supply.
I want to know what will be the proper circuit to power the ESP8266.
I know I have to use an AMS1117 regulator, but I also know I have to use capacitors too. How would I configure the AMS1117 with capacitors to properly power an ESP8266?

A simpler solution for those who don't want to deal with wiring up a regulator is to get the "nodemcu" style of ESP8266 module having its own regulator.  These typically also have a USB serial interface, though determine which chip is used and its driver situation on your computer's operating system before purchasing one.

The ESP8266 power problem keeps coming up, so we need a canonical question to close the re-asks as duplicates against.  I think post-edits this could be a candidate, but perhaps there are other choices.

You don't "need" an AMS1117 regulator. You need a power source that can supply enough current.  One example is an AMS1117-33, although it's not a great one as far as efficiency goes (though it is simple).
The basic circuit is to have a 10µF capacitor on both the input and output of the regulator - that should be enough for most uses.

simulate this circuit – Schematic created using CircuitLab
Powered from more than around 5V the AMS1117-33 would need some heatsinking.  You can also add some smaller (100nF) capacitors in parallel with the 10µF ones if you want to improve high frequency response.
You can pick modules up with this circuit on from eBay for a dollar.
A better power source would be a "buck" switching regulator. These are far more efficient and generate much less heat.  It's harder to search for these on eBay since all the AMS1117-33 modules seem to be labelled erroneously as "buck" regulators (which they so are not!), so be careful when looking around. A true "buck" regulator will have an inductor on it. Here's one example.

Add " -ams1117" to your search query in eBay, to remove listings that has AMS1117 in the title.

@Gerben I did - that's how I got the example one I listed. Still not foolproof though.

The spec says that an AMS1117-3.3 can deliver 1A, but realistically that only works if you run it off 5V. The ESP draws ~400mA when it is transmitting, and at 12V the AMS is dissipating 8.7V x 0.4A =  3.48W. That makes it kinda hot, and it tends to cut out.  A buck regulator, even a tiny one using MP2307, is a much better bet. set the voltage first before connecting to the ESP!

ESP8266 draws ~170mA when transmitting


text:
ESP8266, prints ready at start but no response to AT command
I have been using ESP8266 wifi module with Arduino as FTDI. The power for ESP8266 comes from LM317 5V - 3.3v regulated supply(I am sure 5V is powerful enough to give upto 1A of current).
The RX of ESP8266 is connected to RX of Arduino via a voltage divider to ensure 3.3V logic level. But still, I am not getting any response to AT command, though my laptop and phone wifi have successfully connected to AI-Thinker... SSID(which is an open hotspot from ESP8266).
I am also having some garbage values on the serial port immediately after I turn on the power supply to ESP8266. I have tested all baud rates available in Arduino IDE v1.0.5 with no results.
The resistor values for lm317 are R1 = 125 Ohm, R2 = 225 Ohm with which I am getting around 3.2 Volts.
The connections are as follows:-

-----Arduino UNO-----
RESET ------------ GND

Arduino UNO ----- ESP8266
TX ------------------- TX
RX ---5V to 3.3v--- RX
GND ----------------- GND

ESP8266 --------- LM317(5V to 3.3V)
VCC --------------- 3.3V
GND --------------- GND
CH_PD ------------ 3.3V

EDIT - 1: I have bought a new ESP8266, and even it doesn't responds to any AT commands, thought there is some difference in the previous ESP8266 output and this new ESP8266 output.
The difference is a sort of good news to me, it sends ready after sending some garbage at 115200 baud on boot which never happened with previous one(ESP8266).
Is anyone having some clue why there is no response to AT commands?
May it be a issue with TX line?

EDIT - 2: I have also used another Arduino with same connections doubting the TX pin on Arduino, but with same luck, bad luck. Still, nothing got changed.

EDIT - 3: I am shifting 5v to 3.3v by using three 100 ohm resistors.

Comments are not for extended discussion; this conversation has been moved to chat.

I think, the blue led should blink even at wrong bauds. Correct me If I am wrong.

blue led blinks only when sending some data, not receiving.

The problem was with my logic level shifting.
Any Arduino pin can provide only upto 40mA of current. What current you are trying to draw is:-

5 Volts / 100 Ohm = 50mA

which is clearly more current than what an UNO can provide. Your ESP also adds up its own resistance meaning even more current draw requirement from RX pin.
Instead of using three 100 ohm resistors, use some high valued resistors such as 1K ohm resistors(or even higher value) in the voltage divider circuit so that no much current pass through it, consuming less power affordable by the Arduino RX pin.
Remark: If you don't know how logic level shifting works with voltage divider circuit, click here.

Connect TX of arduino to esp8266 RX, and arduino RX to esp8266 TX.
See this link for more info.

Comments are not for extended discussion; this conversation has been moved to chat.

The rather extensive set of comments (now moved to chat) should be added to the answer, if indeed they help answer the question. This is not a forum-type situation here on Stack Exchange.

First of all your connectons are wrong:
-----Arduino UNO-----
RESET ------------ GND (Why)
Arduino UNO ----- ESP8266
TX ------------------- RX
RX ------------------- TX
(RX is the recieving end, TX is the transmitting end, one should allways connect a transmitter to a reciever both directions, never a transmitter to transmitter or reciever to reciever, and use a logic level shifter)
GND ----------------- GND
ESP8266 --------- LM317(5V to 3.3V) (only for Vcc)
VCC --------------- 3.3V
GND --------------- GND
CH_PD ------------ 3.3V
In these cases you should use a logic level shifter like 74LVC245 or sparkfun level converter and not a voltage regulator. If you must use lm317 connect it correctly, diodes, capacitors and an adjusting potmeter or resistor. Typical application found in the datasheet on p. 10
baudrate should be 57600 on the esp8266.
glhf :)

When we are doing TX-RX, RX-TX, we are trying to communicate between Arduino MCU and ESP8266, that's why these pins are labelled so. But, in case, we are bypassing the Arduino MCU, we do it this way TX-TX, RX-RX. By bypassing Arduino MCU, our TX and RX on arduino gets reversed i.e. they become RX and TX of computer(if we attach a computer with USB cable)with which we can communicate between a computer and ESP8266 bypassing Arduino

Second thing, I think the ESP8266 is getting enough power as it is showing as wifi hotspot in my laptop and phone as well as sending some bits and then ready in serial console, so maybe nothing to do with LM317, i think.

Third thing, Arduino: RESET --- GND because that's a way to bypass Arduino MCU, we could have done physically removing its ATMEGA328p from the board but that's not a elegant way of doing this.

Which version of arduino IDE are you using? I use 1.6.12 and works, it does not work for 1.8 versions.
Also ensure 3.3v power input for the esp8266 separately from arduino power. I suggest using a PC power supply (color orange is 3.3v).

The issue you are running into is that the Arduino Uno cannot source enough current at 3.3V for esp8266 operation. I had to use a separate power supply with grounds tied together and then my esp8266 responded to AT commands.
Summary:

I use the Arduino Uno as the serial bridge (RESET tied to GND)

an external power supply for the esp8266

and a bidirectional level shifter for 3.3V to 5V TX/RX data paths

Connected CHPD of esp8266 to GND, waited 5 sec then reconnected to 3.4V

Arduino IDE > Tools> Serial Monitor > Both NL&CR > 115200 Baud Rate

and I just connect the Uno to esp-01 directly and it works. but it depends on version of Uno. original Rev 3 gives 150 mA on 3.3 V pins, which is enough for esp-01. there is no need to level shift 3.3 to 5 V and the esp8266 has no problem with 5 V logic level with almost no current flow

@Juraj I’ve read in multiple locations the ESP8266 operating voltage is 3.3V. Also, I level shift because the TX/RX of the Arduino Uno expects 5V whereas the ESP8266 expects 3.3V
https://cdn-shop.adafruit.com/product-files/2471/0A-ESP8266__Datasheet__EN_v4.3.pdf

First of all do not use any resistors(try it) for RX pin. Connect it directly.
Second connect RST pin of ESP8266 to 3.3V power supply.
And also try to use arduino directly with esp8266 once. Do not use lm317 or any other separate power supply. Use 3.3 volt power supply of arduino.
And i dont know why you have connected RESET pin of Arduino to GND. Please answer me that.

I have already tried to connect arduino RX to ESP8266 RX without resistors(voltage divider circuit), but it didn't worked either.
Second, I have not tried RST pin of ESP8266 to 3.3V, I am going to try it now and report back soon.

I also used arduino directly without lm317, it does not shows any hotspot until an external power supply to Arduino is given. I gave arduino 5V external supply, and the hotspot showed again, but this time also, no response to AT command, but garbage on starting.

why are you making things complicated. Connect 3.3V of arduino to esp8266 Vcc port. And you obviously have to provide external power supply to arduino. Connect it to PC using USB Cable. And Connect RST pin to 3.3V.  Use a breadboard.

I have used 3.3V of arduino to esp8266 directly. Given, external power supply to arduino, connected arduino to pc and connected RST pin of ESP8266 to 3.3V. I am still geting garbage at serial on starting and no AT response.

@SONIAJOHNSON You need to power the ESP8266 separately from the Arduino - it required a higher current than the Arduino 3V3 pin is capable of supplying. Also, ESP8266 RX pin does seem to be voltage sensitive, requiring a voltage divider or converter to reduce voltage to 3V3.


text:
Optimizing Arduino File Selection from SD card
the following code will display the files on an SD card in an Arduino and allow the user to open a file of their choosing. Here's the code with a walkthrough of what it does.
In the Init state, I call the libraries needed to run the code
// Example use of lfnOpenNext and open by index.
#include<SPI.h>
#include "SdFat.h"
#include "FreeStack.h"

// SD card chip select pin.
const uint8_t SD_CS_PIN = 10;

SdFat sd;
SdFile dirFile;
SdFile file;

// Number of files found.
uint16_t numberOfFiles = 0;

This is the area of the real problem, calling SdFile parIndex[50]; Takes a large amount of dynamic memory. For number of files on an SD card, this is a pretty small number, so I need to get at something better
// Position of file's directory entry.
uint16_t dirIndex[50];
SdFile parIndex[50];
//------------------------------------------------------------------------------

In the Setup phase, we make sure the SD card is plugged in and, if it is, we call the function to give the files on the SD card.
void setup()
{
  Serial.begin(38400);
  while (!Serial) {}

  // Initialize at the highest speed supported by the board that is
  // not over 50 MHz. Try a lower speed if SPI errors occur.
  if (!sd.begin(SD_CS_PIN, SD_SCK_MHZ(50)))
  {
    sd.initErrorHalt();
  }
  if (dirFile.open("/", O_READ))
  {
  printDirectory(dirFile, 0);
  }
}

The printDirectory function (This is the part most open to edits, if there's any way to improve performance here, please let me know as well).
void printDirectory (SdFile CFile, int numTabs)
{
  SdFile file;
  while (file.openNext(&CFile, O_READ))
  {
  if (file.isHidden()||false)
    {
      //file hidden, skip
    }
    else
    {
      for (uint8_t i = 0; i < numTabs; i++)
      {
        //create tabs for spacing
        Serial.print('\t');
      }
      if (file.isSubDir())
      {
        SdFile SubDirFile;
        printDirectory(SubDirFile, numTabs+1);
      }
      else
      {
        // Save dirIndex of file in directory.
        dirIndex[numberOfFiles] = file.dirIndex();
        parIndex[numberOfFiles] = CFile;
        // Print the file number and name.
        Serial.print(numberOfFiles);
        Serial.write(' ');
        file.printName(&Serial);
        Serial.println();
        numberOfFiles++;
      }
    }
  file.close();
  }
}

This is the user interface portion, it was largely slapped together as a proof of concept for the above code. As it's written, the code only accepts index values 0-9, but my actual program could call any index value.
void loop() {
  int c;

  // Read any existing Serial data.
  do {
    delay(10);
  } while (Serial.available() && Serial.read() >= 0);
  Serial.print(F("\r\nEnter File Number: "));

  while (!Serial.available()) {
    SysCall::yield();
  }
  c = Serial.read();
  uint8_t i = c - '0';
  if (!isdigit(c) || i >= numberOfFiles) {
    Serial.println(F("Invald number"));
    return;
  }

After making sure that the input value exists, it calls up the arrays that contain the parent's directory SdFile object and the index of the desired file.
  Serial.println(i);
  if (!file.open(&parIndex[i], dirIndex[i], O_READ)) {
    sd.errorHalt(F("open"));
  }
  Serial.println();

  char last = 0;

  // Copy up to 500 characters to Serial.
  for (int k = 0; k < 500 && (c = file.read()) > 0; k++)  {
    Serial.write(last = (char)c);
  }
  // Add new line if missing from last line.
  if (last != '\n') {
    Serial.println();
  }
  file.close();
  Serial.flush();
  delay(100);
}

The main issue I have is that SdFile parIndex[50]; uses 22% of my dynamic memory vs the rest of the program using 12%. How can I rewrite my code to not require keeping the SDFile objects in dynamic memory?
For anyone unfamiliar, documentation for the SdFat library can be downloaded from that link.

Edit:
In terms of use: The SD files are .csv files that store speed and time parameters for running a motor test. Each test lasts for a few minutes to hours.

Do not store the file object. You can find the file again (albeit inefficiently) from its number by starting at the root and doing the same recursive traversal you did in printDirectory().

You have several possibilities:

Do not store the names of all files, but use the index and iterate through all files again. Disadvantage: this takes a lot of time (every time you need the file name)
Add SRAM to the Arduino (e.g. 23LC1024, 23K256), depending on your memory needs. Disadvantage: you have to 'manage' this memory yourself.
If you know something about the file names, you might generate the name. Probably it's not the case, but just to add another option. E.g. if you know that file nr 10 will always be called 'File10.txt', you can 'generate' the name.
I don't know exactly how you want to use the file names, but you might store only the latest x files used, to prevent having to iterate again reading the SD card. Of course, this only helps if there is a high chance the last x files are used more than the non recent files.

Update:
If you need to read the files while leaving the Arduino unblocked, you have to incorporate it in your loop, but don't read all the files in a loop. Something in pseudo code like:
bool readingSd = false; // True between reading first and last file
uint16_t lastTimeRead = 0; // Last time read
void loop()
{
   // Check if file read needed (initial or one hour past, I don't take
   // overflow into account
   if (lastTimeRead == 0 || (lastTimeRead + 1000 * 60 < millis())
   {
      checkReadFile();
   }

   // Perform your normal code... this will run between processing/reading
   // one file/dir.
   ...
}

void ProcessSingleFile()
{
   readingSd = true; // Within reading first/last file
   "read/process ONE file or dir (without containing files)";
   if ("last file read")
   {
       readingSd = false;
       lastTimeRead = millis(); // Move to top to prevent reading time
         // between first/last to take into account
   }
}

Given these options, I think I'd like to use the index and iterate through the files again. I'll only pull a new file from an SD card once every hour or so so as long as it appears to the user to be fairly quick, this sounds like a good way to go for me.

Also ... of course when the SD card content changes meanwhile it will take the newest file names. If really needed, you should not block the sketch while reading, but maybe this is not needed for you.

Ahh! I hadn't thought of that, for this function I think I'll be ok since writing to a file will be rare. Out of curiosity, is there a good way to do the equivalent of a while loop without blocking the sketch? I'm decently new to programming at this level XD

About blocking, that might get tricky. I will mention it (in a rough form) in my answer

Thanks for the edit. I think I'll look to implement something akin to it depending on how long it takes to read the SD card in full (I don't see there ever being more than 1GB of files so it may be alright to have it blocked during reading)

It's much simpler with blocking ... also 1 GB does not matter (unless you really want to READ the file content), but the AMOUNT of files do matter for iterating through them.
(Please acknowledge (make green) my answer if you think it has solved your question).