text:
please explain the sketch attached
Sorry about a newbie.
1. what mening of:
    if(Xstr[XstrLength-1] != '|'){
      Xstr[XstrLength] = '|';
      Xstr[XstrLength+1] = '\0';

the setup: char Xstr[60]; what means? and then: itoa(Yint,Ystr,10);

Code:
#include <VirtualWire.h>

//gamepad setup
int up_button = 2;
int down_button = 4;
int left_button = 5;
int right_button = 3;
int start_button = 6;
int select_button = 7;
int joystick_button = 8;
int joystick_axis_x = A0;
int joystick_axis_y = A1;
int buttons[] = {up_button, down_button, left_button, right_button, start_button, select_button, joystick_button};

void setup()
{

    //gamepad setup
    for (int i; i < 7; i++)
    {
        pinMode(buttons[i], INPUT);
        digitalWrite(buttons[i], HIGH);
    }

    Serial.begin( 9600 );

    //transmitter setup
    vw_set_tx_pin(12);          // Sets pin D12 as the TX pin
    vw_set_ptt_inverted(true);  // Required for DR3100
    vw_setup(2000);             // Bits per sec
}

int counter = 0;

int Xint;
int Yint;

char Xstr[60];
char Ystr[60];

void loop()
{
    // Read and store Sensor  data
    Xint = analogRead(joystick_axis_x);
    Yint = analogRead(joystick_axis_y);

    // Convert integer data to Char array directly
    itoa(Yint,Ystr,10);
    itoa(Xint,Xstr,10);

    int XstrLength = String(Xstr).length();

    if(Xstr[XstrLength-1] != '|'){
        Xstr[XstrLength] = '|';
        Xstr[XstrLength+1] = '\0';
    }

    char combinedArray[String(Xstr).length() + String(Ystr).length() + 1];
    sprintf(combinedArray, "%s%s", Xstr, Ystr);

    vw_send((uint8_t *)combinedArray, strlen(combinedArray));
    vw_wait_tx(); // Wait until the whole message is gone

    Serial.println(combinedArray);

}

This adds some end of string characters.
if(Xstr[XstrLength-1] != '|'){
    Xstr[XstrLength] = '|';
    Xstr[XstrLength+1] = '\0'

First it checks if Xstr last character is a '|', if not:
   Place a | directly after the last character
   And append a '\0', which is a symbol to 'end' a string
A string in C/C++ is normally build up like this, e.g. "Hello" contains of the bytes:
'H', 'e', 'l', 'l', 'o', \0

Where each of the above are ASCII characters/values and the last \0 a 0 byte.

char Xstr[60]; defines a character array (string) that can contain 60 characters. Note however, that the ending \0 also needs to be in this string, so you can actually only put 59 characters inside.
itoa(Yint,Ystr,10); converts Yint which is an integer value to a string (where each digit has each own byte), and 10 is the length.

Thank you Michel Keijzers.  I confused with char Xstr[60] and  itoa(Yint,Ystr,10), actually they not same thing.

Gladly done, If the answer helps you, please consider upvote and accept my answer.

HI, when used a MCP4261, there is function "digitalPotWrite" , can I use "digitalWrite" replace it? Thanks.

Because the "digitalPotWrite" need be void definition， can't be used inside setup.

digitalPotWrite is a function to communicate with the MCP4261 over SPI. digitalWrite is a function to set an IO pin HIGH or LOW. The two have nothing at all to do with each other.


text:
16*2 1602A LCD not displaying any character or contrast, although correct wiring
I've used my LCD display with a lot of small projects. Now it doesn't work anymore. Most of the diagrams you find online use resistors and potentiometers. However I never done that, but still got it to work nonetheless.
I tried different schematics, but none of them seem to work. So I'm thinking I broke my LCD somehow.
I'm pretty sure the schematic I'm currently using works. The backlight works but nothing is being printed.
Pictures of the project (Warning!! wire hell)
The LCD component is a blue 16x2 1602A v2.0 display.
All the components come from the official Arduino starter kit, except for the wires. Though I tested every single wire for continuity, to make absolutely sure the problem was not within the wires themselves.
Also, turning the potentiometer doesn't show any blocks, or change anything on the LCD as expected.
Code:
#include <LiquidCrystal.h>
//LiquidCrystal lcd(RS, E, D4, D5, D6, D7);
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
  pinMode(6,OUTPUT);
  analogWrite(6,90); //sweetspot for backlight without using a potentiometer.

  lcd.begin(16, 2);
  //lcd.setCursor(0,0);
  lcd.print("hello, world!");
}

void loop() {
}

I'm not sure what's wrong, I tested everything I can think off.
I can upload more (cleaner) pictures if requested, I just didn't want to tear down my other project.

What do you mean? I said that turning the potentiometer doesn't change anything to the display.

Look at the schematic I posted, this is exactly what I'm doing, the potentiometer is connected to the 3rd pin on the display (V0). The brightness is being controlled by PWM on pin 6, value 90 gives it  just enough backlight for things to be readable. I've always used it like this.

Ok so the problem were the wires.
Although I tested every single wire for continuity I went to the store and bought a brand new (expensive/not-from-aliexpress) pack of jumper wires. I rewired the entire project with the schematic and code that was posted in my question-post and it worked like a charm..
So I'm not sure what exactly caused the problem, but it was in the wire. I thought having continuity in a wire is like a 100% proof that the wire works properly. Maybe someone has an idea what could cause this?
So again, I only replaced the wires, not the schematic nor the code, with brand new ones and it worked perfectly.

I have an suggestion.  Try removing the comment from this line:  //lcd.setCursor(0,0);
You need to be sure your text is displaying on the first line, first position(0,0).

(This is a duplicate).
I solved it following this:

The contrast can be adjusted by the potential-meter displayed in the following picture.

credit

The LCD is working perfectly fine (hardware side).
Only 2 changes require in your code.
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
  pinMode(6,OUTPUT);
  analogWrite(6,90); //sweetspot for backlight without using a potentiometer.

  lcd.begin(16, 2);
  lcd.setCursor(0,0);
  lcd.print("hello, world!");
  delay(3000);
}

void loop() {
}

Added delay (it must!) and set the cursor position.
Try above code and let inform.

Adding delay or change the cursor position did not change anything. I don't even think it is necessary. Cursor position is by default on (0,0).

source: Stack Exchange

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

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

sort: votes


text:
Arduino digital input fluctuates with neighbouring pins
I am using digital pins (2,3,4,5) to play midi notes on and off with 3pdt switches with pull down 10k resistor between input pin and ground.
However when I press button 2 randomly at different time interval it sometimes shows pin 3 high in the monitor. (after reading forums here I have realised that it might be due to big switches that I am using where the physical contact plates might be reason for this). I have even changed wires and isolated them from each other to rule out the noise from the wires.
I have checked all the connections and soldered the Arduino board pins with best possible skills that I have and tracks are all clear.
Same case occurs between other buttons as but its not always.
However after reading about Debounce I have made changes to the code as following, now I got the error only once after that I havent seen it. Can someone have look at the code and advice me if I have assigned Debounce function to multiple switches correctly and if not, what should it be as I am new with coding
Since I am using 3pdt switch I have added switch mode..
#include <MIDI.h>

int buttonPin[] = {2, 3, 4, 5};
byte mode[] = {0, 0 , 0 ,0};
boolean currentState = LOW;
boolean lastState = LOW;
int buttonPinM[] = {6, 7, 8, 9};
byte mode1[] = {0, 0, 0, 0};

boolean currentState1 = LOW;
boolean lastState1 = LOW;

long lastDebounceTime = 0;
long debounceDelay = 50;

void setup (){
    MIDI.begin(MIDI_CHANNEL_OMNI);

    int i;
    for (i = 0; i < 4; i++) {
        pinMode(buttonPin[i], INPUT);
    }
    int j;
    for (j = 0; j < 4; j++) {
        pinMode(buttonPinM[j], INPUT);
    }

    {
        int i;
        for (i = 0; i < 4; i++);
    }
    {
        int j;
        for (j = 0; j < 4; j++);
    }
}

// This will track which pin/mode we're using

int j = 0;
int i = 0;

void loop () {
    {
        currentState = digitalRead(buttonPin[i]);

        if ( (millis() - lastDebounceTime) > debounceDelay) {
            switch (mode[i]) {
                case 0:
                    if (currentState == HIGH) {
                        MIDI.sendNoteOff (i+55, 0, 1);
                        mode[i] = 1;
                        lastDebounceTime = millis();
                    }
                    break;
                case 1:
                    if (currentState == HIGH)
                        mode[i] = 2;
                    break;
                case 2:
                    if (currentState == LOW) {
                        MIDI.sendNoteOn (i+55, 127, 1);
                        mode[i] = 3;
                        lastDebounceTime = millis();
                    }
                    break;
                case 3:
                    if (currentState == LOW)
                        mode[i] = 0;
                    break;
            }
        }
        lastState = currentState;
        if (++i > 3)
            i = 0;
    }
    {
        currentState1 = digitalRead(buttonPinM[j]);
        if ( (millis() - lastDebounceTime) > debounceDelay) {
            switch (mode1[j]) {
                case 0:
                    if (currentState1 == HIGH ) {
                        MIDI.sendNoteOn (j+61, 127, 1);
                        mode1[j] = 1;
                        lastDebounceTime = millis();
                    }
                    break;
                case 1:
                    if (currentState1 == HIGH)
                        mode1[j] = 2;
                    break;
                case 2:
                    if (currentState1 == LOW) {
                        MIDI.sendNoteOff (j+61, 0, 1);
                        mode1[j] = 3;
                        lastDebounceTime = millis();
                    }
                    break;
                case 3:
                    if (currentState1 == LOW)
                        mode1[j] = 0;
                break;
            }
        }
        lastState1 = currentState1;
        if (++j > 3)
            j = 0;
    }
}

Please edit your post and format the code using the code formatting markdown (four leading spaces). For help see Markdown help. You should be able to do this by selecting the code and pressing Ctrl+K to have your browser do this for you.

Usually when something "fluctuates" it means that it had not a fixed state: this is usual when you use a button without a pull-up/pull-down. But if you have a double-throw (xxDT) switch and connected BOTH vcc and ground to its terminals, well, maybe it's just a bad contact...

@frarugi87 I cross checked all that and changed the pcb as well. Do you think its the code??

@NickGammon have made the changes.

Your code is very hard to read. The IDE has an auto-format feature. Please use it and re-submit your code. Also please include (an image of) your wiring. Descriptions of wiring rarely do the actual situation justice.

Posting here since it is quite long, but it's not a complete answer, just a few thoughts and a possible improvement.
Ok, so there are a couple of things in your code I don't understand:
1: in the setup()
{
    int i;
    for (i = 0; i < 4; i++);
}
{
    int j;
    for (j = 0; j < 4; j++);
}

