text:
Switch case does not work after booting system
int value1;
int value2;
int runs1 = 0;
int runs2 = 0;

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x3F, 16, 2);
int inPin = 6;
int val = 0;
int push_count = 0;
int buttonState = 0;
unsigned long previousMillis = 0;
const long interval = 1800000;
int currentTime;

void setup() {
  Serial.begin(9600);
  lcd.begin();
  pinMode(inPin, INPUT);
}

void loop() {

  unsigned long currentMillis = millis();
  currentTime = 30-(currentMillis - previousMillis)/60000;
  if (currentMillis - previousMillis >= interval || previousMillis == 0) {
    previousMillis = currentMillis;

  measure();
  }

  buttons();
}

void measure() {
 value1=300;
 value2=300;

  if (value1 <= 650)
{
   lcd.setCursor(8,0);
   lcd.print("Plant");
   lcd.setCursor(10,1);
   lcd.print("1");
   delay(2000);

}
else
{
  lcd.clear();
  lcd.print("Pump 1 turned ON");
  lcd.setCursor(0,1);
  lcd.print("Water for 40 sec");
  runs1++; // increment the number of times pump 1 has run

}

  if (value2 <= 550)
{
   lcd.setCursor(8,0);
   lcd.print("Plant");
   lcd.setCursor(10,1);
   lcd.print("2");
   delay(2000);
   Serial. print("Pump 2 OK");
}
else
{
  lcd.clear();
  lcd.print("Pump 2 turned ON");
  lcd.setCursor(0,1);
  lcd.print("Water for 40 sec");
  runs2++; // increment the number of times pump 2 has run
  Serial. print("Pump 2");
}
  }

void buttons() {
  val = digitalRead(inPin);

  if (val != buttonState && val == HIGH){
    push_count++;
  }
      else {
      // do nothing
    }

  buttonState = val;
  switch (push_count) {
    case 0:
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("Sensor 1 reads");
      lcd.setCursor(0,1);
      lcd.print(value1);
      delay(20);
      Serial. print("Case 0");
      push_count++;
      break;
    case 1:
      Serial. print("Case 1");
      break;
    case 2:
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("Sensor 2 reads");
      lcd.setCursor(0,1);
      lcd.print(value2);
      delay(10);
      push_count++;
      break;
    case 3:
      break;
    case 4:
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("Pump 1 ran");
      lcd.setCursor(0,1);
      lcd.print(runs1);
      lcd.setCursor(5,1);
      lcd.print(" times");
      delay(10);
      push_count++;
      break;
    case 5:
      break;
    case 6:
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("Pump 2 ran");
      lcd.setCursor(0,1);
      lcd.print(runs2);
      lcd.setCursor(5,1);;
      lcd.print(" times");
      delay(10);
      push_count++;
      break;
    case 7:
      break;
    case 8:
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("Next cycle in");
      lcd.setCursor(0,1);
      lcd.print(currentTime);
      lcd.setCursor(5,1);
      lcd.print(" Minutes");
      delay(10);
      push_count++;
      break;
    case 9:
      break;
    default:
      push_count=0;
  }
}

When I boot the system (standalone atmega328p circuit) the connected LCD either shows

Plant
2

originating from
   lcd.setCursor(8,0);
   lcd.print("Plant");
   lcd.setCursor(10,1);
   lcd.print("2");
   delay(2000);
   Serial. print("Pump 2 OK");

or in my real code (where value1 and value2 are actually measured)

Pump 2 turned ON
Water for 40 sec

originating from
  lcd.clear();
  lcd.print("Pump 2 turned ON");
  lcd.setCursor(0,1);
  lcd.print("Water for 40 sec");
  runs2++; // increment the number of times pump 2 has run
  Serial. print("Pump 2");

after I use the button to cycle through all the cases everything works fine. On the next button press I get to case 2 (-> 3).
After a full cycle case 0 (-> 1) gets displayed correctly.
The above MCVE runs perfectly on my breadboard setup, but not in the real setup.
Here's the schematic of the real setup.
So somewhere in the real setup has to be something that my code does not handle properly. The breadboard setup is minimal, just all GND and VCC connections, a 16 Mhz crystal with 22 pF caps.

Consider writing an MCVE

@DmitryGrigoryev I wasn't sure whether I should do that, I didn't want to delete the faulty part of the code by accident. See my edit, I guess I have to do some further testing tonight. I use pull down resistors in my atmega setup for the button.

The "V" part of MCVE means Verifiable – Test the code you're about to provide to make sure it reproduces the problem

@josecanuc For some reason I can't reproduce the error on the arduino or the breadboard. Only in my real system. I know that this makes finding the root cause for people here almost impossible.

Intermittent errors are likely to be undefined values. That could be software uninitialized variables, or hardware: floating pins. You may also be dealing with bouncing button contacts, as noted in one answer.

When I boot the system (standalone atmega328p circuit) the connected LCD either shows .... you do not say what it shows, i am pretty sure that it does not list the code

Could the downvoter elaborate what I could improve? @jsotola Of course it doesn't list the code, I quoted the sections so you can easily see where the output comes from. Updated!

Try posting the results of all those serial prints.

@idkfa, what you think that the code tell it to display is not necessarily the same as what is actually displayed ... you updated the question with the "displayed text" .... i removed the downvote

int buttonState = 0;

So buttonState is initially zero (LOW).
  val = digitalRead(inPin);

  if (val != buttonState && val == HIGH){
    push_count++;
  }

Since you have an external pull-up on inPin it will read HIGH initially. Thus push_count will be incremented immediately.
  switch (push_count) {
    case 0:
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("Sensor 1 reads");
      lcd.setCursor(0,1);
      lcd.print(value1);
      delay(20);
      Serial. print("Case 0");
      push_count++;
      break;
    case 1:
      Serial. print("Case 1");
      break;

Therefore you execute case 1 initially.

Also, I don't see how this works:
 value1=300;
 value2=300;

  if (value1 <= 650)
{
   lcd.setCursor(8,0);
   lcd.print("Plant");
   lcd.setCursor(10,1);
   lcd.print("1");immediately
   delay(2000);

}
else
{
  lcd.clear();
  lcd.print("Pump 1 turned ON");
  lcd.setCursor(0,1);
  lcd.print("Water for 40 sec");
  runs1++; // increment the number of times pump 1 has run

}

  if (value2 <= 550)
{
   lcd.setCursor(8,0);
   lcd.print("Plant");
   lcd.setCursor(10,1);
   lcd.print("2");
   delay(2000);
   Serial. print("Pump 2 OK");
}
else
{
  lcd.clear();
  lcd.print("Pump 2 turned ON");
  lcd.setCursor(0,1);
  lcd.print("Water for 40 sec");
  runs2++; // increment the number of times pump 2 has run
  Serial. print("Pump 2");
}

Since you are doing both if tests it seems likely (indeed certain) that you will display "Plant 1" and then immediately* overwrite it with "Plant 2" so quickly that you wouldn't notice it.
* apart from the 2-second delay of course. :)

Luckily this project is one of my first so everything is still in prototype stage, i.e. a lot of jumper cables so this was an easy fix. So actually my code progressed the cases on release, not on press. To answer the second part of your answer ( ;) ) this is intended. It's just a visualization if you happen to watch the display during measurement. It will display "reading sensors" before. I also got a boot animation which I probably won't ever see again once the system doesn't need changes anymore.

Personally I don't like the way you handle the "state machine", and I'd implement it in what I perceive is a more robust way (I may be wrong, though).
Moreover if you have a button please add a debounce; I usually do this with the Bounce2 library (or alternatives I code which are modified versions of that library). So... Let's change the things in the way I prefer.
// Include the library
#include <Bounce2.h>

// declare a bounce object
Bounce buttonDebounce = Bounce();

//in the setup:
pinMode(IN_PIN, INPUT); // or INPUT_PULLUP?
buttonDebounce.attach(IN_PIN);
buttonDebounce.interval(5);

//in the loop:
buttonDebounce.update();

