text:
buzzwire game in arduino
I'm tring to make buzzwire game in arduino and this is what I have from now on.
#include <TM1637.h> // include display library
#include <pitches.h> // include pitches

TM1637 *_display = new TM1637(12, 13); // create display object, 12 = CLK (clock), 13 = D10 (data)

// music
int songState = 0;

int melody[] = {
 NOTE_F4, NOTE_E4, NOTE_D4, NOTE_CS4,
 NOTE_C4, NOTE_B3, NOTE_AS3, NOTE_A3,
 NOTE_G3, NOTE_A3, NOTE_AS3, NOTE_A3,
 NOTE_G3, NOTE_C4, 0,

 NOTE_C4, NOTE_A3, NOTE_A3, NOTE_A3,
 NOTE_GS3, NOTE_A3, NOTE_F4, NOTE_C4,
 NOTE_C4, NOTE_A3, NOTE_AS3, NOTE_AS3,
 NOTE_AS3, NOTE_C4, NOTE_D4, 0,

 NOTE_AS3, NOTE_G3, NOTE_G3, NOTE_G3,
 NOTE_FS3, NOTE_G3, NOTE_E4, NOTE_D4,
 NOTE_D4, NOTE_AS3, NOTE_A3, NOTE_A3,
 NOTE_A3, NOTE_AS3, NOTE_C4, 0,

 NOTE_C4, NOTE_A3, NOTE_A3, NOTE_A3,
 NOTE_GS3, NOTE_A3, NOTE_A4, NOTE_F4,
 NOTE_F4, NOTE_C4, NOTE_B3, NOTE_G4,
 NOTE_G4, NOTE_G4, NOTE_G4, 0,

 NOTE_G4, NOTE_E4, NOTE_G4, NOTE_G4,
 NOTE_FS4, NOTE_G4, NOTE_D4, NOTE_G4,
 NOTE_G4, NOTE_FS4, NOTE_G4, NOTE_C4,
 NOTE_B3, NOTE_C4, NOTE_B3, NOTE_C4, 0
};

int tempo[] = {
 8, 16, 8, 16,
 8, 16, 8, 16,
 16, 16, 16, 8,
 16, 8, 3,

 12, 16, 16, 16,
 8, 16, 8, 16,
 8, 16, 8, 16,
 8, 16, 4, 12,

 12, 16, 16, 16,
 8, 16, 8, 16,
 8, 16, 8, 16,
 8, 16, 4, 12,

 12, 16, 16, 16,
 8, 16, 8, 16,
 8, 16, 8, 16,
 8, 16, 4, 16,

 12, 17, 17, 17,
 8, 12, 17, 17,
 17, 8, 16, 8,
 16, 8, 16, 8, 1
};

// non blocking setup
// free play
unsigned long previousMillis1 = 0; // time words last changed
const long interval1 = 1500; // interval between changing

// music
unsigned long previousMillis2 = 0; // time last changed
const long interval2 = 100; // interval between notes

int displayStatus = 0; // keep track of what's displayed
int mode = 0; // keep track of game mode -- change to 0 or 1 for different modes

bool countdown = false;

unsigned long previousMillis3 = 0; // time last changed
const long interval3 = 1000; // interval between countdown
int count = 20; // challenge mode timer

void setup() {
 // put your setup code here, to run once:
 pinMode(9, INPUT); // setup circuit
 pinMode(10, OUTPUT); // setup buzzer 1
 pinMode(11, OUTPUT); // setup buzzer 2
 pinMode(2, INPUT); // setup button

 _display->set(5); // set brightness
 _display->point(false); // remove colon
 _display->init(); // start display
}

void loop(void) {
 // put your main code here, to run repeatedly:
 int conductVal = analogRead(9);

 Serial.print("Conduction sensor reads");
 Serial.println(conductVal);

 if(conductVal>410){
  //digitalWrite(10,HIGH);
  tone(11,550,400);
  tone(10,0,400);
  delay(5000);
  countdown=false;
 }
 if(mode == 0) {
   // free play
 toggleFreePlay();

 }
 else {
 // challenge mode
 if(digitalRead(2) == HIGH) {
 delay(25);
 if(digitalRead(2) == HIGH) {
 countdown = true; // stop the countdown
 }
 else {
 countdown = false; // stop the countdown
 }
 }
 if(countdown) {
 showCountdown(); // advance countdown
 }
 }
 if(digitalRead(10) == HIGH) {
 delay(25);
 if(digitalRead(10) == HIGH) {
 while(digitalRead(10) == HIGH) {
 buzz(11, NOTE_B0, 1000/24);
 }
 }
 }
 else
 sing();
}

void showCountdown() {
 // countdown the time remaining
 unsigned long currentMillis = millis(); // current time
 if (currentMillis - previousMillis3 >= interval3) {
 previousMillis3 = currentMillis;
 --count;
 showNumber(count);
 if(count == 0) {
 // game over
 countdown = false;
 count = 20;
 // reset countdown
 // buzz 3 times
 buzz(11, NOTE_B0, 1000/24);
 delay(100);
 buzz(11, NOTE_B0, 1000/24);
 delay(100);
 buzz(11, NOTE_B0, 1000/24);
 }
 }
}

void showNumber(int number) {
 // show numbers (maximum 99) on display
 _display->display(0, 25); // write - to segment 1
 _display->display(3, 25); // write - to segment 4

 // write number to middle of display

  if(number == 10)
  {
     _display->display(1,1);
   _display->display(2,0);
  }
  else if(number > 9)
  {
   _display->display(1,1);
   int newVal = number - 10;
   _display->display(2, newVal);
  }
  else
  {
     _display->display(1,0);
   _display->display(2,number);
  }
}

void toggleFreePlay() {
 // scroll between words without blocking
 unsigned long currentMillis = millis(); // current time
 if (currentMillis - previousMillis1 >= interval1) {
 previousMillis1 = currentMillis;
 if(displayStatus == 1)
 showPlay();
 else
 showFree();
 }
}

void showPlay() {
 // write "PLAY" to the display
 _display->display(0, 21); // write P to segment 1
 _display->display(1, 18); // write L to segment 2
 _display->display(2, 10); // write A to segment 3
 _display->display(3, 4); // write Y to segment 4
 displayStatus = 2;
}

void showFree() {
 // write "Free" to the display
 _display->display(0, 15); // write F to segment 1
 _display->display(1, 23); // write r to segment 2
 _display->display(2, 14); // write E to segment 3
 _display->display(3, 14); // write E to segment 4
 displayStatus = 1;
}

void buzz(int targetPin, long frequency, long length) {
 /* Buzzer example function by Rob Faludi
 http://www.faludi.com
 https://gist.github.com/AnthonyDiGirolamo/1405180
 */
 long delayValue = 1000000/frequency/2; // calculate the delay value between transitions
 //// 1 second's worth of microseconds, divided by the frequency, then split in half since
 //// there are two phases to each cycle
 long numCycles = frequency * length/ 1000; // calculate the number of cycles for proper timing
 //// multiply frequency, which is really cycles per second, by the number of seconds to
 //// get the total number of cycles to produce
 for (long i=0; i < numCycles; i++){ // for the calculated length of time...
 digitalWrite(targetPin,HIGH); // write the buzzer pin high to push out the diaphragm
 delayMicroseconds(delayValue); // wait for the calculated delay value
 digitalWrite(targetPin,LOW); // write the buzzer pin low to pull back the diaphragm
 delayMicroseconds(delayValue); // wait again for the calculated delay value
 }
}

void sing() {
 // play the song in a non blocking way
 unsigned long currentMillis = millis();

 if (currentMillis - previousMillis2 >= interval2) {
 previousMillis2 = currentMillis;
 int noteDuration = 1000 / tempo[songState];
 buzz(10, melody[songState], noteDuration);
 int pauseBetweenNotes = noteDuration;
 delay(pauseBetweenNotes);

 // stop the tone playing:
 buzz(10, 0, noteDuration);

 ++songState;
 // start song again if finished
 if(songState > 79) {
 songState = 14; // skip intro
 }
 }
}

First I want to stop continuous buzzing during the game, and I want to make buzzer react when the handle touches the course. Plus, I also want to know how can I change the mode in arduino( and breadboard).

what is the question?

First align your code (make the { and } nicely arranged, to easier read your sketch.

change the mode ... what is mode?


text:
AC Voltage Sensing using Arduino Uno
Is it possible to sense AC Voltage using analog input for Arduino Uno or can it only read DC?
I mean I've tried connecting an AC voltage source to analog and I'm reading some numbers. However, I don't know if these numbers are actually AC voltage values or something else.
Ultimately I’m trying to find the avg voltage value for a given time duration. I know that analogRead ( ) gives ADC values. However, in my block of code, I have the conversion ratio of 1023/5 to get a good estimate of the voltage. However, I’m not too sure if Arduino analog sensing is suited for AC voltage? I’m using it to sense voltages generated by piezoelectric PVDF film and the frequency is pretty high. All I want is to use avg. voltage value to calculate electrical energy produced by the PVDF film.

the Arduino can read voltage at its analog input pin ... it takes time to convert the voltage to a numetic value ... if the voltage changes by a large amount during the conversion, then the result will not be accurate ... it can also change do quickly, that the change will not be detected

what is the frequency of the signal that you are trying to digitize?

Do you want a RMS value or to record the values of the waveform (eg. peak)?

@jsotola: Re “if the voltage changes by a large amount during the conversion, then the result will not be accurate”: That's not quite true. The ADC uses a sample-and-hold front-end which is actually pretty fast. Once sampled, the input voltage can change without disturbing the ongoing conversion. You get an accurate reading of the input voltage at the time of sampling. Obviously, a rapidly changing signal rises the issues of Nyquist frequency and aliasing, but these are completely unrelated to conversion accuracy.

You have to be a lot more specif if you want any kind of useful answer. What do you mean by the frequency being “pretty high”? What are the typical amplitude and DC offset? Re “I’m trying to find the avg voltage”: the easiest way to get the average voltage is to put a low-pass filter in front of the ADC.

The AC voltage that you are trying to measure is about 50/60Hz depending on where you live. And the maximum effective sampling rate for a regular Arduino ADC is 9615Hz. This means you're not going to experience any aliasing as the sampling rate is well above the 2 * Signal Frequency.
The values that are coming out of analogRead() are raw ADC values which you need to do, further calculation on if you want to have a correct voltage reading.

You have to set the ADC to auto-trigger if you want 9,615 Hz sampling rate. With analogRead() you get at most 8,929 Hz (112 µs/sample).

Ultimately I’m trying to find the avg voltage value for a given time duration. I know that analogRead ( ) gives ADC values. However, in my block of code, I have the conversion ratio of 1023/5 to get a good estimate of the voltage. However, I’m not too sure if Arduino analog sensing is suited for AC voltage? I’m using it to sense voltages generated by piezoelectric PVDF film and the frequency is pretty high. All I want is to use avg. voltage value to calculate electrical energy produced by the PVDF film.

so it is not mains AC with 50 Hz as the answer assumes

that is correct

source: Stack Exchange

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

sort: votes


text:
Mini ethernet shield pins don't have SI
Please somebody who had the same issue help me.
The question is how to connect this Mini Ethernet shield to an Arduino.
The main problem is the pins that my shield have or haven't; my current connections to the Arduino Mega 2560 are:

5v to 5v
GND to GND
LNT to NULL
CLK to NULL
SO  to pin50
WOL to NULL
SLK to PIN52
ST  to ????
RST to RST
CS to PIN53
Q3 to NULL
GND to NULL

But in all cases when I search the connection diagram every picture has SI, but I don't have it (I tried to connect ST to PIN51 without luck).
What kind of Ethernet shield is that? Or how to connect those pins?
I hope someone can help me; thank you in advance.
/*
  DHCP-based IP printer

  This sketch uses the DHCP extensions to the Ethernet library
  to get an IP address via DHCP and print the address obtained.
  using an Arduino Wiznet Ethernet shield.

  Circuit:
   Ethernet shield attached to pins 10, 11, 12, 13

  created 12 April 2011
  modified 9 Apr 2012
  by Tom Igoe
  modified 02 Sept 2015
  by Arturo Guadalupi

 */

#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = {
  0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02
};