What are these for?
2: debouncing
You are not implementing it correctly, at least not for me. You are reading the button every 50ms, without debouncing. Ok, you won't see "bounces", but there are better solutions (see later).
3: modes 1 and 3
They are quite useless. What are they for?
4: pins 6,7,8,9
What are they for?
5: variable laststate
What is it for? You never use it
6: updating one button per loop
Is it needed? I mean, you are just updating one button per loop instead of all of them for each loop.
In the end
Ok, now my suggestions, apart from learning to indent the code (otherwise it's impossible to read it): I always use the bounce2 class to debounce a button, since it contains everything inside and.. Well, it works well. It can also detect the rising and falling edges of the button, thing that you need if I interpreted correctly your code.
One more thing: debounce delay can be lowered (even to just 5ms):
#include <MIDI.h>
#include <Bounce2.h>

int buttonPin[] = {2, 3, 4, 5};
int buttonPinM[] = {6, 7, 8, 9};

Bounce debouncers[4];
Bounce debouncersM[4];

int debounceDelay = 50; // Usually is lower - even 5ms is fine
uint8_t i = 0;

void setup ()
{
    MIDI.begin(MIDI_CHANNEL_OMNI);

    for (i = 0; i < 4; i++)
    {
        pinMode(buttonPin[i], INPUT);
        debouncers[i].attach(buttonPin[i]);
        debouncers[i].interval(debounceDelay);

        pinMode(buttonPinM[i], INPUT);
        debouncersM[i].attach(buttonPinM[i]);
        debouncersM[i].interval(debounceDelay);
    }
}

void loop ()
{
    for (i = 0; i < 4; i++)
    {
        debouncers[i].update();
        debouncersM[i].update();
    }

    for (i = 0; i < 4; i++)
    {
        if (debouncers[i].rose()) // button i switched from 0 to 1
            MIDI.sendNoteOff(i+55, 0, 1);
        if (debouncers[i].fell()) // button i switched from 1 to 0
            MIDI.sendNoteOn (i+55, 127, 1);
        if (debouncersM[i].rose()) // button i switched from 0 to 1
            MIDI.sendNoteOn (i+61, 127, 1);
        if (debouncersM[i].fell()) // button i switched from 1 to 0
            MIDI.sendNoteOff(i+61, 0, 1);
    }
}

Thanks @frarugi87
1.In the set up mode INT i and j are for 2 groups of switches (4 switches each)  and have different functions in this code One group of switches are sending NoteOn command when the Input is high and other group will send NoteOff command when the Input is High.
2.I might be absolutely wrong with my debounce logic with this code
3. BY mode 1 and 3 you mean Case 1 and 3 right???Since its a 3pdt where the switch physically locks the State of the switch I thought its better to make CASE but I will try your code and update if it works with my switch

@Ashish well, you always have just two states. You can use a switch-case approach, but cases 1 and 3 are useless, since you exit from that mode (I called them modes since the variable mode decides the case) immediately (the condition is the same as the previous one). Anyway I suggest you the bounce approach: easier, faster and less error prone

@fraugi87 I understood what you said and it makes sense. Thank you for your prompt reply. I will do some test and revert back asap!!!

@fraugi87 I tried your code and its working fine. I didnt make any changes just your code and it works. Earlier you mentioned its not a complete solution. Is there more to improvise??

@Ashish I said it was not complete because I did not understand where the problem was, and so mine were just "generic" advices. If it works, this becomes a real solution, but again I do not understand why this works and yours not ;) Maybe just because of the incorrect debouncing, but anyway... The only improvement you can make is to remove the division between the two button sets, but it's not a practical improvement, just a more readable solution..

My code is working as well but only sometimes the digital pins reads another number. Maybe you are right about the Debouncing :-)

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


text:
Pass changing analog value from void loop to library .h file
How would I go about passing a void loop analog read value to a library .h file?
I've tried it but it only reads the pot position as soon as I plug the arduino in and does not change once booted up.
arduino main sketch file code;
#include "Arduino.h"
#include "common.h"
#include "synth.h"
#include "serial-in.h"
#include "audio-out.h"

void setup() {
  Synth<0>::initialize();
  SerialIn<0>::open();
  AudioOut<0>::open();
}

void loop() {
  int val = analogRead(A0);
  int val1 = analogRead(A1);
  int val2 = analogRead(A2);
  int val3 = analogRead(A3);
  int val4 = analogRead(A4);
  while (true) {
    if (SerialIn<0>::available()) {
      uint8_t b = SerialIn<0>::read();
      Synth<0>::receive_midi_byte(b);
    }

    int8_t level = Synth<0>::clock();
    AudioOut<0>::write(level);
  }
}

.h file code
#pragma once

// #define private public  // for tests

#include "common.h"

// associations of units
#define IOsc        Osc
#define IFilter     Filter
#define IAmp        Amp
#define IEG         EG
#define IVoice      Voice
#define ISynthCore  SynthCore

#include "osc.h"
#include "filter.h"
#include "amp.h"
#include "eg.h"
#include "voice.h"
#include "synth-core.h"

template <uint8_t T>
class Synth {
public:
  INLINE static void initialize() {
    ISynthCore<0>::initialize();
    int val = analogRead(A0);
    int val1 = analogRead(A1);
    int val2 = analogRead(A2);
    int val3 = analogRead(A3);
    int val4 = analogRead(A4);
    // Preset
    ISynthCore<0>::control_change(OSC_MODE      , 0  );
    ISynthCore<0>::control_change(OSC_COLOR     , val);
    ISynthCore<0>::control_change(MOD_RATE      , 8  );
    ISynthCore<0>::control_change(MOD_DEPTH     , val1);
    ISynthCore<0>::control_change(LPF_CUTOFF_ENV, val2);
    ISynthCore<0>::control_change(LPF_RESONANCE , val3);
    ISynthCore<0>::control_change(ENV_A         , val4 );
    ISynthCore<0>::control_change(ENV_D_R       , 1 );
  }

  INLINE static void receive_midi_byte(uint8_t b) {
    ISynthCore<0>::receive_midi_byte(b);
  }

  INLINE static int8_t clock() {
    return ISynthCore<0>::clock();
  }
};

I think it's going to be hard for anyone to answer the question the way you want. Your code has two sets of variables called val, val1 etc: one in your Synth class, one in the loop().  They are different, separate.  Writing to one will not change the other.
Both sets are changed only at startup - first setup() calls Synth::initialize() which does a load of analogRead calls and sets its val variables.   Then in loop() you do more analogRead calls, and set the local val variables.
Synth only does anything with those values when you call initialize(). Does that help?

First of all, the while(true) loop in the loop function is wrong. You will need to put in the loop only the code which needs to be repeatedly called. So
void loop() {
  if (SerialIn<0>::available()) {
    uint8_t b = SerialIn<0>::read();
    Synth<0>::receive_midi_byte(b);
  }

  int8_t level = Synth<0>::clock();
  AudioOut<0>::write(level);
}

Then, I haven't understood where the analog read values are used. Moreover the fact that in the initialization you read the analog values and in the loop you expect them to be passed is inconsistent. From what I read, the values should be passed to control_change; you can do one of these things, in my opinion:
1) manage the analog reading from the main:
void setup() {
    Synth<0>::initialize(analogRead(A0), analogRead(A1), analogRead(A2), analogRead(A3), analogRead(A4));
    SerialIn<0>::open();
    AudioOut<0>::open();
}

void loop() {
    Synth<0>::change_OSC_COLOR(analogRead(A0));
    Synth<0>::change_MOD_DEPTH(analogRead(A1));
    ...

    if (SerialIn<0>::available()) {
        uint8_t b = SerialIn<0>::read();
        Synth<0>::receive_midi_byte(b);
    }

    int8_t level = Synth<0>::clock();
    AudioOut<0>::write(level);
}

// in h file

INLINE static void initialize(int val, int val1, int val2, int val3, int val4) {
    ISynthCore<0>::initialize();

    change_OSC_MODE(0);
    change_OSC_COLOR(val);
    change_MOD_RATE(8);
    change_MOD_DEPTH(val1);
    change_LPF_CUTOFF_ENV(val2);
    change_LPF_RESONANCE(val3);
    change_ENV_A(val4);
    change_ENV_D_R(1);
}

INLINE static void change_OSC_MODE(int value) {
    ISynthCore<0>::control_change(OSC_MODE, value);
}

INLINE static void change_OSC_COLOR(int value) {
    ISynthCore<0>::control_change(OSC_COLOR, value);
}

INLINE static void change_MOD_RATE(int value) {
    ISynthCore<0>::control_change(MOD_RATE, value);
}

...

or, alternatively,
...
void loop() {
    Synth<0>::change_param(OSC_COLOR, analogRead(A0));
    Synth<0>::change_param(MOD_DEPTH, analogRead(A1));
    ...

}

// in h file

INLINE static void initialize(int val, int val1, int val2, int val3, int val4) {
    ISynthCore<0>::initialize();

    change_param(OSC_MODE, 0);
    change_param(OSC_COLOR, val);
    ...
}

INLINE static void change_param(uint8_t param, int value) {
    ISynthCore<0>::control_change(param, value);
}

(I prefer the firsti since you can prevent the user from using some parameters)
2) manage the analog reading from the library:
void setup() {
    Synth<0>::initialize();
    SerialIn<0>::open();
    AudioOut<0>::open();
}

void loop() {
    Synth<0>::updateAnalog();

    if (SerialIn<0>::available()) {
        uint8_t b = SerialIn<0>::read();
        Synth<0>::receive_midi_byte(b);
    }

    int8_t level = Synth<0>::clock();
    AudioOut<0>::write(level);
}

// in h file
INLINE static void initialize() {
    ISynthCore<0>::initialize();
    updateAnalog();
}

INLINE static void updateAnalog() {
    int val = analogRead(A0);
    int val1 = analogRead(A1);
    int val2 = analogRead(A2);
    int val3 = analogRead(A3);
    int val4 = analogRead(A4);
    ISynthCore<0>::control_change(OSC_MODE      , 0  );
    ISynthCore<0>::control_change(OSC_COLOR     , val);
    ISynthCore<0>::control_change(MOD_RATE      , 8  );
    ISynthCore<0>::control_change(MOD_DEPTH     , val1);
    ISynthCore<0>::control_change(LPF_CUTOFF_ENV, val2);
    ISynthCore<0>::control_change(LPF_RESONANCE , val3);
    ISynthCore<0>::control_change(ENV_A         , val4 );
    ISynthCore<0>::control_change(ENV_D_R       , 1 );
}

Each method has advantages or disadvantages... You should pick the one more suitable for you

On the first method I get this error:
Expected primary-expression before 'int'
ISynthCore<0>::initialize(int val, int val1, int val2, int val3, int val4);

Sorry, that was a typo. The list of the parameters should have gone in the other initialize line... Now I should have fixed it (int val, int val1, int val2, int val3, int val4 goes in the line above the one where you saw it)

Tried that, another error again I'm afraid. Changed the code as you said
'change_MOD_DEPTH' is not a member of 'Synth<0u>'

@CasperRound the ... at the end means "do this for all the other members you need", so just add the remaining ones ;)

I've already done that. Haha

So is it ok now?

How would I go about passing a void loop analog read value to a library .h file?

What you wanted to do makes little sense. But it is certainly doable. The simplest would be to use an "extern" variable as a bridge.


text:
Attach Interrupt problem
I'm just learning how to use the Arduino Uno and I'm trying to control the speed of an AC fan. I made a sketch of this project on proteus but the triac seems not to be responding. I guess there's a problem with the attachInterrupt part of the code. Here's the code:
#define triacPulse 5
#define interruptPin 2

//button event
#define button1 6