Then in the loop you can use the buttonDebounce.rose() function or buttonDebounce.fell() to detect the button presses.
Now, for the state machine. You have four meaningful states (let's call them DISPLAY_1 to 4). It's better to give them more meaningful names. And let's add an invalid state. I usually prefer to use const bytes to force the size rather than enums or defines, but.. whatever ;)
So outside loop or setup declare the values and the state variable:
const byte SM_ErrorState = 0;
const byte SM_Display_1 = 1;
const byte SM_Display_2 = 2;
const byte SM_Display_3 = 3;
const byte SM_Display_4 = 4;
const byte SM_Display_5 = 5;
byte SM_currentState;

Now, the function buttons can be implemented in the classical way I learned to implement state machines, which is first make a switch case to test whether you have to advance, then advance to the next state if necessary and perform the entry action.
void buttons()
{
    buttonDebounce.update();

    nextState = SM_currentState;

    // Check if a new state is requested
    switch (SM_currentState)
    {
    case SM_Display_1:
        if (buttonDebounce.rose())
            nextState = SM_Display_2;
        break;
    case SM_Display_2:
        if (buttonDebounce.rose())
            nextState = SM_Display_3;
        break;
    case SM_Display_3:
        if (buttonDebounce.rose())
            nextState = SM_Display_4;
        break;
    case SM_Display_4:
        if (buttonDebounce.rose())
            nextState = SM_Display_5;
        break;
    case SM_Display_5:
        if (buttonDebounce.rose())
            nextState = SM_Display_1;
        break;
    default:
        nextState = SM_Display_1;
        break;
    }

    // If an advancement is requested, advance and then perform the entry action
    if (nextState != SM_currentState)
    {
        SM_currentState = nextState;
        switch (SM_currentState)
        {
        case SM_Display_1:
            lcd.clear();
            lcd.setCursor(0,0);
            lcd.print("Sensor 1 reads");
            lcd.setCursor(0,1);
            lcd.print(value1);
            delay(20);
            Serial. print("Case 0");
            break;
        case SM_Display_2:
            lcd.clear();
            lcd.setCursor(0,0);
            lcd.print("Sensor 2 reads");
            lcd.setCursor(0,1);
            lcd.print(value2);
            delay(10);
            break;
        case SM_Display_3:
            lcd.clear();
            lcd.setCursor(0,0);
            lcd.print("Pump 1 ran");
            lcd.setCursor(0,1);
            lcd.setCursor(5,1);
            lcd.print(runs1);
            lcd.print(" times");
            delay(10);
            break;
        case SM_Display_4:
            lcd.clear();
            lcd.setCursor(0,0);
            lcd.print("Pump 2 ran");
            lcd.setCursor(0,1);
            lcd.print(runs2);
            lcd.setCursor(5,1);;
            lcd.print(" times");
            delay(10);
            break;
        case SM_Display_5:
            lcd.clear();
            lcd.setCursor(0,0);
            lcd.print("Next cycle in");
            lcd.setCursor(0,1);
            lcd.print(currentTime);
            lcd.setCursor(5,1);
            lcd.print(" Minutes");
            delay(10);
            break;
        default:
            break;
        }
    }
}

Now, the initialization. Remember that I told you to add an error state? This way you can force a state change on initialization by setting the variable to the SM_ErrorState value.
Then, the millis management in the loop. I'd avoid the particular case of the variable equal to 0 to trigger an immediate execution, since this will lead to errors later. Then I also prefer to sum the interval, to avoid having a drift. So I changed your way to another one. I also changed some code for better readability (for instance, letting the "timer" reset every minute rather than every 30 minutes, and changing the defines accordingly).
Here is my complete code; I left out the measure function since it does not impact the other code.
Let me know if this solves your problem. Oh, BTW, UNTESTED CODE, so some bugs may appear...
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Bounce2.h>

LiquidCrystal_I2C lcd(0x3F, 16, 2);

int value1; // I think it is better if these
int value2; // two variables are initialized
int runs1 = 0; // Unsure if this is needed
int runs2 = 0; // Unsure if this is needed
int val = 0; // Unsure if this is needed

int inPin = 6;
unsigned long previousMillis = 0;
const unsigned int millisInOneMinute = 60000U;

byte elapsedMinutes;
const byte intervalMinutes = 30;

Bounce buttonDebounce = Bounce();

void setup() {
    Serial.begin(9600);
    lcd.begin();
    pinMode(inPin, INPUT);
    buttonDebounce.attach(inPin);
    buttonDebounce.interval(5);
    previousMillis = millis();
    elapsedMinutes = intervalMinutes; // Force a new measure
}

void loop() {
    if (((unsigned int)(millis() - previousMillis)) >= millisInOneMinute)
    {
        previousMillis += millisInOneMinute; // Avoid drifting
        elapsedMinutes++;
    }

    if (elapsedMinutes >= intervalMinutes)
    {
        elapsedMinutes = 0;
        measure();
    }

    buttons();
}

void measure() {
    // do your stuff
}

void buttons()
{
    buttonDebounce.update();

    nextState = SM_currentState;

    switch (SM_currentState)
    {
    case SM_Display_1:
        if (buttonDebounce.rose())
            nextState = SM_Display_2;
        break;
    case SM_Display_2:
        if (buttonDebounce.rose())
            nextState = SM_Display_3;
        break;
    case SM_Display_3:
        if (buttonDebounce.rose())
            nextState = SM_Display_4;
        break;
    case SM_Display_4:
        if (buttonDebounce.rose())
            nextState = SM_Display_5;
        break;
    case SM_Display_5:
        if (buttonDebounce.rose())
            nextState = SM_Display_1;
        break;
    default:
        nextState = SM_Display_1;
        break;
    }

    if (nextState != SM_currentState)
    {
        SM_currentState = nextState;
        switch (SM_currentState)
        {
        case SM_Display_1:
            lcd.clear();
            lcd.setCursor(0,0);
            lcd.print("Sensor 1 reads");
            lcd.setCursor(0,1);
            lcd.print(value1);
            delay(20);
            Serial. print("Case 0");
            break;
        case SM_Display_2:
            lcd.clear();
            lcd.setCursor(0,0);
            lcd.print("Sensor 2 reads");
            lcd.setCursor(0,1);
            lcd.print(value2);
            delay(10);
            break;
        case SM_Display_3:
            lcd.clear();
            lcd.setCursor(0,0);
            lcd.print("Pump 1 ran");
            lcd.setCursor(0,1);
            lcd.setCursor(5,1);
            lcd.print(runs1);
            lcd.print(" times");
            delay(10);
            break;
        case SM_Display_4:
            lcd.clear();
            lcd.setCursor(0,0);
            lcd.print("Pump 2 ran");
            lcd.setCursor(0,1);
            lcd.print(runs2);
            lcd.setCursor(5,1);;
            lcd.print(" times");
            delay(10);
            break;
        case SM_Display_5:
            lcd.clear();
            lcd.setCursor(0,0);
            lcd.print("Next cycle in");
            lcd.setCursor(0,1);
            lcd.print(elapsedMinutes);
            lcd.setCursor(5,1);
            lcd.print(" Minutes");
            delay(10);
            break;
        default:
            break;
        }
    }
}

EDIT: Generic implementation of a state machine
Ok, here I post my generic scheme for a state machine. Usually I use the "state-based" state machine, which is actions are linked to states; sometimes I also saw "transition-based" state machines, where actions were linked to transitions, but... Ok, I'm not a real expert, so I don't want to write a lot of (wrong) things.
In this kind of machines, each state can have up to three kind of actions and a check:

actions you perform when you ENTER the state
actions you perform continuously when you are INSIDE the state
actions you perform when you EXIT the state
and of course, you have to CHECK whether you need to make a transition to another state

For instance, when you have in a microwave a state corresponding to the ON state, you have to:

when you ENTER the state, turn on the heater
when you are INSIDE the state, update the timer value
when you are done and you are EXITing the state, turn off the heater
when during the CHECK you see that the timer has expired or the stop button was pressed, you switch to another state

So there are four kind of actions: ENTER, INSIDE, EXIT and CHECK. For linearity I learned that it is much better to write each of them in a separate switch case. This is my usual implementation scheme:
void stateMachine()
{
    byte nextState = currState; // currState of course is defined outside

    switch (currState)
    {
    // Here you have to CHECK, for each state, the conditions
    // needed to switch to another state; if you switch, put
    // the new state in nextState
    }

    if (nextState != currState)
    {
        switch (currState)
        {
        // Perform the EXIT functions for each state
        }

        // Advance to the next state
        currState = nextState;

        switch (currState)
        {
        // Perform the ENTER functions for each state
        }
    }
    else // See note below
    {
        switch (currState)
        {
        // Perform the actions to be performed continuously
        // INSIDE each state
        }
    }
}

NOTE: the else can be omitted or not. If you leave it, in the cycle that you detect the change you do not perform the INSIDE action; if you omit it, the INSIDE action will be performed. This is useful in different cases.
Now, usually (and yours is one of these cases) you only need the CHECK and ENTER sections (if you look at the code, you will see that only these two sections were implemented). Once in a while you will need also the INSIDE section, and once in your life you will also need the EXIT ;) (at least in my experience)

I will report back once I had the time to implement and test the code. Your answer is greatly appreciated. However I have a small note on why I handled the statemachine the way I did: If I see it correctly the selected case runs every loop in your code too. This creates a flickering of the text on the LCD as it gets deleted and rewritten every cycle. That's why I wrote it once, and advanced to the next case where nothing happens.

@idkfa (BTW nice nickname, but I preferred iddqd :P) no, the code is executed just once. I'm adding a quick section at the end of the answer to explain the way I usually implement state machines (it is the way they thought me), but the code here is executed only once..

I finally got around to read through your examples. I learned a lot from it and I must say I definitely understand now why you didn't like my implementation. I also see how this avoids the flickering issue. Thank you very much!

@idkfa I'm glad I could help you :)

You haven't ever set value1 or value2, but your if-else statements depend on them.
Before you can test a variable to have a specific value, you must set the variable at some point prior to using it. In your code, value1 and value2 are declared global, but never initialized and never set, so they are undefined and could have any value in them at the start.

