text:
ESP8266-01 system param error
I'm using esp8266-01 connected to arduino nano.
Every time I tried to upload code to the esp8266 chip I get this error in the serial monitor:

system param error

56 45 52 31 00 00 00 00 ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff 00
00 00 00 00 00 00 00
ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff
ff ff ff ff ff ff ff
ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff 00 00 00 00 ff ff ff ff ff
ff ff ff ff ff ff ff
ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff
ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff
ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff
ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff
ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff
ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff
ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff
ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff
ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff
ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff
ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff
ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff
ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff
ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff
ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff
ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff
ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff
ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff
ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff
ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff
ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff
ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff
ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff
ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff
ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff
ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff
ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff
ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff
ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff
ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff
ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff
ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff
ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff
ff ff ff ff
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮j
00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff

After this log the chip turns off (how this possible ?)
I'm lost in this problem please help.

This error could occur if you are using the wrong settings, like having a ESP-01 with 512K flash and have the IDE settings to 1M fflash.

wich 512K I need to use there's a 3 options.

Have you tried the 3 different options?

Yes I did try and all of the option failed.


text:
for loop iterated only once
I have written a little project, it works so far as it should but the for loop is only iterated once, then the result is displayed on the LCD.
#include <LiquidCrystal.h>
#include <stdlib.h>
const int Contrast=20;
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
const int led = A5;
const int button = A3;

void setup() {
  Serial.begin(9600);
analogWrite(6,Contrast);
lcd.begin(16, 2);

pinMode(led, OUTPUT);
digitalWrite(led,LOW);
pinMode(button, INPUT_PULLUP);
}

void loop() {

unsigned long mittelwert = 0;

for(int i=0; i<10; i++){
  unsigned long r = random(1,5000);
  unsigned long now = millis();

  digitalWrite(led,HIGH);

  while (digitalRead(button) == HIGH){
    lcd.setCursor(0,0);
    lcd.print("druecken");
  }
  mittelwert = mittelwert + millis() - now;
  digitalWrite(led, LOW);  //LED aus

}

lcd.clear();
lcd.setCursor(0,0); //setze Cursor auf 1.Stelle in der 1. Zeile
lcd.print(mittelwert/1000);
lcd.setCursor(0,1);
lcd.print("Sekunden");

delay(5000);
lcd.clear();

}

It does iterate 10 times, it's just really fast.
You probably want to wait some time to debounce the button, and then wait for the button to be released again.
I don't know why you have to keep printing to the LCD during the loop. Wouldn't printing it once before the loop be enough?
There's something wrong with your math as well. To get an average value, you add up all values, and divide by the number of values. Your variable name mittelwert is confusing, totalTime would be more appropriate.
averageTime/1000 is an integer division, so it floors the result. For example, if the average time is 999 ms, ⌊999 / 1000⌋ ==  0.
Use a floating point division if you want a decimal number.
In your setup, you don't have to use digitalWrite(led, LOW); because it is already initialized to LOW when you start the program.
const int led = LED_BUILTIN;
const int button = A3;

const int numberOfTests = 10; // repeat 10 times

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

  pinMode(led, OUTPUT);
  pinMode(button, INPUT_PULLUP);
}

void loop() {
  unsigned long totalTime = 0;
  for (int i = 0; i < numberOfTests; i++) { // repeat 10 times
    int r = random(1, 5000);
    delay(r); // wait a random number of milliseconds (between 0.001 s and 5 s)

    digitalWrite(led, HIGH); // turn LED on
    unsigned long startTime = millis();

    Serial.println("Press button");
    while (digitalRead(button) == HIGH); // wait for the button to be pressed

    totalTime += millis() - startTime;
    digitalWrite(led, LOW); // turn LED off

    delay(25); // button debounce
    while (digitalRead(button) == LOW); // wait for the button to be released
  }

  unsigned long averageTime = totalTime / numberOfTests;
  Serial.print(averageTime);
  Serial.println(" milliseconds");
  Serial.print((float)averageTime / 1000.0, 3); // print the result of the floating point division with 3 digits after the decimal point
  Serial.println(" seconds");

  delay(10000); // Wait 10 seconds before repeating
}

Your button is configured as an input with a pullup.  Therefore, except when the button is depressed to ground that input, this nested loop
while (digitalRead(button) == HIGH){
   lcd.setCursor(0,0);
   lcd.print("druecken");
}

will endlessly repeat, preventing execution from advancing.
Given that your question fails to state what you are hoping to accomplish it's not possible to make any corrective recommendations.  If you do want to make use of the button, you should probably first search and read the existing questions here having to do with debouncing.

source: Stack Exchange

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

sort: votes


text:
Hacking a Chinese Audio Selector Board: IRLib2 with Low Power Sleep Issue
I have an issue getting an arduino based hacked-board to sleep whilst performing ir remote commands properly.
What am i hacking?
Exactly this:
tl;dr it's a 4 in 1 out audio selector with motorised volume pot controllable by an IR remote. But it's got a lot of issues so i've enjoyed hacking it. I will release full details maybe with a re-done PCB layout should people wish to grab a board / diy kit, but at the moment it looks like this:

Why am i hacking it?
As is, it's closed hardware and closed software, the MCU itself is an STC15W408AS which prides itself on not being able to have its flash memory read, and believe me it does it's job well; I've clearly removed it and pulled out the SOP20 footprint to another pcb that can talk to either the original IC, or an arduino nano. the volume pot as well is too slow and requires tapping to change, the relays are not latching so consume a lot of power, the whole unit consumes too much power, and i've more of less changed the majority of the components and layout.
So what's the issue?
I got to a point where i've got quite a nice setup in terms of design, it's more of less exactly how i want it and how an audio component should perform, transparently. This is why i'm now optimising the code, with a strong emphasis on lowering the idle power consumption, given it's an always on device.
The original code can be viewed here:
I've already got it down from 150mA to ~65mA by lowing the clock to 8MHz, removing the regulator, LEDs and everything else that's unnecessary, and have disabled a few modules on the ATmega328 itself, as seen on line 88.
The aim is to have it sleep when it's not being used, but i had a few set-backs since with the intention vs implementation, when it came to the ir demodulator.
A post by Nick Gammon discussed how to put the board to sleep when it's been inactive for more than two seconds whilst using IRLib1.
So i went along and ported that code to IRLib2 shown here, then retrofitted it with my original code, essentially putting the bulk of my IR response code in the 'storeCode' function (shown in the forum post, of course i refactored to more appropriate names).
The code itself works well, but it 'soft-bricks' at rather random intervals (system freezes until manual reset), usually after a few button presses, and almost at every repeat code, [The original code behaves as intended] (i do use repeat codes to allow the user to hold a volume up/down button to continuously change it, i haven't yet ported that functionality to the new sleeping code since it sleeps after 2 seconds of holding, but have begun playing with an idea seen on line 173.
I can see the current draw with the new code is low, at about 10mA for the entire board which is more than ten times lower than before, so i'll be really happy if anyone can point me in the right direction.

Questions on SE sites need to be far more concise - try to shrink this to a piece of a code that will fit in the question itself, and still demonstrate the problem.  That's not only key to making the issue accessible for others to help, there's a good chance that the process of distilling it will lead you to discovery the issue yourself.

@ChrisStratton Thank you for your feedback, I will try to alter the code so it's just showing one example of the fault, then maybe show a before and after. The only issue is i don't know where in the code (or hardware) the fault is occuring, i will try to focus on the code that's new - that being the sleep code.

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


text:
How to connect capacitive touch sensor to Arduino?
The capacitive touch sensor has 3 pinouts: Vin, GND, and OUT and emits an active high signal when the pad is touched. I should be routing the OUT pin to any one of the digital input pins on my Arduino Micro, correct?
Also, I need to power 2 of these capacitive touch sensors along with an IMU. How do you power multiple sensors on the Arduino Micro? There is only one GND pin and one 5 V pin. I would prefer if it could be done without a breadboard as this entire setup will be placed in a stylus.

The capacitative touch sensor has 3 pinouts: Vin, GND, and OUT and emits an active high signal when the pad is touched. I should be routing the OUT pin to any one of the digital input pins on my arduino micro, correct?

Probably, yes. Without more details about what the sensor is we can't really comment.

Also, I need to power 2 of these capacitative touch sensors along with an IMU. How do you power multiple sensors on the arduino micro? There is only one GND pin and one 5 V pin. I would prefer if it could be done without a breadboard as this entire setup will be placed in a stylus.

You can plug as many (within reason) items into the +5V and GND pins as you like. You can twist wires together, use screw terminal blocks, breadboard, solder, whatever you like, to connect the wires together to a single wire that goes to the pin.


text:
Why isn't ESP8266 connecting to wifi when calling yield()?
I'm experimenting with ESP8266 and I want it to cycle through various states: LED on/off, WiFi on/off and measure the connection time, deep sleep.
I wrote the following script, using millis() to define the time intervals. I cut away the previous parts of the code to have a minimum test case.
I read that ESP8266 has the watchdog automatically on, so I used yield() when spending time waiting, instead of using an empty while loop. I didn't use delay() because it block further execution of the code, and I tend to avoid it. I know it would reset the watchdog too.
#include <ESP8266WiFi.h>

const char* ssid = "wifi";
const char* password = "pass";

const int led = 2;

void setup(void){
  unsigned long refTime;

  pinMode(led, OUTPUT);
  Serial.begin(115200);
  digitalWrite(led, 1);

  refTime = millis();
// isssue from here
  while ((millis() - refTime) < 3000) { yield(); }
// to here

  Serial.println("Connecting...");
  refTime = millis();
  WiFi.begin(ssid, password);
  Serial.println("");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  // never gets here when "issue" code enabled
  Serial.println(millis() - refTime);
  digitalWrite(led, 0);
}

void loop(void){

}

If I use the yield(), then I never get a WiFi connection (well, it happened only once, actually).
Why is yield causing issues?

why not just delay() 3 seconds?

Because this way I can add some other code to the main loop and still get the blinking on time. I don't need it in this example, but I find it often useful. Still, why isn't it working? See also https://learn.sparkfun.com/tutorials/esp8266-thing-hookup-guide/using-the-arduino-addon

the code looks alright, but maybe try a delay(1) in the loop instead of yield()...

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


text:
Soft debouncing from an interrupt during stand-by
My current setup has the arduino in 'stand-by' power saving mode, therefore i am unable to use any means of a traditional soft debouncer, such as Bounce2, as far as I know.
I went ahead and attached the buttons to pin change interrupts, since I have one button on each bank, i.e. pin 7 and pin 11.
The technique I'm using doesn't seem to be behaving since the routines are being fired too regularly (inconsistently), and at the rising edge too.
I have the pins set to use their internal pull-ups.
Using the PCI library:
void pciSetup(byte pin)
{
  *digitalPinToPCMSK(pin) |= bit (digitalPinToPCMSKbit(pin));  // enable pin
  PCIFR  |= bit (digitalPinToPCICRbit(pin)); // clear any outstanding interrupt
  PCICR  |= bit (digitalPinToPCICRbit(pin)); // enable interrupt for the

pciSetup(POWER_SWITCH);
pciSetup(SELECTOR_BTN);

// check if IR IN or Power switch
ISR (PCINT0_vect) // handle pin change interrupt for D8 to D13 here
{

  if (digitalRead(POWER_SWITCH) == LOW)
  {
    noInterrupts();
    unsigned long last_millis = millis();
    while (millis() - last_millis >= 500);
    ir_power_pressed = true;
  }
  interrupts();
}

ISR (PCINT2_vect) // handle pin change interrupt for D0 to D7
  noInterrupts();
  unsigned long last_millis = millis();
  while (millis() - last_millis >= 500);
  ir_selector_pressed = true;
  interrupts();
}

Am I doing something silly?
Update 1
As suggested in the comments, i've adjusted the code, but it still triggers on the rising edge, and a few times rapidly at the falling edge.
ISR (PCINT2_vect) // handle pin change interrupt for D0 to D7 here
{
  if (digitalRead(SELECTOR_BTN) == LOW)
  {
    noInterrupts();
    static unsigned long last_millis = millis();
    if (millis() - last_millis >= 500)
    {
      ir_selector_pressed = true;
      interrupts();
    }
  }
}

Hardware debounce with capacitor and resistor?

Make last_millis static, and replace the while loop with an if statement.

@Mike I would do that, but i've put a new MCU in a pre-existing PCB so there's not much space, it'll be my last resort.

@tttapa I did so, but it's still triggering on the rising edge, and firing very fast a few times at the falling edge.
Please see the update for the updated code.

You don't update last_millis.
Also, you don't know whether SELECTOR_BTN went from HIGH to LOW or whether another pin fired the interrupt while SELECTOR_BTN was low. Remember the previous state to solve this.
const unsigned long debounceTime = 50;
volatile bool ir_selector_pressed = false;

ISR (PCINT2_vect) { // handle pin change interrupt for D0 to D7 here
  static unsigned long previousStateChangeMillis = 0;
  static bool previousPinState = HIGH;

  bool pinState = digitalRead(SELECTOR_BTN);
  if (pinState != previousPinState) { // ignore pin changes of pins other than SELECTOR_BTN
    if (pinState == LOW) { // only falling events
      if ((millis() - previousStateChangeMillis) > debounceTime) { // debounce
        ir_selector_pressed = true;
      }
    }
    previousPinState = pinState;
    previousStateChangeMillis = millis();
  }
}

Thank you, this works very well. Is there a reason why you're not deactivating interrupts during the ISR body?

When an interrupt service routine (ISR) is called, interrupts are automatically disabled.  Interrupts are automatically enabled when returning from an ISR.  It is not necessary to explicitly enable nor disable interrupts inside of an ISR.  The processor does these two things for you. Source


text:
Arduino connection with the server failed
I am trying to connect arduino uno and ethernet shield and try to send some data to an asp.net web api application. When i upload the sketch, i get in the serial monitor connection failed.
I don't understand what's going wrong ?
Below is the code i am using
#include "cactus_io_DHT22.h"
#include <SPI.h>
#include <Ethernet.h>
#include <Client.h>

#define DHT22_PIN 2

byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xDD };