void setup() {
  // put your setup code here, to run once:
  pinMode(button1, INPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  if(button1==HIGH){
    attachInterrupt(0, triacControl, FALLING);
  }
}

void triacControl()
{
  delay(5);   //delay for 5 milliseconds
  digitalWrite(triacPulse, HIGH);
  delay(5);

  digitalWrite(triacPulse, LOW);
}

Thanks for the answer in advance

Do not use delay() in an interrupt. Ever.

First of all, please use the code tag to put code here, otherwise it is not readable from the others. Then, as Majenko said, do not use delay() in an interrupt. Ever. And if you ever find an application where you should use delays in an interrupt, you are wrong and you should not use it. As for the program, what do you want to do? In any case the code you wrote is not correct, since it is not the correct way to think interrupts. And finally, what do you expect by turning off and on a triac for 5ms? Usually you turn it on or off for a whole semi-period (but it should be synchronized)

I don't think you should be putting attachInterupt in your loop.  You button may be bouncing so you could be attaching it many times each press.
-- OH BTW Don't take any of these comments as criticism, don't get put off --

First of all your if statement will always be false. You ask if 6 equals 1 (from arduino.h).
It schould be digitalRead(button1) == HIGH. Also it looks like your button should start an impulse of 5ms. Am I right?
In this case you will attach the Interrupt to the Button. Also don't put delays in the Interrupt function. Another thing, that isn't important in small Projects only for you, is to increase the readability by typing "define constants" uppercase, so you know where to find them and that they aren't changeable variables (For this reason HIGH, LOW, INPUT, RISING, ... are all uppercase).
All in all the code should be look like this:
#define BUTTON1PIN          6
#define TRIACPIN            5
#define TRIACPULSE          5                       // [ms]

bool doPulse = false;
long triacStartTime = 0;

void setup(){
  pinMode(BUTTON1PIN, INPUT);
  pinMode(TRIACPIN, OUTPUT);
  attachInterrupt(BUTTON1PIN, pulseISR, RISING);    // attach a Interrupt once!
                                                    // pulseISR is called everytime the button is pressed
                                                    // ISR: Interrupt service Routine (only for Readability)
}

void loop(){
  if(doPulse){
    digitalWrite(TRIACPIN, HIGH);
    triacStartTime = millis();
    doPulse = false;
  }
  if(millis() > triacStartTime + TRIACPULSE){        // Shut down after 5 ms
    digitalWrite(TRIACPIN, LOW);
  }
}

void pulseISR(){
  doPulse = true;                                    // NO delays in ISR! And as short as possible
}

Personally I find it a bit overkill to use an ISR to detect a button. Also, without any debouncing, it will give a lot of troubles. Finally, if he is using a zero-crossing optocoupler (or a solid state relay with a zero crossing optocoupler) he will have problems with 5ms times (remember that a 50Hz wave crosses the zero once per 10ms, while a 60Hz one every 8.3ms). In my opinion, the OP has not clear what he needs to do yet, so better have him figure out what to do rather than providing him solutions that will make things more complicated..

@frarugi87 Of course it is an overkill. But he ask for a solution for his interrupt problem and after seeing his approach i had to show the correct way of using an interrupt. I still think he might want to use some kind of PWM for his speed control, but as you stated, the timing is kind of strange for this purpose.

I'm actually doing a college project on controlling the speed of an AC fan, so the code I uploaded is a form of sketch I wrote to see a prototype simulation on PROTEUS before implementing it. I not going to use a button, but rather a temperature sensor. The button I used is just to force an event. I'm considering a frquency of 50Hz. And of course, the wave crosses the zero once every 10ms. so, I'm tring to achieve a 5ms delay after the crossing to obtain a reduced average power in the end.


text:
Arduino UNO and SPI eeprom (AT93C46D)
I'm trying to write to and read from an AT93C46D eeprom using an Arduino UNO but for some reason the output I'm getting is not what I expect.
The eeprom has a data structure of 128 words of 8 bits each and I'm trying to write 10000010 to each word. When reading back the data however I get 11000001.
When I write 00000000 to all words I get 10000000 for all words when reading. I tested my code on 2 AT93C46D eeproms and both gave the same result.
It looks like the MSB is always 1 (when reading) for some reason.
I'm probably making a stupid mistake but I can't seem to find it, any help is greatly appreciated!
Datasheet: http://www.atmel.com/images/atmel-5193-seeprom-at93c46d-datasheet.pdf
#include<SPI.h>
#define DATAOUT 11//MOSI
#define DATAIN  12//MISO
#define SPICLOCK  13//sck
#define SS 10//ss

void setup()
{
  pinMode(SS,OUTPUT);
  pinMode(DATAOUT, OUTPUT);
  pinMode(DATAIN, INPUT);
  pinMode(SPICLOCK,OUTPUT);
  digitalWrite(SS,LOW);

  Serial.begin(9600);

  SPI.beginTransaction(SPISettings(2000000, MSBFIRST, SPI_MODE0));

  fill();

  dump();
}

void loop()
{

}

void fill()
{
  Serial.println("Send EWEN opcode");
  digitalWrite(SS,HIGH);
  SPI.transfer(B10011); //EWEN
  SPI.transfer(B0000000);
  digitalWrite(SS,LOW);

  delay(100);

  for (int i=0; i < 128; i++) {
    digitalWrite(SS,HIGH);
    SPI.transfer(B101);
    SPI.transfer(i);
    SPI.transfer(B10000010);
    delay(10);
    digitalWrite(SS,LOW);
  }

  delay(100);

  Serial.println("Send EWDS opcode");
  digitalWrite(SS,HIGH);
  SPI.transfer(B1000); //EWDS
  SPI.transfer(B00000000);
  digitalWrite(SS,LOW);

  delay(10);
}

void dump(){
  Serial.println("Dumping AT93C46D");

  byte b;

  for (int i=0; i < 128; i++) {
    digitalWrite(SS,HIGH);
    SPI.transfer(B110); //read opcode
    SPI.transfer(i);
    b = SPI.transfer(B00000000); //clock data out
    digitalWrite(SS,LOW);
    Serial.println(b, BIN);
  }
}

That does not look like an SPI device (or at least 8-bit aligned). Might need to bit-bang that device.

B10011? Don't you mean B10011000?

After looking at the product spec again I think it might be possible to get this working. The protocol is MSB with a start bit S followed by two bit op-code, and parameters. SPI on AVR is 8-bit transfer but transfer can be byte aligned with the start bit.
READ is op-code(10) followed by 7-bit address, a dummy bit and the read value. That is in total 11+8-bits. Mapping that to 8-bit transfer would be:
spi.transfer(0b110);
spi.transfer(addr << 1);
data = spi.transfer(0);

That will give 5-bit zero, start-bit, op-code in the first transfer, and followed by 7-bit address and dummy bit (LSB) in second transfer. The third transfer is the read data.
EWEN would map to:
spi.transfer(0b1001);
spi.transfer(0b10000000);

EWEN has op-code(00), followed by 9-bits, 0b11XXXXXXX.
The WRITE operation becomes:
spi.transfer(0b10);
spi.transfer(0x80 | addr);
spi.transfer(data);

Cheers!

I updated my .ino file per your suggestion: https://gist.github.com/anonymous/5f29911c6f1c15d0660f
But now I get even stranger results, by writing 0 to all bits the output is '10000000' for the first half of the words and '11111111' for the second half.
What is your reasoning behind doing address & 0x7f?

There is much more to consider with the other commands. In any case, the READ command has to create the sequence S(1), OP(10), ADDR(7-bit). The LSB of OP is MSB of the 8-bit with address therefore addr & 0x7f (alternatively alway keep address less than 128). The was a way to explain where the LSB of OP was.

You need to verify all other sequences and then there is a special dummy bit in READ response that needs some consideration.

Thanks for your help!
I adjusted my code one final time and added some comments:
https://gist.github.com/anonymous/3e085bd2d639f137d1a3
It might be useful for other in the future.

You are welcome. I had a look. Here are some possible changes (and tests). line 88-91: Could rewrite this as "data1 = (data1 << 1) | (data2 != 0);". line 82-85: Could you test this: "SPI.transfer(0b110); SPI.transfer(address << 1);  data1 = SPI.transfer(0); "

That works!
The replacement for lines 82-85 is pretty awesome good thinking! No need for the data2 now. Thanks again!

Updated the answer above with this finding.


text:
How to reset millis( )?
I am currently doing a school project.  There you have to program a stopwatch with the Arduino.  I wrote a program where millis starts.  But when I press my start button, millis don‘t start from 0.
Has someone an idea? Please let me know.
Ps: I‘m German, so I‘m sorry for my bad English

You don't. Instead you just remember what millis() was when you pressed your start button, then subtract that from whatever millis() is showing at any other point in the future.

I‘ve just added a picture of my program, maybe you‘re able to take a look

@Laurentien Please... don't post photographs of code. Post the actual code.

BTW: millis() returns an unsigned long. That will make a difference after 24 days of continuous running. And it will allow running forever, even when that unsigned long will roll over.

@DataFiddler but doing stopmillis-startmillis will always return the correct value if the time between start and stop is less than the 24-day rollover.

It's a 49+ day rollover.  unsigned long lets millis() return from 0 to 4,294,967,295 mS.  x 1 second/1000mS, x 1 minute/60 seconds, x 1 hour/60 minutes, x 1 day/24 hours = 49.59 days

@ratchet freak, you're right: The calculation is the same, no matter if interpreted unsigned or signed, so any resulting interval < 24.x days will be positive, even if stopmillis and (in the next period) startmillis become negative.  But negative timestamps (and signed intervals) are harder to imagine. :)

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


text:
Problem driving segment display
First off, I'm not really sure if it belongs here on on electronics stackexchange, since it involves an Arduino, some code and a small circuit.
I'm trying to create a simple countdown timer using a 7 segment display and two 74HC595N shift registers.
The shift register connected to DATA_PIN should set a HIGH value for those segments enabled for a given digit position, while the second one in line enabled one common pin at a time (it's a common cathode display btw)
Here's my code:
#define LATCH_PIN 4
#define CLOCK_PIN 5
#define DATA_PIN 6

#define MILLIS_PER_SECOND 1000
#define SECONDS_PER_MINUTE 60

// Visual feedback when digit encoding goes wrong
#define INVALID_INDICATOR 0b11001001

int remainingSeconds = 128;
int enabledCommonPin = 0; // Ranges 0-4
unsigned long lastElapsedSecond;

void setup() {
  pinMode(LATCH_PIN, OUTPUT);
  pinMode(CLOCK_PIN, OUTPUT);
  pinMode(DATA_PIN, OUTPUT);
}

byte getSegmentsForDigit(int digit) {
  // Segments are encoded [Dp, G, F, E, D, C, B, A]
  switch (digit) {
    case 0: return 0b00111111;
    case 1: return 0b00000110;
    case 2: return 0b01011011;
    case 3: return 0b01001111;
    case 4: return 0b01100110;
    case 5: return 0b01101101;
    case 6: return 0b01111101;
    case 7: return 0b00000111;
    case 8: return 0b01111111;
    case 9: return 0b01101111;
    default: return INVALID_INDICATOR;
  }
}

byte getSegments() {
  int seconds = remainingSeconds % SECONDS_PER_MINUTE;
  int minutes = remainingSeconds / SECONDS_PER_MINUTE;
  switch (enabledCommonPin) {
    case 0: return getSegmentsForDigit(minutes / 10);
    case 1: return getSegmentsForDigit(minutes % 10);
    case 2: return remainingSeconds % 2 == 0 ? 0b10000000 : 0b00000000;
    case 3: return getSegmentsForDigit(seconds % 10);
    case 4: return getSegmentsForDigit(seconds / 10);
    default: return INVALID_INDICATOR;
  }
}

void loop() {
  // subtract a second if at least 1000ms passed since lastElapsedMillis
  if (millis() - lastElapsedSecond >= MILLIS_PER_SECOND) {
    remainingSeconds = remainingSeconds == 0 ? 0 : (remainingSeconds - 1);
    lastElapsedSecond += MILLIS_PER_SECOND;
  }

  // Use the 5 most significant bits for enabled digit
  byte enabledDigit = 1<<(7 - enabledCommonPin);
  byte enabledSegments = getSegments();

  digitalWrite(LATCH_PIN, LOW);
  // Bit-flip enabledDigits since display is common cathode
  shiftOut(DATA_PIN, CLOCK_PIN, MSBFIRST, ~enabledDigit);
  shiftOut(DATA_PIN, CLOCK_PIN, MSBFIRST, enabledSegments);
  digitalWrite(LATCH_PIN, HIGH);

  // Set next commonPin
  enabledCommonPin = (enabledCommonPin + 1) % 5;
}

For completeness, I drew a schematic of my setup. To reduce space, I left out the segment display. All common pins are connected to SR2 through a 510Ohm resistor.
My display has a pin for the Dp segment and one to enable the time separator/colon. I connected those two, so should I accidentally enable the time separator on the wrong position, the decimal point should light up.

simulate this circuit – Schematic created using CircuitLab
When I power up the Arduino, the display shows an unexpected composition of segments (i.e. all decimal points are enabled)
I would at least expect to see a change every second, but even that is not happening. I double checked the wires on my breadboard, both clocks and latches are in sync.
I noticed the unused pins on SR2 are not connected. The datasheet suggested I should either connect them to Gnd or Vcc, but that didn't help.
Is there something wrong with my code or circuit perhaps?
I'm trying to learn how this would work, so please don't advice me to use libraries or ICs like the MAX7219.
Thanks in advance.
EDIT
I've tried Juraj's suggestion and swapped the lines calling shiftOut(). The result was that none of the segments were enabled.
I did some experiment with writing to Serial what values were shifted out in combination with the value of remainingSeconds. Both the enabledDigit and segments values matched with what I expected.
I also tried to shiftOut some hard-coded values for segments, but I still saw the same segments enabled. I thought maybe the IC could be damaged inside, so I replaced both with two other SN74HC595N's. The result was, unfortunately, no difference.
Could this mean there is something wrong with my Arduino?

upvote for well presented question

send segments first

@Juraj That could explain why for each digit I see the same segments enabled, but I thought the data I shiftOut() first gets shifted down the chain of registers? I'll give it a try

a set register sends the data to the next

try all zeros or all 1 for enabledDigit


text:
I2C Communication Matlab - FDC1004
I have a ProtoCentral FDC1004 board (datasheet: http://www.ti.com/lit/ds/symlink/fdc1004.pdf) connected to an Arduino. I am then trying to connect to the system via matlab.
I have found the address (0x50) using addrs = scanI2CBus(a) and I am now trying to read measurements from it.
Page 15 of the datasheet says the following to trigger measurements:
 1. Setting REPEAT (Register 0x0C:bit[8]) to 0.
 2. Setting the corresponding MEAS_x field (Register 0x0C:bit[7:4]) to 1.
    – For example, to trigger a single measurement of Measurement 2 at a rate of 100S/s,
    set Address 0x0C to 0x0540.

Q1: How do I work out where the value "0x0540" comes from?
Q2: I don't seem to be able to write this value, I'm able to write other values to this register and read them back however. How can I write 0x0540 to this register?
My matlab script is as follows:
a = arduino('COM7', 'Uno', 'Libraries', 'I2C');
capdev = device(a,'I2CAddress',0x50);

writeRegister(capdev, 0x0C, 0x0540,'uint16');
readRegister(capdev,0x0C,'uint16')
value1 = readRegister(capdev,0x02,'uint16')
value2 = readRegister(capdev,0x03,'uint16')

readRegister(capdev,0x0C,'uint16') simply displays the last value I wrote to this register during testing (eg 3)
0x02 and 0x03 are supposedly where measurement 2 is stored. These read as 0.
Q3: Any idea what I'm doing wrong, or how to implement this correctly?
Thank you!

Q1 ... see Table 5 ... convert 0x0540 to binary

Q1 - converting to decimal (which i need for matlab) gives 1344. I still cannot write this in matlab (returns "0" when I read it back)

Matlab seems happy for me to specify in whatever (https://uk.mathworks.com/help/supportpkg/arduinoio/ref/writeregister.html#d117e17865) but I can't get this value to write in any format for some reason

why do you believe that you can read back the value that you wrote to register 0x0c?

regarding Q1, why are you converting to decimal? ... have you forgotten what you asked in Q1?

Why do I believe I can read it back? a) because I can read it back when I write test data to it (small integers, 0-15) b) because why wouldn't I be able to

Why convert to decimal? Because I still need to write it in matlab which I can't seem to do with the hex value. The matlab examples I've seen write to registers using decimal so that seemed like a good thing to try. Alas, that didn't seem to work either

converting to decimal has nothing to do with Q1

Why do I believe I can read it back? ... a) makes sense ... try values up to 0xff .... b) you cannot assume that all registers read back what you wrote to them ... always refer to the device datasheet to make sure