I added the values (and confirmed that it still doesn't work). They got lost during creating the MCVE from my code.

Global variables are set to zero by the compiler.


text:
Adadfruit Trinket software not running on ATtiny85
I have an application that uses a pair of nRF24L01+ as a simple RF link between a camera PC sync output and a set of LED flashes. The important factors are power and low latency - hence the 2.4GHz.
I developed both ends using UNOs and then moved to Trinket 3 V. The system works very well with Trinkets.
My next step was to strip this down further to ATtiny85 at least at the receiver end.
I overcame the programming challenges and a day's worth of board installation in Arduino IDE and can not now program the ATtiny85 as well as the Trinket.
I will share the code lower down, but let me explain the difference in result.
With the Trinket the trigger output from the receiver is a simple pulse the width of the transmitted pulse (as is the goal.
               __________________________________
 _____________|                                  |__________________________
The pulse is anywhere from 5 ms to 50 ms.
On the ATtiny85 the link is clearly operational from transmitter to receiver but the output is ugly. Something like this:
                 _____      _____            _____
________________|     |____|     |__________|     |___________
The pulses appear (not always the same number) for the duration of the transmitted pulse and the interval is variable. The pulses themselves are of 8 MHz duration.
The code:
#include "RF24.h"

// Note: these includes looked necessary when I started but during debugging I
// removed them with not change in functionality - strange!
//#include <Mirf85.h>
//#include <MirfHardwareSpiDriver85.h>
//#include <MirfSpiDriver85.h>
//#include <nRF24L0185.h>
//#include <SPI85.h>

/*    **ATtiny25/45/85 Pin map with CE_PIN 3 and CSN_PIN 4**
      nRF24L01 CE oins is tied high and pin3 is used as the trigger output.

                                   +-\/-+
                     NC      PB5  1|o   |8  Vcc --- nRF24L01  VCC, pin2 --- LED --- 5V
      nRF24L01  CE, pin3 --- PB3  2|    |7  PB2 --- nRF24L01  SCK, pin5
      nRF24L01 CSN, pin4 --- PB4  3|    |6  PB1 --- nRF24L01 MOSI, pin6
      nRF24L01 GND, pin1 --- GND  4|    |5  PB0 --- nRF24L01 MISO, pin7
                                   +----+
*/
*    **Trinket 3V Pin map with CE_PIN 3 and CSN_PIN 4 **
* @code
*                                 + -\ / - +
*                   NC      PB5  1 | o   | 8  Vcc -- - nRF24L01  VCC, pin2 -- - LED -- - 5V
*    nRF24L01  CE, pin3 -- - PB3  2 |    | 7  PB2 -- - nRF24L01  SCK, pin5
*    nRF24L01 CSN, pin4 -- - PB4  3 |    | 6  PB1 -- - nRF24L01 MOSI, pin6
*    nRF24L01 GND, pin1 -- - GND  4 |    | 5  PB0 -- - nRF24L01 MISO, pin7
*                                 +---- +

// (Create an instance of a radio, specifying the CE and CS pins. )
RF24 myRadio (3, 4); // "myRadio" is the identifier you will use in following methods
/*-----( Declare Variables )-----*/
byte addresses[][6] = {"1Node"}; // Create address for 1 pipe.
int dataReceived;  // Data that will be received from the transmitter
int flashPin = 3;
int flashValue = 0;
long flashStartMicros = micros();

void setup()
{
  pinMode (flashPin, OUTPUT);

  myRadio.begin();  // Start up the physical nRF24L01 Radio
  myRadio.setChannel(108);  // Above most Wifi Channels
  // Set the PA Level low to prevent power supply related issues since this is a
  // getting_started sketch, and the likelihood of close proximity of the devices. RF24_PA_MAX is default.
  myRadio.setPALevel(RF24_PA_MIN);
  //  myRadio.setPALevel(RF24_PA_MAX);  // Uncomment for more power

  myRadio.openReadingPipe(1, addresses[0]); // Use the first entry in array 'addresses' (Only 1 right now)
  myRadio.startListening();

  digitalWrite(flashPin, 0);
}//--(end setup )---

void loop()
{
  if ( myRadio.available()) // Check for incoming data from transmitter
  {
    flashStartMicros = micros();
    while (myRadio.available())  // While there is data ready
    {
      myRadio.read( &dataReceived, sizeof(dataReceived) ); // Get the data payload (You must have defined that already!)
    }
    if (dataReceived == 8) {
      flashValue = 1;
      digitalWrite(flashPin, flashValue);
    }
  }
  if ( micros() - flashStartMicros > 1500) {
    flashValue = 0;
    digitalWrite(flashPin, flashValue);
  } //END Radio available
}//--(end main loop )---

Simply - I send a character, received it and set trigger high. Then time out and set it low. There is only one statement setting pin 3 (flashPin) low.
I have spent 2 days trying to find the difference.

The flash pin is the same as the CE pin?

CE pin is tied high to Vcc and Flash in is set to output. This works on the Trinket.

change the last digitalWrite(flashPin, flashValue); to digitalWrite(flashPin, 1); .... that will tell you if the output is going low because of that line

I changed the line as you suggested and the LED comes on (the pin goes high) and stays on. I put a delay at the end of the setup() to see when it gets set high and it waited low for the delay then went high. It does not react to the pulse of course. Fair suggestion though.

since you posted a waveform, I assume that you have a scope of some kind. .... check all the other pins of the nRF24L01+ .... see if there is a difference between the Trinket and the ATtiny85 ..... could it be the power supply voltage? ... or maybe something to do with the CE pin

I have and I should do that. Thanks for the suggestions. I'll get to that in the morning.

My debugging effort was in an endless DO loop because I was trying to see why the ATtiny was not acting on the received data like the Trinket. Thanks to some simple questions from #jsotola I looked at what the Trinket signals looked like to compare.
Turns out, my transmitted was broken and that both receivers were dealing with the same garbage. Now I do not have a difference between the 2 receivers and I can go back and make the TX do what I need it to do.
“When you eliminate the impossible, whatever remains, however improbable, must be the truth.”

source: Stack Exchange

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

sort: votes


text:
How to work with analog readings using RPi and Firmata?
For context: I'm working on a project where I need to use sensors to figure out the current state of the environment. This process is done using an Arduino UNO and a RPi. The easiest way that I found to perform communication between both boards is by uploading Standard Firmata and reading the code from RPi using Serial communication. I'm using pyfirmata to write the code in Python on the RPI side. Also, the Arduino is powered by the RPi using the USB port.
My problem was: The ADC component in the Arduino uses as the analog reference the 5V provided by the USB. When I tested the integration, I was using my laptop. So, the computer was providing 5V to the Arduino. So far so good. When I integrated the Arduino board to the RPi, I got some problems related to the precision of the sensor. I figured out that the RPi was only giving 4.75 V to the Arduino Board. This was messing with my readings since the ADC was using 4.75V while my code had 5V to compute things. After adjusting the code, everything proceeded as planned. Both 4.75 V and 5 V were hardcoded in my code.
So, these are my questions:

Is there a way to read the Vcc using pyfirmata to figure out the correct voltage without having this hardcoded?
Is there a way to modify the analog reference to use the INTERNAL reference of 1.1V?

About the analog reference, I found this: https://github.com/firmata/arduino/issues/39 . So, pyfirmata implements send_sysex method, I just have to execute these steps, but I still don't know how.

It does not appear that Firmata has proceeded with the ability to change the analog reference source. You referenced one of the issues opened for it, but I don't see anywhere where it committed to the current master branch.
There's no way for an Arduino to read a voltage without some reference, and as you are experiencing, the default reference is Vcc. That means everything must be compared to Vcc, and if you compare Vcc to itself, you will always find out that Vcc is equal to Vcc.
The pull request to implement is here, so you could play around with it yourself.

So, you are saying that even if I use the send_sysex method (which I'm still not sure that can solve my problem), it wouldn't matter since the analog reference modification is not implemented in the current Firmata version?

I'm not an expert on Firmata, but I searched through the source code for the firmata code that would run on an Arduino and no were in there does it implement anything that sets the analog reference.

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

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


text:
For which type of serial communication is Arduino Severino designed?
Arduino has become quite costly where I come from (2/3 of the price of Raspberry PI) so I have created an Arduino Severino clone.
I had used the device with the RS-232 Usb-Serial converter. But after a (long) while, the device stopped working. My friend came up with a point that RS-232 communication ranges between +6 to -6 V (with thresholds at +3 and -3 volts).
So I have tried FT232 which uses 0 to 5 volts instead. I have a little Chinese FTDI chip designed to do that:

However, after connecting it, it behaves unexpectedly. (it had crashed my PC, one of the communication LEDs is on all the time...) I realised that the Arduino board might get broken for a different reason (an accidental short-circuit is very likely).
So for which type of communication is this "Arduino" designed?

Please see my updated answer.

Looking at the schematic of that board it uses a very crude signal inversion for the RS-232.  This allows it to work of a standard RS-232 signal direct from a computer - just.
It's far from ideal and really should use a MAX232 (or similar) chip for the interface.
Your FT232 adaptor should bypass that chunk of the circuit and connect direct to pins 0 and 1 of the Arduino clone.  The DTR pin of the FT232 should connect to the RESET pin of the Arduino clone via a 100nF capacitor to allow the IDE to reset the board to enter the bootloader.  Oh, and of course, connect the ground to your Arduino clone too (something Arduino users often forget).
You can follow the serial breakout board portion of the Arduino breadboard tutorial and apply it to your board.

The arduino you linked to is designed for RS232-level serial signals, which can be guessed from the use of a DB09 connector.
The FT232 print you show is for 5V TTL (or maybe 3.3V 'TTL') signaling. Not compatible with your arduino. (BTW: that chip is not Chinese at all, it is made by www.ftdichip.com IMO they make the best usb-to-serial chip/driver products.)

The Arduino Severino (Single Sided Serial version 3 - S3V3rino) is designed to work with RS-232 serial interface, not with the TTL serial signal levels of your FT232 board.
So, to use your FT232 board to connect your Severino to a USB port, you'll need connections like those in the schematics below:

So, basically you need these connections:
  FTDI |  ATmega328           | Arduino Severino
----------------------------------------------------
  DTR  |  Pin 1 (thru cap C6) | RESET (thru cap C6)
  RXI  |  Pin 3               | TX (D1)
  TXO  |  Pin 2               | RX (D0)
  VCC  |  Not connected       | Not connected
  CTS  |  Not connected       | Not connected
  GND  |  Pin 8 & 22          | Ground

That's basically the same Majenko suggested (but with a picture added).
I'm not sure you can make these connections directly into the Severino without damaging the board or anything else. You'll probably need to cut the TX/RX traces that go from the ATmega328 to the DB9 female connector on the Severino and wire them to the FTDI header pins.
Best would be to modify the Severino EagleCAD schematics to remove all the RS-232 circuitry and replace it by TTL connector as shown in my schematics above and, with that, etch and assembly a new board. It's a lot of work, but can be done.
I hope this helps.

A typical 5V Arduino will use logic-level serial - that is 0 and 5V signalling.
RS232 has signal levels of plus or minus 3 to 15 volts. RS-232 drivers and receivers must be able to withstand indefinite short circuit to ground or to any voltage level up to ±25 volts
From Wikipedia
Many RS232 interfaces will receive 0-5V signals.
I believe the original serial Arduino had circuitry to tolerate RS232 signal levels on it's inputs.
Since most computers now have USB rather than RS232 ports, Most users of Arduinos use a USB to logic-level serial interface. Some of the most popular chips for this are from FTDI such as the FT232RL on your Chinese clone of a "FTDI Friend". In this case all the signals are logic-level 0-5V (or 3.3V if you change the jumper link).
So the following are probably OK
 PC DE-9 RS232    ----- Severino DE-9
 PC DB-25 RS232   ----- Severino DE-9
 PC USB port ---- "FTDI Friend" ---- Arduino 0(RX), 1(TX), Reset, GND and (optionally) VCC.

@TomášZato: I suspect you don't have a true RS232 signal level anywhere. I'd use a voltmeter if in doubt.


text:
How can I easily see which COM port is used by Arduino?
I'm rather disappointed because I just bought arduino and I am unable to upload any projects. The error I get is:
avrdude: ser_open(): can't open device "\\.\COM3": Časový limit semaforu vypršel.

Can be translated as:
avrdude: ser_open(): can't open device "\\.\COM3": Semaphore time out

Am I expected to brute-force all available ports to see which one is reserved for arduino? How can I, on Windows 7, quickly determine which port to use given that the IDE for some reason can't do that for me.

This has nothing to do with electronics design. You are best off searching on something like SuperUser or Arduino.SE to find out how to locate serial ports in windows and the Arduino IDE respectively.

@TomCarpenter I didn't know Arduino.SE has been resurrected again (how many times was it already...?). And many of those who said Arduino.SE should not be created argumented that all Arduino quesrions can be answered on Electronics.SE.

Looks like EE.SE doesn't agree with you. :) The IDE should detect which port the Arduino is on. I never have to brute-force search for mine. I just bought arduino - which Arduino? You may have to install a device driver. There is a "drivers" directory with some in it.

@NickGammon Do not misunderstand. I am supporting Arduino.SE! I just didn't know it's resurrected - I had all my questions from previous betas migrated. Although I see that I already have some question here. Maybe I forgot. And after installing drivers, the arduino now appears next to the correct port, though I still have to manually select it.

Glad that helped. I turned my comment into an answer to make it more permanent. I have found on Windows / Ubuntu and Mac that if you unplug and replug the Arduino, it often gets assigned a different (COM) port and you may need to select it from the Tools -> Port menu.

Start | Control Panel | System | Device Manager | Ports (COM & LTP).
Watch the list change as you plug / unplug the Arduino. The new port is the Arduino.

You may have to install a device driver. There is a "drivers" directory in the IDE download with some in it.
Example:

According to the readme.txt file:

With this version of Arduino a new all-in-one driver (with
  security signature for Windows 8) is supplied.
The old (deprecated) drivers are still available in the
  Old_Arduino_Drivers.zip


text:
What pins should I use when blinking AtTiny13 with arduino IDE?
I'm trying to program AtTiny13 using Arduino IDE. I have connected the atTiny to my PC using USBasp programer.
I want to write a simple blink application to test whether it works or not. Which pins should I blink?

Because pins 0 and 1 (physical 5,6) are PWM's you should keep them for later ...
and you still have A3 and A2 for analogWrite so,
you should use Pin 2 (Physical 7, next to +5V) like this :
add this in the setup function
pinMode(2, OUTPUT);

And add this in your loop function:
digitalWrite(2,HIGH);

For reference :
SparkFun's Help guide
Remember : Physical pin "1", reset, has a dot  marked on it.

You'll need an Arduino library that supports that chip, to make it appear in the Tools > Board list.  The library docs will tell you which pins then correspond to which Arduino digital I/Os. From that you can decide which pin to attach an LED to (with resistor) and how to edit the blink sketch.
Example: http://www.instructables.com/id/Pimp-Your-Chocolates-with-Arduino-IDE-and-ATtiny13/step2/Program-the-ATtiny13/

There's already Attiny13 in the menu. Should I then just use pins 1-8?

You could of course just try using software "pin 1" and seeing if that works... it's likely that this is ATTiny Port B bit 0 (PB0) which appears on physical pin 5 of the 8-pin DIP chip (see http://www.atmel.com/images/doc2535.pdf for other packages).

For more insight, look at file pins_arduino.h for the ATTiny13 somewhere within your ...\arduino\hardware\arduino??? directory.  I am assuming that at some point you added the core definition files that included ATTiny13, as I don't have them on my machine. Note that different core definitions could assign the Arduino pins to different physical pins.

Shoot, I meant that Arduino digital ZERO (D0) should appear on pin 5 (PB0) of the DIP8, etc.

I have just downloaded Arduino IDE. Maybe ATTiny13 was included - or it just appears to be included but doesn't work as my current experience with it would suggest.

Programming the ATTiny is of course a separate problem. And I'm guessing you can't tell if your problem with blink is in the programming or the program pin assignments. Hmmm.

When you use AVRDUDE to check the device signature, do you at least get a consistent signature value? If not there's something wrong with the electrical connection.

I can't tell, but as soon as I get over uploading problem, I'll face the unknown pin number problem. So I'm solving them simultaneously.

And don't get any value, it just says that Expected signature for ATtiny13 is 1E 90 07 but doesn't output the wrong value. Avter strungling with avrdude for a second time, I find it a very unhelpful software for anyone, who is not 100% sure that he's doing everything right.

avrdude -p t13 -t
... should return device signature. See http://www.nongnu.org/avr-libc/user-manual/using_avrprog.html and this tutorial looks helpful tho not for t13: http://www.ladyada.net/learn/avr/avrdude.html

And presumably you have docs: http://www.nongnu.org/avrdude/user-manual/avrdude.html, specifically command line flags: http://www.nongnu.org/avrdude/user-manual/avrdude_4.html#Option-Descriptions

I would try to install the attiny13 board as per the instructables page. There shouldn't have been a attiny13 in the default install of arduino. As you don't know where it came from, and what core it is using, you're better of starting from scratch. That way you also know how the pin numbers are mapped. avrdude is a pain in the ***, but in my experience it was always right when complaining about signatures.


text:
How to add the -F switch for avrdude in Arduino IDE
So, before starting to learn with something else, I'll give it one last try. The avrdude is complaining that the device signature doesn't match. Whatever, I don't care. To me, what's written on it is what counts.
So I'd like to force it to upload the program. It promises to ignore the problem if -F is specified.
Where are settings for avrdude parameters, like other IDEs have settings for their compilers?

Have you determined that avrdude works with -F outside the IDE yet?

Are you sure you have the correct board type set up and are trying to connect to the correct board?

In the verbose output of the message window at the bottom of the IDE, you could copy and paste the avrdude command line and add the option yourself. I've never manually compiled or tried it this way, give it a go and see if it works

Well, I also don't seem to able to find where is the temporary folder for compiled code. And as of are you sure question - I'm not sure about anything. And avrdude is not helping me to be sure with it's unhelpful errors.

If you have an incorrect device signature, using -F won't fix anything, since it'll be trying to program the wrong microprocessor. What is the actual device signature avrdude is reporting?

The avrdude doesn't bother to report what signature did he get. It just throws an error and fails. As soon as possible, I'll add the actual error in the question.


text:
Which pins are represented by these constants from ABR library?
The following code comes from AtTiny serial library that I want to use:
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>

// change these to use another pin
#define TX_PORT PORTB
#define TX_PIN  PB0
#define TX_DDR  DDRB
#define TX_DDR_PIN DDB0

I have no idea which pins to connect. What do these constants mean and where are they documented?

On the ATTiny13 PB0 is on physical pin 5.

The mapping can be found in the io.h file but also in Arduino core files.
Below is the pin mapping:
                        ATtinyX4
                      +----U----+
  (VCC)-------------1-|VCC   GND|-14------------(GND)
  (D10)-------------2-|PB0   PA0|-13----------(D0/A0)
  (D9)--------------3-|PB1   PA1|-12----------(D1/A1)
  (/RESET)----------4-|PB3   PA2|-11----------(D2/A2)
  (D8)--------------5-|PB2   PA3|-10-------(D3/A3/SS)
  (D7/A7)-----------6-|PA7   PA4|-9---(D4/A4/SCL/SCK)
  (MISO/SDA/D6/A6)--7-|PA6   PA5|-8------(D5/A5/MOSI)
                      +---------+

The serial library uses:
#define TX_PIN  PB0

Which is ATtinyX4 Pin #2, or Arduino attiny core digital pin D10 https://github.com/damellis/attiny/blob/master/variants/tiny14/pins_arduino.h.
Cheers

Question is about ATTiny13

@Gerben No the tag. The actual source code mentioned is ATtinyX4. But in any case the same "lookup" is required.

All his other questions are about the 13A. I don't think that library will work on an ATTiny13A. At the very least, the library assumes it runs at 8MHz, while the 13A runs at 9.6MHz. He'd have to change the OCR0A = 103; with something like 123.

@Gerben Thanks for pointing that out. I know that the library isn't meant specifically for 13A, but I cannot find anything else, so I decided to try to get that to work.

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


text:
How to prevent ATTiny program from running after I flash it with Arduino?
I am making a simple voltage regulator. The whole idea is to just use ADC to read voltage on output side and based on the result, adjust PWM power. I am using PWM on physical pin 5. That's the same pin as the one connected to Arduino pin 10 on this image below:

This means that if I try to flash the program, ATTiny will start to put PWM power into my Arduino. I don't want that to happen. How can I flash the program safely? Can I do something to prevent it from starting?

Other than tying nRESET low?

@IgnacioVazquez-Abrams I'm new to this. What do you mean? Putting some resistor between reset and GND?

This means that if I try to flash the program, ATTiny will start to put PWM power into my Arduino. I don't want that to happen.

Why do you think that is a problem? The "PWM power" cannot be any higher than the supply voltage, and that is 5V. The Arduino has no problem with you providing a 5V PWM signal to an input pin.
The only time it could be a problem is if the pin you are sending the PWM to is set to an output, in which case you could risk overloading the pin. To get around that you just need to insert a small resistor between the ATTiny's pin and the Arduino's pin. 330Ω or so should do it. Just enough to limit the current to a safe value (< 20mA) but small enough that it won't interfere with the programming communication.
A well design schematic for an Arduino ICSP programmer would have had these resistors in all the data communication lines anyway.

I used 2KΩ since that's the smallest I found and it worked. I'll probably add resistors to the other lines too.

I think the Arduino uses 1KΩ between the USB and main MCUs for this same reason. For low(ish) frequencies the resistance isn't that critical. Higher frequencies though can be corrupted by too high a resistance since it acts as a low-pass filter with the gate capacitance of the input pin. 2KΩ should be perfectly fine for the low speeds of ICSP programming.

That isn't a problem but if you really want to prevent ATtiny generating the PWM signal right after flashing the firmware, then you might add a jumper to some free µC input and put the while loop at the beginning of the program which reads that input and waits until you remove the jumper. For example, you could enable internall pull-up on some free input and put the jumper from that pin to GND. Then in the code you can just wait for the input to become high and then proceed with the rest of the code. Then you can just insert the jumper, flash the firmware, remove the connections between ATtiny and Arduino and then remove the jumper.

The Arduino-as-ISP sketch will turn all the OUTPUT pins, connected to the ATTiny, back to INPUT. That way nothing bad can happen, when the ATTiny drives those pins HIGH of LOW.


text:
Custom assert() implementation: not printing the error message
I am writing my own assert() macro on Arduino as shown below.
When I run it from the main() it always works correctly (prints the message and gets into an infinite loop), however when I call it within a class function it gets stuck without printing anything. Why is that?
assert.cpp/.h
#ifndef _ASSERT_H_
#define _ASSERT_H_

void assertion_failure(const char* expr, const char* file, int linenum);

#define assert(expr) \
    if (expr) ; \
    else assertion_failure(#expr, __FILE__, __LINE__)

#endif /* _ASSERT_H_ */

#include "assert.h"
#include "Arduino.h"

void assertion_failure(const char* expr, const char* file, int linenum)
{
    Serial.print("Assertion failed in '");
    Serial.print(file);
    Serial.print("' on line ");
    Serial.print(linenum);
    Serial.print(": ");
    Serial.println(expr);
    Serial.flush();

    while (1);
}

And the context in which the assert gets stuck below (it works well when I call it in main() however):
int ADS1256::assert_debug()
{
    uint8_t id = read_register(STATUS) >> 4;
    assert(false);    // Gets stuck here without printing anything to screen
    return id;
}

EDIT:
looks like it has something to do with build configuration. I am using PlatformIO build system.
It does not work when I use this file structure:
├── include
│   └── assert.h
├── lib
│   ├── ADS1256
│      ├── ads1256.cpp
│      ├── ads1256.h
│      └── ads1256_regmap.h
├── src
    ├── assert.cpp
    └── main.cpp

However, if I move assert.cpp/.h into a dedicated directory within lib/ it works fine. What is the reason behind this?
How can I investigate why this happened?
It works with this layout (again, using PlatformIO default build configuration):
├── include
├── lib
│   ├── ADS1256/
│   ├── Assert/
│       ├── assert.cpp
│       └── assert.h
├── src
    └── main.cpp

Is your source named “Assert.c” or “Assert.cpp”? Are you really writing main() rather than setup() and loop()? If so, do you call init() at the start of main()?

I tried the code you posted, with a minimal stub for the ADS1256 class: it works as expected. Your problem thus lies in some part of your code that you are not showing.

Where is assert_debug() being called from?

@EdgarBonet It is named assert.cpp (my mistake when writing the post, sorry). I am indeed calling main() rather than setup+loop.

In that process did you change your #include directive?

@timemage no, I am always using the same: #include "assert.h".
I am guessing that it is somehow clashing with the assert() macro defined in the avr-gcc toolchain somewhere. But how can I verify/prove this?

That's basically what I'm in the process of writing. It's unfinished, but I guess I'll just post it.  I can try to update.

As per comment on question, this is not as finished as I'd like, but it's a start.
I deeply suspect what you're running into is a conflict between the name of your header and the standard assert.h header.  You're using the same header name and same macro names as is used in the standard c header, that is part of both c++ and "Arduino.".  The standard assert() with the way things are normally set up on the AVR Arduino core does basically just go into a tight loop and do nothing.
I would consider naming your macro something other than assert and naming your header something other than assert.h.  If you want to get into the precise details why, we need to see things like your include path order, and the include directives themselves.  Even then, the advice would be about the same.
Diagnostics
--save-temps
In platform.io you should be able to add --save-temps to the avr-gcc command-line to get it to produce (or keep) the output of the preprocessing stage.  GCC annotates these showing where each section of the entire output came from, so you can see which headers each #include directive actually included and in what order all of this happened.
NDEBUG
Something else you can try, as a diagnostic measure, is to define NDEBUG in your project settings. This is usually defined by IDEs for "release mode".  It basically makes assert() into a NOP, which in turn means that it will not do the usual avr-libc thing of locking up.  If you're seeing the avr-libc assert being expanded instead of your own, then the behaviour will change to just not locking up, but also not doing what your own assert would do.
AVR-based Arduino assert() support
avr-libc's assert() tries to print its assertion message on stderr, which is not configured on AVR based Arduinos to do anything.  So the outward behaviour is that it locks up.  However, you can complete avr-libc's implementation of stderr in terms of the Arduino's Serial.write function, in which case the normal avr-libc assert will work just fine.  Here's one example of completing avr-libc's stdio printing in terms of Serial.
__FILE__ Caveat and SRAM
Something you should be aware of in using __FILE__, and therefore assert (whether it be avr-libc's or yours) is that __FILE__ expands to a string literal which is the full path of the source filename, which can be quite long.  On the UNO (you have tagged) these go into SRAM.  So if you use assert in a couple different files, you can very quickly eat up the available SRAM on the AVR.
For this reason, in my own little assert-type macros, I've taken to not reporting the file but instead a custom tag, which is often just a single letter or number.  Besides, often my asserts are blinking the __LINE__ number on an LED, where __FILE__ is impractical in my typical use case anyway.

Thanks for pointing me to avr-libc's implementation of sterr/assert!
So we agree on clashing with the standard assert.h header. But I want to understand what and how the problem arises. Is it the file name, is it macro name, both?
How could I check which implementation was used (e.g. inspecting binary, symbols or sth)?
I tried using -H preprocessor flag (shows absolute paths of included headers), but couldn't see anything useful from it...

Uhh, I will try to make an update to address that.

See under Diagnostics and --save-temps. I'm not (left that out prior) going to be able to go much further with this as an answer really without working out exactly what to ask you to do or include in the question and then having you provide that, which would probably add a lot of noise to the question.

I asked the same question in the PlatformIO community and clashing with avr-libc's assert macro is indeed the problem.

If that's really the answer you're looking for then you might as well post your own answer calling that one out and I'll get rid of this one.  You would need to mark yours as accepted.


text:
How to get the weather kit with anemometer working using arduino (UNO)?
I tried to build a weather station with anemometer and My setup is,
SwitchDoc Labs' anemometer kit (which is equivalent to sparkfun anemometer kit) connected to the grove weather-pi board with rtc clock DS3231 installed on which is connected to arduino UNO.
According to http://www.switchdoc.com/wp-content/uploads/2016/07/WeatherBoard_CurrentSpecification.pdf and their official tutorial https://www.switchdoc.com/2015/01/weather-arduino-weatherpiarduino/, if I use grove weather-pi board's JP2 connections to connect to the UNO/Mega2560 board then it suggests as following (in my case its UNO)
diagram 1
diagram 2
GroveWeatherPi_board    Mega        Uno     Units
    JP2/1 ->            A0          A0      WindVane
    JP2/2 ->            D2          D3      RainBucket
    JP2/3 ->            D5          D2      Anemometer
    JP2/4 ->            GND         GND     GND

And the supposedly working sketch/library is https://github.com/switchdoclabs/SDL_Weather_80422 which only compiles on arduino-IDE without issue if I use the fork https://github.com/soligen2010/Adafruit_ADS1X15 instead of the original https://github.com/adafruit/Adafruit_ADS1X15 with it but even then the wind-speed and wind-direction unit or to say the whole anemometer part just do not work or in other words, do not give any reading. I have tested the units individually up to the arduino pins with LED light on breadboard, they are sending signals/responding and also mounted the whole project on a Mega2560 as well but results remained unchanged.
I am assuming the pin-outs defined in the https://github.com/switchdoclabs/SDL_Weather_80422 are messed up then but how to redefine it in the sketch/library because in the ino sketch file, these are the pin-out definitions for primarily Mega2560
#define pinLED     13  // LED connected to digital pin 13
#define pinAnem    18  // Anenometer connected to pin 18 (not used in the diagram!) - Int 5 - Mega   / Uno pin 2
#define pinRain    2   // Anenometer connected to pin 2 - Int 0 - Mega   / Uno Pin 3
#define intAnem    5   // int 0 (check for Uno), according to the above two diagrams' comparison, for UNO this pin also goes to the pin 2
#define intRain    1   // int 1 (not used in the diagram! Then why? Its a TX pin)

Where the pinAnem and intAnem both indicates pin 2 for UNO according to the above two diagrams.
When I connect the I2C vcc pin from grove-weather-board to UNO's 5 volts instead of 3.3 volts as shown, the wind direction gets fixed but still no wind-speed reading.
So what are the corrections I need to do in the SDL_Weather_80422 library or in the connection diagram in this case?

This sketch successfully computes only the wind direction though https://github.com/sparkfun/Weather_Shield/blob/master/Firmware/Weather_Shield_Weather_Station_V12/Weather_Shield_Weather_Station_V12.ino after disabling the extra headers.

why do you feel that you need to modify the library??

@jsotola according to any of the diagrams above, have you noticed any A0 definition in the library? I don't, that's why.

this library https://github.com/switchdoclabs/SDL_Weather_80422 (last link in your question) has this command line in the example sketch SDL_Weather_80422 weatherStation(pinAnem, pinRain, intAnem, intRain, A0, SDL_MODE_INTERNAL_AD); .......... A0 is the analog pin for the direction data ..... the other two data pins are also represented

both the anemometer and the rain bucket sensors are simple switches ..... write a simple sketch that reads the switch state and light LED (pin13)  if the switch is activated and turns off LED if switch is not activated...... do that for each of the switches separately

the http://cactus.io/hookups/weather/anemometer/davis/hookup-arduino-to-davis-anemometer-wind-speed sketch reads the anemometer's wind_speed just fine, so it complements the missing functionality of https://github.com/switchdoclabs/SDL_Weather_80422.

According to the above setup only rain bucket unit works.
And as jsotola mentioned both the anemometer and the rain bucket sensors are simple switches, so a simple sketch can be written that reads the switch state and light LED (pin13) if the switch is activated and turns off LED if switch is not activated and that can be done for each of the switches separately.
But instead I took a shortcut.
Fixes:

The wind vane part (on analog pin A0) starts working only when I connect the I2C vcc pin to 5 volts pin instead of 3.3 volts pin of UNO.
Had to ditch the https://github.com/switchdoclabs/SDL_Weather_80422 library's wind_speed reading method and adopting and merging into the http://cactus.io/hookups/weather/anemometer/davis/hookup-arduino-to-davis-anemometer-wind-speed code and adding up the wind_gust function from https://github.com/sparkfun/Weather_Shield/blob/master/Firmware/Weather_Shield_Weather_Station_V12/Weather_Shield_Weather_Station_V12.ino makes the anemometer with rain-bucket with the exact same setup fully functional.


text:
Baud rate dependency
I am currently trying to write (obtain) a code for getting raw acceleration values and yaw, pitch and roll angles using these Jeff Rowberg's examples. I have used MPU6050_DMP example to get this code:
// I2Cdev and MPU6050 must be installed as libraries, or else the .cpp/.h files
// for both classes must be in the include path of your project
#include "I2Cdev.h"

#include "MPU6050_6Axis_MotionApps20.h"
//#include "MPU6050.h" // not necessary if using MotionApps include file

// Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation
// is used in I2Cdev.h
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
#include "Wire.h"
#endif

// class default I2C address is 0x68
// specific I2C addresses may be passed as a parameter here
// AD0 low = 0x68 (default for SparkFun breakout and InvenSense evaluation board)
// AD0 high = 0x69
MPU6050 mpu;

//MPU6050 mpu(0x69); // <-- use for AD0 high

// uncomment "OUTPUT_READABLE_YAWPITCHROLL" if you want to see the yaw/
// pitch/roll angles (in degrees) calculated from the quaternions coming
// from the FIFO. Note this also requires gravity vector calculations.
// Also note that yaw/pitch/roll angles suffer from gimbal lock (for
// more info, see: http://en.wikipedia.org/wiki/Gimbal_lock)
#define INTERRUPT_PIN 2  // use pin 2 on Arduino Uno & most boards
#define LED_PIN 13 // (Arduino is 13, Teensy is 11, Teensy++ is 6)
bool blinkState = false;

// MPU control/status vars
bool dmpReady = false;  // set true if DMP init was successful
uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
uint8_t devStatus;      // return status after each device operation (0 =     success, !0 = error)
uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount;     // count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO storage buffer

// orientation/motion vars
Quaternion q;           // [w, x, y, z]         quaternion container
VectorInt16 aa;         // [x, y, z]            accel sensor measurements
VectorInt16 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
VectorInt16 aaWorld;    // [x, y, z]            world-frame accel sensor measurements
VectorFloat gravity;    // [x, y, z]            gravity vector
float euler[3];         // [psi, theta, phi]    Euler angle container
float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector

// packet structure for InvenSense teapot demo
uint8_t teapotPacket[14] = { '$', 0x02, 0,0, 0,0, 0,0, 0,0, 0x00, 0x00, '\r', '\n' };

// ================================================================
// ===               INTERRUPT DETECTION ROUTINE                ===
// ================================================================

volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
void dmpDataReady() {
mpuInterrupt = true;
}

int16_t ax, ay, az, axd, ayd, azd, axo=0, ayo=0, azo=0;

// ================================================================
// ===                      INITIAL SETUP                       ===
// ================================================================

void setup() {
// join I2C bus (I2Cdev library doesn't do this automatically)
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    Wire.begin();
    Wire.setClock(400000); // 400kHz I2C clock. Comment this line if having compilation difficulties
#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
    Fastwire::setup(400, true);
#endif

// initialize serial communication
// (115200 chosen because it is required for Teapot Demo output, but it's
// really up to you depending on your project)
Serial.begin(38400);
while (!Serial); // wait for Leonardo enumeration, others continue immediately

// NOTE: 8MHz or slower host processors, like the Teensy @ 3.3V or Arduino
// Pro Mini running at 3.3V, cannot handle this baud rate reliably due to
// the baud timing being too misaligned with processor ticks. You must use
// 38400 or slower in these cases, or use some kind of external separate
// crystal solution for the UART timer.

// initialize device
Serial.println(F("Initializing I2C devices..."));
mpu.initialize();
pinMode(INTERRUPT_PIN, INPUT);

// verify connection
Serial.println(F("Testing device connections..."));
Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));

// wait for ready
Serial.println(F("\nSend any character to begin DMP programming and demo: "));
while (Serial.available() && Serial.read()); // empty buffer
while (!Serial.available());                 // wait for data
while (Serial.available() && Serial.read()); // empty buffer again

// load and configure the DMP
Serial.println(F("Initializing DMP..."));
devStatus = mpu.dmpInitialize();

// supply your own gyro offsets here, scaled for min sensitivity
mpu.setXGyroOffset(220);
mpu.setYGyroOffset(76);
mpu.setZGyroOffset(-85);
mpu.setZAccelOffset(1788); // 1688 factory default for my test chip

// make sure it worked (returns 0 if so)
if (devStatus == 0) {
    // turn on the DMP, now that it's ready
    Serial.println(F("Enabling DMP..."));
    mpu.setDMPEnabled(true);

    // enable Arduino interrupt detection
    Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
    attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), dmpDataReady, RISING);
    mpuIntStatus = mpu.getIntStatus();

    // set our DMP Ready flag so the main loop() function knows it's okay to use it
    Serial.println(F("DMP ready! Waiting for first interrupt..."));
    dmpReady = true;

    // get expected DMP packet size for later comparison
    packetSize = mpu.dmpGetFIFOPacketSize();
} else {
    // ERROR!
    // 1 = initial memory load failed
    // 2 = DMP configuration updates failed
    // (if it's going to break, usually the code will be 1)
    Serial.print(F("DMP Initialization failed (code "));
    Serial.print(devStatus);
    Serial.println(F(")"));
}

// configure LED for output
pinMode(LED_PIN, OUTPUT);
}

// ================================================================
// ===                    MAIN PROGRAM LOOP                     ===
// ================================================================
uint16_t lv = 1;
void loop() {
// if programming failed, don't try to do anything
if (!dmpReady) return;

// wait for MPU interrupt or extra packet(s) available
while (!mpuInterrupt && fifoCount < packetSize) {

}

mpu.getAcceleration(&ax, &ay, &az);

// reset interrupt flag and get INT_STATUS byte
mpuInterrupt = false;
mpuIntStatus = mpu.getIntStatus();

// get current FIFO count
fifoCount = mpu.getFIFOCount();

// check for overflow (this should never happen unless our code is too inefficient)
if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
    // reset so we can continue cleanly
    mpu.resetFIFO();
    Serial.println(F("FIFO overflow!"));

// otherwise, check for DMP data ready interrupt (this should happen frequently)
} else if (mpuIntStatus & 0x02) {
    // wait for correct available data length, should be a VERY short wait
    while (fifoCount < packetSize)
    {
      fifoCount = mpu.getFIFOCount();
    }

    // read a packet from FIFO
    mpu.getFIFOBytes(fifoBuffer, packetSize);

    // track FIFO count here in case there is > 1 packet available
    // (this lets us immediately read more without waiting for an interrupt)
    fifoCount -= packetSize;

        // display Euler angles in degrees
        mpu.dmpGetQuaternion(&q, fifoBuffer);
        mpu.dmpGetGravity(&gravity, &q);
        mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
        Serial.print("ypr\t");
        Serial.print(ypr[0] * 180/M_PI);
        Serial.print("\t");
        Serial.print(ypr[1] * 180/M_PI);
        Serial.print("\t");
        Serial.print(ypr[2] * 180/M_PI);
        Serial.print("\t");
        Serial.print("ax ");
        Serial.print(ax);
        Serial.print("\t");
        Serial.print("ay ");
        Serial.print(ay);
        Serial.print("\t");
        Serial.print("az ");
        Serial.println(az);

    // blink LED to indicate activity
    blinkState = !blinkState;
    digitalWrite(LED_PIN, blinkState);
}
if(lv < 501)
++lv;
else
{
  lv = 1;
  digitalWrite(13, !digitalRead(13));
}
}

