text:
ATtiny84A programming without shield
I am thinking about buying an ATtiny84A, which fits perfectly into my project. I want to embed it into a watch that I am designing right now. But I want to buy an SMT version so I have less space to consume. What do I need for programming it through USB? Special Atmel chip? Or just 2 digital pins from USB directly into it? Thank you very much. :)

A USB programmer.

That is too bulky to fit into my project. And I can't find any chip that programmer which would tell me what I need.

You don't fit it into your project. There should be no reason to program it in the field.

What about software updates. Like bug fixes and stuff.

That's the end user's problem.

What the actual hell... Okay thanks for your time gotta find this online

I was searching for this for like 2 weeks. This is my final destination. It's better to be quiet than writing this to me. Thanks

I am studying electronics at high school and my knowledge is limited. Yes I've been searching for a lot of time 2 hours a day but it's starting to be boring.

You need to design your device to permit In Circuit Serial Programming - ISP.  This will let you continue to refine the program once the chip is in the circuit, and it will also be your primary method of programming and testing small production quantities.
Basically this means that the ISP and reset pins of your processor need to be able to be externally contacted - either by a header, pads for "pogo pin" spring contacts, an SOIC test clip, or perhaps micrograbbers hooked onto individual pins.
It also means that anything connected to those pins needs to not interfere with or be harmed by the programming process.  That particularly means that anything which could drive any of these pin needs to not do so while the MCU is being programmed, nor load them, nor get lastingly confused by operations the programmer does on them.
You'll also need an ISP programmer.  Proper ones are sold, but beware of cheap clones and marginal designs as these often give users plenty of trouble.  Fortunately, you can use an everyday Arduino running the ISP sketch to program ATtiny chips.  Do beware though, that if your target is powered at 3.3v it is not safe to use a programmer with 5v signals on it - you might get away with it a few times, but eventually it will cause issues.  So if you want to use an Arduino to ISP a lower voltage target, you either need an Arduino that runs at 3.3v, or to implement level shifting.
Do spend some effort to verify that you have the software support resources you may need for the ATtiny84A - it's one of the less common chips so it won't have the same degree of community support.
A further possibility is to use ISP to put a serial (or other) bootloader into the chip and then rely on that, however this won't cover all eventualities - if you discover you need to change the fuses, you'll need ISP for that, as it's something a bootloader can't do.

On the contrary, nothing short of reprogrammability is remotely acceptable - no actual product has just one prototype, there's a whole pilot run that needs to be iteratively fixed. It's almost certain this improvised "watch" won't have a waterproof case, but even if it does, the connections can be inside. In the real world, people engineer systems to be able to finish them. Or to exercise the trite meme, the 1990's called and they want their OTP MCU's back.  Why would you return there by choice?  Today, even throwaway products often have ISP/SWD pads - because their designers aren't idiots.

You seem to have neither any idea of what you are talking about, nor any reading comprehension - as already explained above ISP requires only a cheap Arduino clone for support.  Building something around an ATtiny84A will be challenging enough (as cautioned above); but intentionally making it even harder by trying to do it without recourse to ISP to iteratively fix mistakes would be the height of masochistic stupidity.

Thank you guys for your discussion :) You helped me a lot. I am an open source developer the code is not a problem. But hardware is a little one. I will find suitable solution with custom firmware for reading sd card for program or another flash built into chip which can be reprogrammed through AVR. There is a lot of solutions but thanks :)

You're welcome - but do note that the AVR chips (of which the ATtiny's are an example) cannot execute programs from external memory or RAM - they can only run from their internal flash.  So putting a program on an SD card is only an indirect method of flashing it into the chip.

Oh yes. That was just an idea. I have no idea how would I get around this problem I was just hoping that would work.


text:
Arduino is not recognized by any computer
I have an Arduino Uno R3 and when I plug it into any computer, the computer doesn't recognize the Arduino. I checked up and the LEDs are working fine and when I open the device manager it doesn't show any Unkown Device.
What it could be? Could the ATMega be dead? I tried on two Windows 7 and one Linux machines, none recognized the Arduino.

Is it an official Arduino board or a clone?

I burned out the USB-serial converter once with a shorted USB cable and it did the exact same thing.  I was still able to program it using another Arduino and everything worked fine except for the USB connection (although it was a real PITA to load sketches to).  Might be something to test if you have another ISP.

@PeterR.Bloomfield It's an official Arduino board.

@Comintern That could be possible, but would that affect the LEDs? Because when I plug the USB the Arduino receives power, but has I said nothing happens.

The reason that it is not connecting can be anything from wrong driver installation to the dead Atmega 16u2 chip. But I must exclude the former option as you said you'd tried on different OS and different computers. So double check the driver installation. And if does not work try to find out whether Atmega16u2 is fried or not. One solution might be to reflash the original firmware through an external ICSP programmer. If don't have any programmer but another arduino uno you might try out the gamon's tutorial on flashing firmware on the little USB to serial interface chip.
Anyway if your arduino is new and official you can get the right support online on arduino.cc. but if it is a clone you may try to contact the reseller whom you bought from.

The problem is that when I plug the arduino it doesn't apear that something new is connected, and when I check the Device Manager there's nothing even the Unkown Device, I'll try to download the drivers again and plug it again to see what happens.

As I said above, you now have only one solution. If it is a new board get help from arduino.cc if it is an older one try to bring back to life the mini USB to serial chip on the board.

The board has almost 2 years so I guess the solution is to bring back to life the mini USB to serial chip, any ideas on how to do that?

I had the same problem. When I connected the board to PC the ON Green LED turned on and the arduino run the last code was uploaded but the board wasn't recognized. Changing the cable fixed this problem for me.

If your arduino runs the last uploaded sketch, the problem is with the ATMega16U2 chip in your Arduino. Try to update the firmware with this tutorial https://www.arduino.cc/en/Hacking/DFUProgramming8U2
If you can't update the 16U2 firmware don't throw away, you can program the Arduino with a ISP programmer like this https://www.pololu.com/product/1300

source: Stack Exchange

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

sort: votes


text:
Sense checking Arduino Uno barebones schematic
I have had some difficulties finding a barebones Arduino board and have had the following made. I just wanted to see if anyone could spot any issues? I think it has everything. I'm really trying to get it as minimalistic as possible, but at the same time able to use a power source like a 12v/24 battery. Any help would be greatly appreciated. Many thanks

You shouldn't put a capacitor under the chip like that. In fact I don't much like the layout of the whole crystal circuit at all.
You need capacitors on the 7805 regulator - around 10µF on both the input and output.
The RESET pin needs a pullup resistor otherwise the chip won't function at all.
You need decoupling capacitors on all VCC pins on your main chip.
Instead of meandering ground traces you should use a ground pour.
Running from the kind of voltages you propose the 7805 is going to melt. You will need a BigAss™ heat-sink on it. For those kind of voltages you would be better using a switching (aka buck) regulator. Maybe as an off-board module to keep your board simple.

Many thanks for your help Majenko. Do you think there is any way to get around the issues with the board as it is? I've (foolishly) already sent 10 of those to print. I'm guessing with 1, I could add the capacitors off board. Also doesn't the 1N4007 help at all?

Most things you can work out a way to solder them in afterwards. The biggest issue will be heat from the regulator. By adding a switching regulator on a separate board to feed the 7805 you would solve that problem. Regulate down to about 7v.

The 1N4007 will just drop 0.7V so does very little in the scheme of things. It is really only for reverse power protection.

Ah I see, so putting something like this to feed the 7805 should solve the problem? http://ebay.eu/2hVTZRX