text:
LSB/MSB and shiftOut
Here is the shiftOut function code from wiring_shift.c
void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val)
{
     uint8_t i;

     for (i = 0; i < 8; i++)  {
           if (bitOrder == LSBFIRST)
                 digitalWrite(dataPin, !!(val & (1 << i)));
           else
                 digitalWrite(dataPin, !!(val & (1 << (7 - i))));

           digitalWrite(clockPin, HIGH);
           digitalWrite(clockPin, LOW);
     }
}

Does this mean that least significant bit is on the left and most significant bit is on the right? Or LSBFIRST means that will be the last outputted bit so it will be "first" in outputted sequence?
One more thing
here is a sample code:
shiftOut(dataPin, clockPin, LSBFIRST, B00101001);
shiftOut(dataPin, clockPin, LSBFIRST, B11010011);

Why does this
union
{
     word uniform;
     byte separate[2];
} state;

state.uniform = 54057; // aka 11010011 00101001
shiftOut(dataPin, clockPin, LSBFIRST, state.separate[1]);
shiftOut(dataPin, clockPin, LSBFIRST, state.separate[0]);

have different output but if i swap last two lines it works correctly?

You should read something about endianness. It'd work as you expect with big endian processor, but the majority is using little endian for the internal number representation.

ok, thank you for answer

Integer values of the Arduino have the MSB left and the LSB right. The shiftOut() function let's you choose, how the order should be timewise. If you provide LSBFIRST, the function will start the transmit with the LSB (on the right) and then go left to the MSB. Otherwise it will start with the MSB and then go right to the LSB. So this effects only the time order of the bits, in that they get transmitted.

Thank you for answer but there is one more problem, I've appended my question

There is no "left" or "right" in a binary number, only in the human representation of that number.
It is traditional for us to place the most significant bit on the left, purely because that his how we represent other numbers - like 1234 (1 is the most significant digit, the thousands).
Given the pseudo-number 12345678 if you shift out LSBFIRST the 8 gets output first, then the 7, then the 6, etc. In MSBFIRST the 1 gets output first, then the 2, then the 3, etc.

I would say, there is "left" or "right" in a binary number. There are even operators for shifting left or right. The human representation comes with the connection of "left" or "right" with LSB and MSB, so that the binary number can be converted to other bases or even printed out (since choosing where LSB/MSB is changes the representation in a different base, but not the binary number itself).

@chrisl There is only a left and right because we, as humans, decide to represent them that way. The shift left and shift right are again just names we have assigned to the operators. They should be called "SMS" and "SLS" for Shift Most-Significant and Shift-Least-Significant, but we choose to give these things chirality.


text:
Strange behavior on 74HC595 Shift Register IC when its GND pin is used
I was following a tutorial similar to this:
https://www.arduino.cc/en/Tutorial/ShiftOut
That is, an array of 8 LEDs that lit up accordingly to the binary representation of a number, which was given in a loop from 0 to 255.
The problem is that when invoked shiftOut() over certain numbers (such as 5, 9 or 13), the LEDs didn't lit as expected.
I even tried replacing the IC, but what finally solved this issue was to disconnect IC's pin 8 (GND) and let only pin 13 (OE) connected to Arduino's ground pin.
Does anyone know the reason this strange behavior happens on 595 IC?
Here's a video showing the circuit finally working (without IC's GND pin connected): https://www.youtube.com/watch?v=NGfpk-kjemo

Please post your code and format the code using the code formatting markdown (four leading spaces). For help see Markdown help. You should be able to do this by selecting the code and pressing Ctrl+K to have your browser do this for you. Please post your schematic. You have done something very very wrong for this to happen.

What size resistor? Check how much current is pulled.

didn't lit as expected. Please expand on that. No leds were lid? Wrong leds were lid? If so which?

As suggested by previous comments, you ought to provide enough information so that replies can give answers instead of speculation.  Besides the video (which seems to show that you correctly oriented the chip), add a couple of clear photos of your breadboard setup, and draw the circuit.

Sorry, I'll try to explain more.
When 595's GND was connected, wrong LEDs were lid only for some numbers. For instance, 3 lid 00000011, 4 lid 00000100, but 5 lid 00000110 (instead of 00000101).
The resistors I used were 150 ohms.
Actually I was following a chapter of this book (in a Brazilian Portuguese version):
https://books.google.com.br/books?id=3TXyAAAAQBAJ&lpg=PR11&ots=vrG79YuC7C&pg=PA111
The project schematics and source code are in this link above. The exceptions are that the 1st edition it recommended 220 ohms resistors (instead of 560 ohms) and the capacitor wasn't present.

The schematics: http://i.imgur.com/WGrNjfY.png?1

Disconnecting the ground pin was not a solution.
It is hard to be certain from video but the resistor values are likely too small because I can't see any color on the bands.  They are 100?
Look closely at the driver data sheet.  It may say an output pin maximum current is +/-35 mA which would suggest that the 100 ohm resistor is okay.
For example, a red LED has a of around 1.6 V.  You are using Vcc=3.3, so a 100 ohm resistor limits the current to <17 mA ((3.3-1.6)/100).  The actual current will be a somewhat smaller as the Vf increases with current..
But you also stay within the maximum Icc and Ignd on the data sheet.  These limits are not necessarily 8 x 35 mA.  For example an NXP max Icc is 70 mA.  That means you cannot drive all the outputs at maximum current, just 2.  This is a logic chip, not a driver.
There is other hint that you should not using all the outputs at the max current spec in the section where the Voh and Vol are described.  The current at which the voltage is specified is 6 mA, which is the maximum you should use if all output are going to source or sink at the same time.
A common LED current is 5 mA, so this chip could drive 8 simultaneously.  If you want high brightness, you need to add a driver such as ULN2003.
Note that the schematic shows red LED's.  The color is important.  Different LED's have different forward voltage.  The blue LED have the highest in the range of 3.3 V and higher.  So with a Vcc=3.3 there is barely enough voltage to light the blue LED.  The red and yellow have much lower forward voltage.  When the chip tries to light the red and blue at same time, the output voltage is dropping enough that the blue is not visible, but the red is easily lit.
From the video, it looks that you have the same resistor on all the LED's.  On different color LED's this will not achieve the same brightness on all LED's.  You need different resistors for each color if you want them the same brightness.
The solution is

Up the Vcc to 5V so that you can reliably light the blue LED's.
Increase the resistor values start with 510 for red and 220 for blue.  This should be about 6 mA for both.

I used 150 ohms resistors. The input Vcc was 3.3 V (from Arduino's).
I realized that LEDs were quickly blinking just before each transition.


text:
RF 433 Module with VirtualWire: transmit and receive using the same Arduino board
I was wondering if it was possible to work, in the same Arduino board, both Transmitter and Receiver RF 433 MHz modules. Is it feasible?
Here is the schematics I tried:
1) a pushbutton toggles a state value (0 or 1) and triggers the RF transmitter to send it as a message to the receiver module
2) the RF receiver, whenever reading the message, turns on or off a LED according to the corresponding value (0 or 1)

Here is the source code I wrote:
#include <VirtualWire.h>