However when this code, run at 38400 or 1920 baud rate, gives the least frequent FIFO overflow errors (sometimes at 38400, otherwise at 19200). If this code is run below this "optimal" baud rate, FIFO overflow frequency increases. If thic code is run at above "optimal" baud rate, the board freezes after about 10 seconds (always, in every case), the TX just stops binking. Any suggested solution? Board : Arduino Uno, being used with MPU6050

Doing a lot of serial printing at a low baud rate will of course cause you to fall behind.  You should try to determine where your code gets stuck in the fast case.  It looks like you have a possible race condition with potentially clearing the interrupt flag before acting on it, also you do an exact equality comparison on a length that might be able (?) to exceed that.  Try putting a counter in your while() loop and printing some output if you are stuck there for a long time.  Make sure you aren't overflowing any 16 bit variables...

@ChrisStratton Well, the above code has been modified by me. I have used long instead of int, and I am quite sure that overflow shouldn't be occuring, and used serial printing for debugging. But none of these seemed to help since the board freezes randomly anywhere. There is no pattern. Also, pressing the reset button should restart the code (which happens for other simpler codes), but it's not happening. The board remains frozen.This is the code in case you wanna see it.

@ChrisStratton Also, it should not be a case of integer overflow, because I have tested overflow on other simpler programs. In case overflow occurs, the value simply rolls over, it does not freeze the program execution.