No, exactly oposite of that - step-up converts low voltage to higher (say input 3.2V and output of 7V (to feed your own 7805). You want step-down (like this one http://www.ebay.co.uk/itm/LM2596-DC-DC-Switching-Adjustable-Step-Down-Voltage-Regulator-Converter-3V-40V-/172058668488?var=&hash=item280f7eedc8:m:mDHLwFGVrh49Tb7BA-Y6CWg or any other with Input rang covering yours 12-24V (rather little more) and OUTPUT of 7V for your 7805. Maybe you can even go with some outputting 5V and big capacitor to filter the switching noise, if you want risk and save more money.

The diode there is good, if you have some other sink (like motor, servo or such) powered by the same batery, as it protects the Arduino from short drops of power, when such motor took big current to start moving and so drops the voltage for a moment. See the picture here (http://petr-kubac.blog.cz/1202/kubacova-magicka-dioda-ktera-se-porad-opakuje), also you can translate it from CZECH by google or so.

there are two ways how to drop voltage - one is switching (with or without transformer), which usually have high efficiency and does not burn much energy, the other is to just burn energy on some resistors, diodes and such, which have efficiency lower when the difference is bigger - as you need the same current going thru and just make heat on the regulator, to eat the voltage. Arguino needs 5V, if you have 24V then you need to burn 19V, which is 4x the Arduino itself eats. And that all goes to the heat. So BigAss heat-sink is needed and even so you drain your battery just for nothing.

long story short, use step-down to the voltage you need, then stabilise it. If you plan for some motors, servos or something like that on the same batery, use the diode too and regulate for 7.7V, send it to the diode, then to the regulator with capacitors around. Otherwise your Arduino is at risk of random restarts every time you use that motor/servo/something.

C4 is under the IC, which may (or may not) do problems, regardless which side of PCB you place it actually. The reset is better to connect via resistor to defined level than to leave floating. Usually there is also capacitor there to delay start until power is stabilized. I would put big capacitor near the stabiliser (also I think, it is recomended by manufacturer of the stabiliser for a reason), but maybe if you have good batery and short wires, it could work too. Also small capacitors between GND and VCC as near the IC as possible are common to reduce noise. And reset button is usefull add-on, but not necessary. Anyway I think, it could work as it is (with the reset defined).
If you have some particular application in mind, then you may use also different layout and/or get more connectors for some pins (some of my "arduinos" does not look like Arduino at all, having all periferials on the same PCB instead on some shields.
also http://download.gilhad.cz/arduinobb_12.jpg this is fully working arduino, which I used many times - so you do not miss anything critical (those LEDS are not necessary)

Many thanks for your help Gilhad. With regards to the reset, would connecting it through a resistor to ground solve the problem? Majenko (above) said it probably would not work without this.

No, that is a boost regulator. You want a buck regulator (step-down). They do some that look very similar to that one.

Yes, he was right (in some way) - depending of intended use the resistor can be onboard, or offboard or managed some other way (as output of some othe system, or programmed to be NOT reset, but I/O, for example). But fof simple generic Arduino board you should put there resistor and if you already send it to production, then just solder the resistor over the board - ugly but sure work.

With regards to the reset, would connecting it through a resistor to ground solve the problem? - no, /RESET needs a pull-up resistor. Something like 10k soldered from Reset to Vcc.

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


text:
GPS North? South? East? West?
I'm using the Adafruit SIM808 breakout board to text a GPS link to Google Maps when pinged. My program is mostly working, but the GPS data that I get has no "N, S, E, W" indicators. In addition, I know that the longitude where I live is negative but it's coming out as positive. This is the output that I get:

This is the code that triggers that output:
int8_t stat;
// check GPS fix
stat = fona.GPSstatus();
if (stat < 0)  {
  Serial.println(F("Failed to query"));
}
if (stat == 0) {
  Serial.println(F("GPS off"));
}
if (stat == 1) {
  Serial.println(F("No fix"));
}
if (stat == 2) {
  Serial.println(F("2D fix"));
}
if (stat == 3) {
  Serial.println(F("3D fix"));
}

// check for GPS location
char gpsdata[120];
fona.getGPS(0, gpsdata, 120);
Serial.println(gpsdata);

I'm already reading about how to fix the GPS data so that it can be used by Google Maps, but I don't know what to do about the issue of not having the directional information/sign.
Here is the full code, just for reference:
#include "Adafruit_FONA.h"
#include <SoftwareSerial.h>

#define FONA_RX 2
#define FONA_TX 3
#define FONA_RST 4
#define FONA_KEY 7
#define FONA_PS 8

// this is a large buffer for replies
char replybuffer[255];

SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX);
SoftwareSerial *fonaSerial = &fonaSS;
Adafruit_FONA fona = Adafruit_FONA(FONA_RST);
uint8_t readline(char *buff, uint8_t maxbuff, uint16_t timeout = 0);

void setup() {
  Serial.begin(115200);
  pinMode(FONA_KEY, OUTPUT);
  pinMode(FONA_PS, INPUT);
  analogReference(INTERNAL);
  delay(2000);

  TurnOffFona();

  Serial.println(F("FONA SMS caller ID test"));
  Serial.println(F("Initializing....(May take 3 seconds)"));
  delay(1000);

  TurnOnFona();

  fonaSerial->begin(4800);
  if (! fona.begin(*fonaSerial)) {
    Serial.println(F("Couldn't find FONA"));
    while (1);
  }
  Serial.println(F("FONA is OK"));

  // Print SIM card IMEI number.
  char imei[15] = {0}; // MUST use a 16 character buffer for IMEI!
  uint8_t imeiLen = fona.getIMEI(imei);
  if (imeiLen > 0) {
    Serial.print("SIM card IMEI: "); Serial.println(imei);
  }

  // turn GPS on
  if (!fona.enableGPS(true)) {
    Serial.println(F("GPS failed to turn on"));
  }

  Serial.println("FONA Ready");
}

char fonaInBuffer[64]; //for notifications from the FONA

void loop() {
  char* bufPtr = fonaInBuffer; //handy buffer pointer

  if (fona.available()) {
    //any data available from the FONA?
    int slot = 0; //this will be the slot number of the SMS
    int charCount = 0;
    //Read the notification into fonaInBuffer
    do  {
      *bufPtr = fona.read();
      Serial.write(*bufPtr);
      delay(1);
    } while ((*bufPtr++ != '\n') && (fona.available()) && (++charCount < (sizeof(fonaInBuffer) - 1)));

    //Add a terminal NULL to the notification string
    *bufPtr = 0;

    //Scan the notification string for an SMS received notification.
    //  If it's an SMS message, we'll get the slot number in 'slot'
    if (1 == sscanf(fonaInBuffer, "+CMTI: \"SM\",%d", &slot)) {
      Serial.print("slot: "); Serial.println(slot);
      char callerIDbuffer[32];  //we'll store the SMS sender number in here

      // Retrieve SMS sender address/phone number.
      if (! fona.getSMSSender(slot, callerIDbuffer, 31)) {
        Serial.println("Didn't find SMS message in slot!");
      }
      Serial.print(F("FROM: ")); Serial.println(callerIDbuffer);

      int8_t stat;
      // check GPS fix
      stat = fona.GPSstatus();
      if (stat < 0)  {
        Serial.println(F("Failed to query"));
      }
      if (stat == 0) {
        Serial.println(F("GPS off"));
      }
      if (stat == 1) {
        Serial.println(F("No fix"));
      }
      if (stat == 2) {
        Serial.println(F("2D fix"));
      }
      if (stat == 3) {
        Serial.println(F("3D fix"));
      }

      // check for GPS location
      char gpsdata[120];
      fona.getGPS(0, gpsdata, 120);
      Serial.println(gpsdata);
      String gpsString;

      gpsString = (String) gpsdata; //re-cast chr array as string.
      Serial.println(gpsString);
      int commaIndex = gpsString.indexOf(',');
      int secondCommaIndex = gpsString.indexOf(',', commaIndex + 1);
      int thirdCommaIndex = gpsString.indexOf(',', secondCommaIndex + 1);
      int fourthCommaIndex = gpsString.indexOf(',', thirdCommaIndex + 1);

      String firstValue = gpsString.substring(0, commaIndex);
      String rawLat = gpsString.substring(commaIndex + 1, secondCommaIndex);
      String rawLon = gpsString.substring(secondCommaIndex + 1, thirdCommaIndex);
      String rawAlt = gpsString.substring(thirdCommaIndex + 1, fourthCommaIndex);

      int decimalIndex = rawLat.indexOf('.');
      String lat1 = rawLat.substring(0, decimalIndex);
      String lat2 = rawLat.substring(decimalIndex + 1, rawLat.length());
      Serial.println(lat1);
      Serial.println(lat2);
      rawLat = lat1.substring(0, 2) + "." + lat1.substring(3, lat1.length()) + lat2;
      Serial.println(rawLat);

      int decimal2Index = rawLon.indexOf('.');
      String lon1 = rawLon.substring(0, decimal2Index);
      String lon2 = rawLon.substring(decimal2Index + 1, rawLon.length());
      Serial.println(lon1);
      Serial.println(lon2);
      rawLon = lon1.substring(0, 2) + "." + lon1.substring(3, lon1.length()) + lon2;
      Serial.println(rawLon);

      char txtmsgArray[80];
      String txmsg = "https://www.google.com/maps/@" + rawLat + "," +  rawLon + ",15z";
      txmsg.toCharArray(txtmsgArray, 80);
      Serial.println(txtmsgArray);

      Serial.println("Sending reponse...");
      if (!fona.sendSMS(callerIDbuffer, txtmsgArray)) {
        Serial.println(F("Failed"));
      } else {
        Serial.println(F("Sent!"));
      }
      delay(3000);
      // delete the original msg after it is processed
      //   otherwise, we will fill up all the slots
      //   and then we won't be able to receive SMS anymore
      if (fona.deleteSMS(slot)) {
        Serial.println(F("OK!"));
      } else {
        Serial.println(F("Couldn't delete"));
      }
    }
  }
}

void TurnOnFona() {
  Serial.println("Turning on Fona: ");
  while (digitalRead(FONA_PS) == LOW) {
    digitalWrite(FONA_KEY, LOW);
  }
  digitalWrite(FONA_KEY, HIGH);
  delay(4000);
}

void TurnOffFona() {
  Serial.println("Turning off Fona ");
  while (digitalRead(FONA_PS) == HIGH) {
    digitalWrite(FONA_KEY, LOW);
  }
  digitalWrite(FONA_KEY, HIGH);
  delay(4000);
}

Using AT+CGPSINF=1 should give you NMEA formatted data. That may be of more use to you.

Send the command:
AT+CGPSOUT=1
That should enable the output of the standard NMEA $GPGGA string which includes all the position information you should need in a format that either you can parse or use one of the many existing libraries to parse. It's not clear from the documentation if this will be a one time output or a 1 Hz output.
There are other NMEA messages available if you need them, see https://cdn-shop.adafruit.com/datasheets/SIM808_GPS_Application_Note_V1.00.pdf for details.

GPS is a positioning system: it doesn't do direction.  If your software has serial information coming in,  it can take the difference in readings and generate that data but GPS doesn't do it for you.
Some devices may add it to the standard,  but that's a per-device feature. .

Op is asking for the hemisphere not the direction

No he wasn't, that's "in addition"


text:
Arduino Uno coding problem voltage varying
I was wondering whether anyone could help me... I am using an Arduino Uno and I am writing my code in the Arduino IDE. I am trying to implement the code so that the output voltage can be varied from 0 - 5 volts using 2 pushbuttons. I want to be able to increment the voltage by +0.5 volts from 0-5 volts every time I push Button A. Also I want to decrement the voltage by -0.5 volts from 5-0V every time I push Button B.
Example: (push Button A): output voltage 0.5: (push Button A): output voltage 1.0 etc.
So far when I upload my code the LED as my test for output just flickers between 2 - 4 volts. Can anyone tell me what I am doing wrong? I am not that good at coding so any help would be awesome.
Here is my code.
int PWMPin = 6; // output pin supporting PWM
int buttonApin = 8; // buttonA to pin 9 PWM
int buttonBpin = 10; // buttonB to pin 10 PWM
float value = 0; // read the value at 0
float fadeValue = value;
float counter = 0;

void setup() {
  pinMode(buttonApin, INPUT);
  pinMode(buttonBpin, INPUT);
  pinMode(PWMPin, OUTPUT);
}
void loop() {
  int port = analogRead(0);
  port = map(port, 0, 10, 0, 255);
  analogWrite(6, port);
  if (digitalRead(buttonApin) == LOW, fadeValue) {
    if (counter >= 10) {
      counter = 10;
    }
    // fade from min to max in increments of 25.5 points: basically (0.5 volts)
    for(fadeValue = 0 ; fadeValue <= 255; fadeValue +=25.5) {
      counter = fadeValue;
      // sets the value (range from 0 to 255):
      analogWrite(PWMPin, fadeValue);
      delay(100);
    }
  }
  if (digitalRead(buttonBpin) == LOW, fadeValue) {
    if (counter <= 0) {
      counter = 0;
    }
    // fade from max to min in increments of 25.5 points: basically (0.5 volts)
    for(fadeValue = 255 ; fadeValue >= 0; fadeValue -=25.5) {
      counter = fadeValue;
      // sets the value (range from 0 to 255):
      analogWrite(PWMPin, fadeValue);
      delay(100);
    }
  }
}

Why would you use a LED to test your output instead of, say, a DMM?

Because it would be the same thing when I connect it to a different source I will still be able to vary voltage IF i can get this running.

Varying the voltage on a LED does almost nothing.

okay so what would use for an output?

Something that gives you an actual number.

obviously if I get the Light to turn on I get light I can dim the light an brighten the light according to how often I push the button to the max 5v i think I'll be fine but what about my code? how bad is it?

"obviously if I get the Light to turn on I get light I can dim the light an brighten the light according to how often I push the button..." No. You can't. This is a LED.

@IgnacioVazquez-Abrams - that is not true - it's not an LED by itself, it's an LED in series with a resistance (external or internal).  And that means that the current which flows, and hence brightness, is a function of overall voltage.  Of course, most LED dimmers work with a fixed, optimal voltage and varying duty cycle.  It's an open question here if the Arduino's PWM output should be considered smoothed, or pulsed - that depends on the frame rate, and capacitance in comparison to load.

@ChrisStratton: The 25ohm resistance of the output is going to be unnoticeable at best.

On the contrary, the resistance whatever it is is going to be extremely noticeable - either the LED fails, or if it doesn't, that effective resistance is what is setting the operating current and preventing it from doing so.  Given the maximum current rating I expect it's a bit higher than 25 ohms effective when operating in excess of rated current.

The statement if (digitalRead(buttonApin) == LOW, fadeValue) is equivalent to if (digitalRead(fadeValue). I guess that's not what you wanted to do. See https://en.wikipedia.org/wiki/Comma_operator

There's a number of very basic things wrong with your code - things that aren't doing what you think, or you just telling it completely the wrong things.
Start by formatting your code properly (INDENTS!) and match up all your brackets.  You'll soon see what I see as far as what is wrong.
I'll give you some clues:

{
if (digitalRead(buttonApin) == LOW, counter)

Where to I start with that one...?

for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=25.5)
  counter = fadeValue;
  digitalWrite(PWMPin, fadeValue);

C is not Python!

digitalWrite(PWMPin, fadeValue);

Writing an analog value to a digital pin?!

Serial.println(PWMPin);

Printing the pin number - now what is the point of that?

... fadeValue += 25.5 ...

Adding a float to an integer - bad practice (and ultimately pointless) - pick one, float or integer, and stick to it.

And then there is the whole logic of your program. I can't work out what it's supposed to be achieving.  It looks like you've tried to get it to do all sorts of parts of different things and not got it to do anything at all.  Strip it right out and get it to do ONE thing - provide a specific, STATIC, voltage.  Then add in some way of changing that voltage afterwards.

I dont get it? what brackets should I take out

You have brackets where you shouldn't have, and you're lacking brackets where you should have them.

And that's just a start...

That's no help at all.  Please edit the code in your original question so I can see it in context

Yes I was going to put it in this comment and It was too long my bad I'm editing it now

uploaded new code now

Your program is still complete gibberish I am sorry to say. It looks like you have copied and pasted bits of other code without first understanding how that code works, and then interspersed it with some random bits that you think look like C but aren't. Go back to basics and get an LED to light at a specific brightness.

You forgot to add. It's useless to scale an analog output by a loop without delays!

Arduino IDE has autoformat function, it does most of the job itself that way.


text:
3-speed DC fan control with Uno
I have built this MOSFET circuit, which is supposed to run 2 DC fans using an Arduino Uno.

I am trying to get the two DC fans running with four settings: OFF, LOW, MED and HIGH. I have been having issues with the MED option, because when its option is selected by the rotary switch (5 V pulse detected by the analog pin A2) the speed of the fan is not the constant 75% duty cycle (191) as defined on line 75 in the code below:
int motorPin1 = 3;
int motorPin2 = 9;
int DCfanSpeed = 0;
int voltageZero = 0;
int voltageOne = 1;
int voltageTwo = 2;
int voltageThree = 3;

void setup() {
  pinMode(motorPin1, OUTPUT);
  pinMode(motorPin2, OUTPUT);
  digitalWrite(voltageZero, INPUT_PULLUP);
  digitalWrite(voltageOne, INPUT_PULLUP);
  digitalWrite(voltageTwo, INPUT_PULLUP);
  digitalWrite(voltageThree, INPUT_PULLUP);
  Serial.begin(9600);
}

void loop() {
  int voltageReadingZero = analogRead(voltageZero); // OFF SWITCH
  int voltsZero = voltageReadingZero / 204.6;
  if (voltsZero == 5) {
    delay(300);
    if (voltsZero == 5) DCfanSpeed = 0;
    // else DCfanSpeed = DCfanSpeed;
    while (voltsZero == 5) {
      analogWrite(motorPin1, DCfanSpeed);
      analogWrite(motorPin2, DCfanSpeed);
      voltageReadingZero = analogRead(voltageZero);
      voltsZero = voltageReadingZero / 204.6;
    }
  }
  int voltageReadingOne = analogRead(voltageOne); // LOW SWITCH
  int voltsOne = voltageReadingOne / 204.6;
  if (voltsOne == 5) {
    delay(300);
    if (voltsOne == 5) DCfanSpeed = 128;
    //else DCfanSpeed = DCfanSpeed;
    while (voltsOne == 5) {
      analogWrite(motorPin1, DCfanSpeed);
      analogWrite(motorPin2, DCfanSpeed);
      voltageReadingOne = analogRead(voltageOne);
      voltsOne = voltageReadingOne / 204.6;
    }
  }
  int voltageReadingTwo = analogRead(voltageTwo); //  MED SWITCH
  int voltsTwo = voltageReadingTwo / 204.6;
  if (voltsTwo == 5) {
    delay(300);
    if (voltsTwo == 5) DCfanSpeed = 191;
    //else DCfanSpeed = DCfanSpeed;
    while (voltsTwo == 5) {
      analogWrite(motorPin1, DCfanSpeed);
      analogWrite(motorPin2, DCfanSpeed);
      voltageReadingTwo = analogRead(voltageTwo);
      voltsTwo = voltageReadingTwo / 204.6;
    }
  }
  int voltageReadingThree = analogRead(voltageThree);  //  HIGH SWITCH
  int voltsThree = voltageReadingThree / 204.6;
  if (voltsThree == 5) {
    delay(300);
    if (voltsThree == 5) DCfanSpeed = 255;
    //else DCfanSpeed = DCfanSpeed;
    while (voltsThree == 5) {
      analogWrite(motorPin1, DCfanSpeed);
      analogWrite(motorPin2, DCfanSpeed);
      voltageReadingThree = analogRead(voltageThree);
      voltsThree = voltageReadingThree / 204.6;
    }
  }
}

Excuse the poor formatting but the basic rundown of the medium option is such that the voltage across the analog pin 2 is measured and converted into volts and if it is 5 Volts (rotary turned to the medium position) then it enters a while loop where the voltage is monitored such that if there is any change then there must be a speed setting change. This is the only option for which I get this pulsating speed on the fans instead of smooth and continuos operation.
Any ideas about how I could improve this? I have taken away one fan to see if one was faulty but this didn't work.

"Excuse the poor formatting". I have done it for you but in the future please do a Tools > Auto Format on your code before posting.

Why are you using analogRead() to read a digital signal from a switch...?

Because if I use digital read won't the compiler assume that I am talking about one of the digital pins on the UNO board and not the analog pins? I have to use the analog pins to detect the 5V signal because the digital pins are way too receptive to interference and switch on and off arbitrarily especially when there is the ports of a rotary switch connected there.

Solved simply by condensing code and getting rid of unnecessary variable declarations.
Corrected program:
    int motorPin1 = 3;
    int motorPin2 = 9;
    int DCfanSpeed = 0;

    void setup()
    {
      pinMode(motorPin1, OUTPUT);
      pinMode(motorPin2, OUTPUT);
      digitalWrite(A0, INPUT_PULLUP);
      digitalWrite(A1, INPUT_PULLUP);
      digitalWrite(A2, INPUT_PULLUP);
      digitalWrite(A3, INPUT_PULLUP);
      Serial.begin(9600);
    }

    void loop()
     {

       int voltsZero = analogRead(A0)/204.6; // OFF SWITCH
       if(voltsZero == 5)
        {
          delay(300);
          if(voltsZero == 5) DCfanSpeed = 0;

           while(voltsZero == 5)
            {
              analogWrite(motorPin1, DCfanSpeed);
              analogWrite(motorPin2, DCfanSpeed);
              voltsZero = analogRead(A0)/204.6;

            }
         }

      int voltsOne = analogRead(A1)/204.6;    // LOW SWITCH
      if(voltsOne == 5)
        {
          delay(300);
          if(voltsOne == 5) DCfanSpeed = 128;
          while(voltsOne == 5)
           {
             analogWrite(motorPin1, DCfanSpeed);
             analogWrite(motorPin2, DCfanSpeed);
             voltsOne = analogRead(A1)/204.6;
           }
        }

       int voltsTwo = analogRead(A2)/204.6;  //  MED SWITCH
       if(voltsTwo == 5)
        {
          delay(300);
          if(voltsTwo == 5) DCfanSpeed = 191;
          while(voltsTwo == 5)
           {
             analogWrite(motorPin1, DCfanSpeed);
             analogWrite(motorPin2, DCfanSpeed);
             voltsTwo = analogRead(A2)/204.6;

           }
        }

      int voltsThree = analogRead(A3)/204.6;  //  HIGH SWITCH
      if(voltsThree == 5)
        {
          delay(300);
          if(voltsThree == 5) DCfanSpeed = 255;
          while(voltsThree == 5)
           {
             analogWrite(motorPin1, DCfanSpeed);
             analogWrite(motorPin2, DCfanSpeed);
             voltsThree = analogRead(A3)/204.6;
           }
         }

    }


text:
How to code water flow sensor and solenoid valve?
I want to know if it is possible to put a boundary or limit to the volume that passes through a water flow sensor, and close the pipe using a solenoid valve.
Example: I only want 400 ml of water to pass, so when the water flow sensor reads how much water has passed in the pipe, if 400 is reached, the solenoid will close the pipe.
Sorry for my bad English, it is not my first language. I'm hopping that someone can help me out.

A snippet of code please .. And a explanation

The time that your solenoid is open, could also be an indication of the amount of water passed.

Have you asked the manufacturer of the water flow sensor how it works? What have you tried yourself? What model numbers do these sensors/actuators have? Have you actually tried something? There is no way that we can/will provide code for a project that we do not know the details or issues of...

I try some codes i find in the internet here http://www.bc-robotics.com/tutorials/using-a-flow-sensor-with-arduino/  and the brand and model of my water flow sensor is sea model yf s201 .. i dont have any idea on how to achieve that or to be able to put limit .

hello @kaisar Great you have not mentioned which flow sensor are you using. I am assuming that you are using flow sensor YF-S201 or YF-S401(Hall Effect).You have to do Little calculation for measuring water flow.
In order to measure the quantity of water being passed in particular time through the water flow sensor it was first passed through the water flow sensor which was taken as input interface in the flow. Formulas are applied in order to measure the number of rotations/pulses in a minute of rotation.
Here I have determined flow rate by change in velocity of water. Velocity depends on the pressure that forces the through pipelines. As the pipe’s cross-sectional area is known and remains constant, the average velocity is an indication of the flow rate. The basis relationship for determining the liquid’s flow rate in such cases is
Q=VxA, where Q is flow rate/total flow of water through the pipe, V is average velocity of the flow and A is the cross-sectional area of the pipe
Calibration Factor = The hall-effect flow sensor outputs pulses per second per litre/minute of flow.(check your datasheet) here I have taken 4.5.
Flow Rate(litres/minute) = ((1000.0 / Total time) x Pulse Count) / calibration Factor
Flow Rate(MilliLitres/Second) = (Flow Rate / 60) x 1000
There you have to calculate the total water flow in a given time by adding flow rate for each second.
There after you have check your set point value(400ml)..if condition satisfied you you can turn off your Solenoid valve.
and the code is
int sensorInterrupt = 0;  // interrupt 0
int sensorPin       = 2; //Digital Pin 2
int solenoidValve = 5; // Digital pin 5
unsigned int SetPoint = 400; //400 milileter

/*The hall-effect flow sensor outputs pulses per second per litre/minute of flow.*/
float calibrationFactor = 4.5; //You can change according to your datasheet

volatile byte pulseCount =0;

float flowRate = 0.0;
unsigned int flowMilliLitres =0;
unsigned long totalMilliLitres = 0;

unsigned long oldTime = 0;

void setup()
{

  // Initialize a serial connection for reporting values to the host
  Serial.begin(9600);
  pinMode(solenoidValve , OUTPUT);
  pinMode(sensorPin, INPUT);
  digitalWrite(sensorPin, HIGH);

  /*The Hall-effect sensor is connected to pin 2 which uses interrupt 0. Configured to trigger on a FALLING state change (transition from HIGH
  (state to LOW state)*/
  attachInterrupt(sensorInterrupt, pulseCounter, FALLING); //you can use Rising or Falling
}

void loop()
{

   if((millis() - oldTime) > 1000)    // Only process counters once per second
  {
    // Disable the interrupt while calculating flow rate and sending the value to the host
    detachInterrupt(sensorInterrupt);

    // Because this loop may not complete in exactly 1 second intervals we calculate the number of milliseconds that have passed since the last execution and use that to scale the output. We also apply the calibrationFactor to scale the output based on the number of pulses per second per units of measure (litres/minute in this case) coming from the sensor.
    flowRate = ((1000.0 / (millis() - oldTime)) * pulseCount) / calibrationFactor;

    // Note the time this processing pass was executed. Note that because we've
    // disabled interrupts the millis() function won't actually be incrementing right
    // at this point, but it will still return the value it was set to just before
    // interrupts went away.
    oldTime = millis();

    // Divide the flow rate in litres/minute by 60 to determine how many litres have
    // passed through the sensor in this 1 second interval, then multiply by 1000 to
    // convert to millilitres.
    flowMilliLitres = (flowRate / 60) * 1000;

    // Add the millilitres passed in this second to the cumulative total
    totalMilliLitres += flowMilliLitres;

    unsigned int frac;

    // Print the flow rate for this second in litres / minute
    Serial.print("Flow rate: ");
    Serial.print(flowMilliLitres, DEC);  // Print the integer part of the variable
    Serial.print("mL/Second");
    Serial.print("\t");

    // Print the cumulative total of litres flowed since starting
    Serial.print("Output Liquid Quantity: ");
    Serial.print(totalMilliLitres,DEC);
    Serial.println("mL");
    Serial.print("\t");
    If (totalMilliLitres =< 400)
    {
      SetSolinoidValveON();
    }
    else{
      SetSolinoidValveOFF();
        }

// Reset the pulse counter so we can start incrementing again
    pulseCount = 0;

    // Enable the interrupt again now that we've finished sending output
    attachInterrupt(sensorInterrupt, pulseCounter, FALLING);
  }
}

//Insterrupt Service Routine

void pulseCounter()
{
  // Increment the pulse counter
  pulseCount++;
}

void SetSolinoidValveON()
{
  digitalWrite(solenoidValve, HIGH);
}
void SetSolinoidValveOFF()
{
  digitalWrite(solenoidValve, LOW);
}

What is the difference between RISING and FALLING in this line of code attachInterrupt(sensorInterrupt, pulseCounter, FALLING);

Actually working principle of this flow sensor is its produce pulses(Square Wave) proportional to flow rate of liquid.  When a circuit is rising edge-triggered, it becomes active when its clock signal goes from low to high, and ignores the high-to-low transition. A falling edge is the high to low transition.

I try this code and it doesn't work , totalMilliLitres stores total liters flowed since starting and it will close the solenoid once .

You have to first modify this code according to your flow sensor datasheet otherwise its gives erroneous result cause parameters are assumed based which I given in this code so it will not match with your flow meter datasheet. anyway upload your skech and output along with your flow sensor datasheet

Using a YF201 you cannot measure less than 1 litre / minute or more than 30 l/m.
(ref http://www.bc-robotics.com/tutorials/using-a-flow-sensor-with-arduino/)
The device sends a pulse for every 2.25ml that flows through it.  All you needs to do is take the amount you want to let through (400ml) and divide that by 2.25ml and you get 177.8 pulses.  So once your Arduino counts 178 pulses then you trigger the valve to close.
Its not going to be very accurate, because unless the valve closes instantly there will be a bit of an overshoot.  and you have to measure in units of 2.25ml.

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


text:
Use a Unicode surrogate pair character in Arduino IDE
I'm writing a sketch for a Wemos D1 Mini to display a web page. This works and I can get Unicode characters to display, but if I try to use ones with surrogate pairs like 🔊 I get a compile error;
  s += "\uD83D\uDD0A";

Error

\uD83D is not a valid universal character

How can I get this character in my code?

There is a nifty new feature in C++11 called string literal, this example shows how to use it with any single line or multi line or utf8 text. You just define starting and ending sequence, in following case --- (starting sequence becomes R"---( and ending sequence )---") and make sure that this sequence does not appear in encapsulated text. This is great for integrating websites into arduino projects:
static const char _index_html[] PROGMEM = R"---(
<html>
<head>
<link rel="icon" type="image/png" href="/favicon.png"/>
</head>
<body>
...
</body>
</html>
)---";

Okay, but what does that have to do with the SMP? Or anything outside ASCII for that matter?

If he had used any unicode capable editor, he could just copy/paste any unicode symbols without caring how to encode them - no need to use escaping sequences. Also this answers shows how to easily integrate mutliline HTML code into arduino project

After some trial and error, I got it using the python style u"\U0001F50A" without the leading u of course
  s += "\U0001F50A";

Too bad I didn't think about googling the error msg, would have saved me some time.

Can you use pure UTF-8 characters in the source code ? It is a risk, because everything should be able to handle them. I think it should work. At least this forum can handle pure UTF-8 characters: ±10 °C, 10 µm, 1 kΩ, ¿

Actually, you can. I didn't even try that.


text:
Is my Arduino possibly broken?
We work in groups on a project at school. We had to build an electric scheme with an Arduino to make a small car moving.
We got the parts from our school, except the Arduino (we had to buy it ourselves). We had to use a battery of 11.5 V. We also had electrical resistors to protect the Arduino and the stepper drivers.
The car worked for a while, but then we wanted to change the program and tried to upload new software to the Arduino. Now the Arduino is not recognized by any computer.
We tried several things, like multiple times unplugging the USB cable, hitting the reset button on a specific timed moment (some method found on the internet).
But it still doesn't work. When the Arduino is connected via USB, the 'on' LED on the Arduino is on. After that all we came also to the conclusion that some people made mistakes on building the electric scheme...

Is it possible that the Arduino is broken, since the battery has 11.5 V?
If the Arduino isn't broken, can the problem that it's not recognized by the computer be solved?

(Arduino Uno)

You can read 10 Ways to Destroy An Arduino, it might help you to find out what did you do. BTW, there is even possibility to destroy USB port, are you sure it's still working?

Without knowing what you did with your sheme or your "electrical resistors" it's impossible to tell. Some pictures and schematics would be useful.

you can get a working Arduino uno online for 5$ on ebay. think of that it's about 7 for the price of one!

This question appears to have been abandoned after being asked. You may get help from Have I bricked my Arduino Uno? Problems with uploading to board. If there is no response I'll close this question. There is no point asking questions and then not responding to queries. We had to use a battery of 11.5 V. We also had electrical resistors to protect the Arduino and the stepper drivers. - that is very unclear.

Considering that you used resistors to lower the 11.5V to an cough - cough "very normal and regulated 5V", that most certainly is the problem.
The "right and cheap" way to lower such high voltage and connect them directly to your 5V (just assuming, since you said that you used resistors to protect the Arduino) is actually to use a voltage regulator. Any cheap 7805 should do the job. The Arduino actually has its own voltage regulator on it, if you connect it though the Vin pin.
The "true and efficient" way to step down some voltage is actually to use a step-down converter. The way this is better then any normal regulator is that a regulator will lower your voltage by creating heat when the step-down converter will do it in a more efficient process.
The USB of your PC might also be the problem. There is a fuse on the Arduino and one in almost all USB ports of decent PCs. If the voltage spike is high enough, it might have burned the port. That is quite a rare event, but still possible.
Need anymore help, just comment. I'll be happy to help you!

If you connect 11.5V directly to the Arduino then you might have killed you Arduino, BUT you say the LED comes up when you hook up the USB lead.  So take things one step at a time.

Get an Arduino that you know is working and try it in the PC with the same cable.  Does it work?  (No -> Cable or PC is broken - Get a new cable/PC)
Remove all wires, shields, etc. from your Arduino.
Connect the USB cable to the PC, does the Arduino power up? (No -> Arduino is almost certainly dead)
Does the PC recognise the board? (Window -> Beeps, tries to download drivers, etc.) (No-> Manually uninstall the drivers and then repeat this step if it doesn't succeed then the Arduino is very unwell)
Start the Arduino IDE and open Examples->Basic->Blink.  Upload the program to your board.  Does it work? (No -> You need more advanced fault finding)
Change Blink so it prints a message every time the loop, Serial.println("Hello"); will do.
Upload you modified program and open the serial monitor.  Does it show the message?  (No -> You need more advanced fault finding)

I know this doesn't fix the problem, but hopefully this will help you narrow down the fault.
My gut feeling is that your Arduino has executed its last lines of code, but you never know...


text:
Is there a way to replace an Arduino core function without modifying the Arduino code?
(Let's just skip the suggestions that it's the wrong idea and interrupts for a while...).
Is there a way to replace the digitalWrite() method (for example) so I can add something more to happen in there? But the following rules must be obeyed:

A call to digitalWrite(pin, value) must invoke the new method.
A call to digitalWrite(pin, value) from a different library included in my code (SD.h for example) must invoke the new method.
None of the Arduino files can be modified (I don't want to do it on every Arduino version upgrade).
Everything must be done in a header file that I can include to use the new function.

I have tried this and it works, but only in my code, not in external libraries that I include after this header:
#include <Arduino.h>

class PinsHook {
  public:
    static void digitalWriteHook(uint8_t pin, uint8_t value) {
      digitalWrite(pin, value);
      if (pin == 8) {
        Serial.print("Pin ");
        Serial.print(pin);
        Serial.print(" changed to ");
        Serial.println(value);
      }
    }
};

#define digitalWrite(pin, value) PinsHook::digitalWriteHook(pin, value)

This library seem to be able to do it using templates.

Not sure about the Arduino IDE (I don't have it installed right now) but using UECIDE it's as simple as defining a new digitalWrite function in your code.  When the whole shebang gets linked together the function in your code overrides the function in the libraries.
void setup() {
    pinMode(13, OUTPUT);
}

void loop() {
    digitalWrite(13, HIGH);
    delay(100);
    digitalWrite(13, LOW);
    delay(800);
}

void digitalWrite(int pin, int level) {
    // Not gonna do anything!
}

Comment out the digitalWrite function and the LED blinks.  Uncomment it and it doesn't blink any more.

Yes, I think it's working in external libraries too! But this way I can't invoke the original digitalWrite() from this method because the method is calling itself (stack overflow!). Can this be solved? If my method was the linked one, then I think the original method was not included at all and can't be called - am I right?

You are correct. You will have to copy and paste the content of the original digitalWrite into your variant to use it.

I have tried that but it doesn't compile. Some things are missing. If you can create an example code of such method, overriding and calling the original method (and add it to your answer), then it will be the answer I'm looking for.

There is probably a huge amount in the existing digitalWrite that you don't need. It's been made to be generic, but if you only want to do specific things with specific pins you could hard-code those calls to the PORT registers yourself.

@P.W. overwriting a single function will only work if it's the only function in the module. "The smallest unit the linker knows about is the object module". So, if the linker finds a matching function in your code, it will bring that module in and ignore the rest of the methods in the code lib. I believe that's what's causing the compiler failure you mentioned. More info in my answer below.

2018: Spend some hours with UECIDE, looks okay however it is not ok, many bugs. After changing some code (AVR) It compiles just once and after relaunching the IDE it didn't compile (define problem which doesn't exists before). ESP code, incompatible defined types in the library, changed, now problem AsyncWebServer which cannot be solved. IDE doesn't pick up library changes, needs to restart the IDE, etc. Don't waste your time on it, maybe try it after a few years.

If you find issues with UECIDE I suggest you raise them as issues on the github repository. that way there is a chance they may get fixed. If you just moan about unspecified problems they will never get fixed. My guess, though, is that you are just too used to the over simplified Arduino environment and haven't found the right options in the menus to do what to want - like the one to rescan all the libraries and suchlike.

Did you try with a C macro?
#define digitalWrite(a, b) \
(pre(), digitalWrite(a, b), post())

this evaluates to the retval of post()
you can omit either the pre() or the post() functions/macros.
This needs to be placed somewhere that is included whenever the header for digitalWrite is included, so that it can override it.
The only other alternative is to become creative with the library binary.
Or, just be reasonable and modify the source code.
It's specifically available so that people can modify it.
Wrt not repeating the modification every time there is a new Arduino release, that should be avoidable.
If you build the environment from the git sources, you can maintain your patch by merging/rebasing onto the master branch.

Yeah, but that's the last resort. Your macro works just like my macro (see last line of my code) - does not work in other libraries. I'm searching for a non-invasive way to make it included into other libraries. Any ideas?

You are going against every design principle used in designing function calls and libraries :-D What you want to do is closer to hacking a binary than altering the source code of a program. The only pseudo-legal option left is to play with the linker. For example rename the original function and use --wrap to hijack it. Check this as starting point https://sourceware.org/binutils/docs-2.21/ld/Options.html#Options

Btw, if you only want to track what is going on at pin level, you could use a logical analyzer - it's very cheap and more reliable than some prints. Plus it adds zero overhead to the program. See the section "sigrok and pulseview" about in the middle of the answer to http://arduino.stackexchange.com/questions/22898/how-to-design-and-debug-a-custom-i2c-master-slave-system

I know. I am thinking about redirecting pins, not debugging. And by redirecting I mean sending them through an expander or shift register for example, which the original libraries just cannot do. I'm out of pins and I don't want to write my own versions of the standard libraries. Does it make sense now?

Just throwing an idea. No time to test now.
Edit: I tested the solution below, and it works as expected,
provided both the __wrap_ and __real_digitalWrite() are declared
extern "C".
If you can convince the IDE to add extra options to the compile command
line, you could:

name __wrap_digitalWrite() your implementation of digitalWrite()
inside it, call __real_digitalWrite() when you want to get the
implementation from Arduino core
add -Wl,--wrap=digitalWrite to the compile command of the final
link step

Example wrapper:
extern "C" {
    void __wrap_digitalWrite(uint8_t, uint8_t);
    void __real_digitalWrite(uint8_t, uint8_t);
}

// Calls to digitalWrite() are diverted to this.
void __wrap_digitalWrite(uint8_t pin, uint8_t value)
{
    __real_digitalWrite(pin, value);  // call implementation from Arduino core
    if (pin == 8) {
        Serial.print(F("Pin 8 changed to "));
        Serial.println(value);
    }
}

Trying to put this inside a class won't help.
C.f. the man page of gnu ld.

Please explain step 3 some more: How do we "add -Wl,--wrap=digitalWrite to the compile command of the final link step"?

Arduino uses the avr compiler to compile its standard library into a core.a file.
Due to the way the avr-gcc linker works and the order in which Arduino specifies the link order, you're able to "override" the behavior of core functions by copying the file that contains the method you want to alter into your project.

The compiler compiles a single high-level language file (C language,
  for example) into a single object module file. The linker (ld) can
  only work with object modules to link them together. Object modules
  are the smallest unit that the linker works with.
Typically, on the linker command line, you will specify a set of
  object modules (that has been previously compiled) and then a list of
  libraries, including the Standard C Library. The linker takes the set
  of object modules that you specify on the command line and links them
  together. Afterwards there will probably be a set of "undefined
  references". A reference is essentially a function call. An undefined
  reference is a function call, with no defined function to match the
  call.
The linker will then go through the libraries, in order, to match the
  undefined references with function definitions that are found in the
  libraries. If it finds the function that matches the call, the linker
  will then link in the object module in which the function is located.
  This part is important: the linker links in THE ENTIRE OBJECT MODULE
  in which the function is located. Remember, the linker knows nothing
  about the functions internal to an object module, other than symbol
  names (such as function names). The smallest unit the linker works
  with is object modules.
When there are no more undefined references, the linker has linked
  everything and is done and outputs the final application.
....
The linker will search libraries in the order that they appear on the
  command line. Whichever function is found first that matches the
  undefined reference, it will be linked in.

Arduino's linking occurs in this order:

Project Files
Libraries
core.a (Arduino std lib)

So, copying the file from the Arduino installation location (C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino) into your project and modifying it will result in it using your modified implementation.
This will certainly over-ride it for any files in your project, and I believe it will also override it in any libraries you're using as well, so be careful with this approach.

The information from Rubber Duck is correct but incomplete.
I need a huge amount of digital PWM output for hobby train control.
So I connected 4 x 74HC595 to my At Mega which must be fed with a 2 kHz bit pattern through 0,5 ms. interrupts.
My serial shift function that shifts 32 bits into the registers takes 562 us per cycle. Impossible.
I made an optimized version of digitalWrite and Read, which takes 328 us. Now it is possible to PWM with 2 kHz. The trick is that my optimized function remembers the last 2 Pins including its bitmasks and outports;  and  I skip the Timer check. It is thread safe. For a single digitalWrite this takes a tiny bit more time. With repeating writing to datapin and clockpin it improves the standard Arduino digitalWrite with about 42%.
By the way: With the digitalWriteFast library the result is 45,8 µs, a really enormous improvement. But this library handles only writes, if the pin number is known (and thus fixed!) at compile time. That is not the case with my LiquidCrystal library, where either 4 or 8 bits parallel are written to the shield via 4 sequential pins.
I got my optimized digitalWrite only working for my application including the LiquidDisplay when I copied the C:\Users\Dell\Downloads\arduino-1.8.5\hardware\arduino\avr\cores\arduino library to a subfolder in the folder of my application, called
C:\Users\Dell\Google Drive\ …\…..\AppFolder\libraries.
When I replaced in both folders the wiring_digital.c with my optimized version, it worked.
I could not get it at work, when I only replaced the wiring_digital.c in the Arduino library (the LiquidCrystal took the standard function somewhere else).
Adding only wiring_digital.c in de subfolder of my application generated a mass of linking errors.
Thus I copied the whole Arduino folder (which is not that large) to my subfolder in the application and it compiles without any problem. Not a very elegant solution, because there is a replication of the whole library; but it works.
Conclusion to override a core Arduino function:
•   Put your changed function(s) (.c and/or .h) in the Arduino library, and copy this library entirely to the subfolder "libraries" in your application folder.  Then all other libraries will also use your own changed function.
Conclusion performance digitalWrite in a real 32 bit serial shift :
•   An optimized  generic digitalWrite and Read easily outperforms the standard one with 42% if 2 pins are used in repetition.
•   digitalWriteFast (with determined pins at compile time) outperforms the standard digitalWrite in a real 32 bit shift application with 92% (is 12,2 times faster).
Hope this helps other Arduino users…..
//**********************
void digitalWrite(uint8_t pin, uint8_t val)
//**********************
{
uint8_t
  timer,
  bit,
  port;

volatile uint8_t *out; // volatile because bitmask may be changed by (higher) interrupt

uint8_t oldSREG;

static uint8_t pin1 = 0,
               pin2 = 0;

static bool    p1   = true; // boolean toggle memory

static uint8_t // Store 2 sets of port/out adresses static

//          timer1, //now exclued. Safety threat?
          bit1,
          *out1,
//          timer2,
          bit2,
          *out2;

  oldSREG = SREG;  // CLI for thread proof function
  cli();
  if ( (pin == pin1) || (pin == pin2) )
  {
    if (pin == pin1)   //Compiler optimizes this excellent (see ASM listing)
    {
      if (val == LOW)
      {
        *out1 &= ~bit1;
      } else
      {
        *out1 |= bit1;
      }
    }
    else
    if (pin == pin2)
    {
      if (val == LOW)
      {
        *out2 &= ~bit2;
      } else
      {
        *out2 |= bit2;
      }
    }

    SREG = oldSREG;
  }
  else  //normal clumsy digitalWrite operation
  {
    SREG = oldSREG;   //Enable interrupts again
    timer = digitalPinToTimer(pin);
    bit = digitalPinToBitMask(pin);
    port = digitalPinToPort(pin);
    if (port == NOT_A_PIN) return;

    // If the pin that support PWM output, we need to turn it off
    // before doing a digital write.
//    if (timer != NOT_ON_TIMER) turnOffPWM(timer);

    out = portOutputRegister(port);

    oldSREG = SREG;
    cli();

    if (val == LOW) {
      *out &= ~bit;
    } else {
      *out |= bit;
    }

    if (p1)        // Save this port, bit and out, also atomic
    {
      pin1  = pin;
      bit1  = bit;
      out1  = out;  // save the pointer, not the value
    }
    else
    {
      pin2  = pin;
      bit2  = bit;
      out2  = out;  // save the pointer, not the value
    }
    p1 = !p1;
    SREG = oldSREG; //enable interrupts
  }
}

//**********************
int digitalRead(uint8_t pin)
//**********************
{

uint8_t
  oldSREG,
  timer,
  bit,
  port;

static uint8_t pin1 = 0;

bool           readBit;

static uint8_t // Store 2 sets of port/out adresses static

//          timer1, //now exclued. Safety threat?
              port1,
              bit1;

  oldSREG = SREG;
  cli();
  if (pin == pin1)
  {
    readBit = (*portInputRegister(port1) & bit1);
    SREG = oldSREG;
    return readBit;
  }
  else
  {
    SREG = oldSREG;
    timer = digitalPinToTimer(pin);
    bit = digitalPinToBitMask(pin);
    port = digitalPinToPort(pin);

    if (port == NOT_A_PIN) return LOW;

    // If the pin that support PWM output, we need to turn it off
    // before getting a digital reading.
  //  if (timer != NOT_ON_TIMER) turnOffPWM(timer);

    oldSREG = SREG;
    cli();
    pin1 = pin;       //Atomic operation pin - bit combi must be correct
    bit1 = bit;
    port1 = port;
    SREG = oldSREG;

    if (*portInputRegister(port) & bit) return HIGH;
    return LOW;
  }
}

"Maybe" using the c++ "functions overriding" feature can help
void digitalWrite(uint8_t P, int8_t V, bool _wrap)
{
  Serial.print("wrap digitalwrite");
  digitalWrite(P,V);
}

Thus, if you call in you main application:
digitalWrite(pin_button, 1, 0);

The wrapped version will be called
and if you used this:
digitalWrite(pin_button, 1);

The original one will be called

You may also use this definition:
void digitalWrite(double P, int8_t V)
{
  Serial.print("wrap digitalwrite");
  //digitalWrite(P,V); Calling it even with (int) P will cause a recursive loop
}

But in-order to use it you need to define a variable with double type:
double pin;
pin = 13;
digitalWrite(13,1);

This doesn't satisfy the first two requirements of the OP.

I know, I just thought that this will help in someway (and maybe enhanced by others comments).

@EdgarBonet see the new update if you're interested. This satisfies all the requested.

Except point 2, when calling from an existing library.

In your code module, define your own wrapper function, and use the global scope operator to reference the Arduino function:
void pinMode(int pin, int pinmode)
{
  /*use my custom function?*/
  if(pin >= MY_OWN_PIN_CODES_BASE)
  {
    /*todo : my own custom pin access*/
    example_pinmode(pin, pinmode);
  }
  else /*use regular Arduino function*/
  {
    /*use global scope operator :: to call Arduino library version*/
    ::pinMode(pin, pinmode);
  }
}

Remember, the linker has rules for which one it references.  The global scope operator forces the linker to choose the globally available one, while the custom wrapper function is seen privately by the module.

To satisfy the OP's requirements, the wrapper should work in global scope. In this situation your technique yields an infinite loop.


text:
Using Arduino and XBee at the same time
I have 2 Arduino Unos, 2 XBees and 2 Wireless Proto Shields. The first setup has a humidity/temperature sensor (SHT21P) and it writes data to serial and it works (I've tested it).
Now, the other Arduino with shield and XBee is plugged in my PC to get data from the sensor. So here's the problem: as far as I understand, I can't use XBee and Arduino at the same time, because USB and Arduino both use TX/RX pins to communicate to PC/XBee. I've tested both of the XBees when they are powered with DC jack and they both work. So can anyone confirm that it's true that they're not made for being used by PC and Arduino at the same time? If so, how can I get the data to my computer?

Okay, I guess I figured it all out. So right now I have the following setup:
1 Arduino Board with Wireless Proto Shield (switch in Micro position) and XBee hooked up via DC jack pin, sends data to serial with Serial.print(variable) where variable is a predefined char array.
1 Arduino with Wireless Proto Shield (switch in Micro position) and XBee is hooked to the PC via USB and with Serial.read() I'm able to read data via the Serial Monitor. No configuration required whatsoever, the only thing you need to do this is to declare Serial.begin(9600) to both boards.
So it's true that I can't use Arduino and XBee at the same time, but this still works for me to solve the problem I had.

If I understand correctly your goal is to receive data on your computer from an arduino connected with xbee? You could use a USB > Xbee board similar to Sparkfun's Xbee USB explorer board. I am not familiar with the shield that you are using, but some xbee shields allow you to select the pins that the xbee is connected to. It sounds like yours is defaulting to Pin 0 and Pin 1, hardware serial on the Uno. If you can switch it to Pin 2 and Pin 3 (or any two digital pins) you could use software serial with the xbee, leaving hardware serial free for your USB connection.


text:
ATmega 2560 with Arduino bootloader running issue
I have designed a board based on an ATmega2560 chip and I burned the bootloader by following this tutorial.
Now I am able to load Blinky and other programs using an FTDI cable. But the issue I am facing right now is the controller runs Blinky fine if I leave the FTDI connected there. If I disconnect the FTDI cable and power-cycle the board it is not running Blinky. If I connect the FTDI, right away it starts blinking.

It looks like something is wrong with my RESET pin connection? Here is what my RESET circuitry looks like:

I also have tried by removing D1 diode but no luck !

Looks like something wrong with my RESET pin connection ... how do you know. please post your schematic

I am not having schematic but I have followed the circuit given above and in additional I put 0.1uf to connect RESET pin with FTDI.

What happens if you momentarily short the reset line to ground and then release it?   Also, what is your power source?  Did you have the 5v line from the FTDI connected when it was working?   Try to figure out which connections to the FTDI correlate with it starting to work.

Chris,
I have 12v supply which is then stepped down to 5v. No I am not using power from FTDI connection. It starts running when I connect my board Ground with FTDI Ground Pin and FTDI plugged into my PC. I checked I have ground line common.

The issue was there was some noise on RX Pin of the chip and because of that when it is powered on in bootloader it was stuck at that place. And it was working good with FTDI because RX gets proper connection with my FTDI.
Solution:- Connect 10K pull-down on RX pin resolved this problem.

Or get rid of C6, I have never used that in a design.

C6 was not a problem. I have posted the exact solution I found in this case.


text:
Arduino Wire.h library: how to communicate with an LCD?
I am having an Arduino Uno and a C2042A LCD with I2C shield on it. Because the VirtualWire library does not work for me. I tried only the wire library but it's still not working:
My code:
#include <Wire.h>

void setup() {
  Wire.begin(0x63);
}

void loop() {
  Wire.write(4);
}

I just read on this website which commands you have to use but it doesn't do anything. What is my fault, how to solve it?

Please add a link to the LCD Shield.

use can see and read about the lcd here: http://www.robot-electronics.co.uk/htm/Lcd03tech.htm

You need to first read about how to use Wire and then the LCD communications protocol. The above code snippet is not a complete command.

SOLVED!
I forgot to write beginTransmission(). Here's my code:
#include <Wire.h>

void setup() {
  Wire.begin(0x63);
}

void loop() {
  Wire.beginTransmission(0x63);
  Wire.write(byte(0x00));
  Wire.write("Temperatur:");
  Wire.endTransmission();
}

The documentation under the link you posted says: "The I2C display is located on the I2C bus at an address of 0XC6.", not the address you have used in your code.

no the adress is 0x63 tested with i2c scanner

@marangisto  many I2C addresses are quoted like this as an 8 bit value - made up of the 7 bit address plus the data direction (read/write) bit.
0b11000110 (0xC6) removing the least significant bit is 0b1100011 (0x63). There is also 10 bit addressing (http://www.i2c-bus.org/addressing/10-bit-addressing/), but that only confuses things even further...

You can't begin writing unless you first initialize it like with Serial.begin
In this case you don't show Wire.beginTransmission.
Perhaps it is in the code you didn't show us, but it is required.


text:
Problems with transmission between ATtiny85 and Arduino Uno with 433MHz RF modules and Manchester
I am trying to transmit from an ATtiny85 running at 16MHz internal clock to an Arduino Uno with the Manchester Library.
The problem is that the Arduino is not receiving any data.
I have hooked an oscilloscope to the ATAD/DATA pin of the transmitter, and I can see data being transmitted. I have also done the same thing on the DATA pin of the receiver, and it shows data being received. But the Arduino Uno is not detecting anything.
I have tried having an Arduino Uno sending data to itself, which does work, but the data gets dropped very often.
Here is the source code of the transmitter:
#include <Manchester.h>

#define TX_PIN 3  //pin where your transmitter is connected

uint16_t transmit_data = 2761;

void setup() {
  pinMode(1,OUTPUT);
 man.setupTransmit(TX_PIN, MAN_1200);
}

void loop() {
  digitalWrite(1,HIGH);
  man.transmit(transmit_data);
  delay(200);
  digitalWrite(1,LOW);
  delay(200);
}

And this is the code on the receiver:
#include "Manchester.h"

#define RX_PIN 4
#define BUFFER_SIZE 22

uint8_t buffer[BUFFER_SIZE];

void setup() {
  Serial.begin(9600);
  man.setupReceive(RX_PIN, MAN_1200);
  man.beginReceiveArray(BUFFER_SIZE, buffer);
}

void loop() {
  if (man.receiveComplete()) {
    uint8_t receivedSize = 0;
    // do something with the data in 'buffer' here before you start receiving to the same buffer again
    receivedSize = buffer[0];
    for(uint8_t i=1; i<receivedSize; i++)
      Serial.write(buffer[i]);
    Serial.println();
    man.beginReceiveArray(BUFFER_SIZE, buffer);
  }
}

This is the code I used to test with only the Arduino Uno:
#include <Manchester.h>

#define RX_PIN 7
#define TX_PIN 8  //pin where your transmitter is connected

uint16_t transmit_data = 2761;
int lastTransmit = 0;

void setup() {
  Serial.begin(9600);
  man.setupReceive(RX_PIN, MAN_1200);
  man.setupTransmit(TX_PIN, MAN_1200);
  man.beginReceive();
}

void loop() {
  if (millis() - lastTransmit > 200) {
    man.transmit(transmit_data);
    lastTransmit = millis();
  }

  if (man.receiveComplete()) {
    uint16_t m = man.getMessage();
    Serial.println(m);
    man.beginReceive();
    //start listening for next message right after you retrieve the message
  }
}

You set receivedSize to zero at instantiation, then load it with buffer[0], which also appears to be zero.  You should check that value to ensure it's correct and that it's at least 2 as 1 isn't less than. Otherwise when you go into the loop, i is 1 and receivedSize is zero (i is > receivedSize.)  So it fails to enter the loop, so no write.
uint8_t receivedSize = 0;

receivedSize = buffer[0];
for (uint8_t i = 1; i < receivedSize; i++)
     Serial.write(buffer[i]);

There may also be a logic problem. If you receive one byte, the receivedSize will be 1 and it still won't print.  Keep in mind that the array goes from 0 to limit and your 'data' lives starting in buffer[1].  Meaning if 6 characters are in the buffer only 5 (1 thru 5) will print. It may be much more clear to add the index at the position 'buffer[i + 1]' then the i can run it's normal 0 to n.

Yeah, I will try modifying the code. The code I used is just sample code. Probably just faulty connections or RF modules


text:
TimerOne Hanging
For the following program. Compiles and runs. I start the Serial Monitor (shown following code) and it asks me to input the Blink Rate. This runs in setup. Then it enters the loop and prints to the serial monitor the rate and starts the >Serial.println("the bl    And it hangs! I can exit the serial monitor and restart it and it does the same thing. So the program/sketch seems to be running fine but somehow the serial communication hangs?  Others have tried it and it works for them?  Using an Alien Aurora R5 running Win10 64bit Home.  Added some delays after another person tried it and it hung on them before adding delay and then ran for them.  They are using Win10 32bit and when tried on their 64bit laptop it hangs.
//Testing the Serial Port

#include <TimerOne.h>

int state = 0;
int value;
long int newtime;

void setup() {
  Serial.begin(9600);
  pinMode(13, OUTPUT);
  digitalWrite(13, state);
  Serial.println("Enter the Blink Rate: ");
}

void loop() {
  if (Serial.available()) {
    value = Serial.parseInt();
    delay(100);
    Serial.print("the blink rate is: ");
    Serial.println(value);
    Serial.println("Enter a new blink rate: ");
    newtime = value * 1000000;
    Timer1.initialize(newtime);
    Timer1.attachInterrupt(blinkme);
    delay(500);
  }
}

void blinkme() {
  state = !state;
  digitalWrite(13, state);
  delay(100);
}

Why delay(100); when you already initialize the Timer1 with the right blink time? Delaying in ISRs should be avoided at all costs.

Delays were added after in attempt to get it to run.  Was advised by another that it hung for them UNTIL they added the delay at end of loop function.

Never ever use a delay in an interrupt

It hangs without any interrupts.

Please change int state = 0; to volatile int state = 0; and remove all delay() calls. Before Timer1.initialize(...), add the line Serial.flush();. Does it work once now but not repeatedly?

If it is the case then the ISR crashes the board. digitalWrite() may disable interrupts.. better use direct port manipulation. Exchange the digitalWrite call with DDRB ^= B00100000;

Did the first comment and got a couple more lines in the monitor before it returned a 0 and hung.  DDRB ^= B00100000;  compiled but did nothing different.

Try using unsigned long as the type for both value and newtime (instead of int and long int). And use 1000000UL instead of 1000000.

Do you have anything connected to D13 that could cause a momentary fault like a short-circuit? If you have an external LED connected you also have the current limiting resistor right?

No change...  still hangs

I have tried it with both an LED and current limiting resistor on D13 and with nothing attached to D13 other than the onboard internal LED.

I have tried multiple versions of UNO and MEGA boards.  I don't think it is board related.  I have also tried a new TimerOne library from GitHub with the same results.

test value for 0 and don't set the timer with 0

Use 1000000L instead of 1000000

0 hangs after the 3rd line on the monitor so it really doesn't like 0 for an input.

No Joy w/ 1000000L

If you enter 1 in Serial Monitor and you have line ends selected, the Serial Monitor sends "1\r\n". parseInt() reads 1 and in next loop \r or \n is available and parses as 0. You then set the Timer to 0. The Serial can't finish printing because the Timer fires without a pause.

BINGO!  Changed the monitor to no line end and now works fine!  Thanks!

@SamR, accept he answer to mark it solved

@SamR, Changed the monitor to no line end ... that is not the way to correct the problem ... instead, insert code that prevents newtime from being zero

Change io 13 to (suggestion) 10 and attach led + 1k resister to io 10.
13 seems to be in use. Also No line end in Serial.

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


text:
How to utilize SPI Serial bus on a ATSAMD21G18?
Like the title suggests, I have a ATSAMD21G18 microcontroller that I want to interface with a LTC6803-4 chip, but I'm not sure how to set up the SPI bus on the microcontroller, and the datasheet proved too confusing for me to understand.

SPI.begin()...? Or aren't you using the Arduino API?

i'm not even that far, I dont know how to physically connect them, not sure what pins to use on the ATSAMD21G18

You connect it to the PAD[x] pins for the SPI port you want to use.

TBH it looks overly complicated on that chip. I'd choose a simpler chip. Any specific reason why you want to use that particular chip?

I wanted to integrate BLE, 3 LTC6803-4 ics, a Real time clock and a microsd reader/writer onto the same board, and i figured i would base it off the Adafruit Feather M0 Bluefruit BLE, but i'm open to recommendations for easier micro controllers

Use the SPI API provided by Arduino (https://www.arduino.cc/en/Tutorial/SPITransaction) and the command format that the chip wants you to use based on the datasheet. Here's a bit of example code for SPI transaction. Though untested, it's what I understood from reading the datasheet. Written for an Adafruit Feather M0 express (uses SAMD21G18 MCU). For pinout see https://learn.adafruit.com/adafruit-feather-m0-express-designed-for-circuit-python-circuitpython/adafruit2-pinouts#logic-pins-2-8.
Also note that Analog Devices does provide Arduino-Code for similiar devices like LTC6803-2 but not for the -4. Still, you can look how they implemented a driver. See here
#include <Arduino.h>
#include <SPI.h>

/* pin setup */
int chip_select_pin = PIN_A2;
/* SPI pins labeled "SCK" "MO" "MI" on the Adafruit Feather M0 express board
 * are used implicitly.
 * PIN_SPI_MISO (22),  PIN_SPI_MOSI(23), PIN_SPI_SCK(24),
 * */

#define LTC6803_4_MAX_SCLK_FREQ 1000000
#define LTC6803_4_USED_SCLK_FREQ (LTC6803_4_MAX_SCLK_FREQ/2)

SPISettings settings(LTC6803_4_USED_SCLK_FREQ, BitOrder::MSBFIRST, SPI_MODE3);

void start_voltage_adc_conversion(){
    SPI.beginTransaction(settings);
    digitalWrite(chip_select_pin, LOW);
    //STCVAD
    //Start Cell Voltage ADC Conversions and Poll Status, with Discharge Permitted
    uint8_t tranfer_buf[2] = {
            0x10, //CODE
            0xB0 //PEC
    };
    SPI.transfer(tranfer_buf, 2);
    //wait for conversion, just a static time. at least 12 milliseconds.
    delay(20);
    digitalWrite(chip_select_pin, HIGH);
    SPI.endTransaction();
}

void read_voltages_1_to_4(){
    //trigger voltage conversion
    start_voltage_adc_conversion();

    SPI.beginTransaction(settings);
    digitalWrite(chip_select_pin, LOW);
    //transfer buffer must have 2 bytes for command
    //and 6 bytes for response (four 12-bit ADC values encoded in 6 registers CVR00..CVR05)
    //plus 1 byte for PEC from chip
    //Read Cell Voltages 1-4, "RDCVA", page 22
    uint8_t tranfer_buf[2 + 6 + 1] = {
            0x06, //CODE
            0xD2 //PEC
    };
    SPI.transfer(tranfer_buf, 9);
    digitalWrite(chip_select_pin, HIGH);
    SPI.endTransaction();

    //recover 12-bit ADC value from C1V[0]..C1V[11] from register values CVR00 and CVR01
    //see datasheet page 24
    uint16_t adc_cell_1 = tranfer_buf[2] | ((tranfer_buf[3] & 0B1111) << 8);
    //adc value to voltage conversion according to page 15
    float voltage_cell_1_millivolt = ((int)adc_cell_1 - 512) * 1.5f ;
    Serial.print("Cell voltage 1: ");
    //print with 5 digits accuracy
    Serial.print(voltage_cell_1_millivolt, 5);
    Serial.println(" mV");
}

void setup() {
    Serial.begin(115200);
    pinMode(chip_select_pin, OUTPUT);
    SPI.begin();
}

void loop() {
    read_voltages_1_to_4();
    delay(2000);
}


text:
How to toggle LED and motor on button press?
we want to have a LED turn on with the press of a button, and become brigther and brighter as times go by (whithin  a defined time frame), and when it reaches maximum brightness to turn off for a couple of seconds and then start again. in addition to that, we are trying to add a motor that will start spinning 720 degrees when the button has been pressed.
Our main problem is the fact that when we let go of the button the led turns off. How do we set the button so that when it is pressed once it turns everything on, and the led runs in a loop, but the motor doesn't; and when we press it again the whole led turns off completely and the motor runs 720 degrees in the opposite spinning direction than the previous.
Here is what we have managed so far (we didn't get to introduce the motor yet as we got stuck along the way):
const int switchPin = 11;
const int motorPin = 6;
int led = 9;
int switchState = LOW;
int previous = LOW;
int i = 0;
int fadeAmount = 5;

void setup()
{
  pinMode(led, OUTPUT);
  pinMode(motorPin, OUTPUT);
  pinMode(switchPin, INPUT);
}

void loop()
{
  int switchState = digitalRead(switchPin);

  for (int i = 0; i <= 255; i++)
  {
    analogWrite(led, i);
  }

  if (switchState == HIGH && previous == LOW)
  {
    if (i == 0)
    {
      digitalWrite (led, HIGH);
      i = i + fadeAmount;
      delay(1000);
    }

    analogWrite(led, i);

    for (int i = 255; i <= 255; i--)
    {
      digitalWrite (led, LOW);
      i = 0;
    }
  }
  else
  {
    //toggle off
    digitalWrite(led, LOW);
    i = 0;
  }
}

PS. WE are beginers. Thanks for the help and understanding!

you are getting distracted by the fading lights and by the motor .... the motor action and the fading lights action are completely separate from the button press action .... the motor and light could be triggered by a timer, by voltage level or by a number of other events ....... the lights should be controlled by a boolean variable ... name it lights_on for example ... the button should set the value of lights_on variable .... the value should be set only by the switch at the transition from button not-pressed state to button pressed state, not by the "pressed` state alone

start by writing button code that controls a single led ... button sets a variable .... LED responds to variable

Here is a program that should fade the LED as you specified. Initially the LED is off. If you press the button the LED starts fading within the time frame to its maximum. Then it switches to zero waits a couple of seconds and starts fading from new. If you press the button a second time the LED stops fading and is set to darkness. ;-) This happens emediately, but of cause, you can only see it if the LED is in the fading phase.
I used interrupts in order to have a well defined state transition I can work with.
Aquiring the button pin in the loop, would be more complex to handle. That would require a state variable and some state transition rules. And I was too lazy to work that out. If interupts can't be used for any reason, I would change the answer. (No Mum I don't want to ...)
I removed the motor pin as it makes no sense for the answer. I also think that one pin would not be enough if your motor (stepper, dc with feedback or a servo) should spin a certain amount of degrees.
I tested the program on a Arduino UNO. The button I used is of low quality so I had to debounce it.
If there is something not clear to you, please ask within a comment.
// Attache the LED to a PWM pin UNO -> 3,5,6,9,10,11
const byte ledPin       = 9;

// UNO -> only pin 2 or pin 3 are interrupt pins
// as we use pullups the button should be connected to GND
const byte interruptPin = 2;

// in milli seconds - The time the LED needs to fully light up
const int timeFrame  = 5000;

// in milli seconds
const int aCoupleOfSeconds = 2000;

const int fadeAmount =    5;

volatile boolean fadeOn = false;
volatile long debounceTime = 800;
volatile long actTime = 0;

int brightness =   0;

int stepCount = 256       / fadeAmount;
int stepDelay = timeFrame /  stepCount;

void setup()
{
  pinMode( ledPin,       OUTPUT       );
  pinMode( interruptPin, INPUT_PULLUP );

  attachInterrupt( digitalPinToInterrupt( interruptPin ), pressed, CHANGE );
}

void loop()
{
  if ( fadeOn )
  {
    delay( stepDelay );
    brightness += fadeAmount;
    if ( brightness >= 255 )
    {
       brightness = 0;
       analogWrite( ledPin, brightness );
       delay( aCoupleOfSeconds );
    }
    analogWrite( ledPin, brightness );
  }
  else
  {
    brightness = 0;
    analogWrite( ledPin, brightness );
  }
}

void pressed()
{
  // the debouncing does not work perfectly

  if ( digitalRead( interruptPin ) == LOW )
  {
    if ( millis() - actTime > debounceTime )
    {
      fadeOn = !fadeOn;
    }
  }
  else
  {
    actTime = millis();
  }
}

"Our main problem is the fact that when we let go of the button the led turns off"

@Juraj Ahhhh, noo, I completely misread the question. Thank you for giving me the hint.

just change a boolean when button is pressed and from there build the code... if(switchstate == HIGH){bool1 = 1;} if(bool1 == 1){...}

@Hamed I have to synchronize the button if it is pressed longer. The OP does not want to hold the button. They press the button than the fading starts, if the LED is complete on, it should be switched off, waits a while and start again fading. If I press the button a second time I switch the LED and fading off. Just holding a boolean state would toggle if I press the button for a longer time. I plan to use interrupts.

millis() in cli()? it is incremented by a timer interrupt

@Juraj I' didn't really thought about that, but my prog. works fine. Perhaps it works because one can read the actual time when entering the ISR (cli block) but the time is not increased while the execution is in the ISR. (and that's not for very long). But because cli and sei don't have any impact of my program I can safely removed them to make it simpler. Thank you for the hint.

Have a look at some code inside the forum from marcello.romani. He posted it on jan 1st, 2013.
  The topic on subject is called : "button pressed more than 2 seconds do somethingelse"
  Marcello's code is so KISS (Keep It Simple Stupid) and efficient that it deserves a Nobel prize.
  The goals is to handle the different signals that come from a button or switch action :
  keyPress, keyRelease, longKeyPress etc.. as you can find in the original sketch.

The OP has no problem with longer or shorter key presses. She only wants to toggle a state by pressing the key. So the code might be good, but it does not answer the question. BTW: that code is for demonstration, and it is not KISS. "Do only the things that must be done". But for demonstration he uses methods with only one statement in it. I had to follow the execution path to find out what happens. No, that is not KISS, although IMHO it is perfect for demonstration purposes as he gives us the places where we can  extend it.


text:
Arduino Modbus RTU VFD control
I need help with this code:
/**
*  Modbus master example 1:
*  The purpose of this example is to query an array of data
*  from an external Modbus slave device.
*  The link media can be USB or RS232.
*
*  Recommended Modbus slave:
*  diagslave http://www.modbusdriver.com/diagslave.html
*
*  In a Linux box, run
*  "./diagslave /dev/ttyUSB0 -b 19200 -d 8 -s 1 -p none -m rtu -a 1"
* This is:
* serial port /dev/ttyUSB0 at 19200 baud 8N1
* RTU mode and address @1
*/

#include <ModbusRtu.h>

// data array for modbus network sharing
uint16_t au16data[16];
uint8_t u8state;

/**
*  Modbus object declaration
*  u8id : node id = 0 for master, = 1..247 for slave
*  u8serno : serial port (use 0 for Serial)
*  u8txenpin : 0 for RS-232 and USB-FTDI
*               or any pin number > 1 for RS-485
*/
Modbus master(0,0,2); // this is master and RS-232 or USB-FTDI, PIN 9 PARA INDICAR QUE TRASMITO

/**
* This is an structe which contains a query to an slave device
*/
modbus_t telegram;

unsigned long u32wait;

void setup() {
 master.begin( 9600 ); // baud-rate at 19200
 master.setTimeOut( 2000 ); // if there is no answer in 2000 ms, roll over
 u32wait = millis() + 1000;
 u8state = 0;
}

void loop() {
 switch( u8state ) {
 case 0:
   if (millis() > u32wait) u8state++; // wait state
   break;
 case 1:
   telegram.u8id = 1; // slave address
   telegram.u8fct = 5; // function code (this one is registers read)
   telegram.u16RegAdd = 0; // start address in slave
   telegram.u16CoilsNo = 2; // number of elements (coils or registers) to read
   //telegram.au16reg = au16data; // pointer to a memory array in the Arduino

   // PARA EL VARIADOR OMRON MX1: MODBUS RTU 01 05 00 00 FF 00 -> START
   // 01 -> SLAVE (VFD OMRON)
   // 05 -> WRITE COIL
   //  00 00 -> ADDRESS COIL
   // FF 00 -> VALUES TO WRITE IN COIL FOR RUN

   telegram.au16reg[0] = 0;
   telegram.au16reg[1] = 0;
   telegram.au16reg[2] = 0;
   telegram.au16reg[3] = 0;
   telegram.au16reg[4] = 0;
   telegram.au16reg[5] = 0;
   telegram.au16reg[6] = 0;
   telegram.au16reg[7] = 0;

   telegram.au16reg[8] = 1;
   telegram.au16reg[9] = 1;
   telegram.au16reg[10] = 1;
   telegram.au16reg[11] = 1;
   telegram.au16reg[12] = 1;
   telegram.au16reg[13] = 1;
   telegram.au16reg[14] = 1;
   telegram.au16reg[15] = 1;

   master.query( telegram ); // send query (only once)
   delay(3500);

   telegram.u8id = 1; // slave address
   telegram.u8fct = 6; // function code (this one is registers read)
   telegram.u16RegAdd = 1; // start address in slave
   telegram.u16CoilsNo = 4; // number of elements (coils or registers) to read
   //telegram.au16reg = au16data; // pointer to a memory array in the Arduino
   //telegram.au16reg = 0000000111110100;

   // PARA EL VARIADOR OMRON MX1: MODBUS RTU 01 06 00 01 01 F4 -> CHANGE FQ
   // 01 -> SLAVE (VFD OMRON)
   // 06 -> WRITE IN REGISTE
   // 00 01 -> REGISTER ADDRESS
   // 01 F4 -> VALUE TO WRITE IN THE REGISTER TO CHANGE THE MOTOR FREQUENCY

   telegram.au16reg[0] = 0;
   telegram.au16reg[1] = 0;
   telegram.au16reg[2] = 0;
   telegram.au16reg[3] = 0;
   telegram.au16reg[4] = 0;
   telegram.au16reg[5] = 0;
   telegram.au16reg[6] = 0;
   telegram.au16reg[7] = 1;

   telegram.au16reg[8] = 1;
   telegram.au16reg[9] = 1;
   telegram.au16reg[10] = 1;
   telegram.au16reg[11] = 1;
   telegram.au16reg[12] = 0;
   telegram.au16reg[13] = 1;
   telegram.au16reg[14] = 0;
   telegram.au16reg[15] = 0;

   master.query( telegram ); // send query (only once)
   delay(3500);
   telegram.u8id = 1; // slave address
   telegram.u8fct = 5; // function code (this one is registers read)
   telegram.u16RegAdd = 1; // start address in slave
   telegram.u16CoilsNo = 2; // number of elements (coils or registers) to read
   //telegram.au16reg = au16data; // pointer to a memory array in the Arduino

   // PARA EL VARIADOR OMRON MX1: MODBUS RTU 01 05 00 00 00 00 -> STOP
   // 01 -> ESCLAVO (VARIADOR OMRON)
   // 05 -> ESCRIBIR EN UNA BOBINA
   // 00 00 -> DIRECCION DE LA BOBINA
   // 00 00 -> VALOR A ESCRIBIR EN LA BOBINA PARA STOP

   telegram.au16reg[0] = 0;
   telegram.au16reg[1] = 0;
   telegram.au16reg[2] = 0;
   telegram.au16reg[3] = 0;
   telegram.au16reg[4] = 0;
   telegram.au16reg[5] = 0;
   telegram.au16reg[6] = 0;
   telegram.au16reg[7] = 0;
   telegram.au16reg[8] = 0;
   telegram.au16reg[9] = 0;
   telegram.au16reg[10] = 0;
   telegram.au16reg[11] = 0;
   telegram.au16reg[12] = 0;
   telegram.au16reg[13] = 0;
   telegram.au16reg[14] = 0;
   telegram.au16reg[15] = 0;
   master.query( telegram ); // send query (only once)
   delay(3500);
   u8state++;
   break;
 case 2:
   master.poll(); // check incoming messages
   if (master.getState() == COM_IDLE) {
     u8state = 0;
     u32wait = millis() + 100;
   }
   break;
 }
}

I've managed to send RUN command to VFD but i can't (so far) send the change frequency command "01 06 00 01 01 F4" + CRC check.
When I connect logic analyzer with modbus rtu decoder, it shows "Device ID:'1' Function Write single coil ('5') Addr: '0' value: '65280' Chksum: '14988'.
The problem is that it pass only 1 telegram (array of packets) for command "RUN" but no the two others. Any help will be appreciated.
This is the link for VFD Omron MX: https://industrial.omron.us/en/media/I570-E2-02B_3G3MX2_UsersManual_tcm849-112721.pdf
TIA

first you should update the comments and remove unused settings like the count fields for request with one value (function 5 and 6). you do not set the value into au16reg like you have it in PARA EL VARIADOR OMRON MX comments

In this sketch, i don't know how this telegram with the vfd commands made of. For example:telegram.u8id = 0x01; // slave address
telegram.u8fct = 0x06; // function code (this one is registers read)
telegram.u16RegAdd = 0x01; // start address in slave
telegram.u16CoilsNo = 0x04; // number of elements (coils or registers) to read
//telegram.au16reg = au16data; // pointer to a memory array in the Arduino
//telegram.au16reg = 0000000111110100; What those 0's and 1's do?

https://en.wikipedia.org/wiki/Modbus#Supported_function_codes

au16reg are the data to be send. ignore the binary format from the example, send data required by the documentation

After clean those telegram.au16reg you said, i 've managed to pass the second and 3rd packet. How can i pass the appropriate value to the frequency? For example: How can i pass the value 40Hz to it?Any way you saved me a lot of searching time! Thank you!

set the value to telegram.au16reg[0]

How can i change the commands with 3 toggle switches. I wrote this code but it doesn't work. https://pastebin.com/UA0WFgQ7

You should update the comments and remove unused settings like the count fields for request with one value (function 5 and 6).
au16reg are the data to be send. ignore the binary format from the example.
To send a value of the coil or register set the value to telegram.au16reg[0].
For the Modbus message protocol see for example the Wikipedia article.

When i call the last code i gave, it works well and i get the correct message. When i call this code with  "master.query( telegram[0] ); // send query (only once)" call, the program doesn't work. What i've missed? Is it a good way to check button statements and send modbus rtu commands to vfd?

I do not see a problem with sending Modbus request triggered by button, but your code is still a mess. you can't do it if you can't understand and write code.

It looks like that i have a conflict when i call this telegram command then. Although i've test many modbus libraries but none works well. Also i can't achieve good timing with the modbus poll software and i got time error reports. Is it possible to help me with a code snippet to catch the missing point?