#define BTN_PIN A0    // pushbutton que aciona a transmissao
#define LED_PIN 13    // LED aceso ao receber o sinal
#define TX_PIN   4    // ligado ao pino DATA do transmissor RF
#define RX_PIN   7    // ligado ao pino DATA do receptor RF

#define SPEED  5000   // velocidade de comunicacao (bits por segundo)

int estado = 0;

void setup() {
  pinMode(BTN_PIN, INPUT);
  pinMode(LED_PIN, OUTPUT);

  vw_set_tx_pin(TX_PIN);  // transmissor
  vw_set_rx_pin(RX_PIN);  // receptor
  vw_setup(SPEED);
  vw_rx_start();

  Serial.begin(9600);
}

void loop() {
  int pressionado = !digitalRead(BTN_PIN);
  char msg[4];

  if (pressionado) {
    estado = !estado;
    itoa(estado, msg, 10);

    vw_send((uint8_t *) msg, strlen(msg));
    vw_wait_tx();

    Serial.print("Mensagem enviada: [");
    Serial.print(msg);
    Serial.println("]");

    delay(500);
  }

  uint8_t buf[VW_MAX_MESSAGE_LEN];
  uint8_t buflen = VW_MAX_MESSAGE_LEN;
  int recebido = 0;

  memset(msg, 0, 4);
  if (vw_get_message(buf, &buflen)) {

    for (int i = 0; i < buflen; i++)
      msg[i] = char(buf[i]);
    msg[buflen] = '\0';

    Serial.print("Mensagem recebida: [");
    Serial.print(msg);
    Serial.println("]");

    recebido = atoi(msg);

    Serial.print("recebido = ");
    Serial.println(recebido);

    digitalWrite(LED_PIN, recebido);
  }
}

When I run it, according to Serial Monitor it sends the message. The problem is no message comes to the RF receiver.
Does anyone have an idea of what could be wrong?

Just to get some background; have you already tried this particular set of modules with 2 Arduinos? I only ask because I noticed that there was no antenna wire on either module, and my experience with these modules is that without even a basic antenna, they will not receive

These lines in the ISR in VirtualWire.cpp
    if (vw_rx_enabled && !vw_tx_enabled)
        vw_rx_sample = vw_digitalRead_rx() ^ vw_rx_inverted;

and
    if (vw_rx_enabled && !vw_tx_enabled)
        vw_pll();

mean that the receive path code is just not executed while the transmitter is enabled.
It kind of seems from the comment as that might not have been true at some point in the past, though I'm not seeing a version history for an "official" version to check.
You could try to modify the code to implement both, but it is worth noting that VirtualWire has been deprecated in favor of the more versatile RadioHead, so you might want to evaluate that and perhaps make modifications there instead.

As said in the comment you definitely need an antenna on both modules.
It is also possible that you are not supplying enough power to the 433 Mhz modules. The Arduino is not capable of outputting much current and RF transmitters generally have large current spikes.
So I would recommend that you use a seperate power supply to power the modules (do not forget to keep common ground between the Arduino and the Transmitter.)
I have also heard that it is preferred to not maintain common ground between the transmitter and the receiver. So if all else fails then use two separate power supplies.

The antennas - this is definitely true, I just tested out a couple of modules and they weren't working at all... added some antennas and with some wiggling around and moving them closer together, was able to get a signal.


text:
Interfacing with desktop computer console software
Recently I bought the following USB to Serial cable: https://www.adafruit.com/products/954
This cable has grd, vcc, rx and tx lines.
I am looking to use this cable to interface with my desktop computer with a program like Tera Term or Hyperterminal so i can output messages for debugging purposes.
Also, I am trying to stay from using the Arduino IDE. I would prefer using C and flashing in the hex manually.
So, can anyone point me to a tutorial or explain how to make this happen?
thanks people.

Just use the Arduino IDE, and enable verbose output in the settings. All the needed commands will be visible in the output window. After that you can ditch the IDE.

Which aspect do you want to know about? Wiring the adapter? Programming the UART code, or compiling a program and uploading on the command line?

"This cable is not good for Arduino re-programming such as a Boarduino, MENTA, Monochron, etc. because it does not have the DTR/RTS wire necessary for initiating the bootloader reboot sequence. "

@MikaelPatel But one can still hold the reset button and release it before the upload sequence begins.

For debugging:
Configure the UART on the ATmega to output TTL serial. If you are using the Arduino libraries, then Serial is what you want. Connect the TX pin of the ATmega to the RX of the USB/Serial cable, and vice versa.
Open the serial device on your computer in the program of your choice. When you write to the UART on the ATmega, you should see the messages in your terminal.
Pretty straightforward.
For programming:
If you're going to be using C and flashing things manually, you'd best go and buy an AVR programmer so you can program the ATmega directly without messing about with a bootloader. A programmer is ~15USD, so you might as well buy one. Then you can use the GNU AVR toolchain, which is very easy to use. Compile code with avr-gcc, and program the device with avrdude.
If you really want to use programming over serial, you'll have to manually hit the reset button each time you program the chip, because (as Mikael pointed out), that serial cable lacks the lines necessary to automatically reset the chip (and drop to the bootloader).

The bootloader is really not an obstacle, and using it is entirely compatible with the GNU AVR toolchain - after all, that is what the Arduino IDE uses.  There is no interdependence of the arduino bootloader and any arduino runtime components, you can use either without the other.


text:
Using buttons with Arrays
I am trying to write a simple program that will cycle through an array using push buttons. My current version of the program uses if statements and prints lines.
My goal is to have contact information for 4 people stored in an array. I can either have an array of strings per person or make different arrays of strings for the different type of information (ie names, phone numbers).
I would like one push button to cycle through the data in one direction and another push button to cycle through the data in the other direction. This is my code so far using the if statements. I modified the code from a traffic light tutorial hence you will see some of the variables named after colors.
//------------------------------- Declare variables
int ledPinOne = 2;
int ledPinTwo = 3;
int ledPinThree = 4;
int ledPinFour = 5;
int buttonPin = 6;
int state = 0;
char user_name_array[32];
char econ_one_name_array[32];
char econ_two_array[32];
char econ_three_name_array[32];

//------------------------------- Setup
void setup() {
  Serial.begin(9600);
  //------------------------------ Sets pins for I/O
  pinMode(ledPinOne, OUTPUT);
  pinMode(ledPinTwo, OUTPUT);
  pinMode(ledPinThree, OUTPUT);
  pinMode(ledPinFour, OUTPUT);
  pinMode(buttonPin, INPUT);
  Serial.println("ID");
  Serial.println(user_name_array);
}

//------------------------------- Main Program
void loop() {
  if (digitalRead(buttonPin)) {
    if (state == 0) {
      Serial.println("Athlete");
      Serial.println("John Smith");
      Serial.println("No allergies, no medications");
      Serial.println("  ");
      setLights(HIGH, LOW, LOW, LOW);
      state = 1;
    } else if (state == 1) {
      Serial.println("Emergency Contact - Sister");
      Serial.println("Eliza Smith");
      Serial.println("Cell - 333.888.777");
      Serial.println("  ");
      setLights(LOW, HIGH, LOW, LOW);
      state = 2;

    } else if (state == 2) {
      Serial.println("Emergency Contact - Hermosita");
      Serial.println("Jackie Smith");
      Serial.println("Cell - 777.888.7777");
      Serial.println("  ");
      setLights(LOW, LOW, HIGH, LOW);
      state = 3;
    } else if (state == 3) {
      Serial.println("Emergency Contact - Father");
      Serial.println("Michael Smith");
      Serial.println("Cell - 888.777.777");
      Serial.println("  ");
      setLights(LOW, LOW, LOW, HIGH);
      state = 0;
    }
    delay(1000);
  }
}

void setLights(int red, int yellow, int green, int blue) {
  digitalWrite(ledPinOne, red);
  digitalWrite(ledPinTwo, yellow);
  digitalWrite(ledPinThree, green);
  digitalWrite(ledPinFour, blue);
}

I also have a 4-LED setup. When the button is pushed one of the LEDs turns on and then when the button is pushed again it turns off and turns the second one on and so forth.
Thank you in advance for any help.
EDIT:
This question was asked again in a more detailed way and has more answers here:
Using a button to cycle an array

You should try and ask 1 question at a time.  That way when other people search with a similar question they can find yours and its answers.

Let's just deal with character strings.
The truth of the matter is that Arduino programming uses the language C.  C is very common and you can search for help in many places.
There are several ways to deal with strings in C.  In this example we are using an array of pointers to strings:
// let's make our own array of strings
char *states[] = {
    "California", "Oregon",
    "Washington", "Texas"
};
int num_states = 4;

for(i = 0; i < num_states; i++) {
    printf("state %d: %s\n", i, states[i]);
}

The output of this code looks like:
state 0: California
state 1: Oregon
state 2: Washington
state 3: Texas

I grabbed this example from here.
added later...
The method "printf" is normally not used in Arduino land.  So that "for" loop would look more like:
for(i = 0; i < num_states; i++)
{
 Serial.println("state ");
 Serial.println(i)
 Serial.println(states[i]);
}

Ahem... printf DOES exists in Arduino land, just include <stdio.h>


text:
20x4 LCD shows up as 20x2
I need help with my LCD. I have a 20x4 LCD and it shows up as 20x2. The LCD address said "// Set the LCD address to 0x27 for a 16 chars and 2 line display". I changed it which says "// Set the LCD address to 0x27 for a 20 chars and 4 line display" and uploaded it, thinking it would show up as 20x4 as it should. But it didn't work:

it says lcd.begin(20,4)

In which way your 20x4 LCD 'shows up' as 16x2? What do you mean by that?

@nori I suggest you to explain what you mean by "shows up", as smajli said, and moreover to add the code you are running, explaining what you expect it to do and what it actually does. Otherwise it is impossible to understand what the problem is

Hi i added a picture to my question so i hope that could give you an insight on it

Are you saying that you changed the textual content of a comment and expected the code to magically know what was required...?

on the picture I see 20 columns and 4 rows.

@majenko , i wanted to show what pops up on my lcd

@juraj im sorry, i meant it shows up as 20 colums and 2 rows, the other 2 are missing.. im really sorry i have no experience in arduino uno. Im doing this for my highschool project

@nori did you properly regulate the contrast? Usually with this kind of displays you have to connect a potentiometer; try to rotate it so that the writings become visible (and use a demo program to test it - if you have issues with this, post the demo program)

@nori, do you have the model number of the display?  I have some 4 row displays.  It took a while, but I finally realized there were actually 2 sets of Hitachi like controllers.  Essentially, there were 2 displays in one.

@Majenko: it's not magic, it's AI uprising! LOL...

@frarugi87: i don't thinkt it's a contrast issue, otherwise every cell should be full-on or full-off, not only half of them. I guess it's an i2c address issue...

Nori, just ignore every code that's after the //, they are just comments and the compiler will just discard them.
Look at the LCD rear, you should see your I2C chip, search google typing
["chip's code"  20x4 arduino]. You'll see which I2C address you most likely need to use. For instance, the PCF8574 has addresses fromm 0x20 to 0x27, the PCF8574A has addresses from 0x38 to 0x3F...
Without this info you are only shooting blindfolded, the 0x27 it's only the "standard" address of the most common PCF8574 module but there are plenty of modules.
Another way to find the address is to upload this code, it's an I2C scanner that will write on the serial monitor any I2C device that replies a "ping" signal.
If you find the address and still it doesn't work or if you can't find the address, check and double and triple check the wiring, especially the false contact.