Again, your best route to a solution is probably going to be figuring out where in the program it does get stuck.


text:
Understanding USBHID_DESC report
Recently Ran the USBHID_DESC program on my Arduino Uno with a USB hub attached to my joystick. I wanted to be able to program my joystick to integrate with my project. Circuits@Home developed the code and have 2 articles dealing with understanding the report. But they are very sparse with details and only have a single example to go off of. Many of the fields that I got returned are not described at all in the tutorial. Further more, attempting to dig through the official documentation from USB.org itself has been extremely overwhelming. I don't really know how to start. Can anyone help me interpret the data fields for this controller?
This is the data that I recieved from the serial monitor:

Start
  0000: 05 01 09 04 A1 01 09 01 A1 00 09 30 09 31 09 32
  0010: 09 BB 15 80 25 7F 46 FF 00 66 00 00 66 00 00 75
  0020: 08 95 04 81 02 C0 09 39 15 01 25 08 35 00 46 3B
  0030: 01 65 14 75 04 95 01 81 02 05 09 19 01 29 04 15
  0040: 00 25 01 75 01 95 04 81 02 95 08 81 01 05 08 09
  0050: 43 15 00 26 FF 00 35 00 46 FF 00 75 08 95 04 91
  0060: 82 55 00 65 00 55 00 65 00 55 00 C0
  Usage Page Gen Desktop Ctrls(01)
  Usage Game Pad
  Collection Application
  Usage Pointer
  Collection Physical
  Usage X
  Usage Y
  Usage Z
  Usage Undef
  Logical Min(80)
  Logical Max(7F)
  Physical Max(FF00)
  Unit(0000)
  Unit(0000)
  Report Size(08)
  Report Count(04)
  Input(00000010)
  End Collection
  Usage Hat Switch
  Logical Min(01)
  Logical Max(08)
  Physical Min(00)
  Physical Max(3B01)
  Unit(14)
  Report Size(04)
  Report Count(01)
  Input(00000010)
  Usage Page Button(09)
  Usage Min(01)
  Usage Max(04)
  Logical Min(00)
  Logical Max(01)
  Report Size(01)
  Report Count(04)
  Input(00000010)
  Report Count(08)
  Input(00000001)
  Usage Page LEDs(08)
  Usage Slow Blk On Time
  Logical Min(00)
  Logical Max(FF00)
  Physical Min(00)
  Physical Max(FF00)
  Report Size(08)
  Report Count(04)
  Output(10000010)
  Unit Exp(00)
  Unit(00)
  Unit Exp(00)
  Unit(00)
  Unit Exp(00)
  End Collection Game Pad Pointer X Y Z Undef(00)(00)(7F)(00)
  Hat Switch(00)
  Btn0001
  (00) Btn0002
  (00) Btn0003
  (00) Btn0004
  (00)
  (00)(00)(00)(00)(00)(00)(00)(00)
  Slow Blk On Time