void setup() {
  // You can use Ethernet.init(pin) to configure the CS pin
   // Ethernet.init(53);  // Most Arduino shields
  //Ethernet.init(5);   // MKR ETH shield
  //Ethernet.init(0);   // Teensy 2.0
  //Ethernet.init(20);  // Teensy++ 2.0
  //Ethernet.init(15);  // ESP8266 with Adafruit Featherwing Ethernet
  //Ethernet.init(33);  // ESP32 with Adafruit Featherwing Ethernet

  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // start the Ethernet connection:
  Serial.println("Initialize Ethernet with DHCP:");
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    if (Ethernet.hardwareStatus() == EthernetNoHardware) {
      Serial.println("Ethernet shield was not found.  Sorry, can't run without hardware. :(");
    } else if (Ethernet.linkStatus() == LinkOFF) {
      Serial.println("Ethernet cable is not connected.");
    }
    // no point in carrying on, so do nothing forevermore:
    while (true) {
      delay(1);
    }
  }
  // print your local IP address:
  Serial.print("My IP address: ");
  Serial.println(Ethernet.localIP());
}

void loop() {
  switch (Ethernet.maintain()) {
    case 1:
      //renewed fail
      Serial.println("Error: renewed fail");
      break;

    case 2:
      //renewed success
      Serial.println("Renewed success");
      //print your local IP address:
      Serial.print("My IP address: ");
      Serial.println(Ethernet.localIP());
      break;

    case 3:
      //rebind fail
      Serial.println("Error: rebind fail");
      break;

    case 4:
      //rebind success
      Serial.println("Rebind success");
      //print your local IP address:
      Serial.print("My IP address: ");
      Serial.println(Ethernet.localIP());
      break;

    default:
      //nothing happened
      break;
  }
}

And result is :