text:
Add id to raw data in an array
I am working on an Arduino project, where I am transmitting GPS data between two Arduinos. This code can transmit the raw GPS data:
int a = Serial1.available();
if(a){
    uint8_t hej[a];
    for(int i=0; i<a; i++){
        hej[i] = Serial1.read();
    }

    rf95.send(hej, a);
}

I need to be able to identify the device that's transmitting the data. This can be in form of an integer value. I have tried to add a value to the array, but that messes up the data when I receive it.
Is there a simple way to add an ID to the data I am transmitting?

Send your data as a struct.

Are you sure your data isn't being messed up when you incorrectly read it from serial? https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/

I have had a lot of trouble sending the GPS data from the transmitter to the receiver. But with this code I atleast get something back, as you can see in this screenshot from the serial monitor on my receiver:
http://prntscr.com/hjtvql
The data is sometimes messed up as you mention, but I don't know how to solve it. The only data I need is actually some kind of ID (this can be premade) and then the location data (latitude and longitude)

I would suggest:

Use a library (TinyGPS++ for example) to read the GPS data and extract just what you want.
Use a struct to craft a packet that you can send over bluetooth, or send the data as a textual representation, depending on your needs.

For a struct you can:
struct packet {
    uint8_t id;
    float latitude;
    float longitude;
};

struct packet myPacket;
myPacket.id = 32; // Unique ID
myPacket.latitude = gps.getLatitude(); // Whatever function call here
myPacket.longitude = gps.getLongitude(); // or whatever
rf95.send((uint8_t *)&myPacket, sizeof(struct packet));

Well, the main problem here is that you don't know when the string will enter from the serial port. For instance, let's see a sample communication:
$GPGGA,154655,4328.1874,N,00340.5185,W,1,03,08.5,-00044.7,M,051.6,M,,*79
$GPGSA,A,2,13,23,25,,,,,,,,,,08.5,08.5,00.9*0E
$GPGSV,3,1,10,02,50,290,26,04,60,210,26,08,33,173,29,10,21,296,00*7E

Making a sample reading like this:
int a = Serial1.available();
if(a){
    uint8_t hej[a];
    for(int i=0; i<a; i++){
        hej[i] = Serial1.read();
    }

    Serial.print("Received \"");
    Serial.write(hej, a);
    Serial.println("\"");
}

you will see something like
Received "$GPG"
Received "GA,1546"
Received "5"
Received "5,4"

or, most probably,
Received "$"
Received "G"
Received "P"
Received "G"
Received "G"
Received "A"

so it is difficult to detect where to insert your ID.
I have two solutions for you.
The simpler one is to use the fact that the GPS sends formatted sentences. According to the NMEA specification, the message is at most 82 chars long and is terminated by a LF (0x10) char. This means that you can do something like this (I assume you want to use a 4-chars ID, and in this case the ID is MYID)
#define ID_LENGHT 5 /* 4 chars and a separator */
#define BUFFERSIZE ID_LENGHT+82 /* ID plus the max NMEA sentence*/
byte recvBuffer[BUFFERSIZE];
byte recvIdx;

void setup()
{
    // ... other initialization

    // Fill the ID at the beginning, and prepare to store data at the end of ID
    memcpy(recvBuffer, "MYID-", ID_LENGHT * sizeof(byte));
    recvIdx = ID_LENGHT;
}

void loop()
{
    // ... other program

    while (Serial1.available())
    {
        byte ch = Serial1.read();
        if (recvIdx >= BUFFERSIZE)
            continue; // Should never arrive here, since the sentences are shorter
        recvBuffer[recvIdx++] = ch;
        if (ch == 0x10) // received LF, so end of sentence
        {
            // Send the buffer (plus the identifier)
            rf95.send(recvBuffer, recvIdx);
            // Reset the idx (and so you will overwrite previous buffer
            recvIdx = ID_LENGHT;
        }
    }

    // ... Other code
}

This approach transfers a lot more thata then needed, since you want to only transfer the latitude and longitude. So the second (and best) approach in my opinion is to have a NMEA parser on the arduino that extracts the lat and long values you need and then sends a (formatted) message to the master, with ID, lat and long.
This is the best solution, but I don't have experience with NMEA parsers so you'd better try searching online for some library and, most important, have the necessary computational power and flash available to perform this computation

You could try NeoGPS.  NeoGPS is smaller, faster, more reliable and more accurate than all other GPS libraries.  It packages all the GPS fields into a structure for you:
#define gpsPort Serial1

struct msg_t {
  uint8_t ID;   // A node's ID
  gps_fix fix;  // The NeoGPS structure containing all configured GPS fields
};

msg_t msg = { THIS_NODE_ID };

void loop()
{
  if (gps.available( gpsPort )) {  // parses characters
    msg.fix = gps.read();          // gets the struct when it's ready (once per second)

    rf95.send( (uint8_t *) &msg, sizeof(msg) );  // send the msg struct
  }
}

The receiving side will similarly read into the same struct, something like:
    rf95.receive( (uint8_t *) &msg, sizeof(msg) );
    if ((msg.id == ROVER_ID) && msg.fix.valid.location) {
      // Check lat/lon against target location
       ...

This will also coordinate the RF transmission with the GPS quiet time, helping to avoid losing GPS characters while the RF transmission is busy.
The gps_fix structure can be quite small, depending on what GPS fields you enable in the NeoGPS configuration files.  This structure is 10x to 80x smaller than the raw NMEA data, so it is transmitted very quickly.  The default configuration uses only 31 bytes; most GPS devices send about 400 bytes per second.
If you'd like to try it, NeoGPS is available from the Arduino IDE Library Manager, under the menu Sketch -> Include Library -> Manage Libraries.  You should also read about Choosing a Serial Port and the Troubleshooting tips.


text:
I can't use buffer without printing in my Nodemcu esp8266
#include <ESP8266WiFi.h>

#include <ESP8266HTTPClient.h>
#include <WiFiClientSecureBearSSL.h>

#define WIFI_SSID "ssid"
#define WIFI_PASSWORD "password"

void setup() {
  Serial.begin(9600);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("Connecting to Wi-Fi");
  while (WiFi.status() != WL_CONNECTED)
  {
    Serial.print(".");
    delay(300);
  }
  Serial.println();
  Serial.print("Connected with IP: ");
  Serial.println(WiFi.localIP());
  Serial.println();
  ////////////////////////////////////////////

  std::unique_ptr<BearSSL::WiFiClientSecure>client(new BearSSL::WiFiClientSecure);
  client->setInsecure();
  HTTPClient http;

  http.begin(*client, "https://jsonplaceholder.typicode.com/photos");
  http.addHeader("Accept", "*/*");

  int httpCode = http.GET();
  Serial.print("HTTP CODE: "); Serial.println(httpCode);

  //reading response with buffer
  static char buff[128] = { 0 };
  while (http.connected() ) {
    size_t size = client->available();
    if (size) {
      int c = client->readBytes(buff, ((size > sizeof(buff) ) ? sizeof(buff) : size));
      //if i uncomment this next line, everything is fine.
      //Serial.write(buff, c); Serial.println();

      //but if i dont use serial.write program never gets here
      if (char * pch = strstr (buff, "quis fuga")) {
        char str[20] = { 0 }; int g =   0 ;
        while (pch[g] != '\"') {
          str[g] = pch[ g];
          g++;
        }
        Serial.print("FOUND IT: "); Serial.println(str);
      }

    }
    else if (!size) {
      Serial.println( "reading done");
      break;
    }
    delay(1);
  }

}

void loop() {

  delay(222222);

}

EDIT
here i created a compilable runnable code. basically i am trying to find a word in a http response. my real examples response isnt json and it is as long as this examples response. one other problem is i cant read all of the repsponse. it unexpectedly finishes reading sometimes after a few lines sometimes after a few hundred. in this particular request my nodemcu cant read after id 258. or id 8. object in the json response: https://jsonplaceholder.typicode.com/photos
if i dont use serial.write print buffer content, it finishes reading immideatly and thats exactly where i have the problem.

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

The Serial printing creates a delay. That delay enables to collect more characters in the buffer. If you read the input in small pieces (3 to 10 bytes) then the buffer doesn't contain the searched substring because it splits into two subsequent buffers. Even if you could read full buffers, it still can happen that the search string will be split.
To search for a string in a stream of data you can use function find(string). The networking Client class inherits this function from Arduino Stream class. find will read the stream until it finds the searched string. Then the next read from the stream will read the data right after the searched string.


text:
Can stack size be determined by free heap?
i have NodeMCU with es8266 onboard on it. I read heap and stack memory are facing each other and if heap or stack gets full and reachs another strange things happen. So i am wondering if can we use ESP.getFreeHeap() to get free heap and conclude usage of stack.
one tiny question here: can Serial.println("asd asd") cause memory fragmentation?

I read heap and stack memory are facing each other and if heap or stack gets full and reachs another strange things happen.

Indeed they do. And such things can be a pain to track down.

So i am wondering if can we use ESP.getFreeHeap() to get free heap and conclude usage of stack.

No, you can't.  The "free" amount of heap does not equate to the top address of heap. Heap can (and generally does) have holes in it. The "free" space is the sum of all those holes plus any extra "heap reserved" space above the highest heap entry.
To get the current stack usage you need to know two things:

The staring address of the stack, and
The current extent of the stack

Item 1 will be a fixed value, though what that value is I have no clue, but some reading will surely give you that value.
Item 2 can be obtained by allocating a local variable in a function and getting the address of that variable.
If all you care about is the change in stack imposed by your code you can record the "starting" stack point and use that in point 1.  For example:
char *stack_start;

void setup() {
    char stack;
    stack_start = &stack;
}

Then you can use that to get the current stack size compared to the start of your program:
uint32_t stack_size() {
    char stack;
    return (uint32_t)stack_start - (uint32_t)&stack;
}

one tiny question here: can Serial.println("asd asd") cause memory fragmentation?

No.  Use of String and other dynamic allocation is what causes memory fragmentation.

but isnt "asd asd" a string? and that stack code seems really useful thanks.

It's a "string literal", not a String. A String is specifically an instance of the (Arduino specific) String class.


text:
Esp and blynk app
It is possible to control one relay using Blynk app and also using an atmega? To a better understanding think at a relay that will turn on a fan when you use the blynk app. but when you don;t have the phone around you, using a pushbutton, you can turn it on from there(the button will be connected to atmega)

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

  pinMode(relCh2,OUTPUT);

  pinMode(relCh3,OUTPUT);

  pinMode(relCh4,OUTPUT);
  digitalWrite(relCh1,HIGH);
  pinMode(EspReadPin, INPUT);
  digitalWrite(relCh3,HIGH);
}
void loop()
{
Serial.println(digitalRead(6));
delay(400);
  if(digitalRead(EspReadPin == 1))
  {
    digitalWrite(relCh3,LOW);
  }
  else if(digitalRead(EspReadPin == 0))
  {
    digitalWrite(relCh3,HIGH);
  }
}

Yes it is possible.
Use the Blynk example sketch to activate the pin of the esp8266. Read the pin of the esp8266 with the ATMega. Handle in ATmega sketch the esp8266 pin as a second button.

i can't understand. Can you please to explain more detailed?

can you please rewrite your question in more detail

Of course ! basically what i want is to control one relay from two different locations. One will be in the house(a panel with buttons) - where will be also this button for the relay. and will be controlled by atmega(when it will be pressed - will turn on the relay). and another "location" will be from the phone. but for this part i will use blynk and esp.

and you have the local part working and want to add the esp8266 with Blynk?

i use the pin from atmega as output. and on the breadboard is connected to relay(as signal) but on the same line(on the breadboard) i put also the pin from the esp. and the problem appears  that if i press the button - relay will turn on. but if i use the blynk app- nothing happens.