Which bits don't you understand?

well i didn't understand a lot of it. it seems to have come out formatted very strangely, your explanation helped a lot...ty*1.1^100

It's pretty easy to follow if you indent and break it up right.  Let me add some annotation too:
Usage Page Gen Desktop Ctrls(01)  // Usages describe what the
Usage Game Pad                    // following data is used for.
Collection Application
    Usage Pointer        // Use the settings for a physical
    Collection Physical  // pointing device
        Usage X       // It has four axes -
        Usage Y       // X, Y, Z and some other undefined axis.
        Usage Z
        Usage Undef
        Logical Min(80) // Output the values 0x80 to 0x7F, which when
        Logical Max(7F) // interpeted as signed bytes is -128 to 127.
        Physical Max(FF00) // The input has a range 0 to 255
        Unit(0000)
        Unit(0000)
        Report Size(08)  // The report value is 8 bits long,
        Report Count(04) // and there are 4 of them (one per axis)
        Input(00000010)  // This ends this "input" section.
    End Collection

    Usage Hat Switch // Describing a HAT Switch now.
    Logical Min(01)  // Interpret it as a value between 1 and 8
    Logical Max(08)
    Physical Min(00) // The input to it is between 0 and 0x3B01.
    Physical Max(3B01) // Not sure that value is interpreted properly.
    Unit(14)
    Report Size(04)  // The report has 4 bits in it,
    Report Count(01) // and there is just one of them.
    Input(00000010)  // And end the input section.

    Usage Page Button(09)  // Next come the buttons.
    Usage Min(01)      // These are basically button numbers
    Usage Max(04)      // - there's 4 buttons, 1 through 4.
    Logical Min(00)    // A button is either off (0)
    Logical Max(01)    // or on (1).
    Report Size(01)    // And can only have one state, so size 1.
    Report Count(04)   // There's 4 buttons, so 4 reports.
    Input(00000010)    // And end the input.

    Report Count(08)   // This is a special one. It keeps the settings
    Input(00000001)    // from before (the haven't been changed), but
                       // is just a dummy one to pad out the data to
                       // the right size. Alignment is key.

    Usage Page LEDs(08)    // Now we have 4 LEDs with an
    Usage Slow Blk On Time // 8-bit PWM value. 0-FF which doesn't
    Logical Min(00)        // need interpreting, so 0=0 and FF=FF.
    Logical Max(FF00)
    Physical Min(00)
    Physical Max(FF00)
    Report Size(08)    // As I said, 8 bit,
    Report Count(04)   // and there's 4 of them.
    Output(10000010)   // And it's output.

    Unit Exp(00)   // Now there seems to be a bit of junk.
    Unit(00)
    Unit Exp(00)
    Unit(00)
    Unit Exp(00)
End Collection Game Pad // And the end.

So interpreting that, you get a report sent to you that has:
Byte     Function
0        X Axis 0-255 which you map to -128 to 127
1        Y Axis 0-255 which you map to -128 to 127
2        Z Axis 0-255 which you map to -128 to 127
3        Another Axis 0-255 which you map to -128 to 127
4        Upper 4 bits buttons, lower 4 bits HAT direction
5        Padding byte to make ita multiple of 16 bits long

And you can send a 4 byte report where:
Byte     Function
0        LED 1 PWM
1        LED 2 PWM
2        LED 3 PWM
4        LED 4 PWM

Those "LEDs" could be force feedback motors or vibrators.
Also I suspect there is maybe a small amount of corruption or mis-interpretation of multi-byte values in the output.


text:
Need library help for Arduino USB host shield
Recently Purchased a "TOOGOO(R) T45 USB Host Shield" from Amazon. I attempted to use the "USB Host Shield Library" from Github, but It seems like it might not support this particular shield.
I would really like to learn how to use this shield to interact with my joystick but the only tutorial information I have found to help me with this is from Circuits@home and they seem to be using a specific shield in their development of the code library.
Can anyone point me to a tutorial or Github library that can help me learn to work with this setup?
I'm using an Arduino Uno and a Thrustmaster USB joystick.
Thanks in advance.
UPDATE*
I fixed the initial problem of accessing the HIDDESC report. I now have the report, but the formatting of the report is particularly hard to understand. Using the Circuits@home articles I'm a little lost on how to read the report data I was given. It does not seem to be formatted in the same way as the example. Can anyone help with interpreting my device report?