IPAddress ip(192,168,0,177);
IPAddress server(192,168,0,11);
EthernetClient client;

DHT22 dht(DHT22_PIN);
float heatindex1 =0.00;
float heatindex2 = 0.00;

void setup() {
  Ethernet.begin(mac,ip);
    delay(1000);  Serial.begin(9600);

    Serial.println("connecting...");
    if (client.connect(server, 80)) {
      Serial.println("connected :D ");
    }
  Serial.print("Arduino server IP address: ");
  Serial.println(Ethernet.localIP());
  Serial.println("DHT22 Humidity - Temperature Sensor");
  Serial.println("RH\t\tTemp (C)\tTemp (F)\tHeat Index (C)\t Heat Index
 (F)\t Max(C)\t\t Min(C)");

  dht.begin();
  dht.readHumidity();
  dht.readTemperature();

}

float max1=dht.temperature_C;
 float min1=100;

void loop() {
  dht.readHumidity();
  dht.readTemperature();
  heatindex1=dht.computeHeatIndex_C();
  heatindex2=dht.computeHeatIndex_F();

  if(dht.temperature_C>max1)
  {max1=dht.temperature_C;}
  if(dht.temperature_C<min1)
  {min1=dht.temperature_C;}

  // Check if any reads failed and exit early (to try again).
  if (isnan(dht.humidity) || isnan(dht.temperature_C)) {
    Serial.println("DHT sensor read failure!");
    return;
  }
  if (client) {

   // When a client sends a request to a webserver, that request ends with a blank line
    boolean currentLineIsBlank = true;

    Serial.println("OK"); }

  if (client.connect(server, 80)) {
    client.print("GET /api/todo?humidity=");
    client.print(dht.humidity);
    client.print("&temperature1=");
    client.print(dht.temperature_C);
    client.print("&temperature2=");
    client.print(dht.temperature_F);
    client.print("&heatindex1=");
    client.print(heatindex1);
    client.print("&heatindex2=");
    client.print(heatindex2);
    client.print("&max1=");
    client.print(max1);
    client.print("&min1=");
    client.print(min1);// And this is what we did in the testing section above. We are making a GET request just like we would from our browser but now with live data from the sensor
    client.println(" HTTP/1.1"); // Part of the GET request
    client.println("Host: 192.168.0.11"); // IMPORTANT: If you are using XAMPP you will have to find out the IP address of your computer and put it here (it is explained in previous article). If you have a web page, enter its address (ie.Host: "www.yourwebpage.com")
    client.println("Connection: close"); // Part of the GET request telling the server that we are over transmitting the message
    client.println(); // Empty line
    client.println(); // Empty line
    client.stop();    // Closing connection to server

  }

  else {
    //If Arduino can't connect to the server (your computer or web page)
    Serial.println("--> connection failed\n");
  }

   Serial.print(dht.humidity); Serial.print(" %\t\t");
  Serial.print(dht.temperature_C); Serial.print(" *C\t");
  Serial.print(dht.temperature_F); Serial.print(" *F\t");
  Serial.print(dht.computeHeatIndex_C()); Serial.print(" *C\t ");
  Serial.print(dht.computeHeatIndex_F()); Serial.print(" *F\t ");
  Serial.print(max1); Serial.print(" *C\t ");
  Serial.print(min1); Serial.println(" *C\t");

  delay(5000);
}

I don't know of this library, but you're using the connection code twice, once in the setup() and later again in the loop().
You're already checking whether the client exists:
if (client) {

Why are you asking a few lines down again to connect?
if (client.connect(server, 80)) {

My guess is, that this if()-Clause is not necessary. Or the connection in the setup() should be removed.
If this isn't the source of the error, first test whether the server on 192.168.0.11 is running and that you can connect (from a different device) to the port 80.


text:
Changes to array not reflected
Here's a simple sketch. I have an array data and a variable idx.
I'm assigning a value to each of the array element, and then sending them to my serial monitor.
volatile uint16_t data[5];
volatile uint16_t idx = 5;

void setup() {
  Serial.begin(9600);

  while (!Serial) { }
  Serial.println("\nHello!");

  data[0] = 1010;
  data[1] = 1011;
  data[2] = 1012;
  data[3] = 1013;
  data[4] = 1014;

  for(int i = 0; i< idx; ++i)
  {
    Serial.print(data[idx]);
    Serial.write(",");
  }

  while(1){  }
}

void loop() {}

When I look into my serial monitor, I get this:
Hello!
0,0,0,0,0,

Why is this happening? Did I overlook something fundamental? I'd appreciate if you could offer your thoughts on this.
I'm testing this code on Arduino Mega2560.

You got confused here:
Serial.print(data[idx]);

You're printing array slice 5 (the sixth entry in a 5 entry array) 5 times.
You probably meant to write:
Serial.print(data[i]);

To improve clarity you may want to #define it instead:
#define DATA_SIZE 5
uint16_t data[DATA_SIZE];

...

for (int i = 0; i < DATA_SIZE; i++) {
    ....
}

Or you can do it the other way round (get the size from the array):
uint16_t data[5];
#define DATA_SIZE (sizeof(data) / sizeof(data[0]))

It's easy to go code-blind ;)

Terrible. Can't believe I missed such a simple thing. Perhaps I would've noticed if I labeled 'idx' as 'last_idx' or something clearer.

For those kind of constants it's better to use a #define and use all capitals.  I'll show you an example in my answer.

It's not a constant, but an incrementing index as I populate an array. ;-)

Ah, right. Well, don't forget that the array size itself is fixed (something many users here don't realise), so you need to allocate all the memory up front.


text:
Is it possible to put ATtiny85 to sleep while using TinywireS?
I have an arduino uno as the master I2C device talking to an ATtiny85 as the slave.
What I want to do is have the Attiny85 receive a message from the UNO to tell it to power off which will then trigger a mosfet to turn all the power off to the UNO and then sleep for a period of time.
This all seems to be working fine but every now and then I seem to get a lock up where the UNO just stays on.
Is what I am doing below ok. I am worried about TinyWireS_stop_check() call and if that is going to be messed up by the fact I have delays in the loop and also the fact it goes to sleep.
Thanks
// Code for the ATtiny85
#include <powernap.h>
#include <TinyWireSlave.h>

#define I2C_SLAVE_ADDRESS 0x4 // Address of the slave
#define POWER A3
// The default buffer size, Can't recall the scope of defines right now
#ifndef TWI_RX_BUFFER_SIZE
#define TWI_RX_BUFFER_SIZE ( 16 )
#endif

uint8_t sleepInterval = 1;
bool cycleComplete = false;
bool sleepNow = false;

Napper napper;

enum InterComms
{
    IDLE = 0,
    PWR_OFF = 1,
    CALIBRATION_MODE = 2,
    SLEEP_INTERVAL = 3,
    KEEPALIVE = 4
};

char rxChrData; //Receives the data.
char rxString[12];  //Varbiable for holding one string of data.
int rxIndex = 0; //Used to index rxString.
int i = 99;
bool calibrationMode = true; //Always true when power is turned on

void requestEvent()
{
    TinyWireS.send(calibrationMode);
}

void receiveEvent(uint8_t howMany)
{
    if (TinyWireS.available()) {
        if (howMany < 1)
        {   // Sanity-check
            return;
        }
        if (howMany > TWI_RX_BUFFER_SIZE)
        {   // Also insane number
            return;
        }

        howMany--;
        uint8_t byte = TinyWireS.receive();
        switch (byte)
        {
        case PWR_OFF:
            i = 100;
            sleepNow = true;
            break;
        case CALIBRATION_MODE:
            calibrationMode = true;
            i = 110;
            break;
        case SLEEP_INTERVAL:
            i = 120;
            howMany--;
            sleepInterval = TinyWireS.receive();
            break;
        case KEEPALIVE:
            i = 130;
            measureTimer = millis();
            break;
        default:
            i = IDLE;
            break;
        }
        //Make sure buffer is emppty
        while(howMany--)
            TinyWireS.receive();
    }
}

void setup()
{
    pinMode(POWER, OUTPUT);
    analogWrite(POWER, 255);

    TinyWireS.begin(I2C_SLAVE_ADDRESS); // join i2c network

    TinyWireS.onReceive(receiveEvent); // not using this
    TinyWireS.onRequest(requestEvent);

    napper.setup();

    measureTimer = millis();
    return;
}

void loop()
{
    unsigned long currentMillis = millis();

    TinyWireS_stop_check();

    if (sleepNow)
    {
        sleepNow = false;
        tws_delay(2000);
        cycleComplete = true;
        calibrationMode = false;
        analogWrite(POWER, 0);
        tws_delay(200);
        napper.napminutes(sleepInterval);
        analogWrite(POWER, 255);
        cycleComplete = false;
        //Reset timer
        measureTimer = millis();
    }

    if ((unsigned long)(currentMillis - measureTimer) > (300000) /*&& !cycleComplete*/)
    {
        analogWrite(POWER, 0);
        tws_delay(1000);
        analogWrite(POWER, 255);
        measureTimer = millis();
    }
}

If you are trying to save power, have you considered getting rid of the ATTINY85 and transistor completely? Power the UNO directly (not using the on board regulator) and have it put itself into deep sleep (where it uses almost no power) on receipt of your message. You could also wake on receipt of of another message. All it would take is a couple free pins on the UNO, and would be a much lower power (and simpler) solution.

Thanks for the reply. The attiny powers down other modules along with the UNO so unfortunately just putting the uno to sleep wouldnt be enough. The uno will be replaced by a standalone atmega328p.

Could you have the UNO be the master controller and have it control the power to the other devices? Likely all it would take is one pin on the UNO (or bare 382) connected to a transistor.

Can you post the schematic of your circuit? Moreover if you turn off the UNO but then put power to its pins because the I2C is still on, you'll power it again...


text:
Is it possible to recover an Arduino if it does not wake up after putting it to sleep
I have an ATTiny85 controlling the power to a number of devices. When I first power on it will power the devices via a mosfet. Take the readings it needs to and then puts itself to sleep for 15 minutes then wake up and repeat.
My question is, because I am using the Watchdog timer to put it to sleep, I can't use the reset functionality of the watchdog (ie wdt_Reset). So is there anyway to detect a lock or hang if the ATTiny85 never wakes up for some reason or would I need additional hardware to check for this. If so what kind of circuit would I need.
Thanks

Do you mean: The sleeping part works fine, but you want to detect some other sort of hang and also use the watchdog timer to recover from that?

Thank you for your comment. Ideally I want to be able to recover from a hang if the chip is sleeping and if it hangs when it is running.

I don't see how it can "hang" if it is already sleeping. You could reconfigure the watchdog timer to reset the chip if it hangs prior to the part of the code which puts it to sleep.

So is there anyway to detect a lock or hang if the ATTiny85 never wakes up for some reason or would I need additional hardware to check for this. If so what kind of circuit would I need.

The whole point of the watchdog timer is to wake (or reset) the chip after a certain (short) time. You don't really need a second watchdog timer to wake the processor if the first one fails.
I made a temperature and humidity sensor which is battery powered, and which uses the watchdog timer to wake it and take readings (which sounds like what you are doing). It has been running for a number of years now (over four) and it has never "hung".

Not sure what you mean by "using the watchdog to put it to sleep". You can sleep with or without the watchdog enabled, and you can even use the watchdog to both wake you with an interrupt and also reset in case of a lockup. Check out section 8.5.2 in the datasheet...

If WDE is set, WDIE is automatically cleared by hardware when a
  time-out occurs. This is useful for keeping the Watchdog Reset
  security while using the interrupt. After the WDIE bit is cleared, the
  next time-out will generate a reset. To avoid the Watchdog Reset, WDIE
  must be set after each interrupt.


text:
Digispark / Digikeyboard code doesn't execute inside setup{}
Here's sample code to demonstrate my problem:
#include <DigiKeyboard.h>

void setup() {
  // put your setup code here, to run once:
  delay(5000);
  DigiKeyboard.print("TESTING TESTING");
  pinMode(1,OUTPUT);
  digitalWrite(1,HIGH);
}

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

My problem is that I can't get Digikeyboard.print() or other Digikeyboard commands (e.g. sendKeyStroke()) to do anything while they are located inside the setup function. The led command after the print command executes properly.
The print command will work if I place it inside the loop function. However, I want to only execute this code once.
Any assistance would be appreciated, and I would be happy to provide more information if necessary.
EDIT: I worked around this by using a if-expression inside the loop function to only run the code once. However, I am still interested in learning why my original code doesn't work.

The (hard to find) documentation on the DigiKeyboard example:
http://digistump.com/wiki/digispark/tutorials/digikeyboard
States:

It is essential that DigiKeyboard.update() is called regularly (the
  beginning of the loop is good) to maintain USB communication. Using
  DigiKeyboard.delay() will automatically spam DigiKeyboard.update()
  calls during the delay period. If your loop code is fast just using
  DigiKeyboard.delay() will be sufficient.

Without looking deeper into it, I suspect that your initial call to DigiKeyboard.print() fills a buffer and DigiKeyboard needs subsequent repeated calls in order to empty the buffer.
Does the problem still exist if you put DigiKeyboard.update() as the only statement in the loop() function?

Problem still persists. However, after reading your cited part from the documentation, I changed delay(5000) to DigiKeyboard.delay(5000), and the code works properly.

In your initial try, did you put the DigiKeyboard.update() in your run-once loop, or outside it?

For your suggestion, I used the code written in the original post, and placed DigiKeyboard.update() as the only statement in the loop() function

DigiKeyboard.delay() will allow the USB interface to enumerate, which is essential before you can communicate in any form over the interface.


text:
AT command to put the A6 GSM/GPRS into sleep / power down
The general AT command for sleep mode (for the SIMCOM GSM modules) is AT+CSCLK=1 (or AT+CSCLK=2). I have given both a shot but they don't work with the A6 module. Does anyone know of any other command that does the same? The manufacturers claim that it can function at very low current levels when in sleep. But sadly they don't mention the sleep AT command.

A6 module uses a hardware pin (INT/GPIO_1) or (EN) enable on some modules.
There is no AT command as in the SIM900.


text:
Arduino Nano v3: is it possible to PCM + AltSoftSerial?
I wonder is it possible to change PCM.h 's lib use of 16-bit timer1 to another 8-bit?
Now I'm getting
libraries\AltSoftSerial\AltSoftSerial.cpp.o (symbol from plugin): In function `AltSoftSerial::read()':

(.text+0x0): multiple definition of `__vector_11'

libraries\PCM\PCM.c.o (symbol from plugin):(.text+0x0): first defined here

collect2.exe: error: ld returned 1 exit status

exit status 1

when compiling
#include <PCM.h>
#include <AltSoftSerial.h>

An attempt to avoid XY problem: make AltSoftSerial work alongside with PCM-alike library on Arduino Nano v3 without SD.
I'm poorly familiar with timers and interrupts, so I'll be very grateful for any advice and suggestion!

It is not easy to make PCM sounds with the Arduino Uno or Nano. A few libraries can do that, but they use two timers: Timer1 and Timer2. Timer0 is already in use by Arduino. When using those libraries, the Arduino Nano is almost completely occupied to make sounds.
A software serial port also requires a lot from the Arduino Nano. The AltSoftSerial uses Timer1.
Those two will never work together. It is not possible.
For what do you need the serial port ?
Could that be done in a different way ?
The normal SoftwareSerial does not use a timer, but because it also occupies the Arduino Nano a lot, using SoftwareSerial together with a PCM sound at the same time will not work. Perhaps if you carefully design the sketch and never use them at the same time, it might work. I doubt if it will be reliable.
A better option is to swap the Arduino Nano for an Arduino Micro. Then you have a extra hardware serial port and you don't need the AltSoftSerial anymore. The library to make PCM sounds has to be compatible with the Arduino Micro. I suppose that not every PCM library is compatible.
The best option is to use a MP3 shield. Then you can send a command to play a MP3 sound. If you use a MP3 shield with a Arduino Micro or Arduino Leonardo or Arduino Mega 2560 or Arduino Zero or Arduino Due, then you have a extra hardware serial port and you don't need libraries that occupy the most of the Arduino board, and your sketch will be a normal sketch that does normal things.


text:
Simon Says Project - Can't go from random lights to user input
I'm new to using an Arduino and I am attempting the Simon Says game. Right now, I do not understand why my program will not go from activating the random lights to the user input. Currently it is flashing all the lights three times like I want it to, but then it will flash three random lights and then go straight to flashing every light, right to left (which is the indicator that the wrong button was pushed).
I am working in Tinkercad/circuits.io and have had the physical implementation looked at, and it is good. I just can't figure out the code. Anything will help, thanks!

// Defining LEDs and buttons.
int leds[] = {12, 10, 7, 4};
int buttons[] = {11, 9, 6, 3};

const int max = 40;
int lightArr[max]; // Array with full patterns of LEDs.
int currArr[max];
int gameState = 0;
int level = 1;
int count = 0; // Counter for every sequence of iterating over the
random array of ints (LEDs).
int buttonPressed = -1;
int correct = 1;

void setup() {
  pinMode(leds[0], OUTPUT);
  pinMode(leds[1], OUTPUT);
  pinMode(leds[2], OUTPUT);
  pinMode(leds[3], OUTPUT);
  pinMode(buttons[0], INPUT);
  pinMode(buttons[1], INPUT);
  pinMode(buttons[2], INPUT);
  pinMode(buttons[3], INPUT);
  randomSeed(analogRead(0));
  allOn();
}

void loop() {
  if (gameState == 0) {
    resetGame();
  } else if (gameState == 1) {
    play();
  } else if (gameState == 2) {
    gameOver();
  }
}

void resetGame() {
  if (level == 1) {
  // Setting up a sequence of random lights.
    for (int i = 0; i < 40; i++) {
      lightArr[i] = random(0,4);
    }
  }
  level = 1;
  gameState = 1;
}

void play() {
  while (correct == 1) {
    showPattern();
    int correct = userInput();
  }
}

void showPattern() {
  for (int i = 0; i < level; i++) {
    delay(500);
    digitalWrite(leds[lightArr[i]], 1);
    delay(500);
    digitalWrite(leds[lightArr[i]], 0);
    delay(500);
  }
}

int userInput() {
  for (int i = 0; i < level; i++) {
    int buttonPressed = readOneButton();
    digitalWrite(leds[buttonPressed], 1);
    delay(500);
    digitalWrite(leds[buttonPressed], 0);
    delay(500);
    if (lightArr[i] != buttonPressed) {
      // User button pressed.
      gameState = 2;
      correct = 0;
    }
  }
}

void gameOver() {
  for (int i = 0; i < 3; i++) {
    digitalWrite(leds[0], 1);
    delay(150);
    digitalWrite(leds[0], 0);
    delay(150);
    digitalWrite(leds[1], 1);
    delay(150);
    digitalWrite(leds[1], 0);
    delay(150);
    digitalWrite(leds[2], 1);
    delay(150);
    digitalWrite(leds[2], 0);
    delay(150);
    digitalWrite(leds[3], 1);
    delay(150);
    digitalWrite(leds[3], 0);
    delay(150);
  }
  gameState = 0;
}

int readOneButton() {
  if (digitalRead(buttons[0])) {
    return 0; // Button: Red
  } else if (digitalRead(buttons[1])) {
    return 1; // Button: Green
  } else if (digitalRead(buttons[2])) {
    return 2; // Button: Blue
  } else if (digitalRead(buttons[3])) {
    return 3; // Button: Yellow
  }
}

void allOn() {
  for (int i = 0; i < 3; i++) {
    digitalWrite(leds[0], 1);
    digitalWrite(leds[1], 1);
    digitalWrite(leds[2], 1);
    digitalWrite(leds[3], 1);
    delay(500);
    digitalWrite(leds[0], 0);
    digitalWrite(leds[1], 0);
    digitalWrite(leds[2], 0);
    digitalWrite(leds[3], 0);
    delay(500);
  }
}

void play() {
  while (correct == 1) {
    showPattern();
    int correct = userInput();
  }
}

Why do you create a new variable called correct and put the value form userInput in that?  Why don't you put the return from userInput into the variable named correct that you already have?  Two variables with the same name in the same scope is NEVER a good idea.  The original correct will never be changed here so this becomes an infinite loop.
Next, look at readOneButton.  It will take the Arduino just a few microseconds to run through that for loop and the whole userInput function.  Unless you are super duper fast at getting that button pressed, it is just going to decide that you didn't press any buttons.  You don't have a case in there for no button pressed, so it is going to return 0.  You should probably wait until the user presses a button before you decide whether he is right or wrong.

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


text:
Arduino mega board 5v pin does not gives 5v when 7.5v is applied through external source
I gave 7.5v to the arduino mega board through battery. 5v pin in the board gives me the same voltage as input. Earlier it was working fine now it is giving problem.Please let me know the solution as soon as possible.
Thanks and regards,
Thippeswamy

Where are you applying the power? on the barrel jack? Where are you measuring the voltage? How? (explain it as clearly as possible, example: I put two wires, one in the 5V pin and one in the GND pin, then attach the two wires to the multimeter set in DC with a 20V range and it reads 7.5V). Moreover do you have a cheap USB power bank?

If you apply 7.5V to the power barrel jack and the 5V pin is 7.5V then your Arduino board is broken. Don't connect it to a computer. Don't use it anymore.

It is highly likely that you have destroyed your Arduino. This can happen in a number of ways. Rugged Circuits has a great article on 10 ways you can destroy the Arduino.
The giveaway is that you are measuring 7.5V on the 5V pin. Most likely the voltage regulator has blown. Page 355 of the ATMega2560 datasheet says the absolute maximum voltage for the chip is 6.0V, so this also means that the microcontroller is blown as well. It is most likely unsalvageable.
Go out and buy yourself a new one. Before you turn it on, check the wiring is correct.
We have all let the magic smoke out at some point.

The link to rugged circuits is broken.

Hmm... it worked for me. https://www.rugged-circuits.com/10-ways-to-destroy-an-arduino/


text:
How do i fill the second byte?
I am using I2C communications to control a AD5694RBRUZ (http://www.analog.com/media/en/technical-documentation/data-sheets/AD5696R_5695R_5694R.pdf) with my Arduino Nano. If i enter two bytes it wil Wire.write only the first line from top to bottom. In the datasheet it is shown that you muust first fill the command byte, then the high and last the low byte. How can i fill the low byte? I have now scraped the idea to input two bytes separately and decided to input one uint16_t byte. How do i fill the low byte at the same time as the high byte, or if it possible how to input the uint16_t value?
My code is as follows:
#include <Wire.h>

#define Address 0x0D

void setup()
{
Serial.begin(9600);
Wire.begin();
AddressWrite(0x3F,0x05B0);
Serial.print ("Biti = ");
Serial.println (AddressRead(0x01));
}

void loop()
{
}

void AddressWrite (byte Naslov, uint16_t Cifra1)
{
byte Hi, Lo;
Hi = highByte(Cifra1);
Lo = lowByte(Cifra1);
Wire.beginTransmission(Address);
Wire.write(Naslov);
Wire.write(Cifra1);
Wire.endTransmission();
Serial.print ("Biti Hi = ");
Serial.println (Hi);
Serial.print ("Biti Lo = ");
Serial.println (Lo);
Serial.print ("Biti Cifra = ");
Serial.println (Cifra1);
}

byte AddressRead (byte naslov)
{
Wire.beginTransmission(Address);
Wire.write(naslov);

Wire.requestFrom(Address,2);

while(!Wire.available())
  {
  }

return Wire.read();
}

Thank you for your time and help.

You can use a number of Wire.write to write data.
The AD5694R should get three bytes and two bytes can be read from it. There is a "multiple dac readback sequence", but that is an extra.
Your AddressWrite requires an extra Wire.write.
Your AddressRead is missing a Wire.endTransmission and the while(!Wire.available()) should be removed.
void AddressWrite (byte Naslov, uint16_t Cifra1)
{
  byte Hi, Lo;
  Hi = highByte(Cifra1);
  Lo = lowByte(Cifra1);

  Wire.beginTransmission(Address);
  Wire.write(Naslov);       // command byte
  Wire.write(Hi);           // msb first
  Wire.write(Lo);           // lsb second
  Wire.endTransmission();
}

uint16_t AddressRead (byte naslov)
{
  Wire.beginTransmission(Address);
  Wire.write(naslov);       // command byte
  Wire.endTransmission(false);  // repeated start

  uint16_t hi, lo, result;
  Wire.requestFrom(Address,2);
  hi = Wire.read();
  lo = Wire.read();
  result = word(hi,lo);
  return result;
}

I have added a repeated start, because that is according to the datasheet.
Could you make the names more according to the datasheet ? For example 'command' or 'commandByte' instead of 'Naslow'. And perhaps better names for the functions, for example 'writeAD5694R' instead of 'AddressWrite'.

Thank you hor the help may good man. The names have been decided by my boss, but i will inform him of your words of wisdom. Oh and one more thing. MAY YOUR BLOOD LINE LAST A 1000 YEARS. THANK YOU MY HERO!!!


text:
Help adding 3 more on/off switches so that I can control 4 LEDs
This code is working fine to switch on/off one LED. Can anyone help me add 3 more on/off buttons so that I can control 4 LEDs?
#include <String.h>
#include <SPI.h>
#include <Ethernet.h>

byte mac[] = {
  0xDE , 0xAD , 0xBE , 0xEF , 0xFE , 0xED
};
byte ip[] = {
  192 , 168 , 2 , 20
};
byte gateway[] = {
  192 , 168 , 2 , 1
};
byte subnet[] = {
  255 , 255 , 255, 0
};
EthernetServer server(80);
String richiesta;
int pinLed = 9;

void setup() {
  Ethernet.begin(mac,ip,gateway,subnet);
  pinMode(pinLed,OUTPUT);
  Serial.begin(9600);
  richiesta = "";
}

void loop() {
  EthernetClient client = server.available();
  if(client) {
    Serial.println("Tujse na ho payega");
    while(client.connected()) {
      if(client.available()) {
        char c = client.read();
        richiesta.concat(c);
        if(c == '\n') {
          Serial.print(richiesta);
          if(richiesta.indexOf("Led=1")>0) {
            Serial.println("Pin will be high");
            digitalWrite(pinLed,HIGH);
          } else {
            Serial.println("Pin will be low");
            digitalWrite(pinLed,LOW);
          }
          client.println("HTTP/1.1 200 ok");
          client.println("Content-Type: text/html");
          client.println();
          client.println("<title> Home Automation</title>");
          client.print(" ButtonOn  Buttonoff ");
          client.stop();
          richiesta = "";
        }
      }
    }
  }
}

Just use an array, int pinMode[4] and then use loops to access it, you will be able to add as many leds as you want (pins allowing).

The html you send must be changes to add the buttons:
client.print(" Button1On  Button1off ");
client.print("Button2On  Button2off ");
client.print("Button3On  Button3off ");
client.print("Button4On  Button4off ");

Then you need to add some ifs:
  if(richiesta.indexOf("Led1=1")>0) {
    Serial.println("Pin1 will be high");
    digitalWrite(pin1Led,HIGH);
  } else if(richiesta.indexOf("Led1=0")>0){
    Serial.println("Pin1 will be low");
    digitalWrite(pin1Led,LOW);
  }
  if(richiesta.indexOf("Led2=1")>0) {
    Serial.println("Pin2 will be high");
    digitalWrite(pin2Led,HIGH);
  } else if(richiesta.indexOf("Led2=0")>0){
    Serial.println("Pin2 will be low");
    digitalWrite(pin2Led,LOW);
  }
  //etc.

you can use arrays and loops to avoid the repeated code each time.

I'm not saying that this solution is wrong, it isn't, but using loops and case statements would make this solution much better.

Use arrays, one for switches, one for leds. I don't see the code for leds in your code.
Note that you need 8 pins (4 for switches, 4 for leds).
Initialize them, e.g.
int switchPins[] = { 2, 3, 4, 5 };
Same for leds
int ledPins[] = {6, 7, 8, 9};

To access them, use a for loop:
for (int iLed = 0; iLed < 4; i++)
{
   digitalWrite(ledPins[iLed], HIGH);
}

Because 4 might be used a lot, consider them making const or define:
#define NR_OF_LEDS 4

for (int iLed = 0; iLed < NR_OF_LEDS; i++)
{
   digitalWrite(ledPins[iLed], HIGH);
}

or use the length of the array
for (int iLed = 0; iLed < sizeof(ledPins) / sizeof(int); i++)
{
   digitalWrite(ledPins[iLed], HIGH);
}

I think the switches are on the web page.

Than add 3 more switches on the web page.


text:
RadioHead library nrf24 sending and receiving struct data problem
I am using RadioHead library for the communication between nrf24l01.
I am sharing the snippet of my code below because the code is too huge.
The problem i am facing here is on the receiver side i am not be able see the data i am sending , it is showing squares and not the proper characters.
my output showing to me is :
name :?!
skill :
Sender Code :
struct DataHolder {
  String name;
  String skill;
};

DataHolder dh;

RH_NRF24 nrf24(10, 9);

//THIS METHOD I AM USING TO SEND DATA FROM SENDER NRF
void sendtonrf(){

 dh.name = "xyz";
 dh.skill = "classA";

 nrf24.send((uint8_t *)&dh, sizeof(dh));

}

receiver code:
struct DataHolder {
String name;
String skill;
};

 DataHolder dh;

 void loop{

 if (nrf24.available()) {

  uint8_t buf[RH_NRF24_MAX_MESSAGE_LEN];
  uint8_t len = sizeof(buf);

    if (nrf24.recv(buf, &len)) {

    String str1 = (((DataHolder*)buf))->name;
    String str2 = ((DataHolder*)buf)->skill;
    Serial.println("name :" + str1);
    Serial.println("skill :" + str2);

    }
 }
}

Your problem is that you are working with pointers.  You have a pointer to a block of memory with some text in it, then you take that pointer, get the address of the variable that stores it, convert it to a pointer to an 8-bit value, and send that.  Which of course won't work.
Instead you need to send the content of the memory the pointer points to:
nrf24.send((uint8_t *)strm, strlen(strm));

strm is already a pointer, you don't need to convert it to a pointer with & - that just confuses things and gives you a pointer to a pointer, which in this context is garbage.
A struct made up of String objects will not do what you think it does.  A String object does not contain the string itself. Instead it just allocates an external block of RAM (from the heap) using malloc() and holds a pointer to that memory. If you try transferring a struct which contains String objects all you will be sending is the data associated directly with those String objects, including the pointer to the string content, which is completely meaningless to the remote end.
Instead you will either have to send the strings separately along with their length and some identifier to say what the string is, or rebuild the string content into a fixed size buffer.
Personally I would use a fixed size buffer. In this method you change your struct so it contains two character arrays with a fixed size. For instance:
struct DataHolder {
    char name[10]; // Room for 9 characters + NULL
    char skill[10]; // Room for 9 characters + NULL
};

Then copy your string data into it:
struct DataHolder data;

strncpy(data.name, "Fred", 10); // Maximum 10 bytes
strncpy(data.skill, "ClassA", 10); // Again, max 10 bytes.

Now you can send the struct in its entirety:

nrf24.send((uint8_t *)&data, sizeof(struct DataHolder));

The data sent (and indeed the data held in the Arduino's RAM) will be:
Fred\0\?\?\?\?\?ClassA\0\?\?\?

Where \? represents any possible character (undefined, basically, and depends on how the variable was created - if it's global it'll be all 0, if it's on the stack then it will be whatever was in that block of memory beforehand) and \0 is the standard C end of string NULL character (ASCII 0).
For receiving it's exactly the same. Use the same struct, and go:
struct DataHolder data;

int len;
if (nrf24.recv((uint8_t *)&data, &len)) {
    // Do something with data.name and data.skill
}

Or you can use a buffer and a pointer, which may be safer since you have no chance of overrunning the buffer with a message coming in that is bigger than the data structure size:
struct DataHolder *data;
uint8_t buf[RH_NRF24_MAX_MESSAGE_LEN];

if (nrf24.recv(buf, &len)) {
    data = (struct DataHolder *)buf;
    // Do something with data->name and data->skill
}

Note the change from . to -> for the struct access since it's now a pointer.
Also note that you don't want your struct to be any bigger than your maximum packet size. To send anything bigger you will have to chunk the data up and send it in little bits.

i changed it. but still getting the garbage but different this time.

Well, you're sending a String but trying to receive a struct. That's not going to work. You have to receive what you send. If you send the content of a character array you have to receive the content of a character array. BTW, a struct of String won't contain the String content, only the objects which don't themselves contain the string content, only a pointer to it.

hi . i cannot share the full code. but i have changed the code above.
Also i really appreciate for the quick response brother.
can you check the code again.
Also i am  very very new to arduino and c,c++ , where i can learn this casting and deep things.

If you want to use pointers, structs, casting, I advice to read a book about C. It does not have to be related to Arduino.

It is not an easy topic. It took me years to master the finer points.

I can agree, I'm a software engineer and still make mistakes with them.

wow. i am feeling so lucky today,
i really appreciate for the such big help
@Majenko : made my day.
i noticed a correction in receiver code.
u have used send command instead of recv.

Well spotted. Copy-and-paste error ;)


text:
How do you post json data to HTTPS endpoint from ESP8266MOD?
Board: ESP8266MOD module from AI Thinker.
Using ArduinoHttpClient I am unable to send a post message to an Azure IOT Hub endpoint. The endpoint is listening on 443 and expects a shared key passed via a custom header.
The error I get is "Connection Timed Out"
Here is the brief sketch
char serverAddress[] = "myapp.azure-devices.net";
int port = 443;
string sig = "Azure shared access signature";
HttpClient client = HttpClient(wifiClient, serverAddress, port);
  String jsonPayload = payload; // passed into this function
  client.beginRequest();
  String contentType = "application/json";
  client.post("/devices/deviceId/messages/events?api-version=2016-02-03");
  client.sendHeader(HTTP_HEADER_CONTENT_TYPE, contentType);
  client.sendHeader("Authorization", sig);
  client.sendHeader(HTTP_HEADER_CONTENT_LENGTH, jsonPayload.length());
  client.beginBody();
  client.print(jsonPayload);
  client.endRequest();

  statusCode = client.responseStatusCode();
  response = client.responseBody();

The Status Code is -3 indicating a Timeout
I then created a simple REST API that accepts the JSON. Hosted it as an Azure website on port 80.
The board is able to connect to this HTTP endpoint
Question(s):
1. Is the board underpowered to handle HTTPS?
2. Is creating an HTTP proxy the only option?
3. Am I not using the right library?
Thanks

You are only making an HTTP request to an HTTPS server. It's not going to work.
AFAIK there is no direct support for HTTPS in the ESP8266 libraries, but there is support for SSL, and you can then manually create an HTTP request over that - as detailed in the HTTPSRequest.ino example.

Thanks for responding. When you say "You are only making an HTTP request to an HTTPS Server", do you mean the library constructs the URL as http:// even though the port specified is 443?
If I change char serverAddress[] = "myapp.azure-devices.net"; to
char serverAddress[] = "https://myapp.azure-devices.net";
it does not work either.

Yes, I mean that the library doesn't know that 443 corresponds to HTTPS, since you can run HTTP on any port, not just 80. Also it doesn't know what HTTPS is. It only talks HTTP.

Thanks to @Majenko I was able to find the right solution.
The resolution is here
Essentially, a secure WiFiClient needs to be created and used in the HttpClient constructor

Paste the HTTPS URL You are trying to connect to, in a browser
window and grab the SHA1 Fingerprint of the certificate
Create aninstance of WifiClientSecure
Call Connect on WifiClientSecure passing in the HTTPS URL and Port number
Upon successful connection, call the Verify method of WifiClientSecure to verify the fingerprint.
Pass the fingerprint from setp1 and URL to this method
Use the WifiClientSecure instance when creating an instance of
HttpClient.

Hope this helps.

Your link doesn't contain any resolution.

@m12lrpv check out sandeepmistry's comment in the thread. I added the steps in an attempt to clarify the comments.


text:
How to control a DC motor via Arduino Uno as a slave and Mega 2560 as master?
Hi I want to control a DC motor using Arduino mega2560 and Arduino Uno as a slave. Mega have to process data from an ultrasonic sensor(measuring distance) and control the motor based on the input. I tried to google but couldn't find a better tutorial or code. I'm using Adafruit motor shield l293d. I have the idea about the wiring part just need a simple code.
Eg:

 if( distance < 20) {
   //send signal to slave to run the motor forward
 }else {
   //send signal to slave to stop the motor
 }

You might look at i2c communication examples, and motor shield examples.  Note that the older L293 based shields are very lossy compared to newer v2 shields with the TB6612FNG FET driver.  There's also no apparent reason in your question to use two distinct Arduinos for this - it would be farsimpler to use the Uno for everything.

I2C, SPI, UART, ... There are tons of protocols. UART is the simplest, but you won't be able to use the USB port (and so even program it) of the UNO without detaching the MEGA. The MEGA, OTOH, has several HW UART. The I2C is a bit more complicated, but not so much. You will be able to further expand the network in the future. The SPI is the fastest, but requires more wires (4, rather than 1 or 2). The UART will enable you to send back data from the UNO to the MEGA too, while I2C and SPI will require the MEGA to ask the UNO for information if you need to transfer back some data...

Serial is quite easy to implement and use the SoftSerial.
Example code for serial can be found in the Arduino IDE under the menu:
File | Examples | 04. Communication

Serial is arguably harder to implement between programs, because you don't have the natural message delineation of something like I2C or SPI.  Software serial also complicates other processor operations.


text:
Arduino (or clone) powered with one or two AA batteries or one CR2032, but still able to give +3.3V or +5V
Are there Arduinos (or clones) that can be powered with one or two AA batteries or one CR2032 3V battery? (it would sleep 99% of the day, and only send a few bytes per day)
If so, will they also have a +3.3V or even +5V output (produced by an internal step-up chip) that can be used by another chip?
(I know it might sound like having one's cake and eat it too, but maybe it exists?)

there's a lot of 5v output boost dc-dc converters that would work a treat for AA batteries.

@dandavis do you think there are ready-to-use Arduinos or clones that would work with 2 AA and include a 3.3 V or 5V boost, out of the box?

not that i've seen, although i think they make power/battery shields that would handle it.

The modern low voltage versions of a bare ATmega chip can run from either 2xAA or a lithium coin cell - you wouldn't want to use a voltage regulator, as that is not only unnecessary but introduces losses but increases the required input voltage by its dropout meaning your circuit will fail earlier in the discharge curve that in it would without.
Bypassing the regulator on an Arduino Mini style of board is possible.  You probably do not want a board with an on-board USB-serial solution.
You'll need to make sure the clock rate is low enough for operation at the rated voltage (and for sleep efficiency).  This might involve using the fuse for the internal oscillator and ignoring a crystal/resonator that might be present, though if your board was originally intended for 3.3v operation it might be okay.
You will also need to set the brownout detector to the lowest voltage or disable it entirely - this again is in the fuses.
A boost converter to a higher voltage is possible but may not be a good idea, especially from a coin cell.  This is because to supply 1 milliamp at 5v, a boost converter must draw 2 milliamps at 2.5v - and then a bit more, to account for its own losses.  If you go shopping for a boost converter to use, make sure it has an enable, look at the quiescent power consumption when disabled and enabled without load, and look at the minimum input voltage.

Thanks @ChrisStratton. Do you think there are ready-to-use Arduinos or clones that would work with 2 AA and include a 3.3 V or 5V boost, out of the box?

Not that I'm aware of. Note that asking for recommendations of products to buy is off topic here.

Actually, I do think of one possibility - before they wisely abandoned the idea, some "drone" flight controllers were Arduino based and included a boost converter to allow 5v operation from a single lithium polymer cell.  This tends to have a higher minimum voltage than the power sources you are looking at, so you'd have to investigate the actual minimum operating voltage.  But it would be best to get the higher voltage requirements our of your design entirely - and realize that for micropower stuff you'll likely end up making your own board anyway.

Good idea! If you find a source/link about such Arduinos I'm still interested :)

That's probably too fine a distinction - besides, if someone said "yes that product exists" wouldn't your next questions be "what is it called" or "who sells it"?

I was wondering @ChrisStratton: The modern low voltage versions of a bare ATmega chip in which Arduino model is this present?

The chip would be present in any modern Arduino, but no Arduino board that I'm aware of can run off such a low voltage without being modified to remove the regulator, and probably also any USB/serial solution.


text:
How can I set up a watchdog interrupt vector timer on the Arduino Redboard/Uno?
I'm trying to set up a watchdog timer interrupt to execute a routine in the WDT_vec ISR at some recurring interval. I don't want the processor to reset, just to execute the code in the interrupt and return to "normal" operation. I have the following test jig appropriated from the 'net that claims to set that up:
#include <avr/wdt.h>

 void setup_WDT() {
      noInterrupts();  // disable all the interrupts
      MCUSR = 0;       // ensure that the reset vectors are off

      /* Disable and clear all Watchdog settings. */

      _WD_CONTROL_REG = (1 << WDCE) | (1 << WDE);
      _WD_CONTROL_REG = 0;

      /* Setup Watchdog for interrupt and not reset, and a approximately 500ms timeout */
      _WD_CONTROL_REG = (1 << WDIE) | (1 << WDP2) | (1 << WDP0);

      interrupts();  // re-enable interrupts
    }

void setup() {
  setup_WDT();
  Serial.begin(9600);
  Serial.println("Startup");
}

void loop() {
}

ISR(WDT_vec) {
  Serial.println("Watchdog Interrupt");
}

The output indicates that the processor is just resetting repeatedly and never reaching the ISR. Also I get the following warning on compilation from the IDE (Arduino 1.8.2):

warning: 'WDT_vec' appears to be a misspelled signal handler, missing
  __vector prefix [-Wmisspelled-isr]  ISR(WDT_vec) {

Be careful using a serial.print line inside of your ISR. Serial communication requires interrupts to function.

@lemontwist Thanks, seems to work well enough just to test whether the ISR is firing, or not. I wouldn't do that in actual work...

Two errors:

The watchdog interrupt vector is named WDT_vect, not WDT_vec.
The statement _WD_CONTROL_REG = 0; serves no useful purpose, and
will likely mess up with the timed sequence for changing the watchdog
setting. Just remove it.

Those changes got it working!

_WD_CONTROL_REG = 0; serves an important purpose. If the Watchdog is accidentally enabled, for example by a runaway pointer or brown-out condition, the device will be reset and the Watchdog Timer will stay enabled. If the code is not set up to handle the Watchdog, this might lead to an eternal loop of timeout resets. To avoid this situation, the application software should always clear the Watchdog System Reset Flag (WDRF) and the WDE control bit in the initialization
routine, even if the Watchdog is not in use.
if you are using it in developing a product whose programme should never freeze than this is important to remember.

this is not a good answer. in Arduino the bootloader controls the MCU some seconds after powerup or reset. correct AVR bootloaders turn off the watchdog. in setup() it is too late for most of the wdt intervals

thanks, @juraj for your kind comment.
The RESET what we percieve normally & reset occured after WDT reset are different. the hard reset runs the bootloader again but WDT reset does not even Reinitialize the RAM, running bootloader is a different issue.
Read article:
https://playground.arduino.cc/Main/ArduinoReset
& There it is written that:
Unfortunately, once the Arduino has started running a sketch, there is apparently no way to write a software function that has exactly the same effect as pushing the reset button.
I will appreciate & feel good if proved wrong & learn something new :).

the watchdog resets to bootloader

then, how can we prove that watchdog resets to the bootloader. please share the code or something authentic..!

there are projects of bootloaders for flashing over Ethernet. but to activate it, the board must be remote reset to bootloader. watchdog reset is used.https://github.com/per1234/Ariadne-Bootloader/tree/master/libraries/EthernetReset

on arduino.cc forum user flashed Atmega with esp8266 with AT firmware connected to RX/TX. From the sketch he initiated with AT commands the connection to the server and then he made a watchdog reset and the server executed the serial flashing over esp8266 in transparent mode.

the case from previous comment https://forum.arduino.cc/index.php?topic=519242.msg3545523#msg3545523

@juraj PFA the link of Atmega328pu datasheet on whose page no. 77, I found my answer as a note which you said is a bad answer..! I am little confused may be I am percieving the datasheet wrong please clarify this fact. Thanks in advance.
http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P_Datasheet.pdf

in an Arduino the clearing of the watchdog flag is a responsibility of the Arduino bootloader. so your answer is out of scope here


text:
Is it possible to use SPI on Redbot Mainboard?
My students use the Sparkfun RedBot Inventor's Kit for their final design projects. The documentation about this board isn't great. There are connectors to SPI pins (they are not soldered to headers, but they exist, see diagram below); however the bumpers and wheel encoders use pins 10 and 11, which are pins used in SPI communication.
My question is: is it possible to solder headers into that SPI socket and use SPI communication without interfering with the bumpers and wheel encoders (for example if my students want to hook up a 7-segment display to show the RedBot's speed)?

From the silkscreen on the board you appear to be either mistaken or already re-purposing signals - pins 10 and 11 are labeled as used for Servo position command PWM, not for sensor input.
Therefore, as long as you don't use those signals for servos (or ignore the labeling and use them for something else) there should be no issue using pins 11, 12, and 13 in the ordinary manner for SPI, by finding them in any available place on the board, including the 6-pin ISP connector your identify.
If you did need to use pins 11 and 12 for another purpose you could still "bit-bang" "software SPI" on any other available set of four pins.
It is also vaguely possible that you could share functions by connecting bumper switches through resistors - when the software is driving those signals as SPI outputs, it will dominate the resistors, but at other times it can re-purpose the pins as inputs to read the bumper switch state. However this may require modification of Arduino library code to accomplish repeated mode switching.

The silkscreen doesn't correspond with how the Redbot is actually used. They are not used for servos, but sensors. The motors are DC motors and are driven by the ICs on the bottom of the mainboard. Thanks for the suggestions though!

You can still use software SPI on any other available pins.


text:
MCU to switch single coil latching relay not working (attempting array with common gnd)
I have several single coil latching relays, (EC2-5SNU).
I am trying to control them by an MCU; connected directly they work fine, but I am iffy about keeping it this way so I'm trying to power them through a darlington pair array, (ULN2003).
Using the non-latching type, these work fine through the ULN2003, but attempting to interface the code below with the latching type isn't going so well and i can't figure out why:
int right = 12;
int left = 10;

void setup() {
  pinMode(right, OUTPUT);
  pinMode(left, OUTPUT);
}

void loop() {
  digitalWrite(right, HIGH);  //reset
  digitalWrite(left, LOW);
  delay(2000);
  digitalWrite(right, LOW); //set
  digitalWrite(left, HIGH);
  delay(2000);
}

I have four connected with a common pin, but to simplify i've tried and failed to have the code above work on a single relay, as shown below:

Measuring the voltages out of the MCU show the correct levels, keeping in mind the ULN2003 acts an inverter, so i've set the boolean logic accordingly.
The voltages at the output of the ULN seem to stick at 0.6V, I've tried a bunch of permutations, including having one pin (on the common pin setup) connected directly to the MCU.
Does anyone have any ideas?

You need to use an h-bridge as if you were driving a motor. For this kind of relay you need to be able to both sink and source current, which a Darlington pair cannot do, it can only sink.
I guess you may be being thrown by the symbol of an inverting buffer used in the schematic symbol for the ULN2803 in your schematic capture package. It's incorrect, since it's not an inverting buffer, it's a Darlington pair:

simulate this circuit – Schematic created using CircuitLab
As you can see, setting the input HIGH will allow the transistor pair to conduct, but setting it to LOW will stop it conducting - so the output is either connected to ground, or is floating.

Thanks, that's the lesson i learnt the hard way. FYI to anyone reading, as calculated on page 8, the relays draw 25mA so can be attached directly to the MCU.

No, they can't be directly attached to the MCU, or not safely anyway. The back EMF from the switching is liable to damage the MCU. You should separate it with a proper H-bridge.

You're right, not the safest option, but connecting them through a bridge rectifier makes it so. https://i.stack.imgur.com/Q0uOL.png

I'm sure that you've solved this, given that the post is old, but it would work if you use pull-ups on the ULN2003 outputs. However, you should wire at least two open-drain buffers of the ULN2003 to both endings of the relay coil to ensure enough current when the microcontroller pulls down.
See this 2009 EDN post:
https://www.edn.com/drive-a-single-coil-latching-relay-without-an-h-bridge-circuit/


text:
How do you make an Arduino count down timer?
I want to make a countdown timer with a LilyPad Arduino for 3 seconds with red (1 second), then orange(1 second), then yellow (1 second), then green (3 seconds), all being triggered by a button. I want to check to see if I have the right code. I am a self taught programmer, so apologies if this is a little messy. (or a lot)
#include <Adafruit_NeoPixel.h>
const int inputPin = 3;

void setup() {
  // put your setup code here, to run once:
  pinMode(inputPin, INPUT_PULLUP);
  strip.begin();
  strip.show();
}

void loop() {
  // put your main code here, to run repeatedly:
  If (digitalRead (inputPin) == LOW) {
    For (int i = 0; i < 12; I++) {
      Int pixelNum1 = 1;
      strip.setPixelColor( pixelNum1, 244, 0, 0);
      strip.show();
      delay (27);
      pixelNum1 ++;
    }

    For (int i = 0; i < 24; I++) {
      Int pixelNum2 = 1;
      strip.setPixelColor( pixelNum, 247, 247, 0)
      strip.show();
      delay (27);
      pixelNum ++;
    }

    For (int i = 0; i < 12; I++) {
      Int pixelNum3 = 1;
      strip.setPixelColor( pixelNum, 0, 247, 41)
      strip.show();
      delay (27);
      pixelNum ++;
    }
  }
}

[edit] your question. Select all the code and hit . Read editing-help for more info.

Also, If, For, and Int are not valid C++ keywords (unless you have some defines/typedefs). Please post the actual code.

Does the code do what you want it to?

variables are case sensitive so i and I are not the same variable

For (int i = 0; i < 12; I++) {
      Int pixelNum1 = 1;
      strip.setPixelColor( pixelNum1, 244, 0, 0);
      strip.show();
      delay (27);
      pixelNum1 ++;
    }

Assuming you fix the upper-case lower-case issues here first, you've still got a scope issue.  Since pixelNum1 is defined inside the for loop, it will go out of scope at the end of the for loop.  So it will be 1 on every iteration and it won't increment like you seem to think it will.
Why don't you just get rid of it altogether and use i+1 instead?

In addition to what has already been said, I would add these two
recommendations:

Do not repeat yourself. If you are repeating the same code, only with
different data, then put that data into an array and loop through it.
Define all your constants at the beginning, instead of having them as
“magic numbers” within the code itself.

Note that those are only good programming practices. They are not
critical for the functioning of your code, but they make it easier to
read and to maintain.
Applying those recommendations, here is my throw at this. Note that the
Color struct is only meant to make it easier to define colors as
constants:
#include <Adafruit_NeoPixel.h>

struct Color {
    uint8_t r, g, b;
};

const uint8_t  INPUT_PIN  =  3;
const uint8_t  STRIP_PIN  =  6;
const int      LED_COUNT  = 12;
const uint32_t LED_DELAY  = 27;
const int      NUM_COLORS =  4;
const Color    COLORS[NUM_COLORS] = {
                   {244,   0,  0},  // red
                   {247, 122,  0},  // orange
                   {247, 247,  0},  // yellow
                   {  0, 247, 41}   // green
               };

Adafruit_NeoPixel strip(LED_COUNT, STRIP_PIN);

void setup()
{
    pinMode(INPUT_PIN, INPUT_PULLUP);
    strip.begin();
    strip.show();
}

void loop()
{
    // Nothing to do until the button is pressed.
    if (digitalRead(INPUT_PIN) == HIGH)
        return;

    // Cycle through the colors.
    for (int i = 0; i < NUM_COLORS; i++) {
        Color color = COLORS[i];
        for (int led = 0; led < LED_COUNT; led++) {
            strip.setPixelColor(led, color.r, color.g, color.b);
            strip.show();
            delay(LED_DELAY);
        }
    }

    // Switch off.
    strip.clear();
    strip.show();
}


text:
Analog pins as output by using digitalWrite
I am making a triac-controlled light dimmer. To control the triac I want to use pins A4 or A5, because others are occupied. I have tried the following functions and methods, but nothing seems to put the pins to HIGH state:
 1. pinMode(A4, OUTPUT);
    digitalWrite(A4, HIGH);
 2. pinMode(18,OUTPUT);
    digitalWrite(18,HIGH);
 3. DDRC |= (1 << DDC4);
    PORTC |= (1 << PC4);

I have tried the same things with A5 and other A# pins to no avail. The only pin that works is A0. Only when the triac is connected to it, the lamp lights on.
Is this a valid way to set analog pins?
void setup(){
  pinMode(A4, OUTPUT);
}

void loop(){
  digitalWrite(A4, HIGH);
}

Edit: My code was quite messy, it appears that some other functions prevented from using pins A4 or A5. It is working now.
It was the DS1307Emulator library. After initialization I had to use DS1307Emulator.busDisconnect();
Didn't know it uses I2C.

I feel that the code is ok.  How can you be sure that the pin is not in high state? Only with the triac? Can you post the schematic here?

Do you use a Atmega328p chip and not an Arduino board ? Did you forget to apply 5V to all the VCC and AVCC pins ? and GND to all the GND pins ? If you have done everything right, then the Atmega32p is broken.

@fra
Actually the pin is in high state when measuring with voltmeter, but when it is connected to the triac, the lamp does not light up, however, it does when it is connected to A0.

@Jot Arduino pro mini is used. All pins are connected. By changing Arduinos results are the same.

@flowian very strange. Do you use an optocoupler between the arduino and the triac? Can you post the schematic?

Can you post the sketch as well ? Are you sure you are using A4 and A5 and not A6 and A7 ? And you don't use I2C ? You could make a small test sketch to test those pins. The problem is in the part that you have not showed us yet.

@fra, there is optocoupler. I posted the schematic. All this works with regular digital pins 2-11 and A0 though.

@Jot I2C is not used. The sketch that is used is in the OP

Got it to work, it appears that there were some things in code which prevented A4 and A5 to set output as high. I am still not sure what it was.

@flowian Can you add "
Edit: My code was quite messy, it appears that some other functions prevented from using pins A4 or A5. It is working now.
It was the DS1307Emulator library. After initialization I had to use DS1307Emulator.busDisconnect();
Didn't know it uses I2C." as a answer and close this question?

My code was quite messy, it appears that some other functions prevented from using pins A4 or A5. It is working now.
    It was the DS1307Emulator library. After initialization I had to use DS1307Emulator.busDisconnect();
    Didn't know it uses I2C.

DS1307 is an I2C device indeed. When I saw you were using A4/A5, an I2C issue was my first thought... Why are you using this library? Do you have an RTC connected to your board?

@dda RTC is not connected to the board, the library is used for internal real-time keeping, which is then displayed on LCD. So there is no need of external RTC module.


text:
Is there a way to shift through sensors
We are doing a project and have to use around 25 temperature sensors. Is there a way to shift through them on one Arduino similar to using a shift-register?
It is a set of analog sensors in a fridge.

Think about using a pair of 16-channel multiplexers. Sparkfun have a board that might be suitable.

What kind of sensors? analog, digital, ...? How far are the sensors? 1mm from each other, 10cm, 2km, ...?

@sempaiscuba, why not flesh out that comment and add it as an answer.

sorry for not being specific enough.
it is a set of analog sensors in a fridge.

@sempaiscuba
thanks for the answer. we will probably go with that.

@sa_leinad Done. :)

As I mentioned in the comments, one way to do this is to use a multiplexer.
You haven't said which temperature sensors you are planning to use, so I'll illustrate this example using the TMP36 Analogue temperature sensor.
Now, if you were using just one of these, the connection would be trivial:

But you want more sensors than available pins. That's where the multiplexer comes in.
I'm going to illustrate this using 16 sensors and the Sparkfun 16-channel multiplexer breakout board which is based on the 74HC4067 multiplexer. For 25 sensors, you could use a 32-channel multiplexer (like the Analogue Devices ADG732, for example), or just combine two 16-channel multiplexers (which is probably cheaper, but requires a little more care in the wiring).
[If your soldering skills are OK, I wouldn't even bother with the Sparkfun breakout board myself. It's pretty simple to connect something like this on protoboard, or make your own PCB.]
The 16 sensors are connected to pins Y0 - Y15 on the 74HC4067 (pins C0 - C15 on the Sparkfun board). Take care to note which sensor is connected to which pin!
With 16 inputs, we need 4 bits to address them. The address pins are labelled S0 - S3. The Sparkfun datasheet for their breakout board includes a Truth Table mapping the addresses to the inputs:

The input from the selected device becomes the output from the multiplexer (pin Z on the 74HC4067; the SIG pin on the Sparkfun breakout board).
The diagram below shows one way of connecting 16 TMP36 analogue temperature sensors to an Arduino Nano using the Sparkfun breakout board:

Note the mapping chosen for the address pins:

D5 -> S0
D4 -> S1
D3 -> S2
D2 -> S3

This makes the drawing layout simpler, but may not be the most intuitive mapping when you come to write your code. My advice is to assign meaningful labels to the pin-mappings in your code, and document that decision with comments! (I'm sure that I'm probably preaching to the choir here, but this may help someone reading this in the future to avoid some of the pitfalls.)
Now, you cycle through a loop:
while true {
    increment the address to be written to pins D5-D2 (note the order)
    read the input on A0
    <do whatever you need to do with the temperature reading>
}

And Robert is the male relative of your choice.

Have you looked at OneWire temperature sensors? You connect them to a bus IC and the bus IC to your Mcu. This allows you to multiplex many sensors.
You can also forego the master bus IC and just bit bang using a GPIO pin. The Arduino OneWire library uses this approach.
You can learn a lot about from this one wire sensors tutorial.

Another way to do this is with a series of actual shift registers (74HC595 or similar, daisy-chained.)
The shift register outputs drive a transistor. Each transistor has its collector connected to the temperature sensor, and the emitters are all collected into a single Arduino input. Depending on the number you shift into the shift register, you can pick any of the temperature sensors you want to query.

The LED in this simplified schematic actually represents the Arduino input pin. Shift a 2 into the register to query T1; 4 to query T2; 8 to query T3, and so on.

If you are using analog sensors, consider using the CD4051B analog multiplexer (link to data sheet). It's great for expanding analog I/O pins.


text:
Getting no such directory file error when compiling
I recently got my wifi module and connected it to my Uno. I am now trying to send a http request. I have the code that comes with the esp8266wifi library in which it demonstrates and gives an example on how to send a http request. This is the code:
CODE.
I am getting the following error
    Arduino: 1.8.4 (Windows 8.1), Board: "Arduino/Genuino Uno"

In file included from C:\Users\Yasmeen\Documents\Arduino\libraries\ESP8266WiFi\src/ESP8266WiFi.h:33:0,

                 from C:\Users\Yasmeen\AppData\Local\Temp\arduino_modified_sketch_200757\HTTPSRequest.ino:14:

C:\Users\Yasmeen\Documents\Arduino\libraries\ESP8266WiFi\src/ESP8266WiFiType.h:26:19: fatal error: queue.h: No such file or directory

 #include <queue.h>

                   ^

compilation terminated.

exit status 1
Error compiling for board Arduino/Genuino Uno.

Obviously it seems to be an file path error but I'm not sure why. I've imported the library through the Arduino IDE.. But maybe the way I aquired the library was wrong? What I did was download the esp8266wifi folder (here) and zipped the file and imported it.. is that okay to do?

The ESP8266WiFi library is for programming the ESP8266 directly. You are trying to compile source code for the ESP8266 for the Arduino UNO, that obviously won't work.
A Beginner's Guide to the ESP8266


text:
Connecting multiple load cells to the same microcontroller
This is my first post and I am a little bit confused about one thing.
I would need to do the following project:
have about 5-6 load cells to be connected to a microcontroller.
I am not sure if there is a way to connect multiple load cells to the same arduino.
I would need each load cell to act individually, so I would need an individual result from all each load cell.
I believe I would need to connect 1 load cell to 1 load cell amp and then connect the load cell amp to the Arduino and repeat this process 5-6 times (for each load cell that I need)
I'm not sure if this is possible using one Arduino or I would need 1 Arduino for each individual load cell.
The main idea of the project is to have a load cell to be placed under different kitchen supplies (1 load cell to continuously check the weight of Flower, another one to check for bread, another to check for paprika, and so on)
After this is read from the sensors, I need to write the weight of each item in a table / DB every 30 minutes.
Also, if this can be done with another board, like a microcontroller (Raspberry Pi) I'm open to that.

All you need is the following :

Arduino (Mega, if you need alot of inputs.)
Load Cell Amplifier
Load Cells (I recommend only using four wire cells)
Resistors (Only if you are connecting one cell to one amplifier)

If you are using only one load cell per "Scale" , you would connect it as you say correctly. One load cell to each load cell amplifier and then to the Arduino.
Yes, a single Arduino can in theory take as many scales as the number of Digital inputs you have can provide. You can use the Analog inputs as well but from my experience I would recommend you only use the Digital inputs. You can just share the power and ground sources.
Usually each Load Cell Amplifier will need to use two(2) Digital inputs.
If you want to use multiple load cells together (to improve accuracy) to act as a single scale, you would connect them together in what they call a Quarter, Half or Full Bridge wiring configuration depending on how many you would like working together.
You can write to a DB if you want sure.
What I personally like to do is send the readings to the cloud using dweet.io or ThingSpeak. ThingSpeak.com would probably be best for you.
I usually use the NodeMCU arduino boards that have WiFi built in. They are cheap and work great.
I hope this helps.

Thanks a lot for your answer, it helps very much. About sharing the same power (5v) and grounding, I just simply connect multiple wires to the same pin on the board? Won't that overload the pin, if for example, I connect 5 "energy draining" load cell amps to the same 5v pin?

Well in general , load cell amplifiers such as HX711 , based on their spec sheets, only draw 1.5ma . On an Arduino board, the maximum current draw per pin is 40ma for I/O pins and 200ma for VCC & GND . If you are using an Arduino UNO or something like that I recommend attaching a Proto shield on top of it which would give you some flexibility for your wiring and vcc / gnd sources.

I had a similar project awhile back that involved multiple flex sensors. I ultimately had to use multiple op amps to boost each signal from the flex sensors.
Some IC contain multiple op-amps though which will lessen your circuit footprint.
Each output of the op amp was run to a separate ADC channels on an Arduino. Depending on your Arduino you should have 8 (mini) - 16 (mega) analog pins to read your sensors.

You can use multiplexers to multiplex the loadcells and you can select the loadcells using only less selector pins


text:
Floating-point without FPU
Since a Floating Point Unit (FPU) is not present in Arduino Uno, I wanted to know how float operations are performed. If it is simulated as integer operations, I want to know how exactly the simulation is done.

Floating point operations are implemented (rather than “simulated”) in software. You can disassemble any program using floats and see how it's done.

Implementing floating point in software would mean breaking the number into its mantissa and exponent components (represented as integers) and performing arithmetic on them. Is this correct?

Of course. The splitting is done by the function __fp_split3.

As I said in my comment, all float operations are implemented in
software. As a simple test, I compiled the following program:
volatile float x, y, z;

int main(void)
{
    z = x + y;
    return 0;
}

The compiler translated the sum operation into a call to __addsf3.
This function extends its arguments to flt40_t format (non-standard 40
bits float), calls __addsf3x to do the 40-bit addition, then calls
__fp_round to convert the result into the standard float format.
__addsf3x also makes a few library calls of its own. In the end, the
addition pulled the following functions into the compiled program:
__subsf3, __addsf3, __addsf3x, __fp_inf, __fp_nan,
__fp_pscA, __fp_pscB, __fp_round, __fp_split3, __fp_splitA,
__fp_zero and __fp_szero.
All these functions are provided by the avr-libc. You can find them in
the libm/fplib directory. See for example the files:

addsf3.S
addsf3x.S
fp_round.S

software emulation. The float is decomposed into sign, exponent and mantissa and then integer operations are used to do the actual math.
Addition and subtraction means shifting the mantissas to a common magnitude, adding/subtracting them and then checking the highest set bit for the new exponent.
Multiplication means adding the exponents and multiplying the mantissas. Division is subtracting.


text:
Recognize Morse-like code words
In a line there're voltage levels representing words of dots and dashes. In particular, the device is intended to raise an output each time a given pattern of five short/long signals (say 1s and 2s durations, respectively) is recognized (and restart if nothing comes in for a given time). A sort of Morse code recognizer (Arduino Uno preferred, but others are also OK) would be a good starting point. Any hint is welcome, I'm new in this community.

Use a GPIO of an Arduino and check (at the speed you need) the HIGH/LOW state.
Depending on the speed at which is sent, you can check the dots and dashes being sent, e.g. by keeping a timer since the last change checking if it is a short or long 'HIGH'.
You have to sample often enough to check if there is a drop (between dots/dashes).

Is Arduino Uno the best selection to implement this device? Since it's going to be embedded (the smallest, the better), I would like to know the best fitting option.

There are many microcontrollers. Arduino is not the smallest or cheapest, but probably the easiest to program, especially if you are new to microcontrollers). There are smaller, like Arduino micro/nano etc, which also are not difficult to program.
There are also other (small) microcontrollers, even cheaper, but mostly those have a more steep learning curve, like PIC, STM8/32.