so for the moment i can control it using just atmega. if i remove the pin coming from the atmega - blynk works perfect.

so then read my answer again. the part about "read the esp8266 pin with ATmega"

so how should i do that? i mean.. the only solution i am thinking right now is to define another pin of atmega as INPUT and to read it.

is it a problem?

i am afraid it wont work.

why would it not work? this is what microcontrollers do

i've just try it and nothing. ..

it reads pin as high but only that

do you have a plain esp8266? what pin of the esp8266 did you use? (add the info to the question)

no, i have an NodeMCU and the pin used is D0 = GPIO 16

did you upload the Blynk sketch into the NodeMcu?

yes. Esp and blynk works perfect. The problem appears on the atmega side. even the relay module it goes crazy. Even if i set them in the setup function to be opend, when the sketch is uploaded, they close. and i cannot understand why.

i have tested what you told me to do on the arduino nano and i set the pin as input. if it's high, then the built in led will be on, else should be off. and works. it;s ok. but on the mega... something goes crazy.

anyway, you helped me. Thank you!

are the relays active LOW?

yes. if i set them as low - they are closed

something strange happening here.  i wrote a sketch to test one btn and if is high to turn the relay on. Ok...i uploaded the code and then if i press the button the atmega it sees that is high and execute 'digitalWrite(relay,HIGH); ' .the problem is that the relay wont close. i use dmm to measure the voltage at the relay signal pin and is 4.7V- normally it should close. but no. the led in front of the relay barely glows.

only pull-up on INPUT pin? not OUTPUT? check the pin numbers in sketch

now, if i test it using 2 conditions more - it works

i have posted the code above. so if i remove in the if statements  && and all after. it wont wok

if (b == HIGH || a == LOW) {} else {}?

i tested with your suggestion. this is what it happens. the led in front of relay(that who shows if the relay receive voltage) barely lights in both situations(if i use the app or i push the btn) BUT if i press the button and i use the app in the same time. the relay close.

it turns on and off fast?

no. if i press the button on blynk to turn it on. it wont turn on. instead the led glows (barely- like it receive the minimum voltage on the junction to let the current flows) but if i measure the voltage- there is 4.7V but the relay wont close.

Looking in the serial Monitor it looks like the relay will close only when it receive 0 but that is for LOW. and i set it to HIGH. My head hurts..don't know wtf is happening here. Very probably is that i had done something wrong.

has the button a pull-down resistor? it is better to wire the button to ground and use the internal pullup with INPUT_PULLUP mode like in DigitalInputPullup example


text:
I am having an issue reading a HIGH LOW signal from a pressure switch
I'm trying to read either high or low from a pressure switch, I do have a pulldown resistor attached but even if I plug in a wire with nothing on it i get a false high. I've changed pins, tried adding INPUT_PULLUP to the program but it it reads false.
The code i'm using is:
const int mainPump = 2;
const int prePump = 3;
const int idleValve = 4;
const int chemTankLow = 5;
const int chemTankHigh = 6;
int pressure = 8; //7 originally removed const
const int chemValve = A7;
const int mem2 = A6;
const int mem3 = A5;
const int mem4 = A4;
const int mem5 = A3;
int tankLow = 0;
int tankHigh = 0;
int pressureFault = 0;
int lpe = 0;
int maxlpe = 2;
unsigned long timer[10]; //number of timers needed
byte timerState[10]; //store timers
int goNoGo = 0;
int readVoltage = 0;
int var = 0;

void setup() {

  pinMode(idleValve, OUTPUT);
  pinMode(prePump, OUTPUT);
  pinMode(mainPump, OUTPUT);
  digitalWrite(mainPump, HIGH);
  pinMode(pressure, INPUT);   //removed _PULLUP after input
  pinMode(chemTankLow, INPUT);
  pinMode(chemTankHigh, INPUT);
  pinMode(chemValve, OUTPUT);
  pinMode(mem2, OUTPUT);
  pinMode(mem3, OUTPUT);
  pinMode(mem4, OUTPUT);
  pinMode(mem5, OUTPUT);

  digitalWrite(mem2, HIGH);
  digitalWrite(mem3, HIGH);
  digitalWrite(mem4, HIGH);
  digitalWrite(mem5, HIGH);
  digitalWrite(chemValve, HIGH);
  digitalWrite(idleValve, HIGH);
  digitalWrite(prePump, HIGH);
  digitalWrite(prePump, HIGH);
  digitalWrite(idleValve, HIGH);
}
void loop()
{

       tankLow = digitalRead(5);
   tankHigh = digitalRead(6);

  if (tankLow == LOW && tankHigh == LOW){ //start day tank refill
   digitalWrite(A7, LOW);
  }
  if (tankLow == HIGH && tankHigh == HIGH){
    digitalWrite(A7, HIGH);
  }
  static int state = 1; // initial state is 1, the "idle" state.
  static unsigned long ts;

  switch (state)
  {
    case 1:
    ts = millis();

  if (delayMilliSeconds(1, 6000)){//600000

  digitalWrite(prePump, LOW);

  goNoGo = digitalRead(mainPump);
  if (goNoGo == LOW) {

    digitalWrite(idleValve, HIGH);
  }
    else {
      digitalWrite(idleValve, LOW);
          digitalWrite(mem2, LOW);
    digitalWrite(mem3, LOW);
    digitalWrite(mem4, LOW);
    digitalWrite(mem5, LOW);
    }

        readVoltage= digitalRead(idleValve);
    if(readVoltage==LOW){

    delay(4000); // wait time motors to stablize
    // read the input on analog pin 0:
    int sensorValue = analogRead(A0);
    // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
    float voltage = sensorValue * (4.83 / 1023.0);

    if (voltage >= 2.00)
    {
      state = 2;
    }

    else {
      delay(56000); //on time for test
    //  if (delayMilliSeconds(2, 51994)){
    digitalWrite(mem2, HIGH);
    digitalWrite(mem3, HIGH);
    digitalWrite(mem4, HIGH);
    digitalWrite(mem5, HIGH);

     digitalWrite(idleValve, HIGH);
      digitalWrite(prePump, HIGH);
      digitalWrite(mainPump, HIGH);
    }
    }

}
//} for if timer
break;

    case 2:
       ts = millis();
      digitalWrite(mainPump, LOW);
      digitalWrite(idleValve, HIGH);
       digitalWrite(mem2, HIGH);
        digitalWrite(mem3, HIGH);
        digitalWrite(mem4, HIGH);
        digitalWrite(mem5, HIGH);
        delay(20000);
        state = 3;

        break;

        case 3:

      digitalWrite(mainPump, LOW);
      digitalWrite(idleValve, HIGH);
       digitalWrite(mem2, HIGH);
        digitalWrite(mem3, HIGH);
        digitalWrite(mem4, HIGH);
        digitalWrite(mem5, HIGH);

      pressureFault = digitalRead(pressure);
  if (pressureFault == HIGH){

    state = 4;
  }
   if (millis() - ts > 3600000){
    state = 5;
  }

   break;

   case 4:
   digitalWrite(mainPump, HIGH);
   digitalWrite(prePump, LOW);
   digitalWrite(idleValve, LOW);
      digitalWrite(mem2, LOW);
    digitalWrite(mem3, LOW);
    digitalWrite(mem4, LOW);
    digitalWrite(mem5, LOW);
    delay(3000);
    digitalWrite(mainPump, HIGH);
   digitalWrite(prePump, HIGH);
   digitalWrite(idleValve, HIGH);
      digitalWrite(mem2, HIGH);
    digitalWrite(mem3, HIGH);
    digitalWrite(mem4, HIGH);
    digitalWrite(mem5, HIGH);
    delay(600); //60000
    state = 1;

    break;

    case 5:
    ts = millis();
        digitalWrite(idleValve,LOW);
        digitalWrite(prePump,LOW);
         digitalWrite(mainPump, HIGH);
           delay(60000); //60000 for standard
           digitalWrite(mem2, LOW);
           delay(60000);
           digitalWrite(mem2, HIGH);
           digitalWrite(mem3, LOW);
           delay(60000);
           digitalWrite(mem3, HIGH);
           digitalWrite(mem4, LOW);
           delay(60000);
           digitalWrite(mem4, HIGH);
           digitalWrite(mem5, LOW);
           delay(60000);
           digitalWrite(mem5, HIGH);

           delay(1000);   // leave this time
         digitalWrite(idleValve, HIGH);
         digitalWrite(mainPump, LOW);
       state = 2;
         break;
         default:

         state = 1;

         break;

  } //switch
} //loop

int delayMilliSeconds(int timerNumber,unsigned long delaytime){
  unsigned long timeTaken;
  if (timerState[timerNumber]==0){    //If the timer has been reset (which means timer (state ==0) then save millis() to the same number timer,
    timer[timerNumber]=millis();
    timerState[timerNumber]=1;      //now we want mark this timer "not reset" so that next time through it doesn't get changed.
  }
  if (millis()> timer[timerNumber]){
    timeTaken=millis()+1-timer[timerNumber];    //here we see how much time has passed
  }
  else{
    timeTaken=millis()+2+(4294967295-timer[timerNumber]);    //if the timer rolled over (more than 48 days passed)then this line accounts for that
  }
  if (timeTaken>=delaytime) {          //here we make it easy to wrap the code we want to time in an "IF" statement, if not then it isn't and so doesn't get run.
     timerState[timerNumber]=0;  //once enough time has passed the timer is marked reset.
     return 1;                          //if enough time has passed the "IF" statement is true
  }
  else {                               //if enough time has not passed then the "if" statement will not be true.
    return 0;
  }

}

As for wiring it is as basic as it gets 3.3v pin off the arduino to a pressure switch and then back to the arduino . but i'm not even making it to the switch before i have an issue literally plug in a 3ft wire not connected to anything and it goes to case 4
I've tried setting the code up to go to case 4 if it detects a LOW but hasn't changed my issue.

Datasheet, circuit diagram, and code where?

Don't be put off by the downvotes just yet; if you add what has been asked then you'll probably find they start to disappear...

Could you post the whole code? What type is pressureFault? And state? Too many questions that can be answered with a simple copy/paste. I'll even format it (again) if you don't know how. HINT: highlight any text you want to turn into block code and click the double-brackets "{ }" button at the top of the text box...

Thank you for uploading the code. I can't spot any immediate errors so you're going to have to strip back the code, as @Trillian86 says, to make sure there are no hardware faults. If case 4 is being reached, i take it you mean the program is correctly navigating to case 3, and then state is set to 4 regardless of the value of pressureFault?

correct, pressure fault is just connected to a spdt pressure switch i just need it to read high or low.

Follow Trillian's advice and just use a barebones code to prove that the switch is working. If you can't use the serial monitor use the onboard LED on pin 13 to be on if the switch reads high or off otherwise.

As a hint.  Start by removing the stuff you added an just try to detect a grounding of your input pin (I'm assuming digitalRead(pressure) is the standard read the digital value of a pin and not some funky function you've written)
Use some code like this to test your hard ware
int    pressure;

void setup()
{
    Serial.begin(9600);  //Start a serial monitor to see the results
    pressure = 4;  // Assumes your pressure input is pin 4
                   // change if need be
    pinMode(pressure,INPUT_PULLUP);  //Sets put to input with pullup
    digitalWrite(pressure,HIGH);      //Activates pullup
}

void loop()
{
     if (digitalRead(pressure))
     {
          Serial.println("Pin is High");
     }
     else
     {
          Serial.println("Pin is low");
     }
     delay(1000);
  }