Start
  0000: 05 01 09 04 A1 01 09 01 A1 00 09 30 09 31 09 32
  0010: 09 BB 15 80 25 7F 46 FF 00 66 00 00 66 00 00 75
  0020: 08 95 04 81 02 C0 09 39 15 01 25 08 35 00 46 3B
  0030: 01 65 14 75 04 95 01 81 02 05 09 19 01 29 04 15
  0040: 00 25 01 75 01 95 04 81 02 95 08 81 01 05 08 09
  0050: 43 15 00 26 FF 00 35 00 46 FF 00 75 08 95 04 91
  0060: 82 55 00 65 00 55 00 65 00 55 00 C0
  Usage Page Gen Desktop Ctrls(01)
  Usage Game Pad
  Collection Application
  Usage Pointer
  Collection Physical
  Usage X
  Usage Y
  Usage Z
  Usage Undef
  Logical Min(80)
  Logical Max(7F)
  Physical Max(FF00)
  Unit(0000)
  Unit(0000)
  Report Size(08)
  Report Count(04)
  Input(00000010)
  End Collection
  Usage Hat Switch
  Logical Min(01)
  Logical Max(08)
  Physical Min(00)
  Physical Max(3B01)
  Unit(14)
  Report Size(04)
  Report Count(01)
  Input(00000010)
  Usage Page Button(09)
  Usage Min(01)
  Usage Max(04)
  Logical Min(00)
  Logical Max(01)
  Report Size(01)
  Report Count(04)
  Input(00000010)
  Report Count(08)
  Input(00000001)
  Usage Page LEDs(08)
  Usage Slow Blk On Time
  Logical Min(00)
  Logical Max(FF00)
  Physical Min(00)
  Physical Max(FF00)
  Report Size(08)
  Report Count(04)
  Output(10000010)
  Unit Exp(00)
  Unit(00)
  Unit Exp(00)
  Unit(00)
  Unit Exp(00)
  End Collection Game Pad Pointer X Y Z Undef(00)(00)(7F)(00)
  Hat Switch(00)
  Btn0001
  (00) Btn0002
  (00) Btn0003
  (00) Btn0004
  (00)
  (00)(00)(00)(00)(00)(00)(00)(00)
  Slow Blk On Time

I think you will need to get the library for your shield.

Identify the chip on your shield, and identify the chip on the shields that are supported.  Typically these fly-by-night boards are just clones of better supported ones, but you could have anything including an inert paperweight.  Worth considering that a host shield on an Arduino is generally a bad idea to begin with; if you want to host a USB peripheral, use a processor that can do so natively - it will be both cheaper and less roundabout.  Also realize that only trivial well documented USB peripherals make sense for MCUs; for more complex things you probably want an embedded Linux system.

@code Gorilla, where would I get the library for my shield?

@ChrisStratton the chip is a max 3421EE 1637. It seems to work fine, and be designed well enough, but thanks for the input.

@B.Guisgand - The library, if it exists, will be somewhere on the internet, I know that isn't helpful but what else can I say.  I think you might have misunderstood Chris's point.  Put bluntly you well down S creek with no paddle and he was handing you an outboard motor.

@CodeGorilla lol. Yeah I figured as much. I'm trying my best with this project, but can't drop $66 just for joystick functionality, might just have to scratch that portion of the project if I can't buy a cheaper shield option. Honestly all i need is the ability to plug a cheap joystick in and get it to increase or decrease the digits on a 4 digit 7 segment display.

So use a cheap plain joystick directly wired to the Arduino.

@ChrisStratton and where would i get one, been looking everywhere.

The photos on Amazon show a clone of the circuit@home board so the same library should work. You may be running into the problem mentioned in the following page.
https://esp8266-notes.blogspot.com/2017/08/defective-arduino-usb-host-shield-boards.html