16:41:14.242 -> Initialize Ethernet with DHCP:
16:41:14.804 ->    Failed to configure Ethernet using DHCP
16:41:14.848 -> Ethernet    shield was not found.  Sorry, can't run
without hardware. :(

ST is SI. what is the chip? what library do you use? did you init the library for 53 as CS?

I use <SPI.h> and  <Ethernet.h>, Sketch for DHCP Client which is integrated in arduino examples. Ethernet > DHCPAddressPrinter and it shows me on serial monitor Ethernet shield was not found.  Sorry, can't run without hardware. :("

I assigned pin 53 to CS too but still nothing :(

I asked about chip . I suspect you try to use the Ethernet library with the enc28j60 chip

@Juraj Sorry for that. Yes you are right I use enc28j60 Chip.

In my question I added code and result

The "Mini Ethernet Shield" uses ENC26j60 chip. The Arduino Ethernet library is for Wiznet W5100/W5200/W5500 chips. You can't use it with ENC26j80.
With Arduino Mega I would recommend to use the UIPthernet library for ENC26j80. Other option is the EtherCard library.
The UIPEthernet library has the same API as the the Arduino Ethernet library.

I think you are right, I used wrong library and now I tested with UIPethernet.h and it works great. Thank you Juraj.

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


text:
MAX471 giving too high current readings
I want to measure current using the MAX471 sensor that outputs voltage proportional to the current (1V/A according to the datasheet). To test the module, I connected a 330 ohm resistor to the sensor and powered it from 3.3V arduino. Using ohms law, I was expecting an output voltage of around 10 mV (for ~ 10 mA) in my circuit. However, I am getting an output of around 2.17 volts which seems wrong.
Does anyone see any mistake in my circuit or how I am trying to measure the current?
Here is my circuit:

My Code:
#include <Arduino.h>

void setup()
{
  Serial.begin(115200);
}

void loop()
{
  int adc_val = analogRead(A5);
  float vol = 3.2 / 4095 * adc_val; // using a 12 bit adc

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

Where is your current shunt resistor?

@timemage inside the MAX471: "The MAX471 has an internal 35mΩ current-sense resistor and measures battery currents up to ±3A. "

@dandavis, interesting.  I've not seen that done before with these.

@dandavis it's actually an ESP32 but I only found arduino uno as the only microcontroller in the schematic software. That's why it says 12 bit ADC

That's actually a completely different beast, and make sure you compensate for YOUR ESP32's ADC's unique response curves. If you have a SMU you can easily calibrate this, but you can also do it using a reliable current source, a high-precision resistor, and a pair of off-the-shelf DMMs.

@dandavis you are right about the nonlinearity in ESP32's response so I have also compared it to ADS1115 which is 16 bit ADC. I still get around 2.2V as output. This is too high i.e. 2.2 A of current (considering 1A/V as stated in the datasheet)

the ADS1115 measures voltage, not current. 2.2 makes no sense, it should be dang close (~1%) to 0 or 3.3v. Are you really omitting the 2k output pulldown shown in the MAX471's datasheet?

It's not a bare sensor rather it's a module [like this] (https://www.aliexpress.com/item/4000045481675.html?spm=a2g0o.productlist.0.0.1c3718b2OUADuF&algo_pvid=e642e394-a894-4408-a48a-fcb926c21c51&algo_expid=e642e394-a894-4408-a48a-fcb926c21c51-0&btsid=0b0a556616139293222028857e2f2a&ws_ab_test=searchweb0_0,searchweb201602_,searchweb201603_). There is a 2k resistor which I suppose serves as a pulldown resistor for Vout.

According to the datasheet " In the MAX471, the current-gain ratio has been preset to 500µA/A so that an output resistor (ROUT) of 2kΩ yields 1V/A for a full-scale value of +3V at ±3A." So I believe I don't need to divide the Vout by anything. Whatever the Vout is it will be equal to current in the circuit. Are you also suggesting to divide by 2000 in my calculations?

Do you have the same operating circuit that is shown on page 1 of the datasheet? do you have the 2K resistor they specifically from OUT to ground? Also, it may be worth adding the 1 uF capacitor they recommend from OUT to ground too
The other thing to consider is the actual voltage over the resistor. Check an see if the voltage over the resistor is 3.3 and that there isn't a voltage drop from the chip
If the voltage is fine, there may be a problem with the chip or the arduino

I've got a few MAX471 modules and instead of current readings i get around 90% of input voltage on all of them.
With increasing load the output voltage decreases a bit and the MAX471 chip gets very hot (for example 12V 0mAh = 10V, 12V 200mAh = 9,6V).
I guess we are just "lucky" to get a bad batch or counterfeit chips...


text:
Toggling a blinking led ON & OFF
I am trying to implement a toggle switch to turn blinking ON & OFF. However, the code only turns the led ON or OFF and that too unreliably. Can you help me understand why it isn't working?
   const int redLed = 10;
const int buttonPin = 2;
unsigned long newTime;
unsigned long oldTime = 0;
byte newButtonState;
byte oldButtonState = 0;
boolean ledState = false;
boolean blinkState = false;
boolean state = LOW;

void setup() {
  pinMode(redLed, OUTPUT);
  Serial.begin(9600);
  pinMode(buttonPin, INPUT);
}

void loop() {

  newButtonState = digitalRead(buttonPin);
  delay(100);

  // check if button state has changed
  if (newButtonState != oldButtonState) {
    // if button was pushed
    if (newButtonState == HIGH) {
      // check led state
      if (ledState == false) {
        ledState = true;
        blinkState = true;
      } else {
        ledState = false;
        blinkState = false;
      }
      if (ledState == true && blinkState == true) {
        newTime = millis();
        if (newTime - oldTime >= 250) {
          state = !state;
          oldTime = newTime;
        }
        digitalWrite(redLed, state);
      }
    }
  }
  oldButtonState = newButtonState;
}

Also it is not needed to add '== true' for comparing booleans, you can remove '== true' and instead of '== false' you put ! in front of the expression.

Thanks I didn't know that. I have seen a few sketches where they have used booleans without using "==" and I wondered if it's a different notation of if statements. But what if you are evaluating two booleans at once e.g. "if (ledState == true && blinkState == true)" , can you also write them without the == signs?

Yes than you can write if (ledState && blinkState), if you want to write if (ledState == true && blinkState == false) you can write if (ledState && !blinkState)

Cool. Learnt something new. Thanks

I added an answer to show another improvement.

I don't see why you would set blinkState together with ledState. I assume, that you want the button to toggle the blinking. 1 press --> LED is blinking, another press --> LED stops blinking, ...
I suggest to restructure your code. First separate input and output, meaning button check code and LED blink code. For blinking you already have a state variable named blinkState. So in your loop() function you first write
newTime = millis();
if(blinkState && newTime - oldTime >= 250){
    ledState = !ledState;
    oldTime = newTime;
}

That will toggle ledState, whenever blinkState is set, in intervals. Now we simply digitalWrite() that value out directly after that:
digitalWrite(redLed, ledState);

Now we need to handle the button. Your button if statements seem to be good, so we only need to change, whats inside the statements. There we simply negate the blinkState variable:
if (newButtonState != oldButtonState) {
    // if button was pushed
    if (newButtonState == HIGH) {
        blinkState = !blinkState;
    }
}
oldButtonState = newButtonState;
delay(100);

With this code the LED will stop changing and keep the state, that it had, when you pressed the button. If you want the LED to turn off at that point, you shoud add ledState = false; after negating blinkState.
Note, that this code doesn't need your state variable. 2 variables are enough for this. 1 for the current led state, 1 for the blinking state.
Also note, that using delay() is not the best way to debounce a button. It is an easy way, but it might not behave exactly, like you want to. If you want better debouncing, you can use the Bounce2 library from github. If you don't want to use a library for it, you can still learn about their ways to debounce in the Readme file.

Thanks for your very clear explanation. Also the suggestion to break the code makes it easier to follow.

I will try to follow this approach but all these state variables that are interdependent are new to me and at time confusing. I have also read about the concept of state machine and I wonder if it would be easier to code in such contexts

The state variables are not interdependent. You could see both variables to be of a different kind. While ledState directly describes the current output value of the LED pin, blinkState describes an action, which is a bit more abstract. Think of setting one foot before the other, which you could call one step. By changing a fictional state variable like footstate we could change, which foot is the front one, and thus do steps. Then the action "walking" is more abstract, since it is a succession of steps. walking describes the action of successively changing the front foot.

In this case a state variable will not be particular easier to implement. To be exactly: With this code you already have a state machine (as you handle state variables and act upon them). Just not one, that can easily be extended. You can change that to the more extendible version (on the web and on this side are many tutorials about FSMs), though that would be more to make it easier to extend the functionalities. With the current scope of the code you are fine with this structure.

Note, this is not an answer, but I want to show some code examples based on the comment:
You can use as said in the comment:

Remove '== true' in a boolean condition
Replace '== false' by '!' in a boolean condition

You will get this:
  // check if button state has changed
  if (newButtonState != oldButtonState) {
    // if button was pushed
    if (newButtonState == HIGH) {
      // check led state
      if (!ledState) {
        ledState = true;
        blinkState = true;
      } else {
        ledState = false;
        blinkState = false;
      }
      if (ledState && blinkState) {
        newTime = millis();
        if (newTime - oldTime >= 250) {
          state = !state;
          oldTime = newTime;
        }
        digitalWrite(redLed, state);
      }
    }
  }
  oldButtonState = newButtonState;
}

About the following fragment:
  if (!ledState) {
    ledState = true;
    blinkState = true;
  } else {
    ledState = false;
    blinkState = false;
  }

Since you write ledState and blinkState in both clauses, and the condition is simple (so you don't need to put it in a temporary variable, you can replace this fragment by:
blinkState = !ledState;
ledState = !ledState;

Note you have to reverse the order as blinkState depends on ledState.

Your blink code is only active
if (newButtonState != oldButtonState)

so it won't blink (by itself)
To toggle blinking, just change it e.g. like this
void loop() {
  bool newButtonState = digitalRead(buttonPin);
  if (newButtonState != oldButtonState) {
    // button state has changed
    delay(5);  // debounce
    oldButtonState = newButtonState; // run only once per button push
    if (newButtonState == HIGH) {
      // toggle blink state
      blinkState = ! blinkState;
    }
  }

  if (blinkState) {
     // BlinkWithoutDelay
     unsigned long newTime = millis();
     if (newTime - oldTime >= 250) {
        state = !state;
        oldTime = newTime;
        digitalWrite(redLed, state);
     }
  } else {
     // no Blinking : just leave redLed as is
  }
}

Now please clean up the global variables: some are not required globally, some are not required at all.

You never set the pinMode of buttonPin.
Normally it defaults to INPUT if you don't manually specify anything, and I assume from your results that you don't have an external pullup or pulldown resistor.  Therefore you need to specify pinMode(buttonPin, INPUT_PULLUP); and make sure that your switch or button connects the input pin to ground when activated (which means that "active" will be LOW).
Or, if you do have an external pullup or pulldown resistor then it sounds like it may not be wired corrcetly.

There is a pull down resistor in the circuit. I have added the pinMode but it still doesn't work. I suspect it has to do with the conditional statements. I tried changing the "if ledState == true && blinkState == true" to a while and it does start blinking but then it doesn't turn off. I really want to understand what's wrong with my logic here.


text:
Is there a better way to combine if statement with an ISR?
In my sketch when an interrupt gets triggered, a state variable is toggled from high to low and vice versa. Depending upon the variable state I have an if statement in the main loop that will call alarm_On function if state is high and the else part of the conditional statement will call alarm_Off function if the interrupt is triggered a second time. Thus I want this if condition to run only when the interrupt is triggered. In all other circumstances I want to run other code but if it concerns the same components e.g. the leds, the other code doesn't execute. If it's not a common component then it works fine. How can I overcome this "common component" issue?
 // Analog Input devices
# define humiditySensor A5

// Alarm input
# define alarmButton 2 // Pushbutton

// Output Devices
# define redLed 10
# define yellowLed 11
# define greenLed 12
# define waterPump 9 // LED on relay
# define spk 5

// Variables
volatile byte alarm = LOW;

void setup() {
  pinMode (alarmButton, INPUT);
  pinMode (redLed, OUTPUT);
  pinMode (yellowLed, OUTPUT);
  pinMode (greenLed, OUTPUT);
  pinMode (waterPump, OUTPUT);
  attachInterrupt(digitalPinToInterrupt(alarmButton), ISR_Alarm, RISING);
  Serial.begin(9600);
}

void loop() {
  if (alarm == 1) {
    alarm_On();
  } else if (alarm == 0) {
    alarm_Off();
  }
  int humVal = analogRead(humiditySensor);
  Serial.println(humVal);
  if (humVal >= 500) {
    digitalWrite(redLed, HIGH);
  } else {
    digitalWrite(redLed, LOW);
  }
} // void loop

void ISR_Alarm () {
  alarm = !alarm;  // toggle alarm function if pushed more than once
}

void alarm_On() {
  tone (spk, 100);
  digitalWrite(waterPump, HIGH);
  static byte ledState = LOW;
  static unsigned long oldTime = 0;
  if (millis() - oldTime >= 250) { // loop to blink leds in emergency
    oldTime = millis();
    if (ledState == LOW) {
      digitalWrite(redLed, HIGH);
      digitalWrite(yellowLed, HIGH);
      digitalWrite(greenLed, HIGH);
      ledState = HIGH;
    } else {
      digitalWrite(redLed, LOW);
      digitalWrite(yellowLed, LOW);
      digitalWrite(greenLed, LOW);
      ledState = LOW;
    }
  }
} // end of alarm on function

void alarm_Off () {
  noTone (spk);
  digitalWrite(redLed, LOW);
  digitalWrite(yellowLed, LOW);
  digitalWrite(greenLed, LOW);
  digitalWrite(waterPump, LOW);
} // end of alarm off function

void high_Humidity() {
  digitalWrite(waterPump, HIGH);
}

void low_Humidity() {
  digitalWrite(waterPump, LOW);
}

the first if - else statement is incorrectly formulated

your code does not block, as far as i can tell .... you should be able to add more functions to loop() without a problem

the alarm_On() code does not need the if (ledState) code block .............. use ledState = ((ledState == LOW) ? HIGH : LOW);  followed by digitalWrite(redLed   , ledState);, etc.

It does block the code if I want to do anything with the components/sensors that are mentioned in the arlam_on & alarm_Off functions. The only case where it doesn't interfere is when the code doesn't involve those components

@jsotola you also mention that the first if-else statement is incorrectly formulated. Can you please tell how can I properly formulate it?

else statements shouldn't have a condition with them.

@Zaffresky, google c++ if-else

Does this even compile? } else (alarm == 0) {

@ThomasWeller, no, the code does not compile ... the compiler returns a expected ';' before '{' token error .... the OP has been negligent in presenting a non-working code

Sorry my bad but I have taken out the errors and repasted the code.

Your code is not blocked, but ON or OFF are called each loop so your change are to the "common" components are overwritten quite fast.
Do not track the state within the IRQ. You could do something like:
volatile byte alarm = 1;
byte alarm_state = 1;

void ISR_Alarm () {
    alarm = 1;
}

void loop() {
    if (alarm){
        alarm = 0;

        if (alarm_state) {
            alarm_state = 0;
            alarm_Off();
        } else {
            alarm_state = 1;
            alarm_On();
        }
    }

    // other code
}

I was using the "blocking" in a different context but indeed the code is not blocking. It was easier to understand with your code example. Thanks


text:
Sending arduino signal to another arduino
I'm working on a project which consists of 2 different function. since the arduino only can do 1 function so i decide to use 2 arduino instead. my idea is 1st arduino will give a output and the sketch on the 2nd arduino will run Only after the input given from the 1st arduino. So can i make a digital output which will be send to the input of 2nd arduino?
if it could be, i already make a code for the 2nd arduino which will be run after there was an input from the 1t arduino:
//define the input/output pins
#define FLOAT_SWITCH_PIN 2
#define PUMP_1_PIN 4
#define LED_PIN 7
#define output1starduino 3
//setup runs once
void setup()
{

  pinMode(FLOAT_SWITCH_PIN, INPUT_PULLUP);
  pinMode(output1starduino, INPUT_PULLUP);

  //setup output pins for relays/pumping station and LED board
  pinMode(PUMP_1_PIN, OUTPUT);
  pinMode(LED_PIN, OUTPUT);

}

//loop() runs indefinitely
void loop()
{

  if(digitalRead(output1starduino) == HIGH) // output from 1st arduino
  if(digitalRead(FLOAT_SWITCH_PIN) == LOW)
  {
     digitalWrite(PUMP_1_PIN, HIGH); //turn on the pump
     digitalWrite(LED_PIN, HIGH);    //turn on the LED
  }

  {
     digitalWrite(PUMP_1_PIN, LOW); //turn off the pump
     digitalWrite(LED_PIN, LOW);    //turn off the LED
  }
}

as i write on the line, the "output1starduino" which an digital output from the first arduino. Is this the right way for me to write if i want the program here to run only right after the output from 1st arduino given?
*** this is the code of first arduino which will be sent to the 2nd arduino
int motorPin = 3; // motor pengisian (m1)
int blinkPin = 4; //
int motor1 = 5;// motor pembuangan
int motorklorin = 6;// pam topap
int switch1 = 2;// switch float
int indicator1 = 7;
int indicator2 = 8;
int indicator3 = 9;
int output1starduino = 2;
void setup()
{
  pinMode(motorPin, OUTPUT);
  pinMode(blinkPin, OUTPUT); // penujuk fasa pengisian
  pinMode(motor1, OUTPUT);
  pinMode(motorklorin, OUTPUT); // MOTOR UNTUK topap
  pinMode(switch1, INPUT_PULLUP);// PELAMPONG
  pinMode(indicator1, OUTPUT);// lampu penunjuk fasa pembuangan
  pinMode(indicator2, OUTPUT);// lampu penunjuk topap
  pinMode(indicator3, OUTPUT);// lampu menunggu
  pinMode(output1starduino, OUTPUT); // KELUARAN KE ARDUINO 2
}

void loop()

{
  digitalWrite(motorPin, HIGH); // turn on the motor
  digitalWrite(blinkPin, HIGH); // turn on the LED
  digitalWrite(motor1, HIGH);// on lampu
  digitalWrite(motorklorin,HIGH);
  delay(1000);        //

  digitalWrite(motorPin, HIGH);  //
  digitalWrite(blinkPin, HIGH);  // penunjuk fasa pembuangan hidup
  digitalWrite(motor1, LOW);// motor pembuangan jalan (air start turun/pembuangan
  digitalWrite(motorklorin,HIGH);
  delay(180000);        //tempoh pembuangan

  digitalWrite(motorPin, LOW); // turn on the motor (motorisi balik air jalan/pengisian
  digitalWrite(blinkPin, LOW); //
  digitalWrite(motor1, HIGH);// filling motor on
  digitalWrite(indicator1, HIGH); //indicator
  delay(150000);        // duration filling

  digitalWrite(motorPin, HIGH);  // turn off the motor
  digitalWrite(blinkPin,HIGH);  // turn off the LED
  digitalWrite(motor1, HIGH);//
  digitalWrite(output1starduino, HIGH);
  delay(100000);        // multiply by 60000 to translate minutes to milliseconds
  }

One arduino can do many functions. My asks data over modbus, calculates and sets pwm, makes some http requests, serves web pages from SD card and ajax requests, handles 4 relays, reads a current sensor and a temperature sensors, lights leds, checks a button, calculates consumption, writes events to eeprom, csv log and consumption stats to SC card... https://github.com/jandrassy/Regulator/tree/master/Regulator

Combine them like this - I moved the duplicate pins to other pins
//define the input/output pins
#define FLOAT_SWITCH_PIN 2
#define PUMP_1_PIN 4
#define LED_PIN 7
#define output1starduino 3

byte motorPin = 11; // motor pengisian (m1)
byte blinkPin = 12; //
byte motor1 = 5;// motor pembuangan
byte motorklorin = 6;// pam topap
byte switch1 = 2;// switch float
byte indicator1 = 13;
byte indicator2 = 8;
byte indicator3 = 9;
byte output1starduino = 10;

//setup runs once
void setup()
{

pinMode(FLOAT_SWITCH_PIN, INPUT_PULLUP);
pinMode(output1starduino, INPUT_PULLUP);

//setup output pins for relays/pumping station and LED board
pinMode(PUMP_1_PIN, OUTPUT);
pinMode(LED_PIN, OUTPUT);

pinMode(motorPin, OUTPUT);
pinMode(blinkPin, OUTPUT); // penujuk fasa pengisian
pinMode(motor1, OUTPUT);
pinMode(motorklorin, OUTPUT); // MOTOR UNTUK topap
pinMode(switch1, INPUT_PULLUP);// PELAMPONG
pinMode(indicator1, OUTPUT);// lampu penunjuk fasa pembuangan
pinMode(indicator2, OUTPUT);// lampu penunjuk topap
pinMode(indicator3, OUTPUT);// lampu menunggu
pinMode(output1starduino, OUTPUT); // KELUARAN KE ARDUINO 2

}

//loop() runs indefinitely
void loop()
{

if(digitalRead(output1starduino) == HIGH) // output from 1st Arduino
{
digitalWrite(motorPin, HIGH); // turn on the motor
digitalWrite(blinkPin, HIGH); // turn on the LED
digitalWrite(motor1, HIGH);// on lampu
digitalWrite(motorklorin,HIGH);
delay(1000);        //

digitalWrite(motorPin, HIGH);  //
digitalWrite(blinkPin, HIGH);  // penunjuk fasa pembuangan hidup
digitalWrite(motor1, LOW);// motor pembuangan jalan (air start turun/pembuangan
digitalWrite(motorklorin,HIGH);
delay(180000);        //tempoh pembuangan

digitalWrite(motorPin, LOW); // turn on the motor (motorisi balik air jalan/pengisian
digitalWrite(blinkPin, LOW); //
digitalWrite(motor1, HIGH);// filling motor on
digitalWrite(indicator1, HIGH); //indicator
delay(150000);        // duration filling

digitalWrite(motorPin, HIGH);  // turn off the motor
digitalWrite(blinkPin,HIGH);  // turn off the LED
digitalWrite(motor1, HIGH);//
digitalWrite(output1starduino, HIGH);
delay(100000);        // multiply by 60000 to translate minutes to milliseconds
}

if(digitalRead(FLOAT_SWITCH_PIN) == LOW)
{
 digitalWrite(PUMP_1_PIN, HIGH); //turn on the pump
 digitalWrite(LED_PIN, HIGH);    //turn on the LED
}

{
 digitalWrite(PUMP_1_PIN, LOW); //turn off the pump
 digitalWrite(LED_PIN, LOW);    //turn off the LED
 }
}

Duplicate pins might need some more cleanup.

Why the downvote?


text:
TLC5917 Electrical Characteristics
I am using an Arduino Uno to communicate over SPI to 3 cascaded TLC5917 chips corresponding to the Red, Green and Blue rows of an RGB LED Matrix.
I am using direct output IO from the Arduino to power the columns.
Now I intend to use multiplexing to avoid drawing too much current at once, although it could still potentially be quite alot (3 x 8 x 20ma).
I have managed to display a full white screen using multiplexing with quite a high brightness, however this should not be possible to my knowledge.
Looking at the data sheet I found that at both at 3V and 5V the Output Voltage is rated at Vdd - 0.4 for Voh (Voltage High Level Output).
This means that at 5V the minimum output voltage should be 4.6V and at 3V it should be 2.6V.
Disabling multiplexing and simply writing to the registers and columns, and then measuring the voltage shows 2.5V, 2.8V and 1.8V for different colors.
This contradicts the data sheet.
The circuit contains no resistors except from GND to REXT using a 680Ohm Resistor.
The Arduino is powered over USB.
(http://www.ti.com/lit/ds/symlink/tlc5917.pdf)
Why is the Voltage so low, should it not be higher given the data sheet?
Am i reading the correct attribute?
How can my Arduino manage to drive so many LEDs (albeit through LED Drivers)?
What can I do to make this circuit more electronically safe and stable?

You are confusing logic signals with constant current sinks.

The concepts of HIGH and LOW, and thus the voltages associated with those concepts, apply only to logic signals.
LED drivers are not logic signals - they are constant current sinks. The voltages you are measuring are the forward voltages of the LEDs.


text:
PWM multiplexing on Arduino nano

simulate this circuit – Schematic created using CircuitLab
Its a simple project. I am trying to drive 3 RGB LEDs using Arduino Nano. Since Arduino Nano does not have 9 PWM pins, the only solution I can think of by multiplexing them. I have try multiplexing 12 7-segments driven by atmega16, the results was satisfying. Is it possible to do PWM multiplexing on Arduino Nano?
So far, here is what I have done:
const int R=9, G=10, B=11, M1=5, M2=6, M3=7;

//I use pin 5,6,7 as selector since they are on same PORT (PORTD)

void setup()
{
    pinMode (R,OUTPUT);
    pinMode (G,OUTPUT);
    pinMode (B,OUTPUT);

    pinMode (M1,OUTPUT);
    pinMode (M2,OUTPUT);
    pinMode (M3,OUTPUT);
}

void led(int r, int g, int b)
{
    analogWrite(R,255-r);
    analogWrite(G,255-g);
    analogWrite(B,255-b);
}

void loop()
{
    for(int i=0; i<256; i++)
    {
        led(0,0,i);
        __asm__("nop\n\t");     //one clock cycle delay
        PORTD = B10000000;      //select LED-1

        led(0,i,0);
        __asm__("nop\n\t");     //one clock cycle delay
        PORTD = B01000000;      //select LED-2

        led(i,0,0);
        __asm__("nop\n\t");     //one clock cycle delay
        PORTD = B00100000;      //select LED-3
    }

    for(int i=256; i>0; i--)
    {
        led(0,0,i);
        __asm__("nop\n\t");     //one clock cycle delay
        PORTD = B10000000;      //select LED-1

        led(0,i,0);
        __asm__("nop\n\t");     //one clock cycle delay
        PORTD = B01000000;      //select LED-2

        led(i,0,0);
        __asm__("nop\n\t");     //one clock cycle delay
        PORTD = B00100000;      //select LED-3
    }

}

But still, this does not work. The result is all the led turned on, with 'a little bit' different color, mainly white with a little addition of another color (while it supposed to be contrast, R, G and B for each LED), and its blinking. The blink is very short, but still, its annoying. One possibility I can think of my code still not optimum.
Someone had an idea?
EDIT
I fixed the diagram, I hope the diagram does not make any misunderstandings. As the suggestion from @jwpat7, I forget to inform that the led still error even if there is just one for-loop.
I am using __asm__("nop\n\t") as delay substitution because "theoretically", 1 clock cycle from 16mHz clock is shorter than 1 microseconds. (correct me if I am wrong, but I think its about 62.5 ns)
Thanks in advance

I've copied and slightly modified your diagram, as below.  Note the added connections of R1, R3 cathodes to that of R2, and similarly for green and blue LEDs.

simulate this circuit – Schematic created using CircuitLab
I'm supposing that unlike the original diagram, this one represents what you actually wired up.
A basic problem with your program is that it spends most of its time changing PWM settings, without letting PWM cycles actually occur.  To see this, do some timing analysis on the code.
The code repeatedly executes sections of code like the following:
    led(0,i,0);
    __asm__("nop\n\t");     //one clock cycle delay
    PORTD = B01000000;      //select LED-2

The call to led() results in three calls to analogWrite().  As seen by perusing at garretlab the source code for analogWrite(), digitalWrite(), and pinMode(), each of those analogWrite() calls takes a few handfuls of cycles – let's say 50 at most – so the three lines of code shown above take less than a dozen microseconds to execute.  Thus each of the two for loops takes less than 10 milliseconds to complete, causing the loop() routine to run more than 50 times per second.  Persistence of vision will result in observers just seeing the average level of light, rather than any ramping up or down.
To fix the ramps-not-visible problem, determine how long you want each ramp up or down to take, and add corresponding delays in the for loops.  For example, suppose you want to go up in one second and down in two.  As 1000000 μs /256 passes ≈ 3906 μs per pass, you could add delayMicroseconds(3906-36) at the end of the first for loop, and delayMicroseconds(2*3906-36) at the end of the other, to achieve the specified rates.  (The -36 term accounts for time used by other code in each loop.  It's probably an overestimate and perhaps should be left out.)
However, the previous paragraph doesn't take multiplexing effects into account.  You may, of course, want a different PWM level for each of the nine different LED chips.  It probably is practical to just directly use as many PWM outputs as you have available, and emulate PWM in software for any remaining LEDs.
For more information about software PWM, see some articles that google turns up, including:
• Arduino PWM pin vs digital pin PWM simulation on electronics.stackexchange, which presents basic ideas and some pros and cons of software-based PWM
• AnyPWM Revisited, a blog article by Nick Borko about PWMing 12 LEDs using software PWM
• PWMAllPins, an arduino.cc article apparently by Paul Badger or Seth Wolf about PWMing 11 LEDs using software PWM
Generally, software PWM hogs computing cycles and can be difficult to coordinate with other calculations.  But if PWM control is the only significant task a processor is handling, software PWM can be an economical way to produce extra PWM pins.

Thanks jwpat, I did not notice the mistake on diagram before. I edited my original question. "emulate PWM in software", sounds interesting, can you explain more?

@dpw, I added some links that help with the software PWM concept.

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


text:
What is the maximum power consumption of the Arduino Nano 3.0?
What is the maximum power consumption (in mW) of the Arduino Nano 3.0, when it is running in its default state (at 16MHz, no LEDs removed) and powered by an external regulated 5V supply so it bypasses the built in voltage regulator?
This will give us an upper bound on the power consumption of the Arduino Nano that can be used during estimates.

Well, it depends on what you have attached to the Arduino. If you are using the pins to do things you will definitely require more current.
If you ONLY want to power the Arduino, then I calculated what I think it should be below. (You should also check with someone who owns this device for an experimental value, and not just a calculated value. )
Based on the datasheet (fig 30-8, p 319), I would say the the processor will draw around 2.4 mA at 5 volts.
http://www.atmel.com/images/doc2545.pdf
The USB chip draws around 15 mA depending on several things (p 18)
http://www.ftdichip.com/Support/Documents/DataSheets/ICs/DS_FT232R.pdf
Then you have 2 LEDs with 680 ohm resistors. (Assuming 2 volt drop for each led)
(5-2)/680  = around 4 mA per led.
So depending on how much you use the serial port, and the LEDs I would guess around (2.4 + 15 + 4*4) = 33.4 mA
33.4 mA * 5V  = 0.167 Watts
I suspect you want to know to the total amount of power the Arduino can source, which is a bit harder to calculate.
The pins can provide up to 200 mA. (p 303 http://www.atmel.com/images/doc2545.pdf)
So 33.4 + 200 = 233.4
I would also add a 20% safety margin (around 50 mA)
So I would want a 280 mA supply, if I was going to attach the Arduino to different things.
280 mA * 5 = 1.4 Watts
Let me know if my numbers are way off.
P.S.: Be careful making your own supply. It is critical that the voltage be very stable. An unstable supply can/will destroy an Ardiuno. I suggest using a linear regulator, like the LM7805. or maybe the LM317

7805 and 317 both peak initially at 6V when first powered up from f.x. 12V. Doesn’t destroy my boards though.

@user13180 - clamp with a Zener and use a cap

does the usb draw that much if it is used nly to power the board? DO you have a good library to put Nano to sleep? Thanks

Yes, the i/o can source 40mA @ 5v (or 3v3) per pin, but the limit is'nt 40mA from each pin simultainiously but the limit is the processors dissipation. Read the 328A data sheet carefully and the truth will become clear.

"Each of the 14 digital pins on the Nano can be used as an input or output."
There are 6 analog input pins which are also digital pins, you must take those into account.
However, Note 3 under Table 32-2 of the '328P datasheet says:
"Although each I/O port can source more than the test conditions (20mA at VCC = 5V, 10mA at VCC = 3V) under steady state conditions (non-transient), the following must be observed:
3.1. The sum of all IOH, for ports C0 - C5, D0- D4, ADC7, RESET should not exceed 100mA.
3.2. The sum of all IOH, for ports B0 - B5, D5 - D7, ADC6, XTAL1, XTAL2 should not exceed 100mA.
(but ADC6 and ADC7 are analog input only, and should not be sourcing current)
So I would suggest that to keep your Nano healthy, 200mA x 5V = 1W be considered for the IO, and then the amounts noted above for the Power LED, L LED (which is driven by D13), and internal running of the chip be taken into account.

From website https://store.arduino.cc/usa/arduino-nano:  Each of the 14 digital pins on the Nano can be used as an input or output. They operate at 5 volts. Each pin can provide or receive a maximum of 40 mA.
Therefore i would assume maximum power consumption is 14 x 40mA x 5V = 2.8W, depends on the board effeciency %, for example let's say 80%, so input could be 3.5W, but again you rarely use all 14 pins at once as outputs hence it is way way lower than 3.5W.This is just a ballpoint figure.

If an individual pin can provide 40mA, it does't mean that they can provide 560mA at once.

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


text:
Adding devices makes I2C read 0
I'm using an Arduino Due with a logic level converter to interface with two different 5v sensors via I2C. Being of poor quality, these sensors have no data sheet.
When either one of these sensors is plugged in, I am able to read from it without issue. The moment I plug the other one in as well, the I2C stops working, and I just get 0. I know that it's not an address collision issue, because they have different addresses.
I tried adding an additional set of pull-up resistors (such that they are in parallel with the built-in ones) in order to counteract potentially increased bus capacitance, but no dice.
What could be causing this issue? I apologise for asking such a noob question.

The best way to diagnose I2C problems is to look at the signals with a scope. Then you can see whether the slaves are acknowledging the master's commands, check each sensor address and all. Can you do that and post the shot? Also, schematics would help a lot.

Another guess is that maybe you should remove one set of pullups from one of the boards. But that would probably damage it, so think carefully about it.

@Ricardo unforunately, I'm in high school and don't have access to a scope. can I ask how removing a set of pullups might resolve the issue?

Well, I was just guessing. As I said, without a scope, there's no way of knowing what's going on. But I read somewhere that each I2C module comes with its own set of pullups. Then, if you place too many of them on a bus, their resistance will divide up, changing the optimal pullup value. So, someone suggested that the modules should come without the pullups, so that one would calculate the optimal pullup resistance of the set of modules and solder it up in one of them (closer to the master I guess).

Somebody else said that it's easier to ship the modules with the pullups and then remove some of them if you combine several modules.

Here it is, the discussion is in this answer to a question of mine. Look at the 3rd comment from the top.

Your problem is probably from the level converter. Which one did you use?
Most level converters are uni-directional, and don't work for I2C.
See the App note and device from NXP:
http://www.adafruit.com/datasheets/an97055.pdf

OP said it worked with one device


text:
Will an ATmega2560 board be faster than a Uno for hard real-time data logging?
I am designing a hard real-time data logger. The Uno is a bit marginal in processing speed.
a) Would it be faster if I changed to an ATmega2560?
b) On the datasheet, ATMEGA2560 has 135 instructions; it is 4 instructions more than the ATmega328p.
What are the extra 4 instructions for?
Are they involved in floating point maths?
c) How to select compiler option for fastest code at the expense of bigger code size, longer compilation time, etc.?
The system is:

Receive data from wireless transceiver chip via hardware SPI port.
A good portion of the time is spent on data calculation using floating point maths.
Output processed data on serial port (then to PC via the Arduino board USB to Serial chip).
Code and RAM size is not an issue, Uno has plenty space left.

The Uno is actually faster than the Mega, especially if there is a high frequency of function calls and return. Easiest way to check this is to simply read the number of clock cycles for typical instruction sequences.

If you need speed replace the floating point math with fixed point. And to reduce latency pipeline input/output with the processing.

If you are concerned about performance, don't use an ATmega-based Arduino at all.  Today's ARM parts, from many vendors (even Atmel themselves) are many times faster, no more expensive, work better on low battery voltages, and several have Arduino ports.

If it's connected to a PC, then you could just offload the calculation to the PC. But I'd first do some measurements and see if there is even a problem, and where this problem lays. Could you for example speed up the SPI clock. Doing optimizations without measurements is just silly, as you don't know if they worked, or if they made things even worst.

@Chris Stratton, could you please list some example parts, if it is not against the 'rules' for this forum. (Can I ask this under forum rules) Is STM323F1xx a good choice? assume able to use its (non Arduino) development package and IDE STM32CubeMX.

No, it will not be any faster. The extra instructions are to access the extra flash memory of the 2560. Instructions like EIJMP - Extended indirect jump, EICALL - Extended indirect call, etc.
The compiler option -O3 optimises the most, but there are other options you can enable, such as -funroll-loops which will cause major code bloat but speed things up.  Read the GCC manual pages to boggle at all the millions of optimisation options.
Or... use a faster chip, like an ARM or PIC32.

Use the newest Arduino IDE, because some time ago the 'lto' option was added which is a major optimization for both speed and size.
It is possible to test a few compiler options with the #pragma. Try for example these at the top of the sketch:
#pragma GCC optimize("-O3")
#pragma GCC optimize("-ffast-math")

The 'fast-math' is dangerous, be careful with it.
The Arduino Zero and Arduino Due are faster but not a lot faster, because they are not fast with analogRead() and with floating point calculations.
A common mistake is that someone asks for a faster Arduino board, but uses a sketch and libraries with a lot of delay() in it. That won't be any faster with an other Arduino board. Have a good look at your code and at the source code of the used libraries.
Have you tried increasing the baudrate for outgoing data ? If that baudrate is slow, the whole sketch is slowed down because the Serial functions will wait until they can write the data into the Serial buffer. The fastest "baudrate" can be achieved with the Leonardo, Micro and Pro Micro boards. They transmit the data directly onto the USB bus without using the baudrate.

In the platform.txt file found in ~/Arduino15/packages/arduino/hardware/avr/1.6.17 or similar, you can change the three instances of -Os with -Ofast. The size of the code can increase dramatically though.

They have very nearly the same instruction set and the same execution speed, so there will be no increase there. If your project spends a significant amount of time in floating-point arithmetic, replacing it with fixed point arithmetic will give you a noticeable speed up. If a few calculations are executed repeatedly (which is typical), you can get most of the advantage by rewriting only that part.
In a nutshell, fixed point arithmetic is what the computer does already, but with an assumed binary point (just like a decimal point) always to the right of the least significant bit. Fixed point arithmetic uses the built-in arithmetic, but you assume the binary point to be wherever you need it, keep track of it during multiplies and divides, and make sure you keep the intermediate results from overflowing.
Search for Fixed Point Arithmetic and you'll find out a whole lot more.


text:
Common wireless gadget with rotary encoder to connect with Arduino
I'm looking for a common "wireless gadget" with a rotary encoder that can be accessed by an Arduino. Background: I need a portable rotary encoder to create a simple way to control model railway locomotives. The only one I have found so far is a wireless mouse where the scroll wheel can be easily used as rotary encoder.
But they usually are using USB on the PC side which is not that easy to handle by Arduino. Does anybody knows about other common "wireless gadgets"?

That sounds like a candidate for building your own.  It shouldn't be too hard.
There's plenty of low-cost Arduino-compatible wireless modules available.  My choice for this would probably be the nRF24L01 - dirt cheap, reasonable range, well supported.
Attach that to an Arduino Mini or Arduino Nano (for instance) and connect a rotary encoder of your choice.  Write the sketch.
Add another nRF24L01 to your main Arduino to receive whatever you send.
Due to the way the nRF24L01 works you could quite easily have a number of remote modules talking to the Arduino through the same channel.  I'm sure you could think of other things you could do with that wireless channel :)

Excellent solution. I was about to post a similar answer when I saw yours. +1

In addition to @Majenko,
If your device is going to talk to a PC/Laptop (or cellphone!), then HC05 or HC06 bluetooth serial module may be a better fit. You will still need to write software to receive the data, but you won't need another Arduino at the other end.


text:
Using USB or ethernet to carry digital signals
I need to send six digital signals about 4 feet through wires. An ethernet cable has 8 little wires that should do the trick. I could split the ends and solder them to my boards.
Is there an adaptor that will let me plug in the ethernet cable cable to my board and have access to the signal from each wire on a pin? If not, can I accomplish this through USB? Is there a more elegant solution than having six long wires?

You mean like a RJ-45 jack?

10BaseT cables have 4 twisted pairs.  USB cables have 4 wires, 2 for signal and 2 for power.  Careful how long you make the wire.  High speed digital signals like ones that a processor can make can not go far with out special attention.

something like https://www.ebay.nl/itm/Kit-RJ45-8-pin-Connector-and-Breakout-Board-For-Cat5-Cat5e-Cat6-Ethernet-Cables/131857340868 . Don't forget that you also need one wire for the GND connection.

@IgnacioVazquez-Abrams do you know of one that has pins at a right angle that can go down into a breadboard?

@Gerben perfect make that your answer I will accept it

@Gerben for bonus points which one carries the +/gnd for POE?


text:
ESP8266(01) doesn't work when servo connected to GPIO-2
the wiki here says http://www.esp8266.com/wiki/doku.php?id=esp8266_gpio_pin_allocations
0 Low
1 High
x floating
MODE                   GPIO15   GPIO0   GPIO2
SDIO (BootSDCard)       1       x        x
UART (UploadCode)       0       0        x or 1
FLASH (NormalRunning)   0       1        x or 1

Can connecting my GPIO 2 to a servo Signal Wire cause it to go LOW? because some how my ESP8266 doen't boot when I have a servo hooked up to it.
I tried to change it to RX (which is GPIO3 on ESP8266) and everything seems to work fine. But I wanna know the reason why GPIO2 didn't work.
Thank you.
p/s:http://www.goodluckbuy.com/ld-1501mg-metal-gear-digital-servo-17kg-for-rc-robot.html this is the servo, if it matters. Also GPIO-2 works when I use another servo of different type instead (I don't know its name though)

only one conclusion: the servo pulls the input down

add external pull-up to io 2

It's what Juraj said.

add external pull-up to io 2 -Juraj

sovled it


text:
Why does my IDE fail to open files?
I'm using Version: 2.0.3 - Date: 2022-12-05T09:30:25.33 on Windows 10 Pro. Installed under Local user - not for all users.
When I try and open a ino file (either double clicking on a ino file - or file->Open) - it spawns a new window - but then I just see the standard sketch with an empty setup() and loop()
I've uninstalled and re-installed both for my own users and all. But still, it does the same thing. I'm having to open all my sketches in notepad++ and then save them in whatever temp Arduino file it creates. Its hellishly annoying

2.0.3 may be broken ... try another version

Hmm. happening on 2.0.2 too

And if you run it as "Administrator" ?

And here https://forum.arduino.cc/t/arduino-2-0-not-starting-up/950998/2 in answer #3 you can start Arduino from CLI and debug it.

Thanks @MatsK - I think its a bug due to my dodgy filesystem on windows..   I see this in the output
2023-02-21T11:22:21.224Z sketches-service WARN Warning! The request sketch path was different than the response sketch path from the CLI. This could be a potential bug. Request: <\ace-svr02\Users$\wwade\Documents\GitHub\X80\firmware\x80Tester\x80Tester.ino>, response: <\ace-svr02\Users$\wwade\Documents\GitHub\X80\firmware\x80Tester>.

If you try to open a sketch from a shared drive on Windows, it does not work. See the bug here. When opening a sketch fails, IDE returns to a new temp sketch. That's why you see void setup(){} void loop(){}.


text:
Digital pins are no longer outputting enough to click a relay
I've been working on a project for awhile now, and I ran into a problem a week ago I couldn't solve. I'm using an Arduino uno R3.
My project involves the use of 4 relays triggered by the digital pins. Write a HIGH value, relay clicks. Write a LOW value, relay unclicks. Rather simple.
One day, I come back to it to discover it can no longer click the relays. No changes were made to my code that worked previously. The relay light came on, but no click. Could it be that I sent HIGH to 4 at the same time? My theory is that I could've drawn too much power at the same time, weakening it in a way that causes it to not output as much as it did previously.
I tested a relay on a different board and it works perfectly fine.

how are the relays powered?

The relay has 3 pins. 5V in, GND, and signal. It's powered by the board. Reconnecting the signal wire from the PWM pin to the 5V triggered the relay, so it's not a voltage problem or a relay problem. I've also tested many relays

stop calling it PWM pin. it is a digital pin. you don't use PWM to control a relay

Relays need a certain current and Arduino pins can only provide a small amount of current. Normally you don't power the relay coil directly from a pin.
Please post a schematics of your wiring, as well as a reference or datasheet for the relay you're using.

Are you recommending I use the relay in a different way? I'm unable to provide a visual diagram for my wiring, but it goes like this: 5V power to DC+; GND to DC-; PIN6 to IN1.

Yes I am. You can use an online schematic tool or either draw a crude one by hand. In any case, the specs of your relay is an important information (either part reference or datasheet).

Not knowing the reference of your relay, my answer is generic but should suit your needs.
Relays need 2 things in order to work properly: a sufficient voltage source, and one that can provide enough current.
The Arduino output pins provide 5V on 5V boards or 3.3V on 3.3V boards. BUT, most Arduino GPIO can provide only 20 mA of current. That might not be enough for your relay. The solution here is to use a transistor to drive the relay.
Also, relay coils are inductive loads that generate voltage spikes when current is turned off. That voltage can rise much higher than 5V and damage your Arduino pins and weaken or destroy them. The solution to this problem is to add a flyback diode.
This is what a typical circuit with relay driven by an Arduino looks like:

When the Arduino pin is LOW, the transistor is turned off and no current goes through the relay.
When the Arduino pin turned ON, the transistor turns on fully saturated and the relay coil is energized.
When the Arduino pin is turned LOW, the coil generates a negative voltage and current is allowed to go through the diode, dissipating energy in the relay coil. More information on flyback diodes: https://en.wikipedia.org/wiki/Flyback_diode

inductive loads generate reverse voltage spike when it is turned OFF

Well-spotted, thx.

There is another thing: the SUM of currents (driving or sinking), may be a thing. Despite proper operation of one relay, even two, when situation comes to drive all relays this may be too much when all currents add. For ATMEGA328P-PU sum of currents may not exceed 200mA. Recommended lecture: Arduino Uno R3 microprocessor's datasheet (ATMega328P-PU)

For 4 relays, the OP would be limited by the per pin current limitation way before being limited by the per chip limitatation. Using a transistor would reduce the current provided by the chip to way below both limits.

Post a link to the relay you are using, I do not know if it is a plane relay or a relay module for the arduino. The modules are less then a buck from your favorite china supplier.

As I stated on the other Forum a Power Supply the Arduino Is NOT! What else is connected, I have a feeling if you touch the regulator on the Arduino you will burn your finger and it may even be loose. Use a volt meter and measure the 5V, I think that is your problem.


text:
variable or field declared void Error
For a larger sketch, I have separated a chunk of code in a separate .cpp file
#include "msg.h"
#include <Arduino.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>

void parseResponse(String &payload, float &temp, float &wind, int &pressure, int &humid, float &feel, int &uv)
{

    String json = payload;

    // Serial.println(json); // enable to debug

    StaticJsonDocument<128> filter;

    JsonObject filter_current = filter.createNestedObject("current");
    filter_current["temp_c"] = true;
    filter_current["wind_mph"] = true;
    filter_current["pressure_mb"] = true;
    filter_current["precip_in"] = true;
    filter_current["humidity"] = true;
    filter_current["feelslike_c"] = true;
    filter_current["uv"] = true;

    StaticJsonDocument<256> doc;

    // Deseriliaze and display error description if there is any
    DeserializationError error = deserializeJson(doc, json, DeserializationOption::Filter(filter));

    if (error)
    {
        Serial.print("deserializeJson() failed: ");
        Serial.println(error.c_str());
        return;
    }

    JsonObject current = doc["current"];
    temp = current["temp_c"];          // 80
    wind = current["wind_mph"];        // 5.6
    pressure = current["pressure_mb"]; // 1005
    humid = current["humidity"];       // 93
    feel = current["feelslike_c"];     // 6.9
    uv = current["uv"];                // 1
}

together with its header file as below:
#ifndef MSG_H
#define MSG_H

void parseResponse(String &payload, float &temp, float &wind, int &pressure, int &humid, float &feel, int &uv);

#endif

I have included all the relevant libraries in the .cpp files. However, when I try to compile the code I get multiple errors such as
In file included from src/weatherapi.cpp:1:0:
include/weatherapi.h:4:17: error: variable or field 'getRequest' declared void
 void getRequest(String &payload);
                 ^
include/weatherapi.h:4:17: error: 'String' was not declared in this scope
include/weatherapi.h:4:25: error: 'payload' was not declared in this scope
 void getRequest(String &payload);
                         ^
Archiving .pio\build\lolin32\liba47\libPubSubClient.a
In file included from src/msg.cpp:1:0:
include/msg.h:4:20: error: variable or field 'parseResponse' declared void
 void parseResponse(String &payload, float &temp, float &wind, int &pressure, int &humid, float &feel, int &uv);
                    ^
include/msg.h:4:20: error: 'String' was not declared in this scope
include/msg.h:4:28: error: 'payload' was not declared in this scope
 void parseResponse(String &payload, float &temp, float &wind, int &pressure, int &humid, float &feel, int &uv);
                            ^
include/msg.h:4:37: error: expected primary-expression before 'float'
 void parseResponse(String &payload, float &temp, float &wind, int &pressure, int &humid, float &feel, int &uv);
                                     ^
include/msg.h:4:50: error: expected primary-expression before 'float'
 void parseResponse(String &payload, float &temp, float &wind, int &pressure, int &humid, float &feel, int &uv);
                                                  ^
include/msg.h:4:63: error: expected primary-expression before 'int'
 void parseResponse(String &payload, float &temp, float &wind, int &pressure, int &humid, float &feel, int &uv);
                                                               ^
include/msg.h:4:78: error: expected primary-expression before 'int'
 void parseResponse(String &payload, float &temp, float &wind, int &pressure, int &humid, float &feel, int &uv);
                                                                              ^
include/msg.h:4:90: error: expected primary-expression before 'float'
 void parseResponse(String &payload, float &temp, float &wind, int &pressure, int &humid, float &feel, int &uv);
                                                                                ^
include/msg.h:4:103: error: expected primary-expression before 'int'
 void parseResponse(String &payload, float &temp, float &wind, int &pressure, int &humid, float &feel, int &uv);

The function parseResponse doesn't return anything so I don't know why it's complaining about being declared as void. Same is true for the function getRequest. Also, is there something wrong in the function prototype as I am passing references?
Edit: Here is the weatherapi.cpp & .h file
#include "weatherapi.h"
#include <HTTPClient.h>
#include <Arduino.h>

const char url[] = "http://api.weatherapi.com/v1/current.json?key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

void getRequest(String &payload)
{

     HTTPClient getClient;

    getClient.begin(url);

    int httpCode = getClient.GET();

    //get response and check HTTP status code returned
    if (httpCode > 0)
    {
        payload = getClient.getString();
        Serial.print("HTTP Status: ");
        Serial.println(httpCode);
    }
    else
    {
        Serial.println("Error on HTTP request");
    }

    getClient.end();
}

weatherapi.h file
#ifndef WEATHERAPI_H
#define WEATHERAPI_H

void getRequest(String &payload);
#endif

Your problems start before the code you have shown us. Specifically in (or even before) weatherapi.h. It says it doesn't know what String is - did you include Arduino.h in there?

Yes I have included Arduino.h but still the same error :(. Please see updated post

Order is important.... Arduno.h must be included before it is used...

In C order is important. Everything is parsed sequentially, and header file inclusions are replaced literally with the header contents at compile time.
Things must be defined before they can be used, and that includes anything that is defined in the Arudino.h header file - that file must be included before anything that uses it - and of course that means that it must come before any headers that use things from Arduino.h
To be safer it's good to include Arduino.h in every file that uses anything from it so you don't run into these problems in future.

Included Arduino.h in all .cpp files and it compiles without error.  Though I omitted it only in places where I thought it wasn't needed at all but perhaps it was required somewhere.


text:
ATmega328p bootloader issue : [avrdude: stk500_recv(): programmer is not responding]
I am using an arduino uno board and have placed the new ATmega328chip in the socket as a simple setup as mentioned in Minicore installation instructions. However, I am unable to burn the bootloader. I am using your minicore and selected the ATmega328 chip. I have tried using 8MHz internal crystal as well as 16 MHz external crystal but get the same error. I even tried using a different ATmega328p but the result was same. Here is the output:
avrdude: Version 6.3-20201216
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Users\Administrator\AppData\Local\Arduino15\packages\MiniCore\hardware\avr\2.1.2/avrdude.conf"

         Using Port                    : COM4
         Using Programmer              : stk500v1
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x03
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x03
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x03
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x03
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x03
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x03
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x03
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x03
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x03
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x03

avrdude done.  Thank you.

Error while burning bootloader.

Before trying this Minicore option I also tried different tutorials which ask for external crystal and extra capacitors. It's been two days I am trying to make it work but sadly haven't managed it yet. Initially I suspected a faulty ATmega but even three other chips result in the same error or device signature error.
Here are the other connections I have used:

Could you please help me fix it? Thanks

Do you have an STK500 Version 1 programmer that you're using to burn the bootloader? Or are you just plugging the Arduino into USB and praying that something miraculously happens?

I don't have that programmer but an AVR asp programmer. For minimal setup I thought I just need to replace the new ATmega in the socket and then then burn the bootloader by plugging the arduino into usb. I didn't even pray though :) May be I didn't understand the minimal setup correctly.

I did also try with the FTDI/UART connection and the ISP to burn the bootloader but was getting a signature error.

I have edited original post with the connection sketches

To program the bootloader you need either a hardware programmer or a working Arduino to use as a programmer. But I am confused (and likely you are too). You say you put the chip in the socket then show us a circuit with a breadboard...

Here is sequence of what I have tried so far. First I tried to burn the bootloader with the ATmega328p & other components on a breadboard following the two different connection schemes shown above.  I got error "avrdude: Yikes! Invalid device signature. Double check connections and try again, or use -F to override this check." At last I simply replaced the ATmega on my working uno board to burn the bootloader.

The former is what you need to do, not the latter. Set it up on a breadboard again and try various tutorials again. Many miss out disabling the Arduino's auto serial reset which you have to do for it to work.

I started a new with clean wiring and tried the tutorial on the arduino website and it does use a pullup resistor on the reset pin. It worked :) Thanks for the pointer

you can't burn bootloader into ATmega by putting it on Uno. even if the ATmega is on Uno you have to use a programmer (or other Arduino as programmer with Arduino as ISP sketch)

@Juraj yeah I misunderstood one of the tutorial. I thought by just placing it on the uno board socket I wouldn't need any external circuitry like caps, resistors and the crystal. Also I would be able to use the serial to usb connection on the board to burn the bootloader. But it's clear now

You have to install the bootloader using either an working Arduino or a hardware programmer.
There is one step that many many tutorials on this subject miss out (and both the circuits you show have missed it out), and that is to disable the automatic reset of the programming Arduino.  That can be done a number of ways:

Add a low-value pullup resistor to RESET
Add a high-value capacitor between RESET and GND
Cut the "RESET-EN" trace on the underside of the board

Once the bootloader is installed in this way you can then put the chip into an Arduino and program it through USB, or connect it to a USB to UART adapter and program it through that.

I used the first method. However, even with a 10K resistor it worked


text:
Is this class declaration wrong? " Declaration has no storage class or type specifier" error
While trying to setup  an ESP32 as mqtt publisher I am getting strange errors. Here is my code:
#include "mqttSetup.h"
#include <WiFi.h>
#include <PubSubClient.h>

static byte httpFailCounter = 0;
byte counter = 0;

const char *ssid = "SSID";
// const char *password = "xxxxx";
const char *passphrase = "xxxxx";

WiFiClient espClient;

const char *mqtt_server = "192.168.1.39";
const int mqttPort = 1883;
const char *mqttUser = "xxxx";
const char *mqttPassword = "xxxxx";

PubSubClient pubClient(espClient);

pubClient.setServer(mqtt_server, mqttPort);

void checkConnection()
{
    if (WiFi.status() == WL_CONNECTED)
    {
        counter = 0; //reset counter
    }
    else if (WiFi.status() != WL_CONNECTED)
    {
        WiFi.begin(ssid, passphrase);
    }
    while (WiFi.status() != WL_CONNECTED)
    {
        delay(500);
        Serial.print(".");

        counter++;
        if (counter >= 60)
        {
            ESP.restart();
        }
    }
}

void reconnect()
{

    while (!pubClient.connected())
    {
        Serial.print("Attempting MQTT connection...");
        // Create a random client ID
        const char *clientID = "ESP32D-MQTT";
        // Attempt to connect
        if (pubClient.connect(clientID))
        {
            Serial.println("connected");
            // Once connected, publish an announcement...
            pubClient.publish("outTopic", "Hello from ESP");
            // ... and resubscribe
            //   client.subscribe("inTopic");
        }
        else
        {
            Serial.print("failed, rc=");
            Serial.print(pubClient.state());
            Serial.println(" try again in 5 seconds");
            // Wait 5 seconds before retrying
            delay(5000);
        }
    }
}

I don't understand why the compiler is spitting out the following two errors:
this declaration has no storage class or type specifier (referring to my pubClient declaration)

expected a ';'

It doesn't have any issue when I declare the pubClient but at the line :
pubClient.setServer(mqtt_server, mqttPort);
where I use the pubClient it gives the error.
Besides I don't see any ; missing in the code.
Could you please help me figure out the source of error?

Header file for this code chunk
#ifndef MQTTSETUP_H
#define MQTTSETUP_H

void checkConnection();
void reconnect();

#endif

------------ Main sketch---------
#include <Arduino.h>
#include "Wire.h"
#include "tempSensor.h"
#include "mqttSetup.h"

void setup()
{
  Wire.begin();

  Serial.begin(115200);
  while (!Serial)
    ;

  shtBegin();
  checkConnection();
}

void loop()
{
  uint32_t newTime = millis();
  static uint32_t oldTime = 0;
  static uint32_t t2 = 0;

  float temp = 0.0;
  float humid = 0.0;

  char senVals[50];

  if (newTime - oldTime >= 10000)
  {
    oldTime = newTime;

    readsht(temp, humid);
    snprintf(senVals, 50, "Temp: %.2f Humid: %.2f", temp, humid);
    Serial.println(senVals);

  }
}

Code goes in functions, not the global scope.
Your line
pubClient.setServer(mqtt_server, mqttPort);

should be inside a function. Most probably setup() so it gets called when your program starts.
Incidentally - where are setup() and loop() - the two functions that are required by Arduino code?

This code chunk is contained in a separate .cpp file. I was trying to keep the main sketch clean from setup and function definitions for different components. That's why you don't see the main sketch. I intended to call only a publish function(not yet implemented in my code) in the main sketch. I will update my post with the header file and the main sketch

@Zaffresky Then you should wrap that line in a function which you can then call from setup().

I have updated my post with main sketch and the relevant header file. I don't fully understand why I should put the line  "PubClient.setServer(mqtt_server, mqttPort);"  in a new function. My understanding was that the PubClinet.serServer function is already defined in the PubSubClient library and in my separate mqttSetup.cpp file I was calling this function so that this file would be self-contained and I wouldn't need to call any PubSubClient library functions directly in the main sketch. Rather I would only call my function publishMQTT() in the main sketch. Is this approach wrong?

@Zaffresky Because code goes in functions not in the global scope.  Anything you call during the sequence of the execution of your program must go in a function. The only things that can go in the global scope are variable declarations (with or without an immediate assignment).

I see it now. I was not considering the scope in that seperate .cpp file. I mistakenly assumed that the concept of scope was applicable only to the main sketch. Thanks for clarifying


text:
I change ESP8266 baudrate and now it doesn't work
I was trying some AT commands using the monitor of the Arduino Web Editor with an Arduino Uno and a ESP8266 module. It was working at 115200 bauds but then I changed it with AT+CIOBAUD=19200 and now it can't communicate.
How can I change the baudrate to 115200?
Now I see this:

How were you "trying" those AT commands?

Have you tried setting the web editor's baud rate to both the old and the new values? I ask because the CIOBAUD command has been obsolete for a while now so, depending on the age of your device, it may have done nothing. The command was replaced by "AT+UART_CUR" and "AT+UART_DEF" which have a different syntax.
See this answer to a similar question.
Update:
Yes, here's an example:
// Declare a serial object to talk to ESP8266
SoftwareSerial EspSerial(WIFITX_PIN, WIFIRX_PIN);  // RX, TX

void setup(void){
   // Init WiFi serial
   EspSerial.begin(9600);
   delay(10);
}

I've used 9600 baud in my example since SoftwareSerial may not work well at faster speeds.
Update 2:

Is it possible to send AT commands from the code instead of the
  monitor?

Yes, easily. Once the above code has run (and note that I've deleted an unnecessary line since update 1), you can send strings to the ESP with EspSerial.print() and EspSerial.println(). Here's an AT command example:
// Set 9600 baud, standard 8-bit frame, and save as power-on default:
EspSerial.println("AT+UART_DEF=9600,8,1,0,0");

Is it possible to set baudrate inside the code with a sentence?

Is it possible to send AT commands from the code instead of the monitor?

your question has been answered. why are you posting new questions here?


text:
"Best" architecture for handle events
I come from web world, so i usually code in a more procedurally manner, so the loop is a bit difficult to handle.
i mean if i do something like if(condition) doSomething() it will exec doSomething() a lot, or a click of a button....
bool condition = false;
void loop(){
  if(condition){
    doSomething();
  }

}

void doSomething(){
  condition = false;
  // ........
}

iam doing things like this, but i feel its wrong somehow
so iam struggling why could be the "best" architecture to execute doSomething() only once, in a way it not become a hell of state management, some kind of event driven, event sourcing or something more battle tested for arduino
iam totally newbie in this hardware/arduino world

add a flag that signals that the function already ran ... it is unclear what the actual problem is ... if you have a real world example  then add it to your post

I guess that for a web browser application, when you register an event in a script, say a button press, that in a loop (hidden somewhere) that button object will be tested regularly and, if pressed, the event handler will be executed. With the Arduino there is no run time system to support such things directly so if you want to test a button regularly, you have to do so explicitly in a loop.

Coming from the Web world, you are most likely used to work in a
single-threaded environment (save for Web workers). You have been
trained to program in a non-blocking fashion, as blocking the browser's
UI thread would freeze the user interface. This is actually a valuable
asset when moving to Arduino programming. Most Arduino programs run on
a single-threaded, bare-metal platform. Non-blocking code is a must for
all but the most trivial programs, and is not easy to master for
newcomers.
The most striking difference between an Arduino and your typical
JavaScript environment (be it a browser or Node.js) is that in
JavaScript the event loop is implicit. You do not see it, but it runs
under the hood of your interpreter. It looks conceptually like this:
void JavaScript_event_loop() {
    if (there_is_a_pending_event()) {
        dispatch_the_event_to_the_registered_callback();
    }
}

On the Arduino, however, you have to write the event loop yourself. Most
often you do not need full-blown event queue management, as you know
beforehand the set of events your program will have to handle. Your
typical Arduino loop should normally look like this:
void loop() {
    if (event_foo_happened())
        handle_event_foo();
    if (event_bar_happened())
        handle_event_bar();
    if (event_baz_happened())
        handle_event_baz();
    // etc...
}

There are a few recurring idioms for testing common events. Here are
some examples:
// Handle a periodic event (like setInterval()).
uint32_t now  = millis();
static uint32_t last_event_time;
if (now - last_event_time >= event_period) {
    // Use `last_event_time = now;` instead of this if you want to
    // guarantee a minimal interval between events:
    last_event_time += event_period;  // this avoids systematic drift
    handle_periodic_event();
}

// Handle a rising edge on an input_pin.
uint8_t pin_state = digitalRead(pin);
static uint8_t previous_pin_state;
if (previous_pin_state == LOW && pin_state == HIGH)
    handle_input_rising_edge();
previous_pin_state = pin_state;

// Handle Serial data.
if (Serial.available())
    handle_input_byte(Serial.read());

// Handle a push button with a debouncing library.
button.update();
if (button.fell())
    handle_button_press();

A few recommended readings:

The Blink Without Delay Arduino tutorial shows how to handle
periodic events
Reading Serial on the Arduino is a tutorial showing how to
buffer serial input in order to handle one full message at a time
Bounce2 is an example of a button-debouncing library
The Finite State Machine is a nice tutorial on writing finite
state machines, which sooner or later you will need for handling some
situations in a non-blocking way

Edit: Regarding the example code you posted, I would like to rewrite
your loop() like this:
void loop() {
    if (condition) {
        doSomething();
        condition = false;  // <- move this out of doSomething()
    }
}

It doesn't look like a big change, but there is an idea here that can
help make your code more readable and maintainable. The idea is to think
of your program in terms of “events” you have to respond to. This should
feel natural to someone raised on JavaScript, and it is also a good
approach for programming microcontrollers. You then want to handle the
event detection/dispatching and the event response as separate problems.
The function doSomething() should not have to care about the
condition variable, as it is only used to handle the event detection
and dispatching, which is the responsibility of the event loop.

When i said to execute once I mean, when press a button, it should do
something only once, this control of what should/was executed is a bit
tricking, can go out of control and became a mess.

To detect a button press you do have to manage some state, there is no
way around it. Your program should not respond to the state of the
button (pressed or released) but instead to specific transitions of
this state (press or release events).
In its most basic form, the problem is about detecting a falling edge
(or rising edge, depending on how the button is wired) on the input
signal. This is handled by remembering the state you had on the previous
loop iteration, and comparing this previous state with the state you are
reading right now, as show in the “Handle a rising edge on an input pin”
example above.
Real buttons have an additional issue, namely mechanic bounce: when the
button is actuated, the signal can go through many fast transitions
before settling into a stable state. In order to deal with this, you
have to look at the timing of the transitions and sort out the legit
ones from the spurious ones. This is called debouncing. There are a
few libraries out there than can handle this for you. Most will also do
edge detection, which makes handling button presses as simple as testing
for button.fell() (again, see example above). Some will even report
distinct event types for short press, long press and double press.

Great answer, but I'd just make a modification in your periodic example. I think usually what you prefer when doing a periodic check is to have something periodic, not something guaranteed to be above the time. I mean, if the period is 1 second and the first cycle is 1.1s then I'd prefer the second to be 0.9s to "catch up" rather than 1s (so delays don't add up). So usually I prefer to write last_event_time += event_period;.

@frarugi87: Edited the answer, thanks.

The usual way to do things only once (at startup) is to put them in setup().
You put only statements in loop() that need endless repetitions.
You can think of the underlying main function as:
int main() {
    setup();
    for (;;) {
        loop();
    }
}

Therefore, your example can be:
void setup() {
    doSomething();
}

void loop() {
}

void doSomething() {
    // ........
}

Addition after clarification
You commented:

as far as i know i cant detect a button press outside of the loop right? when i said to execute once i mean, when press a button, it should do somenthing only once, this control of what should/was executed is a bit tricking, can go out of control and became a mess

With that requirement, you are right, you need to put the check and reaction inside loop(). However, you can "hide" the "mechanic" inside the called function:
void setup() {
}

void loop() {
    doSomething();
}

void doSomething() {
    static bool isDone = false;
    if (!isDone && condition) {
        isDone = true;
        // ........
    }
}

A dedicated variable is simple and clear. You might choose some other type and value, depending on the actual things to do.

as far as i know i cant detect a button press outside of the loop right? when i said to execute once i mean, when press a button, it should do somenthing only once, this control of what should/was executed is a bit tricking, can go out of control and became a mess

@NeuberOliveira See my edit. It is always better to tell us your complete intent in the question. ;-)

You don't have to use their "setup" and "loop" paradigm, you know. This will work:
#include <Arduino.h>

int main ()
  {
  init ();  // initialize timers
  Serial.begin (115200);
  Serial.println ("Hello, world");
  Serial.flush (); // let serial printing finish
  }  // end of main

So, inside your code, if you want to do something once, do it once. If you want to make a loop, make one. Just like in C++. Which is what the Arduino code is.

so iam struggling why could be the "best" architecture to execute doSomething() only once

Put it in setup if you want to run with their "setup" and "loop" paradigm. It was just designed for beginners, to clarify that some things you do once, and some things you do in a loop.


text:
Line Following Robot
I have written a code and it works OK with the robot on straight, curved, intersections.   But the robot just moves forward in the current direction whenever it comes across an acute angle turn. I am attaching the code in the description ....can anyone please guide me through the necessary changes or the troubleshoot procedures?
#define left_pwm 6
#define right_pwm 3
#define left_1 5
#define left_2 7
#define right_1 4
#define right_2 2
const int ledPin1 = 9;

int left1;
int left2;
int left3;
int left4;
int right1;
int right2;
int right3;
int right4;
int lc=1;
int sc=0;

float Kp=120, Kd=130;
float error=0, P=0, D=0, PID_value=0;
float initial_motor_speed_l=100;
float initial_motor_speed_r=100;
float left_motor_speed=0, right_motor_speed=0;
float previous_error=0;

int left=0;
int right=0;

void setup()
{

  pinMode(A0,INPUT);
  pinMode(A1,INPUT);
  pinMode(A2,INPUT);
  pinMode(A3,INPUT);
  pinMode(A4,INPUT);
  pinMode(A5,INPUT);
  pinMode(11,INPUT);
  pinMode(10,INPUT);

  pinMode(right_pwm,OUTPUT);
  pinMode(right_1,OUTPUT);
  pinMode(right_2,OUTPUT);
  pinMode(left_1,OUTPUT);
  pinMode(left_2,OUTPUT);
  pinMode(left_pwm,OUTPUT);
  pinMode(ledPin1,OUTPUT);

}
void loop()
{
    line_follow();
 if (right4==lc && left==lc)
 {
  brake();
 }
 else {
  forward();
 }

    if(right3==lc && left3==lc)
  {
    digitalWrite(9,HIGH);
  }
   else
  {
    digitalWrite(9,LOW);
  }
}
void pid()
{
    if((left1==lc)&&(right1==lc))
   {
    error=0;
   }
   else if(right1==lc)
   {
    error=0.5;
   }
   else if((right1==lc)&&(right2==lc))
   {
    error=1;
   }
   else if(right2==lc)
   {
    error=1.5;
   }
   else if((right2==lc)&&(right3==lc))
   {
    error=2;
   }
   else if(right3==lc)
   {
    error=2.5;
   }
   else if((right3==lc)&&(right4==lc))
   {
    error=3;
   }
   else if(right4==lc)
   {
    error=3.5;
   }
   else if(left1==lc)
   {
    error=-0.5;
   }
   else if((left1==lc)&&(left2==lc))
   {
    error=-1;
   }
   else if(left2==lc)
   {
    error=-1.5;
   }
   else if((left2==lc)&&(left3==lc))
   {
    error=-2;
   }
   else if(left3==lc)
   {
    error=-2.5;
   }
   else if((left3==lc)&&(left4==lc))
   {
    error=-3;
   }
   else if(left4==lc)
   {
    error=-3.5;
   }

   P = error;
   D = previous_error-error;
   PID_value = (Kp*P) + (Kd*D);
   previous_error=error;
   left_motor_speed = initial_motor_speed_l+PID_value;
   right_motor_speed = initial_motor_speed_r-PID_value;
   if(left_motor_speed>=255)
   {
    left_motor_speed=255;
   }
   if(left_motor_speed<=0)
   {
    left_motor_speed=0;
   }
   if(right_motor_speed>=255)
   {
    right_motor_speed=255;
   }
   if(right_motor_speed<=0)
   {
    right_motor_speed=0;
   }
   analogWrite(left_pwm, left_motor_speed);
   analogWrite(right_pwm, right_motor_speed);
   digitalWrite(left_1,HIGH);
   digitalWrite(left_2,LOW);
   digitalWrite(right_1,LOW);
   digitalWrite(right_2,HIGH);
}
void line_follow()
{
    left4=digitalRead(A0);
    left3=digitalRead(A1);
    left2=digitalRead(A2);
    left1=digitalRead(11);
    right1=digitalRead(10);
    right2=digitalRead(A3);
    right3=digitalRead(A4);
    right4=digitalRead(A5);

    if(left4!=0)
    {
     left=0;
    }
    if(right4!=0)
    {
     right=0;
    }
    if((left4==0)&&(left3==0)&&(left2==0)&&(left1==0)&&(right1==0)&&(right2==0)&&(right3==0)&&(right4==0))
    {
      if((left>150)&&(right<150))
      {
            left1=digitalRead(11);
          right1=digitalRead(10);
          while((right1==0)&&(left1==0))
      {
        right_turn();
        left1=digitalRead(11);
            right1=digitalRead(10);
       }

      }
      else if((left<150)&&(right>150))
      {
            left1=digitalRead(11);
            right1=digitalRead(10);

            while((left1==0)&&(right1==0))
        {
         left_turn();
         left1=digitalRead(11);
             right1=digitalRead(10);
            }
          }
        }
     pid();
     left=left+1;
     right=right+1;
     if(left>20000)
     {
       left=1000;
     }
     if(right>20000)
     {
       right=1000;
     }

}
void right_turn()
{
   analogWrite(left_pwm,75);
   analogWrite(right_pwm,75);
   digitalWrite(left_1,HIGH);
   digitalWrite(left_2,LOW);
   digitalWrite(right_1,HIGH);
   digitalWrite(right_2,LOW);
}
void left_turn()
{
   analogWrite(left_pwm,75);
   analogWrite(right_pwm,75);
   digitalWrite(left_1,LOW);
   digitalWrite(left_2,HIGH);
   digitalWrite(right_1,LOW);
   digitalWrite(right_2,HIGH);
}
void brake()
{
   analogWrite(left_pwm, 0);
   analogWrite(right_pwm, 0);
   digitalWrite(left_1,HIGH);
   digitalWrite(left_2,HIGH);
   digitalWrite(right_1,HIGH);
   digitalWrite(right_2,HIGH);
}
void forward()
{
   analogWrite(left_pwm,100);
   analogWrite(right_pwm,100);
   digitalWrite(left_1,HIGH);
   digitalWrite(left_2,LOW);
   digitalWrite(right_1,LOW);
   digitalWrite(right_2,HIGH);
}

Does it detect the line at all? You may blink an LED or send debug messages (bluetooth/serial?) to indicate that the sharp turn has been seen. Or is it a software error?

Just a small comment: did you really use 8 int variables for booleans? Moreover please describe more what is this setup... What are the sensors, how are they placed, what is the control technique?

@Paul it doesn't detect the acute turn lines , rest all the lines are detected by it perfectly. I suspect its a calibration and software error but I have no idea how to fix it ..can you please guide me through.

@frarugi87 the sensor used is a 8 sensor line following array clubbed with two 500 rpm medium torque motors. I have  used tb6612fng as the motor driver and Arduino uno as the microcontroller. I am attaching the picture of my robot in the description.

@frarugi87 the  6 out of 8 int variables read analog values not digital values . So basically only two of the int variables return Booleans.

@SomitSinha the left# and right# variables are only modified with a digitalRead, so they are either HIGH or LOW..

There are some lines in pid() that will never be called.
else if (right2 == lc)
{
    error = 1.5;
}
else if ((right2 == lc) && (right3 == lc))
{
    error = 2;
}

if right2 == lc then the second else if will never be called.
You need to refactor this function, its horrid.  Firstly the right and left values for error only differ in sign, so you could right a function that took 4 values in and returned an absolute number.  If you called it for left then make the result negative.  Something like this is actually better, but will prevent the error you had.
else if (right3 == lc)
{
      if (right4 == lc)
        error = 3.0;
      else
        error = 2.5;
}
else if (right4 == lc)
{
      error = 3.5;
}


text:
Performance tuning PORTB manipulation - mask
I have the following snippet that seems to be taking a total of 6 CPU cycles per invocation.
Can I speed this up somehow? x  is a byte with the 3 lowest bits set.
#define SET_COLOR(x) PORTB = (PORTB & ~(7)) | x

@TisteAndii: Interesting suggestion, but it ends up using an identical amount of instructions. I assume the compiler is smart enough.

@tisteandii compilers are smart enough to do this for you.

@Gerben So I gathered. Dont know much about the optimizations they perform.

4 cycles:
IN Rd,PORTB
CBR Rd,7
ORI Rd,x
OUT PORTB,Rd

Translation into proper GCC inline assembly syntax is left as an exercise for the reader.

Thanks. In the end (with some proper analysis) it showed the original code was resulting in exactly 4 instructions, as well.