Now compile, upload and activate the serial monitor.  Every second you will get the read of the pin on the monitor.  See if grounding the pin is detected.  If not, you may have popped the port.
BTW.  3 ft of wire will need some filtering and protection.  That will pick up a lot of noise.
Cheers


text:
Strange phenomenon when declaring double
Consider this question closed, found my answer through the answers I had
I am trying to make a position profile curve depending on Looptime, accelerationloops,Setposition,Currentposition(position) and velocity.
The curve should look like this:

Is someone able to check what is wrong with my code?
float array[30];

struct Formula {
  int LoopTime = 1000;
  int AccelerationLoops = 11;
  float VelocityLoop = 0;
  float VelocityFactor = 0;
  int TotalLoops = 0;
  float DeltaPosition = 0;
  int Setpoint = 0;
  int Iteration = -1;
  float EndOne = 1.25;
}Formula;

float SetPosition = 1404;
float Position = 0;
float Velocity = 36;

void setup() {
  Serial.begin(115200);
  for(Formula.Iteration ; Formula.Iteration <= Formula.TotalLoops; Formula.Iteration++){
    ProgFormula();
    Serial.println(Formula.Iteration);
    if(Formula.Iteration >= 0) {array[Formula.Iteration] = Formula.Setpoint;}
  }
  for(Formula.Iteration = 0 ; Formula.Iteration <= Formula.TotalLoops; Formula.Iteration++){
    //Serial.println(array[Formula.Iteration]);
  }
}

void loop() {
  // put your main code here, to run repeatedly:

}

void ProgFormula(){
  if(Formula.Iteration == -1) {
    Formula.DeltaPosition = SetPosition - Position;
    Formula.VelocityLoop = Velocity / (1000 / Formula.LoopTime);
    Formula.TotalLoops = Formula.DeltaPosition / Formula.VelocityLoop + Formula.AccelerationLoops;
    Formula.VelocityFactor = Formula.VelocityLoop * 0.5 / Formula.AccelerationLoops;
    Formula.EndOne = (Formula.VelocityFactor*pow(Formula.AccelerationLoops,2));
  }
  else if (Formula.Iteration >= 0 && Formula.Iteration <= Formula.AccelerationLoops) {
    Formula.Setpoint = Formula.VelocityFactor * pow(Formula.Iteration,2);
  }
  else if (Formula.Iteration > Formula.AccelerationLoops && Formula.Iteration <= (Formula.TotalLoops - Formula.AccelerationLoops)) {
    Formula.Setpoint = Formula.VelocityLoop * Formula.Iteration - Formula.EndOne;
  }
  else if (Formula.Iteration >= (Formula.TotalLoops - Formula.AccelerationLoops) && Formula.Iteration <= Formula.TotalLoops) {
    Formula.Setpoint = -Formula.VelocityFactor * pow((Formula.TotalLoops - Formula.Iteration),2) + Formula.DeltaPosition;
  }
  else {
    Formula.Setpoint = Formula.Setpoint;
  }
}

In setup(), array[Formula.Iteration] = Formula.Setpoint yields undefined bahavior when the index is −1.

Bit of a shame that i missed that... Edited my code, what is the reason my double values of the array are just integers with extra zero's?

In avr-gcc, double is the same size as float.

But in what way will that effect my results?

Please be more specific about what the problem is: What behavior do do expect from your code? What behavior do you have instead?

I am trying to make a motion profile for the position (edited my question).

If an answer provides the solution you want you should accept it. Also, writing an "answer found " message at the top is not what's done because the site is trying to build a set of matched questions and answers. So the 'green tick' when you accept serves the same purpose.

OK, this may not be a proper answer. I'm just having a hard time reading
your code, and I cannot understand why you make it so complicated. If
you know the acceleration profile, computing the position profile is
just a matter of integrating twice. Here is an example, not for Arduino
but for a PC. It should not be very different on an Arduino, you just
wouldn't use printf():
/* Compute position for any acceleration profile. */
void compute_profile(float (*acceleration)(int), int max)
{
    float x = 0, v = 0;

    for (int t = 0; t <= max; t++) {
        v += acceleration(t);
        x += v;
        printf("%d\t%f\n", t, x);
    }
}

/* Your particular acceleration profile. */
float VttgJ(int t)
{
    if (t <  7) return t;
    if (t < 13) return 12 - t;
    if (t < 40) return 0;
    if (t < 46) return 39 - t;
    else        return t - 51;
}

int main(void)
{
    compute_profile(VttgJ, 50);
    return 0;
}

The user inputs the following: Position and Velocity. They both need to be controlled. Because this isn't possible I have build three different formules by integrating the velocity curve. The system is able to measure a position and has a constant looptime. My code is rather complex and can probably a lot shorter. Maybe a modification of your code will be a lot smaller.


text:
Linking Mulitiple Arduino's
I have a project in which several Arduinos will be running independent programs. I would like to use an Arduino Mega as the main controller. It will receive input from a variety of switches, as well as data input from 2 Arduino Unos and 3 Arduino Nanos.
Each Nano will run a basic collection of switches and LED displays.
Each Arduino Uno will be connected to a 2 axis joystick and will have several button inputs from the joystick, as well as several 7 segment Led displays and several LED indicator displays.
The Mega would need to gather information of at least 16 bytes from each slave at highest possible speed, and be able to transfer at least 16 bytes to each slave at the same rate. I would also need the clock signal for all devices to default to the Mega.
What would be the best way to begin setting up the program logic to get these boards to interact in a smooth manner without a lot of lag in communication between boards?
Also, what would be the limitations on speed with this sort of com setup between the boards?
If more setup or function information is needed I can add description, just didn't want this post to be overly lengthy.

running independent programs .... your description says otherwise

I would use SPI. It uses 4 pins on slaves and 3 pins on master plus one pin on master for every slave (slave select). You can use ICSP header 2x3 connector for firm connection.

but then the slaves can't use SPI as master (for LCD).

a serial ring communication library exists, but there if one arduino fails the entire communication stops

You could use I2C if the distances are short. For longer distances RS485 is the (wired) norm. Or use one of the many wireless technologies around. nRF24L01+ is cheap and well supported. Or ESP8266 and WiFi if you can't use SPI.

Could you clarify your specifications? When you say the information gathering should happen "at the highest possible speed", it's difficult to come up with a solution, since you may be unwilling to make certain compromises in speed that would make the system work better as a whole. So first set the goal/target data rate and work from there. For an Uno to monitor the joystick, button inputs, and multiple 7-segment displays, your communication speed must be limited. If all your devices are on a common bus, each slave will have to provide it's data in turn, etc.

One advantage of RS485 is that you can make 3 independent buses using the UARTS 1, 2 and 3 of the Mega, and still keep UART 0 for debugging. Then you have 3 times the throughput, as the UARTs can work in parallel.

@jsotola Each Arduino will have an individual program that runs a specific part of the "ship" for instance Nano1 runs the power systems. All of it's lights and switches are independent. But it will need to receive information from other systems (for instance Nano 3 which runs the shields systems) that can tell it if "power" is being used by other ship systems, which it can then output on it's "power level" displays.

@josecanuc The entire system is built into a roughly triangluar shaped "tabletop" for lack of a better word that has a base length of 6.5' and a height of 3.5'. The distance between the MEGA and the farthest processor is no more than 3 feet. My response to Code Gorilla explains the joystick usage in my project but I can provide more details if necessary. Any delay in processing that can be mitigated is acceptable. I just don't want them to turn the "shields" to full and the "engine power" display to remain unchanged for several seconds.

Why do you need so many Arduinos, Nanos and a Mega?  You want to read/control 2 joysticks, some switches and some LED.  If you do this using a multi-processor environment then you are adding a significant overhead to the processing and the development time which you can probably do without.
So, could you connect everything to a Mega, do you have enough IO pins?  If not would the use of GPIO expander ICs, I2C devices, etc help solve this issue.
Connecting the joysticks via interrupts will allow a more responsive system, can you do this?
Is an Arduino even the best platform for this?  What about an ESP32 or PI?
You want to minimise the comms overhead, so a star network would be better than a ring.
Serial is going to be the lowest programming overhead solution, but by far the slowest.  Using WIFI via an ESP8266 is going to be the simpelist and you can hand off some of the processing to the ESP.

I will have to answer your questions in multiple comments due to character limit.

The different Arduinos are used because each micro-controller will be running a separate panel of the project and have it's own program running. (Nano 1 for instance only deals with the ships Power systems. It accepts input data from the Mega when other ship systems are activated. It runs 3-12 segment bar-graphs, 7 indicator LED's, and 6 toggle switches. The processor only needs to calculate current system power usage and emergency states, so not a heavy processing load.)

Arduino Unos along with a USB shield are used to control each joystick individually and change the "position" of the ship, which is displayed via 3 separate 7 segment displays. Additionally the Uno's program will deal with weapons fire, in particular counting how many missiles were fired, and display that number on a second 7 segment display. (this is a pilot and co-pilot setup, co pilot takes control of ship positioning during docking procedures) Also the toggle switches and indicator lights for thrust and weapons are each dedicated to the Uno's.

so as far as the number of Arduino's, I think I've minimized it well enough. I don't want the program complexity and length to overwork any individual processor, or overflow the memory capacity.

Simply making all the different components and systems connect via expansions to a single mass processor doesn't seem to be the solution, but perhaps I'm wrong, might need more clarification on how that could work.

I definately think the joysticks should be via interupts, but I'm not sure quite how to do that, would love more detail on that process. (At the moment I will be using the low cost thrustmaster USB $16 joysticks and a usb shield for the UNO. I am still waiting on shipping for the shield to begin proto testing this. Have some tutorials on the interface but very difficult to figure out so far)

Arduino may not be the best platform for this, but it's what I have, and I've made the investment in it so I want to see if it's possible. I keep scaling back the project to make it feasible, so I'm willing to try alternate approaches, but not really wanting to just ditch arduino and start from scratch again. It's for my kids so if it's got lots of cool lights and switches their happy (but for me I want them to be able to grow this project in the future and really make something of it).

How does a "star network" work? where could I learn about that?

it is a star topology. master in the middle and a line to every slave.

@Juraj, ok I was planning to do something like that. I was going to have the MEGA occupy the middle and use it to link all the other boards, using it as the master for them all. How might you connect the boards to do that? Would it be best to simply allow the slave boards to run their programs, and transfer relevant data to the Mega, who would then return relevant data to the appropriate slaves? what would that program look like? what would the wiring look like?

read my comments under the question

It sounds like the dashboard for a cobra mk3.  By eliminating processors you remove the need to communicate between them, and the timing issues you will need to handle.  Adding in ICs that do very specific tasks will reduce the program complexity further.  The shield displays can be linked via a serial to parallel converter, means one pin connects to the IC an that controls the whole display.  All the buttons can trigger the same interrupt and then you can scan the buttons to see which on was pressed, again this is a serial to parallel IC.


text:
ESP8266 Flash - Maximize SPIFFS size
the board i use has 1MB Flash Size. My program however downloads 512K+ of data for processing.
Arduino Options i see are:

Ideally i would like to use 1MB of SPIFFS, is this even possible?
I don't use OTA, and compile with:

To minimise the footprint of the main sketch.
Thanks in advance.

You need to get a ESP with more flash for this project.

No.
Even if you don't use OTA, your program is stored in flash. If you have 1MB of flash, there's no way you can use all 1MB for SPIFFS; that would leave no space for your program.
Here's a page showing how flash is divided up in an Arduino environment.
Even if you eliminate space for OTA images and the EEPROM, the Arduino environment will still reserve space for the sketch itself and for its wifi config and possibly a little more data.
You can never use 100% of the flash storage for SPIFFS.