text:
How do I correctly choose components for my current project?
Previously I asked a question that was a bit to broad so I'm narrowing the focus to a single component board of my design.
I have a set of 3 luckylight R/G bar graphs
(datasheet here: https://cdn-shop.adafruit.com/datasheets/KWL-R1230XDUGB.pdf)
A 5.1 V 2A power source
(recycled ac/dc converter voltage tested datasheet here: http://pdf1.alldatasheet.com/datasheet-pdf/view/322359/BOTHHAND/M1-10S05.html)
a series of 5 SN74HC595 (for controlling the LED multiplexing)
and an Arduino Nano.
The purpose of the bar graphs is to show the player how much of his available system energy he/she is using.
The first three bars of the graph are set to Red, the next 5 are yellow, and the final 4 are green.
As various components are switched on, or other activities drain the power of the engine core, a program level command will switch the multiplexing array to have them shut off.
The problem I'm having is getting enough power to each of the LEDs of the bar graph without overloading the IC pins on the Arduino or shift registers and making the colors appear correctly.
I know I could use Darlington arrays, or a bunch of transistors to keep the power going to the LEDs on a line independent of the ICs, but i'm not sure the right way to go about this. I have a few ULN2803 Darlingtons and a lot of 2n2222a transistors.
(Also my current Arduino code only has, at max, 8 LEDs from each register on at the same time, with a forward voltage of 2.4 volts and 20mA per LED. There are three cycles to my code because the bar graphs have three shared cathode pins that run three 2x4 matrices.)
Additionally I don't know precisely how to calculate the resistor values I would need for this arrangement to maintain the same voltage being applied to the 24 simultaneously running LEDs and get their brightness to be equivalent. Currently i'm noticing LEDs that are farther down the 595 logic chain are receiving less power and appearing weaker. (yes i have been running them off the power coming from the Arduino thus far)
Hopefully this is a narrow enough question.

LOL, you don't seem to be having much luck asking questions here. Your earlier one was closed  by community voting (not by me) as too broad, and now this one as not about the Arduino. Maybe you should have mentioned Arduino in the question. I stand by my answer, but if the question isn't re-opened try asking on Electrical Engineering Stack Exchange. Make sure you put the word "Arduino" in the question, and they will quickly close it and migrate it back here. :)

As for the people that voted to close this, you know perfectly well that if the word Arduino was mentioned it wouldn't last 10 minutes on EE Stack Exchange, and would be sent back here.

I guess I didn't word something right, but i also understand this question could have been about another microprocessor environment. Either way it is an Arduino question, but about best practices when using higher output currents than the Arduino can source directly.

According to this datasheet the 595 can drive up to 6 mA per output pin with a maximum of 20 mA for the input to the chip (so, 2.5 mA if you are driving all outputs).
Since your LEDs are quoting a forward current of 25 mA it seems that you will fall somewhat short of providing the 25 mA per LED.
There are higher power shift registers, eg. the TPIC6B595.
You might want to consider a multiplexing LED driver such as the MAX7219. I have a post about using that chip.
Your LEDs sound similar to the things that the MAX7219 is designed to drive. It also has inbuilt current-limiting with the current selected by a single resistor.
It isn't clear from your question whether you have the common anode or common cathode device, but you need a common cathode for the MAX7219.

The MAX7219 is not that expensive if you buy it from eBay. For example search for "MAX7219 kit". I found hits for 4 x MAX7219 for $US 9.75 including boards, capacitors and LEDs. Just discard the LEDs (8 x 8 dot matrix) and run the wires to your bargraph.

As they are designed to run 7 segment displays how would I connect it to transfer from my current 16 bit binary shift setup ...

They can run in a couple of modes (see the Decode Mode register) and one is to send arbitrary bits. Since you can program in any combination of bits (in my link above there is an array which does a CP437 font) you can therefore make up any combination of bars on and off. I would get one as an experiment (buy one of those kits from eBay) and try the idea out. It will be a lot less mucking around than 595 chips, transistors, current-limiting resistors, and so on.
There are various kits around, some are pre-soldered (which you won't want), some come with SMD chips and some with through-hole chips. Choose SMD or through-hole depending on your confidence with soldering SMD parts.

I know on my shift registers pins 1-8 go to the LED anodes and Pins 9-11 go to transistors that run the cathodes. Can you help me understand the pin connections to get the MAX to run this?

Looking at your bar graph specs:

You have 3 rather than 8 cathodes (pins 14, 9 and 8 are duplicates of 1, 6 and 7). So, you would run the cathode wiring (1, 6, 7) to the first 3 "digit" pins (2, 11 and 6) on the MAX7219. The other 8 wires (marked anodes) would go to the 8 anodes (2, 3, 4, 5, 10, 11, 12, 13).
As you have only used 3 cathode pins you could wire up a second bargraph using another 3 cathode pins (and run the anodes in parallel). That way a single MAX7219 can drive two bargraphs, giving you a total of 24 bars, each of which can show red, green, or yellow at one time.

Example wiring and code
I ordered a couple of the LED modules and worked out a schematic for them:

One MAX7219 can drive two of the modules.
Example of wiring:

Example code:
#include <SPI.h>

 // define max7219 registers
const byte MAX7219_REG_NOOP        = 0x0;
const byte MAX7219_REG_DIGIT0      = 0x1;
const byte MAX7219_REG_DIGIT1      = 0x2;
const byte MAX7219_REG_DIGIT2      = 0x3;
const byte MAX7219_REG_DIGIT3      = 0x4;
const byte MAX7219_REG_DIGIT4      = 0x5;
const byte MAX7219_REG_DIGIT5      = 0x6;
const byte MAX7219_REG_DIGIT6      = 0x7;
const byte MAX7219_REG_DIGIT7      = 0x8;
const byte MAX7219_REG_DECODEMODE  = 0x9;
const byte MAX7219_REG_INTENSITY   = 0xA;
const byte MAX7219_REG_SCANLIMIT   = 0xB;
const byte MAX7219_REG_SHUTDOWN    = 0xC;
const byte MAX7219_REG_DISPLAYTEST = 0xF;

// which groups of bars we are addressing
const byte BARS_1_4   = MAX7219_REG_DIGIT0;
const byte BARS_5_8   = MAX7219_REG_DIGIT1;
const byte BARS_9_12  = MAX7219_REG_DIGIT2;
const byte BARS_13_16 = MAX7219_REG_DIGIT3;
const byte BARS_17_20 = MAX7219_REG_DIGIT4;
const byte BARS_21_24 = MAX7219_REG_DIGIT5;

// within a group, which one (from the left)
const byte BAR1_RED = 0x80;
const byte BAR2_RED = 0x20;
const byte BAR3_RED = 0x08;
const byte BAR4_RED = 0x02;

const byte BAR1_GREEN = 0x40;
const byte BAR2_GREEN = 0x10;
const byte BAR3_GREEN = 0x04;
const byte BAR4_GREEN = 0x01;

// yellow is done by adding red and green
const byte BAR1_YELLOW = BAR1_RED + BAR1_GREEN;
const byte BAR2_YELLOW = BAR2_RED + BAR2_GREEN;
const byte BAR3_YELLOW = BAR3_RED + BAR3_GREEN;
const byte BAR4_YELLOW = BAR4_RED + BAR4_GREEN;

void sendByte (const byte reg, const byte data)
  {
  digitalWrite (SS, LOW);
  SPI.transfer (reg);
  SPI.transfer (data);
  digitalWrite (SS, HIGH);
  }  // end of sendByte

void setup () {

  SPI.begin ();

  sendByte (MAX7219_REG_SCANLIMIT, 5);   // show 6 digits
  sendByte (MAX7219_REG_DECODEMODE, 0);  // using an led matrix (not digits)
  sendByte (MAX7219_REG_DISPLAYTEST, 0); // no display test

  // clear display
  for (byte col = 0; col < 8; col++)
    sendByte (col + 1, 0);

  sendByte (MAX7219_REG_INTENSITY, 7);  // character intensity: range: 0 to 15
  sendByte (MAX7219_REG_SHUTDOWN, 1);   // not in shutdown mode (ie. start it up)
}   // end of setup

void loop ()
 {
  // send various test combinations
  sendByte(BARS_1_4, BAR1_RED | BAR2_GREEN | BAR3_RED | BAR4_GREEN);
  sendByte(BARS_5_8, BAR2_RED);
  sendByte(BARS_9_12, BAR2_YELLOW);
  sendByte(BARS_13_16, BAR1_RED | BAR2_GREEN | BAR3_RED | BAR4_GREEN);
  sendByte(BARS_17_20, BAR2_YELLOW);
  sendByte(BARS_21_24, BAR1_RED | BAR2_RED);
 }  // end of loop

This is documented in my page about the MAX7219.

It is common cathode. The MAX7219's are a bit pricey, considering I need 9 bar graphs for the project. I was hoping to use the cheaper 595's and just add a transistor array to increase power, but looks like the 7219 might be the way to go. As they are designed to run 7 segment displays how would I connect it to transfer from my current 16 bit binary shift setup, to the correct pins on the MAX. I know on my shift registers pins 1-8 go to the LED anodes and Pins 9-11 go to transistors that run the cathodes. Can you help me understand the pin connections to get the MAX to run this?

See amended answer.

According to the Adafruit page for that product "Since the display is multiplexed we suggest using 3 NPN transistors to drive the cathodes with microcontroller pins and then a 74HC595 to drive the 8 anodes." So, certainly using transistors and a 595 is a possibility. But for 9 of them I think you will find yourself swamped by wires, transistors and resistors, and that the MAX7219 will simply the process.

Thanks, that was very helpful. Just FYI the common cathodes are each doubled so cathodes 8,9,&14 are not necessary. They just allow you to wire from either side of the display easier. I'll try to find a better deal on the MAX7219's. I was a little nervous buying the cheap kits that came with them rather than buying from manufacturer, simply because of the massive price difference. I'll give that a try though.

So far I haven't had a problem with the eBay ones, and for the price, even if I did, I wouldn't be too concerned. I've ordered a couple of your bar LED displays to see how easy it would be to adapt them to the MAX7219. I suspect it will be fairly easy.

Thanks Nick. I've built the test mode for just 2 with 595's. The wiring is a bit intense. According to my design I will only have at max 4 displays per Arduino board. The setup has 5 different interlinked Arduinos.

@B.Guisgand - I've amended the answer with an example of wiring up the LED modules, and some code.

Thanks this was exactly what I needed. Much Appreciated.


text:
servo.read() starts at negative value, no matter where servo actually is
I don't like how my servo quickly jumps to the default middle position, so I commented out the line where DEFAULT_PULSE_WIDTH is set in Servo.cpp:
//servos[this->servoIndex].ticks = usToTicks(DEFAULT_PULSE_WIDTH);

Unfortunately while this stopped the servo from moving on execution of attach, the position of the servo is now showing up as -52!
Just running the following in setup() is enough to generate the bug:
int servo_pin = 53;
servo.attach(servo_pin);
Serial.print("Initial position: ");
Serial.println(servo.read());  //returns -52

This last line returns -52 no matter what position the servo is actually in, which has bad consequences (its initial movement is way off).
Note I get the same behavior when I set the DEFAULT_PULSE_WIDTH to 0 in Servo.h.
I am using a Mega -- an Elegoo clone -- on Windows 10.
Note I got the ideas for stopping the servo from moving on initialization from these threads:

https://stackoverflow.com/questions/40892922/how-to-stop-an-arduino-servo-from-moving-during-the-myservo-attach-command?noredirect=1&lq=1
https://stackoverflow.com/questions/26695670/attach-arduino-servo-without-moving

you are using Windows 10 to control the servo somehow?

Yes, mentioned at the end of my question.

how are you using Windows to to control the servo?

I'm using the IDE in windows just using a standard sweep algorithm. You can see code here: https://onlinegdb.com/HJIKaZv9z  But really all you need to reproduce it is what I showed above in setup().

You seem to be starting from a fundamental misunderstanding of RC hobby type PWM servos.  To put it simply, they do not electronically output any position information.
Until you have commanded a position and the servo loop has had a fair chance to seek to that, the position of the servo is utterly and entirely unknowable.
This is stated in the documentation of the Arduino servo system:
read()

Description

Read the current angle of the servo (the value passed to the last call to write()).

As this explains, the returned value is not the physical position, but rather the last commanded position.
Until you have commanded a position (something your code does not do) the return value of this call is physically meaningless.

For those curious, what you would need is a servo with feedback. Something like this: https://www.adafruit.com/product/1404  I thought I was accessing that information, but no.


text:
SH1106 - Transferring long buffer via SPI
I am using an SH1106 and am creating my own driver for it. Nearly everything is doing great with about 2/3ms send time using transfer16. I did notice however that I can use transfer with a buffer and length to give a 1ms display time; something that'd be extremely useful.
For reference before here is the datasheet:
http://support.technologicalarts.ca/docs/Components/OLED13-SPI/SH1106.pdf
So the working solution is this:
SPI.beginTransaction(settings);
//
for (int page = 0; page < 8; page++)
{
    digitalWrite(DC, LOW);
    SPI.transfer(0xB0 + page);
    SPI.transfer(0x02);
    SPI.transfer(0x10);
    digitalWrite(DC, HIGH);

    for (int column = 0; column < 128; column += 2)
        SPI.transfer16(buffer[(page * 128) + column]);
}
digitalWrite(DC, LOW);
//
SPI.endTransaction();

This for each of the 8 pages writes the 128 bytes 2 at a time. I want to write the 128 bytes in a single call. This would be something like this:
SPI.transfer(buffer + (page * 128), 128);

This however sort of inverts the display. It literally turns every pixel on for some reason and I can't figure out why. I am just using a few bytes set to 255 for testing and with the original method this works perfect.
Am I using the call wrong? Is there a limit to the buffer size I could use, I haven't really seen anything about that at the moment. I tried changed the pointer arithmetic but wasn't successful. I tried moving the 128 bytes into a temporary location and use that but still nothing.
Obviously this isn't major and maybe I could somehow improve the transfer in other ways but if you have any advice I'd love to have it
----- EDIT -----
I have had some luck now with using the transfer with buffer method when I changed the page datatype to a uint8_t. It also caused a few more issues however and I am not sure what is causing them.

Firstly with a fast display rate the display inverts itself once again with all pixels on.
With a delay between display calls, it works! But after a few seconds those pixels slowly go away, something I have never experienced before.

Here is the edited code:
SPI.beginTransaction(settings);
//
for (uint8_t page = 0; page < 8; page++)
{
    SPI.transfer(0xB0 + page);
    SPI.transfer(0x02);
    SPI.transfer(0x10);

    digitalWrite(DC, HIGH);
    SPI.transfer(buffer + (page * 128), 128);
    digitalWrite(DC, LOW);
}
//
SPI.endTransaction();

It's hard to explain whats actually happening. But without a large delay between the calls of the buffer transfer method the screen freaks out and will maybe invert completely if it's too often. Even with the large delay the pixels randomly vanish over time, something I have never actually seen.
The 2 byte send method doesn't have any of these problems. No delay will work fine.

Check endianess. Swap the byte order for every 2-byte pair in the buffer for a test.  (for(int i=0; i < sizeof(buffer); i +=2) { byte tmp = buffer[i]; buffer[i] = buffer[i+1]; buffer[i+1] = tmp; }

No issues there, just this method on it's own

Where is buffer declared?

Within the class, as 'uint8_t buffer[1024] = {0}'

You seem to have understood the following but just for clarification:
transfer16(uint16_t word), as the name implies, shifts 16bits/2bytes instead of just 8bits/1byte like transfer(uint8_t byte).
transfer(uint8_t* buffer, unsigned int size) on the other hand takes a pointer and the amount of bytes to shift.
Now to pointer arithmetic. Operations on pointer variables are dependent on their explicit data type(as well as processor architecture!). Therefore, in our case, a +1 on uint8_t* val will advance the pointer by 8bits.
+1 on uint32_t* val will do so by 4bytes/32bits.
Check buffer's data type
It should be any of char, unsigned char, uint8_t, int8_t

Ah I see, it's a uint8_t. So by using page as an integer I assume I am pushing it 4 bytes instead of 1. Seems I need to do a bit of revision!

I made some progress but am encountering more issues. I edited the post detailing these


text:
Comparing button presses to correct sequence
I am creating a memory game with the Arduino. It has four buttons, each for a different colored led. The leds will blink in a random sequence and either fail or add another light in the next sequence if the user presses the correct buttons. I have also attached an lcd screen to late implement a score tally.
Right now, the welcome lights display and the sound is working fine, but when the sequence starts, it will act as though I am pressing a button and proceed through the fail light method. I think the last method is causing this issue where I am comparing the button pressed to the sequence.
I would appreciate any help!
This is essentially my wiring just with different pins chosen:

What have you done to try to understand the problem? Put some debug prints in, see where it's going wrong.

I have outputted the button states as well as the button state right before it checks the sequence along with the seq. In the serial monitor it will say button3 = 1 when I have not pressed any buttons since the start of the program.

the buttons in schema have pull-down resistors

That was one of the things I was thinking could be wrong since I declare the pinModes with INPUT_PULLUP. Should I instead just use INPUT? Or would it be more efficient to not have the pull down resistors?

I found that I did not need the pull down resistors for each button since I had declared the pinMode for each button to be INPUT_PULLUP. So instead of the schematic above, I took out the resistors for the buttons and instead wired one side of the buttons to ground.

The problem might be that you do not debounce the buttons. When you press a button, there is somehwere between fully pressed and not pressed (or backwards) a state there it 'bounces', e.g. you get lots of state transitions, resulting in seeing a button pressed twice or many times instead of once.
Check the debounce example in the default Arduino Tutorial

Thank you. I don't even press any buttons though, and it does this.

Check the variable button just before FailLight, is it -1 (expected) or has it a button (press) value?

the button value is 0 before the fail light

Are you sure that if(button0 == LOW){
should be LOW and not HIGH?

well for the pinMode of the buttons, i set them to INPUT_PULLUP so doesn't that make the states opposite? (HIGH when not pressed and LOW when pressed)

I think it would be best just to load the most simple example from using buttons and check the result... also you will probably need the debounce algorithm anyway.

Let us continue this discussion in chat.