text:
Dice is not showing the correct numbers
I've made a dice roller (to make it easier to roll the dice) using an Arduino UNO and an LCD keypad shield but I can't get the correct numbers (1, 6 (7)) to show up, I've tried using int, float and everything in between. the buttons on the shield are connected to A0, can someone help me please?
#include <LiquidCrystal.h>
// select the pins used on the LCD panel
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

#include "DFRkeypad.h"
String line2 = "Press Select to roll"; // Scrolling line

// just some reference flags
//int stringStart, stringStop = 0;
//int scrollCursor = screenWidth;

// define some values used by the panel and buttons
int lcd_key     = 0;
int adc_key_in  = 0;
#define btnRIGHT  0
#define btnUP     1
#define btnDOWN   2
#define btnLEFT   3
#define btnSELECT 4
#define btnNONE   5

// read the buttons
int read_LCD_buttons()
{
  adc_key_in = analogRead(0);      // read the value from the sensor

  // For V1.0 comment the other threshold and use the one below:

  if (adc_key_in > 1000) return btnNONE; // We make this the 1st option
  for speed reasons since it will be the most likely result
  // For V1.1 us this threshold
  if (adc_key_in < 50)   return btnRIGHT;
  if (adc_key_in < 195)  return btnUP;
  if (adc_key_in < 380)  return btnDOWN;
  if (adc_key_in < 555)  return btnLEFT;
  if (adc_key_in < 790)  return btnSELECT;

  return btnNONE;  // when all others fail, return this...
}

void setup() {
  randomSeed(analogRead(1));
  lcd.begin(16, 2);              // start the library
  lcd.setCursor(3, 0);
  lcd.print ("Catan Dice");
  lcd.setCursor(0, 1);

  // while(line2)
  //
  // lcd.print(line2);
  // break;
}

void loop() {

  //Dice
  byte DiceOne = random(1, 7);
  byte DiceTwo = random(1, 7);

  //local varables
  int buttonState = read_LCD_buttons(); // read the button pad
  int lastButtonState = btnNONE; // previous state of the button

  // the following variables are unsigned longs because the time, measured in
  // milliseconds, will quickly become a bigger number than can be stored in an int.
  unsigned long lastDebounceTime = 0;  // the last time the output pin was toggled
  unsigned long debounceDelay = 50;    // the debounce time; increase if the output flickers

  switch (buttonState)
  {
    case btnSELECT:
      lcd.clear();
      //Row, Colum
      lcd.setCursor (0, 4);
      lcd.print(DiceOne);
      lcd.setCursor (1, 4);
      lcd.print(DiceTwo);
      break;
  }

  DELAY(100)

  // read the state of the switch into a local variable:
  int reading = digitalRead(buttonState);

  // check to see if you just pressed the button
  // (i.e. the input went from LOW to HIGH), and you've waited long enough
  // since the last press to ignore any noise:

  // If the switch changed, due to noise or pressing:
  if (reading != lastButtonState) {
    // reset the debouncing timer
    lastDebounceTime = millis();
  }

  if ((millis() - lastDebounceTime) > debounceDelay) {
    // whatever the reading is at, it's been there for longer than the
    debounce
    // delay, so take it as the actual current state:

    // if the button state has changed:
    if (reading != buttonState) {
      buttonState = reading;
    }
  }

UPDATE, i got it working now

what do you mean by can't get correct numbers to show up?

The question is unclear, what do you mean do not get correct number? The official Arduino documentation recommends using a "long" type variable https://www.arduino.cc/reference/en/language/functions/random-numbers/random/

i want 1 through 6 to show up insted of larger numbers

What "larger numbers" are you getting?

42, 43,62 and 55, i want it to generate numbers 1,2,3,4,5,6 at random when i push the button

You are calling setCursor() with:
//Row, Colum
lcd.setCursor (0, 4);
lcd.print(DiceOne);
lcd.setCursor (1, 4);
lcd.print(DiceTwo);

While your comment notes the order is Row, Column, there appear to be several LiquidCrystal libraries floating about, some of which use Column, Row order in the SetCursor() function. The official Arduino library source indicates the col, row order.
You are writing both values on row 4 (even though that doesn't exist on your display), and in columns 0 and 1, thus you are correctly computing the Dice values, but they are being written with no gap between.

Yes I'm writing them in the same row but different columns and I'll be away from my dice for a few days, we'll continue this when I get back, sound good?

You noted that you got it working. If you share the results, it may help others in the future who are having a possibly similar question.

all i did was switched the numbers in the
lcd.Setcusor from lcd.setCursor (0, 4);
lcd.print(DiceOne);
lcd.setCursor (1, 4);
lcd.print(DiceTwo);                                                                                to lcd.setCursor (4, 0);
lcd.print(DiceOne);
lcd.setCursor (4, 1);
lcd.print(DiceTwo);

It seems that your issue is probably connected with LCD timing. Sending data to LCD requires a precise timings, and the onboard chip of the LCD module very much like a few milliseconds of time to finish processing the data sent, instead you pass the entire clear and draw command each loop cycle.
I used the default Tinkercad LCD display example.
This code works fine:
#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
  randomSeed(analogRead(1));
  lcd.begin(16, 2);
  lcd.setCursor(3, 0);
  lcd.print ("Catan Dice");
  lcd.setCursor(0, 1);
}

void loop() {
  byte DiceOne = random(1, 7);
  byte DiceTwo = random(1, 7);

  lcd.clear();
  lcd.setCursor (0, 4);
  lcd.print(DiceOne);
  lcd.setCursor (1, 4);
  lcd.print(DiceTwo);
  delay(100);
}

but as soon as I remove the delay(100)
void loop() {
  byte DiceOne = random(1, 7);
  byte DiceTwo = random(1, 7);

  lcd.clear();
  lcd.setCursor (0, 4);
  lcd.print(DiceOne);
  lcd.setCursor (1, 4);
  lcd.print(DiceTwo);
  //delay(100);
}

Weird things start to show on the LCD.

Try rewriting your code that the commands are sent to LCD only once per button press.

I believe the serial LCD driver in the LiquidCrystal library is synchronous and won't return until it has finished sending the commands to display your desired characters.  The digital interface should not get confused even without delays.

My guess is that without the delay, the LCD updates so fast that the liquid crystals don't finish shifting to display a given pixel pattern before the next number is sent. (LCD displays have crystals suspended in a liquid, and when you change the pixel pattern, it takes significant time for the crystals to shift into the new patterns. If you watch the change with a high speed camera, the pixels seem to "ooze" into the new pattern.)

i have it so it generates the numbers upon a push of the right button


text:
I want to print onto serial monitor when it's detected the value change
This code is measuring distance from object by using the Ultrasonic Sensor and print onto serial monitor.
However, serial monitor constantly output values.
I want to print only one time if detected value not change.
and serial monitor print again only when detected value change.
and The above condition keeps repeating.
How can i change the code?
int distance ;
int trig = 3;
int echo = 2;

void setup()
{
  Serial.begin(9600);
  pinMode(trig, OUTPUT);
  pinMode(echo, INPUT);
}

void loop()
{
  digitalWrite(trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(trig, LOW);
  distance = pulseIn(echo, HIGH) / 58;
  Serial.println(distance);
}

the loop() block keeps repeating over and over ... think about how you would remember what the value of "distance" was the last time around

Store the distance in another variable, like int distanceValue; and then you can do this: if(distance != distanceValue){Serial.println(distance); distanceValue = distance;}.

int distance;
int last_distance; // <== To hold the value from the previous pass
int trig = 3;
int echo = 2;

void setup()
{
  Serial.begin(9600);
  pinMode(trig, OUTPUT);
  pinMode(echo, INPUT);
}

void loop()
{
  digitalWrite(trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(trig, LOW);
  distance = pulseIn(echo, HIGH) / 58;
  if (distance != last_distance) {  // <== Check if new distance is different
    Serial.println(distance);       //     Print only if the values are different
  }
  last_distance = distance;         // <== Store this loop's distance for next round
}

I recommend AGAINST providing fully functional code for beginner questions. When you do that newbies tend to copy/paste the solution without understanding it. It's more work for both you and the OP if you tell them how to solve it and then support them as they work through it, but ultimately the questioner learns more that way.

source: Stack Exchange

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

sort: votes


text:
No Device Found On Bare-bones SAM3X Chip
0
I've been trying to make my own board with a SAM3X and W5500 (Arduino Ethernet Shield) on it with those two chips connected via SPI.
From the Arduino Due Board, most of the stuff, we don't need. So obviously, almost everything went off. Particularly, I remove the power switching circuits since we won't be varying power anyway. The native USB Programming also went off as well as the Programming port circuit.
I've only left headers so I can connect the 16U2 (with 16MHz crystal) circuit externally. Headers are VIN (5V from USB), RX (from a level shifter), TX and Ground. I'd not included the reset signal so from the 16U2 pin, I connected a 1kohm resistor (R23) to the reset line in my board.
The 16U2 I have externally is programmed with the new file in
https://github.com/arduino/ArduinoCore-sam/tree/master/firmwares/atmega16u2
When I connect the 16U2 circuit to my USB Port, I was able to see it as the programming port correctly. However, when I try uploading a sketch to the board (sample blink), the IDE says No Device Found on the COM port.
I've tried using bossac and modifying the COM port thru command prompt but I still get the same result.
I've checked the SAM3X checklist and it says there that for SAM-BA to boot, I only need to have the correct supplies and the 12 MHz Crystal Oscillator. I've checked everything using multitester and all the supplies are in the correct voltage. I've checked the crystal using an oscilloscope and I can see that it outputs the expected waveform.
I've also checked the TX and RX line from the 16U2. There are data being send by the 16U2 but the SAM3X is not responding.
One thing I notice is that the 32 kHz crystal is not working. But from what I've read in these forum, that is not powered by the SAM3X until the slow clock oscillator is enabled to be externally sourced.
The last thing I think that I've done different is that I'd connected the VBUS pin to the 3.3V supply rail where it was directly connected to the USB power. The reason I've done this is because I'm not using USB anyway.
Also, the data lines for the native USB, I've terminated them using 1MHz resistors to ground just so they're not left flaoting.
Are these (VBUS and datalines) causing my SAM3X to not reply and properly work so sketches can be uploaded? Would want to confirm VBUS first before destroying the trace in my board as I'm afraid I might fry the SAM3X chip with 5V.
Are there other things I've done wrong?

SAM3X doesn't have Ethernet as MCU peripheral?

It has. Just that in our development, we'd used W5500 and opt not to change that part.

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


text:
Reconnect to a com port
I want my Arduino to log data while connected to a battery.
After few hours, I need to reconnect the Arduino via COM port to a PC and read the logged data.
The com port will not reconnect. This is part of the code I am using. It works if I am not disconnecting the com port. Any idea how to fix this?
if (digitalRead(buttonPin) == HIGH) {
    LoopIndex=0;
    Serial.begin(9600);
    Serial.println("Start printing");
    while (LoopIndex < MinCounter) {
        // print the results to the serial monitor:
        Serial.print("Time = ");
        Serial.print(PressurePerMin[LoopIndex++]);
        Serial.print("\t sensor = ");
        Serial.println(PressurePerMin[LoopIndex++]);
    }
 }

Serial.begin(9600); does not "connect". Actually, plugging in/out the USB cable from an Arduino Uno does not affect the Serial port directly. Connecting to the COM port on the PC side might however reset the arduino. (There are several ways to avoid this)

Your snippet does not show the problem you describe. A minimal but complete test environment is highly recommended.


text:
Arduino IDE gives error a1 is not declared
#include <LiquidCrystal.h>
LiquidCrystal lcd(A0,A1,A2,A3,A4,A5);

in this code the error given by IDE is 'A1' was not declared in this scope.
So whats the problem please help

Is that your whole code?

in Arduino IDE? with Nano selected in Tools menu?

Try using the GPIO numbers LiquidCrystal lcd(14,15,16,17,18,19); rather than the analog pin numbers. https://i2.wp.com/christianto.tjahyadi.com/wp-content/uploads/2014/11/nano.jpg has the pinout diagram.


text:
Can you connect BH1790GLC and TMP117 sensors to an Arduino board?
I would like to use those two components for an upcoming project :

BH1790GLC heart rate sensor
TMP117 temperature sensor

I especially like the fact that they’re so tiny.
Could I connect them directly to an Arduino board or some other well-known microcontroller ?

Both of those sensors use I2C to communicate, so yes you can connect them to Arduino. but you gonna need a library and if the library doesn't exist you probably have lots of coding ahead of you. good luck. TMP117 library

Actually there are Arduino libraries available online for both of these sensors, which is one of the reasons why I chose them

Yes, the sensors will work with microcontroller(s). What you look for is the interface they use. In this case it is I2C interface. Be careful thou: You have to check voltage levels your microcontroller works with and selected sensor voltage level. Some of the Arduino works with 5V levels and some sensors may accept max of 3.3V or 4.5V on I2C pins. This is why you would need either:

Choose 3V powered microcontroller
Use 5V powered microcontroller (like Arduino Uno) and voltage level converter

Also worth to note that these two sensors would need some additional circuitry to work with your microcontroller. Before any commitment I would try to find a development board (a board with mentioned circuitry with easy to acces pins for providing necessary signals/voltages/ground/etc).
Good luck!


text:
mBlock update firmware
Total Arduino newbie here.
I was playing with mBlocks, with the Arduino Uno extension enabled. That extension offers you to "update firmware" which I accidentally did. What exactly is this firmware? Is it just a compiled sketch or does it alter stuff like bootloader or reside permanently in the memory?

Usually by Firmware we understand "a program that was prepared by company that produced the hardware and that is necessary for that hardware to work correctly". I suppose that developers of mBlock are smart enough not to allow people to "brick" their Arduino's. I suspect that ether you updated your bootloader (it's also a firmware) to latest version or simply nothing happened. In both cases your device should be operational. Burning a bootloader onto an Arduino is not as hard as it seems so even if you broke something you should be able to fix it.

Hm, I thought one couldn't modify the bootloader by just merely connecting it to the PC via a USB cable as you need a special programming device or additionally manipulate the onboard fuses for that? So, other than that, nothing could possibly have been modified, and the board can still be fully used in other projects?


text:
ESP8266 seems to be bricked , how to recover?
In a part of my sketch I put by mistake
pinMode(7,INPUT_PULLUP);
Which is dedicated pin for external flash chip (gpio7/SDIO_DATA_0/SPI_MISO) that not supposed to use for sketch. after uploading sketch now ESP is not responding to any further programming.
Could be Flash chip got corrupted due to the above mistakes?. Is it possible to recover?
I already bricked two of my modules with same sketch before identifying above mistake.
Sketch where working normal on Modules without above code.
When I connect to module with boad-rate 74880 chip returns
 ets Jan  8 2013,rst cause:2, boot mode:(3,7)
please check what happens when I try to upload the code upload error

No, you have not bricked your ESP8266 by turning on GPIO7's pullup.  All that will do is provide a weak pullup on the MISO line of the flash chip, which itself will have no effect - the flash chip's SPI Data Out pin will be able to easily override that weak pullup.
You can remove the flash chip and replace it with a completely blank brand new flash chip with nothing on it and still upload new code. There is nothing in the flash chip that the ESP8266 relies on to operate.
The boot sequence of the ESP8266 is as follows:
- Start executing the bootloader from the built-in ROM
  - Read the GPIO pins to determine code execution source
  - If flash is selected then initialize flash chip and read from address 0
    - Code on flash examines partition table to find code entry point
    - Jump to code entry point
  - If UART is selected then initialize UART
    - Wait for commands over the UART and respond accordingly

The startup code (boot stage 0) is in ROM. It's impossible to "brick" that.  All that is in the flash is the code that tells the ESP8266 how to find the user's code, and that gets flashed to the chip every time you reprogram it.
You can think of it like BIOS boot on a PC.  In the ROM is the BIOS that tells the CPU how to read from the hard drive. Then at the start of the hard drive is the code that tells the CPU how to load the operating system.  The hard drive doesn't come with that code on it - you install that along with the operating system. But the motherboard has the BIOS built into ROM which tells it how to get going and read that boot sector.
However it is possible to destroy an ESP8266 by connecting the wrong things up to it in the wrong way.  It is also possible to destroy some USB chips (the CH340G in particular) by wiring things up wrong.
So chances are that if you have bricked your ESP8266 it has nothing to do with your program and everything to do with what you have wired to it.

@sim son and Majenko Thanks for your efforts to address my issue. Now it is clear for me that unless I damage the chip itself it will be recoverable even some thing goes wrong and corrupted the flash.
Yesterday night as a further attempt I restarted my PC hoping that the serial driver or hardware did something faulty, now I'm able to flash my modules again !!. I'm still puzzled and looking into what did the problem actually.

No, your sketch can not brick the device in that way. It's the bootloader that decides after a reset/power-up whether the esp has to accept a firmware (flash button is pressed) or has to run the uploaded sketch. At that point, nothing of your sketch has yet been executed and gpios have their default configuration, which is input anyway.
Also, when a pullup is in charge, one can still apply a logic level to the respective pin. The gpio then won't see any effect from the pullup.

On your first paragraph it is clear that bootloader will decide about pin status during process of sketch upload. But what happens once it has been downloaded and the sketch executed which in turn manipulates the flash memory control gpio and corrupts the bootloader on flash memory like some memory area written with '1' (eg: 1111 1111).
I have no other clue since I bricked my second Lolin board also with the same sketch before identifying the above mistake (gpio7 as input)

@saif The bootloader is in ROM, not flash. You cannot corrupt it. It is that ROM bootloader that looks at the IO pins and decides where to "boot" from (one option of which is "Through the UART for programming").  It is possible to remove the flash chip and replace it with a brand new completely blank one and still program it. There must be something else fundamentally wrong with what you are doing.


text:
How to manage button state
Extreme Newbie here ...I am using an Arduino Uno and a PCA9685 16 Ch. Driver board to control servos using a push button and LED feedback.  When I pust the button, the servo move but when I release the button, the servo move back to it original position.  What I would like to have happen is that when I push the button once, the servo moves and holds its position.  When I push the button again, return to its starting position.  Thanks in advance for the assistance.
Here is the sketch:
#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>

Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();

int buttonPin0 = 2;   // Can add as many buttons as needed
int ledPin0C = 3;     // C designates Closed position of turnout
int ledPin0T = 4;     // T designates Thrown position of turnout
int buttonState0 = 0;

int buttonPin1 = 5;
int ledPin1C = 6;
int ledPin1T = 7;
int buttonState1 = 0;

void setup() {
    Serial.begin(9600);
    Serial.println("pca9685_TurnoutFinal!");
    pwm.begin();
    pwm.setPWMFreq(60);
    delay(30);

    pinMode(ledPin0C, OUTPUT);
    pinMode(ledPin0T, OUTPUT);
    pinMode(buttonPin0, INPUT);
    pinMode(ledPin1C, OUTPUT);
    pinMode(ledPin1T, OUTPUT);
    pinMode(buttonPin1, INPUT);
}

void loop() {
    ///////////
    buttonState0 = digitalRead(buttonPin0);
    if (buttonState0 == HIGH) {
        pwm.setPWM(0, 0, 370);
        digitalWrite(ledPin0T, LOW);
        digitalWrite(ledPin0C, HIGH);
    }
    else {
        pwm.setPWM(0, 0, 285);
        digitalWrite(ledPin0C, LOW);
        digitalWrite(ledPin0T, HIGH);
    }
    //////////
    buttonState1 = digitalRead(buttonPin1);
    if (buttonState1 == HIGH) {
        pwm.setPWM(1, 0, 370);
        digitalWrite(ledPin1T, LOW);
        digitalWrite(ledPin1C, HIGH);
    }
    else  {
        pwm.setPWM(1, 0, 285);
        digitalWrite(ledPin1C, LOW);
        digitalWrite(ledPin1T, HIGH);
    }
    //////////
}

The code in loop is always running so when you release the button, the code sees this as digitalRead(btn) = HIGH.
You need a state variable to know where the motor is currently.  Something like this:
boolean state = false;
int oldButton = HIGH;

void loop() {
    delay(20); // enough to debounce very most buttons

    int newButton = digitalRead(buttonPin0);
    if (oldButton == HIGH && newButton == LOW) { // only when button changes from "released" to "pressed"
        state = !state;

        // tell the servo where to go
        if (state) {
            pwm.setPWM(0, 0, 370);
        } else {
            pwm.setPWM(0, 0, 285);
        }
    }
    oldButton = newButton;
}

Thank you ... I will try to figure out where it goes.

Also take button bouncing into account.

Michel would it be possible for you to elaborate on button bouncing?

Disregard Michel ... I did a little reading and now know what it is ... not sure if it will affect my project but again thank you for making me aware of it.


text:
How to use more than 2 I2S microphones on MKR Zero?
I am trying to build a portable device that can record from at least 3 microphones. I had a look and saw I2S is good for audio so I bought an Arduino MKR Zero to read them with. I was wondering how to record from multiple microphones on the I2S bus at once. The only thing that I have been able to do is record stereo from two mics but I need the microphone readings to be mono. I am using the Adafruit I2S MEMS Microphone SPH0645LM4H.

By definition, the I2S bus only allows up to 2 channels to be transmitted at the same time.  Here is a quote from the Details section of the Wikipedia's I2S page:

The word select clock lets the device know whether channel 0 or
  channel 1 is currently being sent, because I²S allows two channels to
  be sent on the same data line.

This is further illustrated in Figure 8 / Page 6 of the Knowles SPH0645LM4H data specifications.  In this figure we see where 2 SPH0645LM4H microphones are configured (ground or Vcc to the SEL pin 2) such that they can be multiplexed onto the I2S bus by the I2S bus master.


text:
Can 1 wiegand output for 2 controllers?
recently I have this project which needs to read 2 wiegand signal using Arduino Mega 2560.
I have an access control device which will output wiegand signal once the user is allow to enter, and there's a RFID reader which will transmit the card no in wiegand signal to my access control device.
So I need to get card no from the RFID reader and also from the Access control device, so I connect them like the attachment given, using a library here: ( https://github.com/ugge75/Wiegand-V3-Library-for-all-Arduino ), everything works fine at first, but once a while, I can't read signal from the RFID Reader, and sometimes I can. Could anyone let me know why is this happening?

In the readers there is switch transistors that pull down voltage provided from controllers, in other words is shutting signal to the ground. In my practice i tested many solutions and simplest one is with diodes from each controller D0 D1 in direction to the reader. In that case is not crossing voltage from controllers. For 2 controllers and 1 reader you need 4 diodes - 2 on each line.
Controller 1 - D0 --> anode on Diode 1 --> cathode to common connection for line D0
Controller 1 - D1 --> anode on Diode 2 --> cathode to common connection for line D1
Controller 2 - D0 --> anode on Diode 3 --> cathode to common connection for line D0
Controller 2 - D1 --> anode on Diode 4 --> cathode to common connection for line D1
Common connection D0 --> reader D0
Common connection D1 --> reader D1
Works fine up to 20 meters since every diode makes voltage drop.
For diodes 1N4001/4007 works fine.
Noise is not a problem, this is very slow connection with 5v amplitude.

There is missing information.  Assuming a 5V Arduino and all D0s and D1s swing from 5V to 0V as the Wiegand protocol defines.  This despite the 12V power supply in the question's diagram.
Examining the driver code on GitHub, we see it's falling edge interrupt driven.  So any noise when the line is expected to be at a steady 5V will cause the driver to run.  And there are a number of locations in the code where data is dumped because it is considered bad. It appears that any unexpected noise during a valid signal will cause missing data.
Consider the possibility of noise affecting the RFID data.  Shorten the length of the RFID's Wiegand cable in an effort to improve the RFID reliability.
Consider re-writing the driver code to improve noise rejection.  Currently, it appears the driver code will accept any falling edge as valid data to be processed.  Alternatively, the driver code could detect a falling edge then sample the same input a fixed interval of time later.  A valid signal is assumed to last longer than noise.  Therefor any falling edge interrupt followed by a high sample can assumed to be noise and ignored / not-processed.

Thanks for your reply, I'm using same source of power 12V for both the access control device and Arduino (VIN), may I know if it's really the problem of rejection, could I use this modue to improve: https://www.rfideas.com/products/converters/wiegand-splitter
Is it the problem of me using the 1 output of wiegand for 2 controllers?

I don't think you need to split the signal. And the way you power devices sounds fine. Just make sure you are using an Arduino that is running at 5V (not 3.3V) internally. When researching this question, it was difficult to find Wiegand circuit examples. That is why I left that part of the answer brief. It was frustrating that the data rate or termination resistances are not talked about more. I really think you are picking up noise which causes the missing data. And I really think the code could be improved upon as described in my answer. Do test short cables to verify if noise is a problem.


text:
Where is tcp.h?
This is for an esp8266 project that uses EasyAsyncTCP. In EasyAsyncTCP.cpp they   #include "lwip/tcp.h". But I can't figure out where that file is. I've found a tcp.h in the following directories on my c drive:

c:\Program Files (x86)\Arduino\hardware\arduino\avr\firmwares\wifishield\wifiHD\src\SOFTWARE_FRAMEWORK\SERVICES\LWIP\lwip-1.3.2\src\include\lwip
c:\Program Files (x86)\Arduino\libraries\WiFi\extras\wifiHD\src\SOFTWARE_FRAMEWORK\SERVICES\LWIP\lwip-1.3.2\src\include\lwip
c:\Users\me\AppData\Local\Arduino15\packages\esp32\hardware\esp32\1.0.2\tools\sdk\include\lwip\lwip
c:\Users\me\AppData\Local\Arduino15\packages\esp32\hardware\esp32\1.0.2\tools\sdk\include\lwip\lwip\prot
c:\Users\me\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.2\tools\sdk\lwip\include\lwip
c:\Users\me\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.2\tools\sdk\lwip2\include\lwip
c:\Users\me\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.2\tools\sdk\lwip2\include\lwip\prot

but so far I've only tested the first two. I've tested them by either straight up deleting the directory and using the #error got here directive. No matter what I do my project builds. So I think I must either have the wrong file or it doesn't rebuild the entire thing.
How can I determine which tcp.h my program is including?

do you see the esp8266 folders. one of them it is. LWIP version is selected in Tools menu

yes! thank you.

While this isn't the right way of doing it I'm sharing the way that I figured it out.
Step1:
cd c:\
dir tcp.h /s
c:\Program Files (x86)\Arduino\hardware\arduino\avr\firmwares\wifishield\wifiHD\src\SOFTWARE_FRAMEWORK\SERVICES\LWIP\lwip-1.3.2\src\include\lwip
c:\Program Files (x86)\Arduino\libraries\WiFi\extras\wifiHD\src\SOFTWARE_FRAMEWORK\SERVICES\LWIP\lwip-1.3.2\src\include\lwip
c:\c:\Users\Me\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.2\tools\sdk\lwip2\include\lwip\protUsers\Me\AppData\Local\Arduino15\packages\esp32\hardware\esp32\1.0.2\tools\sdk\include\lwip\lwip
c:\Users\Me\AppData\Local\Arduino15\packages\esp32\hardware\esp32\1.0.2\tools\sdk\include\lwip\lwip\prot
c:\Users\Me\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.2\tools\sdk\lwip\include\lwip
c:\Users\Me\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.2\tools\sdk\lwip2\include\lwip
Step2:
I went through and tested each one. It was... C:\Users\Me\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.2\tools\sdk\lwip2\include\lwip\tcp.h


text:
How fast is flash reading compared to SRAM?
I'm working on a project that will eventually scale to 864 LEDs on WS2815 LED strips (three rows of 288 LEDs). I'm currently running it on an Arduino Uno with a single test strip of 144 LEDs.
FastLED stores its data in 3-byte structs, so I obviously cannot simply hold all of the data in SRAM and work with it directly (at least not without upgrading to a controller with more memory). I'm going to use a Raspberry Pi to send the Arduino data, one section at a time. To further save memory, I want to implement an RGB color lookup table in flash, then instead of
CRGB pixels[PIXEL_COUNT];

taking up over 2KiB of memory 800+ values, or
CRGB pixels[PIXEL_BUFFER_COUNT];

with a buffer of 288 RGB values consuming most of my working memory (864 bytes), I would have
CRGB *pixels[PIXEL_BUFFER_COUNT];

Where each pointer would reference a location in a PROGMEM 256-entry table of CRGB values. This is a more manageable 576 bytes in SRAM.
I realize FastLED does not work this way. There's a  lot of work ahead of me if I do this, but before I get started, my question:

Will I run into issues with reading the actual data from flash memory while sending to the LED strips? As currently implemented in FastLED, RGB data is in SRAM, but each pointer dereference will require reading from flash. Is the subsequent delay enough that it will cause an issue with sending data to the strips?

On an Arduino Uno, or other AVR-based Arduino, reading a byte from RAM
takes 2 CPU cycles. Reading it from flash takes 3 cycles. So flash vs.
RAM is not such a high overhead. However, if you store a LUT in flash,
and the color indexes in RAM, then each pixel would require:

2 cycles for reading the color index from RAM
3 × 3 cycles for reading the RGB values from flash.

That's a total of 11 cycles, vs. 6 cycles it would take to read the RGB
values from RAM, as is done in the stock FastLED library.
It sounds bad, but it could be that the precise timing is not such a big
issue. I don't know the WS2815, but if they are similar to the WS2812,
then you don't need to be anywhere as precise with the timings as the
datasheet suggests. C.f. the blog post NeoPixels Revealed: How to (not
need to) generate precisely timed signals.
Edit: there will be a few more cycles needed for the pointer
arithmetic. I estimate something around 7 cycles. At low level, the code
for getting a color should look roughly like this:
uint8_t *pixel = ...;
uint8_t index = *pixel;            // read from RAM: 2 cycles
uint8_t pgm_p;                     // pointer to flash
pgm_p = &pgm_lut + 3 * index;      // pointer arithmetic: ≥ 7 cycles
struct CRGB color;
color.r = pgm_read_byte(pgm_p++);  // read from flash: 3 cycles
color.g = pgm_read_byte(pgm_p++);  // read from flash: 3 cycles
color.b = pgm_read_byte(pgm_p);    // read from flash: 3 cycles

The WS2815 is basically a 12V WS2812B. Thank you for the detailed breakdown.

Your edit is also very helpful. With the NeoPixels Revealed article and some buffering, I might be able to pull this off. Since my LEDs will be displaying a gradient of the palette to an extent, I can read the nearest CRGB values into SRAM and just move the pointer ahead as needed when I find an index I don't have locally.

Because flash is on a different data bus to SRAM there is extra shuffling around needed internally in the CPU to get the data to where it needs to be.  This uses a special "LPM" instruction (Load Program Memory), which takes an extra clock cycle to operate. On top of that the only way of using it is through the Z "index" register - there's no kind of immediate or offset loads.  So it can be a little clunky to work with.  All that is masked by the provided C functions, of course.
The upshot is that yes, it is somewhat slower reading from flash.  How much slower, though, is impossible to say.  Best case scenario: each access will take 1 more clock cycle. Worst case: well, it's impossible to know.  That somewhat depends on both how you implement your reading of the CLUT and how the compiler batches things together.
I would suggest that you will need to employ the use of an oscilloscope and just try it out.  Implement your changes, then manually adjust the delays and timing to get the output waveform just right.

Exactly what I needed to know. Thanks.

Can always use a '1284P based board with 16K SRAM, lots of room to store patterns, etc. for quick access.

@CrossRoads I’ve looked at larger boards but am enjoying the challenge of this. Storing my data in 32bit blocks is also (probably, I have not benchmarked) speeding things up.


text:
How to set "IPAddress ip" using a variable?
Created a "variableInput.h" file for editing variables in one place; instead of searching multiple lines of code, to find lines needing editing.
//   variableInput.h
//
//   User defineable variables; one location for editing variables

// Replace with your network details
#define host = "esp32"
#define ssid = "YOURSSID"
#define password = "YOURPASSWORD"

//NTP Time Servers
#define udpAddress1 = "198.50.238.156"  //NTP Time server
#define udpAddress2 = "132.163.96.3"  //NTP Time server

//publicIP accessiable over Internet with Port Forwarding; know the risks!!!
//WAN IP Address.  Or use LAN IP Address --same as server ip; no Internet access.
#define publicIP = "YOURPUBLICIP"
#define LISTEN_PORT  8030  //default listening Port 80 for "GET" requests.

//Graphing requires "FREE" "ThingSpeak.com" account..
//Enter "ThingSpeak.com" data here....
//iframes of graphed data are available from "ThingSpeak.com."
#define myChannelNumber = 123456
#define myWriteAPIKey = "E12345"

//FTP Credentials
#define ftpUser = "FTPUSER"
#define ftpPassword = "FTPPASSWORD"

//setting the addresses
#define ip(10,0,0,200);
#define gateway(10,0,0,1);
#define subnet(255, 255, 255, 0);
#define dns(10,0,0,1);

//Restricted access to client ip list.
#define Restricted = "/ANYNAME"

//OTA Credentials
//default username: USERNAME
//default password: PASSWORD

// "setting the addresses" is the part that I do not understand.

Segment of related code from "wifi_Start" function:
//setting the addresses
IPAddress ip;
IPAddress gateway;
IPAddress subnet;
IPAddress dns;

Is there a solution?
William

it is unclear what you are asking ... you included a badly formatted code listing, but it is unclear how it relates to your question ... please explain in more detail what you are trying to do ... also, please format the code listing

constants .h in my project https://github.com/jandrassy/Regulator/blob/master/Regulator/consts.h

you should not use #define for constants. #defines are directives for the preprocessor

You are not using #define correctly. The syntax is #define {name}  {value}.  There is no = between name and value so for your IP address lines you want #define myIp ip(192, 168, 1, 11)

Ended up with "#define ip {10,0,0,11 }" in the "variableInput.h" file and "IPAddress ip;" in the wifi-Start function.  Appreciate the help!

Here's how I do it (for an Arduino that connects to my Mosquitto server) using wired ethernet (WiFi works the same way):
#include <Ethernet.h>
#include <PubSubClient.h>
EthernetClient ethClient;
PubSubClient client(ethClient);

byte mac[]    = {
  0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe
};
IPAddress ip(192, 168, 1, 75);
IPAddress server(192, 168, 1, 11);
void setup() {

  client.setServer(server, 1883);
  client.setCallback(callback);

  Ethernet.begin(mac, ip);

}

I understand this is the usual, useage; I need to have variable for "192.168.1.11.".

You can build an IPAddress(0,0,0,0) struct and assign a value to it. You'll need to take a dotted decimal address vvv.xxx.yyy.zzz and multiply vvv256^3+xxx256^2+yyy256^1+zzz256^0 to get the value to assign.


text:
I don't know how to do the code for an rtc controlling a relay
I'm doing a project for my brother witch is an automatic watering thing,
it's all working fine but I just don't know how to repeat the code to make the relay say come on for 5min at 0900 than 5min at 1200 and also 5min at 1700.
how do I do this, I'm not very good at this so I need clear instructions or someone to write it.
pls help.
thank you, James.
here is the code I need to be repeated to meet what I need done, basically I just need the relay to trigger every 4h for 5min. its on an rtc on an Arduino UNO.
#include <DS3231.h>

int Relay = 4;

DS3231  rtc(SDA, SCL);
Time t;

const int OnHour = 19; //SET TIME TO ON RELAY (24 HOUR FORMAT)
const int OnMin = 55;
const int OffHour = 19; //SET TIME TO OFF RELAY
const int OffMin = 56;

void setup() {
  Serial.begin(115200);
  rtc.begin();
  pinMode(Relay, OUTPUT);
  digitalWrite(Relay, LOW);
}

void loop() {
  t = rtc.getTime();
  Serial.print(t.hour);
  Serial.print(" hour(s), ");
  Serial.print(t.min);
  Serial.print(" minute(s)");
  Serial.println(" ");
  delay (1000);

  if(t.hour == OnHour && t.min == OnMin){
    digitalWrite(Relay,HIGH);
    Serial.println("LIGHT ON");
    }

    else if(t.hour == OffHour && t.min == OffMin){
      digitalWrite(Relay,LOW);
      Serial.println("LIGHT OFF");
    }
}

why don't you simply add two more if blocks?

no matching function for call to 'DS3231::DS3231(const uint8_t&, const uint8_t&)
please help me out

You will most likely find nobody here, who will write the code for you, since this is not a free code writing service. But I will suggest a good way.

I just need the relay to trigger every 4h for 5min

The phrase "every x hours" screams for using the modulo operator %. Modulo gives you the rest value of an integer division. See these values:
0 % 4 = 0
1 % 4 = 1
2 % 4 = 2
3 % 4 = 3
4 % 4 = 0
5 % 4 = 1
...
7 % 4 = 3
8 % 4 = 0

You see, the modulo 4 operation gives you zero every 4 hours starting with midnight. So make an if statement based on that
if(hour % 4 == 0 && min == 0)

to switch on and
if(hour % 4 == 0 && min == 5)

to switch off. Just change your code in this way and you are done.

Thankyou, I will give it a try tomorrow and see how it goes  then let you know.

Also were do I put all the 0%4 things?

In your code you already have if statements for turning the relay on and off. And I included corresponding if statements using the modulo operator in my answer. These if statements can be used to turn the relay on and off. It is your part, to write that in your code. If something in my answer is not clear, please specify what, so that I can better explain how this works.

I understand were the statements go but I have no idea were to put the list of values, as I sayed I'm pretty dumb when it comes to this so I'm sorry if I'm being a bit stubborn. I'm young and don't have a lot of knowledge on how to write this. Your hell so far is very much appreciated.

The list of values doesn't belong in your code. I've just included it to show  how the modulo operator works

'hour' was not declared in this scope

As I said, I will not write the code for you. You have to take the if statements from my answer and change them for your case. Try to understand your old code. Then try to understand, what the principle is, that I described. Then you should be able to change your code accordingly. But you need to learn and understand. You can also do some basic tutorials with your Arduino to learn the absolute basics. And learning C is also good.


text:
ESP32 playing wav sounds distorted or too fast (but not all wav's)
I am building a sound project on an ESP 32 via I2S  using an example from:
https://github.com/nhatuan84/esp32-i2s-sdcard-wav-player
It works fine with the example wav file t.wav posted in the repository.
But when I try to use a custom wav which I exported from audacity it sounds distorted  and/or too slow/fast (it sounds fine when I play it within audacity).
This is an example that is totaly distorted when playing from the esp with I2S:
badly sounding wav
While it sounds fine when playing from audacity.
I tried different settings in audacity exporting 16 bit, 32 bit. 44100 Hz, 11025.
Any hints or tips what I could try or am doing wrong?
Thx!
Jeroen

The provided file from the repo is 16 bit mono with 11025 Hz. Have you tried these settings?

@crisl yes I did (at least I think I did but I am no expert on audacity...), it is this file: link 11025 file. This file is not distorted but plays too fast ( I think twice the speed)

@jstola. Not sure I understand what you propose. I created the wav file from https://text-to-speech-demo.ng.bluemix.net/. Then I opened it in audacity, converted it to several different sample frequencies exported the file to 16 bit pcm wav and put it on the sd. I just tried to copy the file back from the pc and play them and that works fine

sounds like maybe the data rate is too high, or low, depending on your perspective. i see the github file as a mono 32bit float at 11k. chances are, you just need to keep trying permutations of settings until you nail it.

I know this is an old question, but I ran into the same issue and spent days trying to figure it out, so I hope this answer can save another poor soul from that:
The Problem
For reference, I have an ESP32 (HUZZAH32 from Adafruit) hooked up to a breakout board that uses a PCM5102a chip as an external DAC. I would set the sample rate to 44.1khz but it seemed my song, which I confirmed had accurate data, would play at double speed. Lowering the sample rate to 22.05khz made it play at the correct speed, but quality seemed reduced.
The Root Cause
The issue was that my .channel_format value was set to I2S_CHANNEL_FMT_RIGHT_LEFT, however my data was mixed to mono in Audacity. This problem may exhibit itself differently depending on how you push bytes via I2S, but for me, this meant double speed. This is because the protocol was reading every 2 samples (which should be separate) as the left/right channels. Effectively, this meant that it was skipping every other sample, which doubled the playback speed.
Code Snippets
My i2s_config_t code:
#define DMA_BUFFER_COUNT 8
#define DMA_BUFFER_LENGTH 1024

i2s_config_t i2s_config = {
    .mode = I2S_MODE_MASTER | I2S_MODE_TX,
    .sample_rate = 44100,
    .bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT,
    .channel_format = I2S_CHANNEL_FMT_ONLY_LEFT, // this was causing double speed due to being I2S_CHANNEL_FMT_RIGHT_LEFT
    .communication_format = (i2s_comm_format_t) (I2S_COMM_FORMAT_I2S | I2S_COMM_FORMAT_I2S_MSB),
    .tx_desc_auto_clear = true,
    .dma_buf_count = DMA_BUFFER_COUNT,
    .dma_buf_len = DMA_BUFFER_LENGTH,
    .use_apll = false,
    .intr_alloc_flags = 0
};

My code for sending bytes to the external DAC (which is its own task):
(rx_buffer and readPointer here are part of a ring buffer that I streamed in over wifi on a separate task, please only use as reference and substitute for your own sound data)
int FRAMES_TO_SEND = 1024;
int32_t frames[FRAMES_TO_SEND];

for (int i = 0; i < FRAMES_TO_SEND; i++) {
    // copy into i2s buffer
    int32_t sample = (int32_t)rx_buffer[readPointer];

    // write bytes to the i2s peripheral
    esp_err_t err = i2s_write(i2s_num, (char *) &sample,
        sizeof(int32_t), &bytesWritten, 100);

    if(err != ESP_OK) {
        printf("ESP32 i2s Errorcode %i", err);
    }

    readPointer++;
    if (readPointer == TOTAL_BUFFER_SIZE) {
        readPointer = 0;
    }
}

Hopefully this helps out some of you, or at least get you on track to the solution. Unfortunately, the I2S protocol on the ESP32 is not very well documented so there's a lot of trial and error to be had. Keep at it!


text:
MKR GSM 1400 Works only when connected to computer
My MKR GSM 1400 works fine when connected to a computer (powered USB) and after opening a serial connection to it.  It does not when I plug it into a power supply. My power supply is a 5V 3A with a USB adapter.
void setup() {
  // put your setup code here, to run once:
  //...
  while (!Serial);
  //...
}

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

What means that it does not work? What does actually happen? Also show us your code and your circuit. Currently you don't give us enough information to help you.

@chrisl The sketch doesn't run = It does not work. Is my power supply sufficient? Is it ok to power it through the USB connection or do I need to power it somewhere else? I don't think my code is the issue.

do you have while (!Serial); in the sketch?

How do you see, that it doesn't run? As asked: please say, what actually happens instead of what doesn't happen.

I’ll upload a minimal sketch later. I have an Xbee connected. The sketch makes an http request. If it were running I’d see data in the database. If I connect to the computer, it runs. I do use Serial to let me know what’s going on while connected to the computer.

It was the while(!serial)

I've posted a question with more details since I am having the same issue at: https://arduino.stackexchange.com/questions/77324/arduino-mkr-gsm-1400-fails-to-start-up-without-serial-monitor

If your sketch on an Arduino with native USB doesn't run if not connected to USB, always first check if you didn't forget to disable a dependence on Serial.  A common error is a while (!Serial) {} endless loop in setup().


text:
Neopixel LED control without library
I plan to use a single address LED (SK6812 or WS2812) to indicate controller status.
The goal is to include colors: Green / Blue / Red.
There are libraries like Neopixel, Fastled, and others, but I don’t have much space to include them in the program.
How difficult is it to implement color inclusion without the use of libraries and interrupts?

You could try the code from this article. It does not use any library for controlling any number of Neopixels. Only code that controls the timing

Why not use a regular RGB-led? Connect the led to 3 output pins (with resistors), and use digitalWrite to turn the colors on and off.

not difficult ... check the datasheet for required data signal timing

Again, to develop a solution we need to know more.  The tricky part of controlling the WS2812 is developing a signal that the WS2812 expects.  If you are just changing colors, say, no faster than once a second & you can wait and do nothing else with the processor during the fraction of a second it takes to talk to the WS2812, then, as @jsotola said, read the WS2812 data sheet and develop the correct serial signal.  You could further simplify it by only requiring the WS2812 to light up Red, Green, Blue or Off.  Then you would only need to send out 1 of 4 fixed patterns.


text:
ESP8266 using deep sleep, http connection fails after 360 successful connections
I am building a monitoring device for my chicken stable. Therefore, I want to measure temperature, humidity, and a reed switch every minute and send the results to a server, then sleep 60s and repeat. It works fine for a couple of hours, but then fails continously. I can see the esp connecting successfully to the access point (in the AP web interface), but the http request gives me a -1 (connection refused) status code on the esp (and doesn't reach the server. Can anyone tell me how to debug this further? Here's the ESP code:
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>

// WiFi credentials.
const char* WIFI_SSID = "myssid";
const char* WIFI_PASS = "mypass";

Adafruit_BME280 bme; // I2C

void connect() {

  unsigned long wifiConnectStart = millis();

  // Connect to Wifi.
  //Serial.println();
  //Serial.println();
  //Serial.print("Connecting to ");
  //Serial.println(WIFI_SSID);

  WiFi.disconnect();
  delay(10);

  WiFi.persistent(false);
  WiFi.mode(WIFI_OFF);
  WiFi.mode(WIFI_STA);

  WiFi.begin(WIFI_SSID, WIFI_PASS);

  while (WiFi.status() != WL_CONNECTED) {
    // Check to see if
    if (WiFi.status() == WL_CONNECT_FAILED) {
      //Serial.println("Failed to connect to WiFi. Please verify credentials: ");
      delay(10000);
    }

    delay(20);
    //Serial.print(".");
    // Only try for 15 seconds.
    if (millis() - wifiConnectStart > 15000) {
      //Serial.println("Failed to connect to WiFi");
      return;
    }
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  unsigned long timePassed = millis()-wifiConnectStart;
  //Serial.println("Connecting time in milliseconds: ");
  //Serial.println(timePassed);
}

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

  Serial.println("Device Started");
  Serial.println("-------------------------------------");
  Serial.println("Running Deep Sleep Firmware!");
  Serial.println("-------------------------------------");

  connect();

  if (!bme.begin())
  {
    Serial.println("Could not find BME280 sensor at 0x77");
  }

  bme.setSampling(Adafruit_BME280::MODE_FORCED,
                  Adafruit_BME280::SAMPLING_X1, // temperature
                  Adafruit_BME280::SAMPLING_X1, // pressure
                  Adafruit_BME280::SAMPLING_X1, // humidity
                  Adafruit_BME280::FILTER_OFF);

  pinMode(D5, INPUT_PULLUP);

  bme.takeForcedMeasurement();

  bool chickdoor = digitalRead(D5);

  float temperature = bme.readTemperature();
  Serial.print("Temperature = ");
  Serial.print(temperature);
  Serial.println(" Celsius");

  //int32_t pressure = bmp.readPressure();
  //Serial.print("Pressure = ");
  //Serial.print(pressure);
  //Serial.println(" Pascal");

  //Serial.println();

  float humidity = bme.readHumidity();
  Serial.print("Humidity = ");
  Serial.print(humidity);
  Serial.println("%");

  StaticJsonBuffer<300> JSONbuffer;
  JsonObject& JSONencoder = JSONbuffer.createObject();

  JSONencoder["temperature"] = temperature;
  JSONencoder["humidity"] = humidity;
  JSONencoder["chickdoor"] = chickdoor;

  char JSONmessageBuffer[300];
  JSONencoder.printTo(JSONmessageBuffer, sizeof(JSONmessageBuffer));
  Serial.println(JSONmessageBuffer);

  //http debug stuff:
  //Serial.print("DNS #1, #2 IP: ");
  //WiFi.dnsIP().printTo(Serial);
  //Serial.print(", ");
  //WiFi.dnsIP(1).printTo(Serial);
  //Serial.println();

  //IPAddress resolvedIP;

  //if (!WiFi.hostByName("my.domain.here", resolvedIP)) {
  //  Serial.println("DNS lookup failed.  Rebooting...");
  //  Serial.flush();
  //  ESP.reset();
  //}
  //Serial.print("my.domain.here");
  //Serial.print(" IP: ");
  //Serial.println(resolvedIP);

  WiFiClient client;
  HTTPClient http;

  http.begin(client, "http://my.domain.here/chickinfo");
  http.addHeader("Content-Type", "application/json"); //Specify content-type header

  int httpCode = http.POST(JSONmessageBuffer); //Send the request
  String payload = http.getString(); //Get the response payload
  Serial.print("HTTP status code: ");
  Serial.println(httpCode); //Print HTTP return code
  Serial.print("HTTP response: ");
  Serial.println(payload); //Print request response payload
  http.end(); //Close connection

  Serial.println("Going into deep sleep for 60 seconds");

  ESP.deepSleep(60e6); // 60e6 is 60 seconds
}

void loop() {
}

why is the server refusing the connection?

reduce your code to the least amount of code that still exhibits the problem

The server log did not show the connection at all @jsotola. I upgraded the board (and with it, the httpclient library) in the Arduino IDE and it has been working for 24 hours now.

post that as an answer and then you can accept it as a solution ... other people with similar problem will be able to find it


text:
How to calibrate an inclined MPU 6050 on Arduino?
I'm trying to use the MPU 6050 sensor (gyroscope + accelerometer) with my Arduino UNO to get some data when walking, running and making some other moves while carrying it. The problem is that my welding makes the sensor stay inclined. The first photo is from the sensor and the second from the 3-D visualization using the Processing IDE:

Is there a way to calibrate the sensor to "act as if it were straight" based on its reads when inclined on the breadboard (as shown in the photo)? I am still a beginner with Arduino, so sorry if this is a silly question/problem.

Can you show us the sketch you're using?

your question is not about the Arduino ... it is about a Processing program ... just subtract the tilt before displaying the data


text:
CLion + Arduino -- Cannot find any CMake profile
I'm trying to get CLion 2019.2 working with Vladimir Schneider's Arduino Support plugin (v1.4.4, from the Jetbrains Plugin repository)
I installed MinGW from https://sourceforge.net/projects/mingw/ into c:\mingw, then went to Settings -> Build/Execution/Deployment -> Toolchains, added a new MinGW toolchain from c:mingw, and allowed it to autodetect make, gcc, and g++.
I got an error that GDB was too old,  selected "use bundled GDB", and the error went away.
I then created a new Arduino/Genuino Uno project, and attempted to build it.
At first, I was getting CMake Error at CMakeLists.txt:5 (set), due to line 5 being "set(${<@PROJECT_NAME@>}_BOARD uno)".
I found a post in the Arduino plugin's bug tracker said it's a bug in the plugin, and the work-around is to hand-edit CMakeLists.txt to replace every instance of "${<@PROJECT_NAME@>}" with "{PROJECT_NAME}" (apparently, there's a bug somewhere that causes it to wrap some environment variables with <@ and @>).
Now, I'm getting a different error whenever I try to build: "Cannot find any CMake profile"
I think I remember seeing a bug report thread for CLion itself speculating about the existence of a bug in CLion where the preferences UI implies that a configuration change has been made, but CLion doesn't actually update the file used by CMake to reflect the change. From what I recall, someone in the thread asked what specific file needed to be changed, and what specific changes were necessary... then the thread died without any subsequent posts for the past ~6 months.
Any ideas about what to try next?
Other relevant links for background info & context:
CLion's Arduino plugin by Vladimir Schneider: https://plugins.jetbrains.com/plugin/11301-arduino-support
Vladimir's project is a fork of an earlier plugin that was apparently broken by the release of CLion-2018.1. I'm under the impression that it still works for CLion 2019 under Linux, but was either broken by 2018.2 or 2019.1 for Windows, or never quite worked properly under Windows at all.
I've gotten the impression that, at least as of 2017-2018 (which is when a large number of postings about CMake-under-MinGW/Windows, CLion, and Arduino were made), CMake under Win32 via MinGW was still kind of buggy and brittle. The number of postings about them in 2019 is a lot smaller than 2017 and 2018, but I'm not sure whether that's because the problems people were talking about 2 years ago were solved, or because the people talking about them 2 years ago just got frustrated, decided it was a bit too bleeding-edge for them, and (at least temporarily) threw in the towel to wait for them to mature a bit.
Update: I just found another post theorizing that some of these problems might be due to limits imposed by Windows (by default) on the number of characters allowed in filename paths. I know Windows 10 allows you to increase the limit, but I know there are still a bunch of issues associated with doing that (Explorer can't touch anything with a path > 260 chars, cmd.exe -- and possibly Powershell -- requires using \\?\ notation, and Very Bad Things™ will happen if you physically attach a hard drive with files whose pathnames exceed the limit to a different computer running Windows that's still enforcing the old limit).
A tutorial for it that unfortunately seems to have gotten broken slightly by a subsequent release of CLion or one of its Arduino dependencies: https://vxlabs.com/2018/03/24/developing-arduino-sketches-with-jetbrains-clion-a-minimal-example/
(note to mods: I tried to tag this with "CLion" and "CMake", but the tags don't already exist, and my reputation isn't high enough yet to create new ones)

the reason that those tags do not exist is because they have nothing to do with an Arduino

Not quite. In theory, CLion can be used for C++ Arduino development (though, it appears, getting it to work with Windows instead of Linux is a major fragile ordeal at the moment), and CLion's "Arduino" plugin is CMake-based. It kind of feels as if CLion appeared on the scene right around the time CMake became relevant, and everyone writing Arduino plugins for it decided CMake was "the future"... and unfortunately, CMake STILL kind of appears to be "the future" (and not quite "the present"). See https://github.com/francoiscampbell/arduino-cmake


text:
ESP32 access point code not compiling
I'm trying to use the ESP32 board to control an LED, buzzer, and motor (ABA) through an access point.
I got some code from this page:
https://lastminuteengineers.com/creating-esp32-web-server-arduino-ide/
Which is amazing! I changed some names here and there and evrything okay (to control ONLY 2 things).
Now that I wanted to add the 3rd device, the code is not compiling.
I get this error:
exit status 1

too few arguments to function 'String SendHTML(uint8_t, uint8_t, uint8_t)'

With the line in bold marked.
server.send(200, "text/html", SendHTML(ABA1status,false));
#include <ETH.h>
#include <WiFi.h>
#include <WiFiAP.h>
#include <WiFiClient.h>
#include <WiFiGeneric.h>
#include <WiFiMulti.h>
#include <WiFiScan.h>
#include <WiFiServer.h>
#include <WiFiSTA.h>
#include <WiFiType.h>
#include <WiFiUdp.h>

#include <HTTP_Method.h>
#include <WebServer.h>

/* Put your SSID & Password */
const char* ssid = "ESP32DeltaSolutions";  // Enter SSID here
const char* password = "deltasolutions123";  //Enter Password here

/* Put IP Address details */
IPAddress local_ip(192,168,1,2);
IPAddress gateway(192,168,1,1);
IPAddress subnet(255,255,255,0);

WebServer server(80);

uint8_t LED1pin = 25;
bool LED1status = LOW;

uint8_t BUZZ1pin = 32;
bool BUZZ1status = LOW;

uint8_t ABA1pin = 35;
bool ABA1status = LOW;

void setup() {
  Serial.begin(115200);
  pinMode(LED1pin, OUTPUT);
  pinMode(BUZZ1pin, OUTPUT);
  pinMode(ABA1pin, OUTPUT);

  WiFi.softAP(ssid, password);
  WiFi.softAPConfig(local_ip, gateway, subnet);
  delay(100);

  server.on("/", handle_OnConnect);
  server.on("/led1on", handle_led1on);
  server.on("/led1off", handle_led1off);
  server.on("/buzz1on", handle_buzz1on);
  server.on("/buzz1off", handle_buzz1off);
  server.on("/aba1on", handle_aba1on);
  server.on("/aba1off", handle_aba1off);
  server.onNotFound(handle_NotFound);

  server.begin();
  Serial.println("HTTP server started");
}
void loop() {
  server.handleClient();
  if(LED1status)
  {digitalWrite(LED1pin, HIGH);}
  else
  {digitalWrite(LED1pin, LOW);}

  if(BUZZ1status)
  {digitalWrite(BUZZ1pin, HIGH);}
  else
  {digitalWrite(BUZZ1pin, LOW);}

  if(ABA1status)
  {digitalWrite(ABA1pin, HIGH);}
  else
  {digitalWrite(ABA1pin, LOW);}

}

void handle_OnConnect() {
  LED1status = LOW;
  BUZZ1status = LOW;
  ABA1status = LOW;
  Serial.println("GPIO4 Status: OFF | GPIO5 Status: OFF");
  server.send(200, "text/html", SendHTML(LED1status,BUZZ1status,ABA1status));
}

void handle_led1on() {
  LED1status = HIGH;
  Serial.println("GPIO4 Status: ON");
  server.send(200, "text/html", SendHTML(true,LED1status));
}

void handle_led1off() {
  LED1status = LOW;
  Serial.println("GPIO4 Status: OFF");
  server.send(200, "text/html", SendHTML(false,LED1status));
}

void handle_buzz1on() {
  BUZZ1status = HIGH;
  Serial.println("GPIO5 Status: ON");
  server.send(200, "text/html", SendHTML(BUZZ1status,true));
}

void handle_buzz1off() {
  BUZZ1status = LOW;
  Serial.println("GPIO5 Status: OFF");
  server.send(200, "text/html", SendHTML(BUZZ1status,false));
}

void handle_aba1on() {
  ABA1status = HIGH;
  Serial.println("GPI35 Status: ON");
  server.send(200, "text/html", SendHTML(ABA1status,true));
}

void handle_aba1off() {
  BUZZ1status = LOW;
  Serial.println("GPI35 Status: OFF");
  **server.send(200, "text/html", SendHTML(ABA1status,false));**
}

void handle_NotFound(){
  server.send(404, "text/plain", "Not found");
}

String SendHTML(uint8_t LED1status,uint8_t BUZZ1status,uint8_t ABA1status){
  String ptr = "<!DOCTYPE html> \n";
  ptr +="<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\">\n";
  ptr +="<title>LED Control</title>\n";
  ptr +="\n";
  ptr +="\n";
  ptr +="\n";
  ptr +="
ESP32 Web Server
\n";
  ptr +="
Using Access Point(AP) Mode
\n";
  ptr +="
Delta solutions
\n";

   if(led1stat)
  {ptr +="
LED1 Status: ON
OFF\n";}
  else
  {ptr +="
LED1 Status: OFF
ON\n";}

  if(buzz1stat)
  {ptr +="
BUZZ1 Status: ON
OFF\n";}
  else
  {ptr +="
BUZZ1 Status: OFF
ON\n";}

  if(aba1stat)
  {ptr +="
ABA1 Status: ON
OFF\n";}
  else
  {ptr +="
ABA1 Status: OFF
ON\n";}

  ptr +="\n";
  ptr +="\n";
  return ptr;

Any suggestions?
Thanks!

SendHTML has 3 parameters, but you only provide 2. Its clear  that the compiler gives you that error

The syntax of six SendHTML you use with true and false is actually wrong.
By defining a function like this String SendHTML(uint8_t LED1status,uint8_t BUZZ1status,uint8_t ABA1status), you mean that first, second and third input to this function are Status of LED1, Status of BUZZ1 and Status of ABA1.
So try replacing all six SendHTML with true and false functions to this SendHTML(LED1status,BUZZ1status,ABA1status)


text:
Error Compiling any coding in Arduino IDE
I was using the example code of "Blink", and when I try to compile it, it pop out an error as below.
I tried to:

uninstall and installed back the Arduino IDE
installed different versions of Arduino IDE
update the u8glib library
installed different version of Arduino AVR boards

but still doesn't work.

Arduino: 1.8.9 (Windows 10), Board: "Arduino/Genuino Uno"
C:\Program Files (x86)\Arduino\arduino-builder -dump-prefs
  -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -hardware C:\Users\ASUS\AppData\Local\Arduino15\packages -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files
  (x86)\Arduino\hardware\tools\avr -tools
  C:\Users\ASUS\AppData\Local\Arduino15\packages -built-in-libraries
  C:\Program Files (x86)\Arduino\libraries -libraries
  C:\Users\ASUS\Documents\Arduino\libraries -fqbn=arduino:avr:uno
  -vid-pid=0X2341_0X0043 -ide-version=10809 -build-path C:\Users\ASUS\AppData\Local\Temp\arduino_build_109130 -warnings=none
  -build-cache C:\Users\ASUS\AppData\Local\Temp\arduino_cache_111506 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.arduinoOTA.path=C:\Program Files (x86)\Arduino\hardware\tools\avr
  -prefs=runtime.tools.arduinoOTA-1.2.1.path=C:\Program Files (x86)\Arduino\hardware\tools\avr
  -prefs=runtime.tools.avr-gcc.path=C:\Program Files (x86)\Arduino\hardware\tools\avr
  -prefs=runtime.tools.avr-gcc-5.4.0-atmel3.6.1-arduino2.path=C:\Program Files (x86)\Arduino\hardware\tools\avr
  -prefs=runtime.tools.avrdude.path=C:\Program Files (x86)\Arduino\hardware\tools\avr
  -prefs=runtime.tools.avrdude-6.3.0-arduino14.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -verbose
  C:\Users\ASUS\Desktop\FSR\FSR.ino
Error compiling for board Arduino/Genuino Uno.

reinstall Arduino IDE. better try 1.8.10


text:
AVR program upload overrides unrelated program area
I develope a new bus system (uartbus) which includes a host application that can handle new program uploads throught the bus.
How it's work in short: The host application flashed to the AVR. This located between 0-2000 addresses and the flashing function at the end in the NRWW section. Application is written between 2000 and before NRWW section when it's received from the bus.
It's worked for a while with small AVR codes, but now as i try to integrate with the arduino system i've faced a weird problem: sometimes a page between
100 and 180 (one 128 byte page) been erased and some code filled almost at the beginning.
I thought the flashing function has been called with some wild parameter that results this fault, so i added some guard condition to check before write the flash:
__attribute__((section(".bootloader"))) void bootloader_main()
{
    asm ("jmp 0x0");
}

//modified version of:
//https://www.nongnu.org/avr-libc/user-manual/group__avr__boot.html#gaeb0dba1dd9d338516a94c0bd8a8db78a
__attribute__((section(".bootloader")))  void ubh_impl_write_program_page(const uint32_t page,const  uint8_t *buf,const uint8_t size)
{
    if(page < 0x2000 || (page > 0x7900+SPM_PAGESIZE) || size > SPM_PAGESIZE)
    {
        return;
    }

    uint16_t i;
    uint8_t sreg;
    // Disable interrupts.
    sreg = SREG;
    cli();
    eeprom_busy_wait ();
    boot_page_erase (page);
    boot_spm_busy_wait ();      // Wait until the memory is erased.
    for (i=0; i<size; i+=2)
    {
        // Set up little-endian word.
        uint16_t w = *buf++;
        w += (*buf++) << 8;

        boot_page_fill (page + i, w);
    }
    boot_page_write (page);     // Store buffer in flash page.
    boot_spm_busy_wait();       // Wait until the memory is written.
    // Reenable RWW-section again. We need this if we want to jump back
    // to the application after bootloading.
    boot_rww_enable ();
    // Re-enable interrupts (if they were ever enabled).
    SREG = sreg;
}

But the problem remained. Because the host code has been partially overwritten, the AVR can't receive new code from the bus. After dumped the AVR's flash and disassembled to invesigate what's happened.
avrdude -p atmega328p -b 19200 -P /dev/ttyUSB0 -c avrisp -U flash:r:flash.hex:i
avr-objdump -j .sec1 -d -m avr5 flash.hex > flash.asm

  ... good code ...
      fc:       fb 01           movw    r30, r22
      fe:       31 83           std     Z+1, r19        ; 0x01
     100:       ff ff           .word   0xffff  ; ????
     102:       ff ff           .word   0xffff  ; ????
     104:       ff ff           .word   0xffff  ; ????
     106:       ff ff           .word   0xffff  ; ????
     108:       ff ff           .word   0xffff  ; ????
     10a:       ff ff           .word   0xffff  ; ????
     10c:       ff ff           .word   0xffff  ; ????
     //looks like this code is from the application space between 2b8e and 2b96
     10e:       ff 1f           adc     r31, r31
     110:       05 90           lpm     r0, Z+
     112:       f4 91           lpm     r31, Z
     114:       e0 2d           mov     r30, r0
     116:       09 94           ijmp
     118:       ff ff           .word   0xffff  ; ????
     11a:       ff ff           .word   0xffff  ; ????
     11c:       ff ff           .word   0xffff  ; ????
     11e:       ff ff           .word   0xffff  ; ????
 ....

     17c:       ff ff           .word   0xffff  ; ????
     17e:       ff ff           .word   0xffff  ; ????
     180:       9f 93           push    r25
     182:       8f 93           push    r24
     184:       0e 94 9e 0a     call    0x153c  ;  0x153c
   ...good code ...

How is this possible to happen even after adding some guard condition before writing the flash?
(Another guard is also installed: when AVR accidentally starts in bootloader mode it's jumps immedialty to 0x00).
I also checked, there's no SPM instruction in the code i uploaded and as far as i know they can be run outside of the NRWW section.

doesn't page 100 start at 0x3200 byte address?

Yes, the 0x3200 is the 100th page of the memory. (On the atmega328, the SPM_PAGESIZE is 128. The 0x3200 in decimal is 12800.). Hmm, that address is acutally writeable and previously i uploaded only shorter codes (under 2 Kbytes, so under the 0x2000+0x800). Maybe that's the root of this weird connection, but i don't have an idea how they connected.

then the 'guarding' if can't apply. so what is the problem?

It can. However the variable name 'page' is a bad name for that, it's actually stores the start address of the page, not the page offset itself. (This name comes from the original source of this flash function: https://www.nongnu.org/avr-libc/user-manual/group__avr__boot.html) There's no call example attached, but this code worked prevously with shorter codes to upload and absolute code addresses.

but I don't understand why it is a problem that the page 100 at byte address 0x3200 is written and how and why should the if(page < 0x2000 || (page > 0x7900+SPM_PAGESIZE) prevent it?

The host program (which accepts the uploaded code and implements also other functionalities) is placed between 0x0-0x2000. And that host program writes the received paged to the flash area between 0x2000 and FLASH_END. The condition page < 0x2000 should prevent to write any page under the application area (prevent to overwrite the host). This condition  page > 0x7900+SPM_PAGESIZE added because documentation says nothing about what happens when you call boot function with higher addresses than we have on flash. Condition size > SPM_PAGESIZE is yet another check for failure condition.

So the application area is between 0x2000 and FLASH_END. To override the area i shown in the dump (0x100-180) i, or something*  should calls this function with page = 0x100. When this happen somehow, this guard conditions rejects the call.
( note to i or something*): Like restart to bootloader mode, where the execution can walk to this flashing function with uninitialised values, which prevented by the "jmp 0x0" instruction, placed right before this function. Months ago that made randomly failures .

so you meant the page at byte address 0x100, not the 100th page

More precisely, i meant a whole page between 0x100 and 0x180 (well yes, i've missed the 0x notation). That shows that erase executed successfully but the write sequence got broken. Meanwhile i try to reporduce this failure on other device, but i can't. Because this failure happens randomly (or for ahidden reson), it makes to reproduce much harder.

Randomly: On the original device, after 6 code upload it happend. On a new device, i've uploaded new code at least 15 times but still no error. Ok, maybe it is a device (instance) specific error, but when later happens on a deployed node it will be very frustrating.


text:
Time information from GPS receiver: how to tell whether it is fresh or stale?
I see that TinyGPS++ library extracts time information from GxRMC and GxGGA NMEA sentences streamed by GPS receiver. However, in my experiments I observed that both of my GPS receivers generate GxRMC sentences with time data in them at least once a second even when they have no access to satellites.
I presume that the time data comes from the internal clock of the receiver (and is maintained between warm startups). This is perfectly OK. However, I would like to know what measures are required by NMEA specification to ensure the reliability of this time data.
Am I correct in assuming that the device itself is supposed to understand that after certain period of time its internal clock will diverge? And that after that period the device will by itself stop pumping out these GxRMC sentences, until it gets a chance to see a satellite and re-sync its internal clock? Or should I expect to see the next field in GxRMC sentence to change from A to V?
If not, then what is the proper way to ensure that I receive "satellite time" (or close to that) or nothing at all?

Most of the GPS modules keep on sending the data in the NMEA format whether they have a GPS fix or not, however, you can parse the GPS data to find whether the data is the latest data received from the GPS or not. If you look at the definition of the NMEA data here, there are a few variables in the data that you can use to find whether the data is the latest data from the GPS or not.
You can use the "Fix Quality" in GPGGA as well as "Validity/Receiver warning" in GPRMC for your module. The tinyGPS indeed has both of these variables being parsed.
In the tinyGPS library, if _gps_data_good is true then the data coming from the GPS module is the latest data it received from the GPS satellites. The program uses either the fix or validity to determine this (Refer to the library here and here).
You should just keep checking this variable to find whether the current data is the latest from the GPS or is it being calculated internally.

Yes, thank you. Indeed, I just noticed that the warning field in GPRMC/GNRMC messages changes between A and V. When there's no fix, the time is reported with V (unreliable). Moreover, after a relatively long while without access to satellites, my receiver stops reporting time in GxRMC sentences entirely - the time field is left empty.

It is interesting that in this state, after partial exposure to open sky (e.g. just one or two satellites visible, no fix), the receiver again begins reporting time in GxRMC, but with V label (unreliable). At first sight, this is strange, since the time information in this case is apparently received from the satellites. V changes to A only when position fix is achieved, which is overkill in my case (I don't need position, just time).


text:
Noisy analogRead
I'm trying to read voltage using Arduino, here's the code:
float r1 = 99700;
float r2 = 10004;
float adc, voltage;
unsigned long analog;
void setup() {
  Serial.begin(9600);
  analogReference(EXTERNAL);
  pinMode(A0, INPUT);
}

void loop() {
  for (int i = 0; i < 64; ++i) {
    analog += analogRead(A0);
    delay(1);
  }
  analog = analog / 64;
  adc = (analog * 2.441) / 1024;
  voltage = adc / (r2 / (r1 + r2));
  Serial.print(analog);
  Serial.print(", ");
  Serial.print(adc);
  Serial.print(", ");
  Serial.print(voltage);
  Serial.println(" ");
}

Had a VERY noisy reading and what I did was adding an external voltage reference (TL431) and also connected a 9V switching adapter to Arduino UNO. But I still had some noise in analog readings so as you can see in the code I'm taking 64 sample and averaging them.
After doing all those noise reduced a lot but not completely:

What else should one do to get an steady reading?
By taking 1024 sample noise will be removed but then I'm sacrificing performance...

your 0.46 looks very steady :) SCNR.  You might look at the sensor itself and it's wiring. Add capacitors ...

@DataFiddler it looks steady in that screenshot but it's not, after all the value IS depended on the raw analogRead...

the range of analogRead is 0 to 1023. you read 190. what are the magic numbers?

@Juraj the numbers doesn't matter i can calibrate it one way or other, what i want is an steady reading.

common ground is connected?

@Juraj yes they're connected.

What is it you are reading from? How is it wired to the Arduino?

@Majenko reading is from two 1% resistor voltage divider and wired on a breadboard.

I solved the problem by adding 3 capacitors:

220uF on the Arduino power supply.
100uF on TL431 output.
1uF on A0 input.

I also increased the sampling rate to 128 times (and removed the delay).
Here's the result, as accurate as my multimeter:

There's still 2mV difference in higher voltages which is because of my 2.5V reference voltage and Arduino ADC 10bit resolution (2.5 / 1024 = 0.002).

Effectively, Serial.begin(9600); and the lots of output control speed.

A/D converters are always noisy.  If you dive into the specific processor's specifications you may find a 10 bit A/D converter only has, maybe, 8 bits of meaningful data.  1) Have you verified the processor is tracking the voltage as expected by changing the voltage at the A/D converter's input?  2) What are you using as a reference voltage.  And, consider using exponential averaging instead of averaging a fixed group of A/D conversions.

@st2000 yeah it shows the correct voltages with ~2mV difference, the voltage reference is TL431. i don't even know what exponential averaging is! gonna google it now. thanks.

Looks like wikipedia calls it exponential smoothing, not exponential averaging.  Pick values based on powers of 2's to keep the math simple and adapt to embedded programming.


text:
Running loop for a specific time period
I currently have a loop that runs without a time condition:
unsigned long previousMillis = 0;        // will store last time LED was updated

int WET=4;//wet line
int DRY=5;//dry line
int Inhale=1000;//msec
int Exhale=1000;//msec
//int Noflow=3000;//msec

void setup() {
  // put your setup code here, to run once:
  pinMode (WET, OUTPUT);
  pinMode (DRY, OUTPUT);
}

void loop() {
  //inhale
  digitalWrite(WET,LOW);
  digitalWrite(DRY,HIGH);
  delay (Inhale);
  //exhale
  digitalWrite(WET,HIGH);
  digitalWrite(DRY,LOW);
  delay (Exhale);
  //No flow
  //digitalWrite(WET,HIGH);
  //digitalWrite(DRY,HIGH);
  //delay (Noflow);
}

Then i have tried to code a "timer" for each cycle,but i got error:"
exit status 1
Error compiling for board Arduino/Genuino Uno."
Code with timer:
unsigned long previousMillis = 0;        // will store last time LED was updated

int WET = 4; //wet line
int DRY = 5; //dry line
//int Inhale=1000;//msec
//int Exhale=1000;//msec
//int Noflow=1000;//msec
int BPM = 60;
int IE = (((60 * 1000) / BPM) / 2);

void setup() {
  // put your setup code here, to run once:
  pinMode (WET, OUTPUT);
  pinMode (DRY, OUTPUT);
}

void loop() {
  for (int i = 0; i = 20;)
    int BPM = BPM + 10;
#include <elapsedMillis.h>

  elapsedMillis timeElapsed;
  unsigned int interval = 60000; //one minute in ms

  while (timeElapsed < interval) {

    //inhale
    digitalWrite(WET, LOW);
    digitalWrite(DRY, HIGH);
    delay (IE);
    //exhale
    digitalWrite(WET, HIGH);
    digitalWrite(DRY, LOW);
    delay (IE);
    //No flow
    //digitalWrite(WET,HIGH);
    //digitalWrite(DRY,HIGH);
    //delay (2000);
  }
}

Target ouput: to run every cycle of the loop for 1 min.
Any one familiar with this error?
Many thanks for your help

Your code has a number of problems:
Don't put #include statements for header files in the middle of your code. They belong at the top, before any other code. (What is the header file elapsedMillis.h?)
Another thing: Your for loop is a mess. It should read something like: for (int i = 0; i < 20; i++) (That would cause the for loop to run 20 times, with the value of i ranging from 0 to 19.) However, what do you want to happen in your for loop? Without braces after that code, the ONLY line that will execute 20 times is the int BPM = BPM + 10; line (which doesn't make any sense.)
You really shouldn't use time-based while loops inside your main loop function. That defeats the purpose of using timers instead of delay statements. And you should get rid of your calls to delay() and use millis() to manage all your timing. Do a search on "Arduino blink no delay" and study the examples for information on how to restructure your code.

Your for loop won't run as initially i is equal to 0 and you are comparing it with 20 also you didn't have any 3rd variable refreshing condition in your for loop.
You are declaring BPM new every time your loop run which is wrong
Also you are including header file in between your program run which will mess up your code and it is totally wrong practice.


text:
How to make a custom character on a TFT LCD display? (128x128)
I'm currently using the ucglib library. I'm new to arduino and I'm wanting to simply display a lcd smiley I made with the byte generator. I still have some of the original 'font hello world' stuff down the bottom but I'm curious how to make my character work.
I want to make different smileys in different colours but I'm unsure how to go about this as every guide is on a 16x2 lcd and not a tft one. I have an arduino nano that is just hooked up to that lcd display. I'm going to make pressing buttons change the smiley after I've figured out how to actually put a smiley into it. Hope someone can help.
 * LED =   3.3V
 * SCK =   13
 * SDA =   11
 * A0 =    8
 * RESET = 9
 * CS =    10
 * GND =   GND
 * VCC =   5V

    #include "Ucglib.h"  // Include Ucglib library to drive the display

// Create display and define the pins:
Ucglib_ST7735_18x128x160_HWSPI ucg(8, 10, 9);

int smiley = byte customChar[] = {
  B00000,
  B01010,
  B01010,
  B00000,
  B10001,
  B10001,
  B11111,
  B00000
};

void setup(void)  // Start of setup
{

  //ucg.begin(UCG_FONT_MODE_TRANSPARENT);  // It doesn't overwrite background, so it's a mess for text that changes
  ucg.begin(UCG_FONT_MODE_SOLID);  // It writes a background for the text. This is the recommended option

  ucg.clearScreen();  // Clear the screen

  ucg.setRotate180();  // Put 90, 180 or 270, or comment to leave default

  ucg.setColor(0, 255, 255, 255);  // Set color (0,R,G,B)
  ucg.setColor(1, 0, 0, 0);  // Set color of text background (1,R,G,B)
  ucg.setPrintPos(0,24);  // Set position (x,y)
  ucg.print("Welcome");  // Print text or value

  // Draw smiley:
  ucg.setColor(0, 255, 255);  // Set color (0,R,G,B)
  ucg.drawFrame(0, 58, 60, 30);  // Start from top-left pixel (x,y,wigth,height)

void loop(void)  // Start of loop
{

  Variable1++;  // Increase variable by 1
  if(Variable1 > 150)  // If Variable1 is greater than 150
  {
    Variable1 = 0;  // Set Variable1 to 0
  }

  // Convert Variable1 into a string, so we can change the text alignment to the right:
  // It can be also used to add or remove decimal numbers.
  char string[10];  // Create a character array of 10 characters
  // Convert float to a string:
  dtostrf(Variable1, 3, 0, string);  // (<variable>,<amount of digits we are going to use>,<amount of decimal digits>,<string name>)

  // We are going to print on the display everything that is dynamic on the loop, to refresh continuously:

  // Write to the display the Variable1 with left text alignment:
  ucg.setFont(ucg_font_inb16_mr);  // Set font
  ucg.setColor(0, 255, 255, 0);  // Set color (0,R,G,B)
  ucg.setColor(1, 0, 0, 0);  // Set color of text background (1,R,G,B)
  ucg.setPrintPos(9,81);  // Set position (x,y)
  ucg.print(Variable1);  // Print text or value

  // There is a problem when we go, for example, from 100 to 99 because it doesn't automatically write a background on
  // the last digit we are not longer refreshing. We need to check how many digits are and fill the space remaining.
  if(Variable1 < 10)  // If Variable1 is less than 10...
  {
    // Fill the other digit with background color:
    ucg.print(" ");
  }
  if(Variable1 < 100)  // If Variable1 is less than 100...
  {
    // Fill the other digit with background color:
    ucg.print(" ");
  }

  // Write to the display the string with right text alignment:
  ucg.setFont(ucg_font_inb16_mr);  // Set font
  ucg.setColor(0, 0, 255, 0);  // Set color (0,R,G,B)
  ucg.setColor(1, 0, 0, 0);  // Set color of text background (1,R,G,B)
  ucg.setPrintPos(76,81);  // Set position (x,y)
  ucg.print(string);  // Print text or value

}  // End of loop

Simple: you don't.
You only need to create a "custom character" on character-only displays (where you are actively programming a new character into the display's internal character set).
With a graphical display there is no "character" - only graphics.  The graphics library has fonts, which it then uses to convert text into graphics.
To display something that isn't in your currently selected font, just draw it. That could be from a bitmap graphic (there will be examples in your chosen graphics library) or using primitives, like circles and lines.

ah I see, my bad. I'll try my best to search up it then. I'm assuming I could just 'print' :) and it would display on the screen okay?

You could change the font that you are printing with. Make a custom font. No idea how you'd do that with your chosen library though. There may be examples and tutorials, or there may not...

I'm more than happy to use a different library, this one just seemed right on the mark for what I wanted. I think they have a whole list of fonts so I may just choose a pixel one and try my best from there. I know this is a different topic, but if my arduino is completely off a breadboard and linked up to the lcd, can I use a button on a breadboard and just put a wire to it or is it best to attach the arduino nano to the breadboard itself to make buttons work?

Makes no difference.

Thank you Majenko. If you're still here, on a 128 x 128 screen, which y and x axis would be the middle? I've tried a few but i think the text is still off screen? Having trouble with that

64x64 is the middle of a 128x128 screen.

oh it's half. Ha I must be an idiot. Thank you, you've made my night so much easier! I shall leave you be =). Thanks once again


text:
Menus not changing when button is pressed TFT 128 x 128
I've just followed a tutorial so that when a button is pressed it goes through a menu. Click once, next slide. Only issue is it isn't appearing on my screen at all. It has uploaded but I'm a total novice when it comes to breadboards etc. Here is my code:
    #include "Ucglib.h" // library for this display
#include <TFT.h> // Hardware-specific library
#include <SPI.h>

#define CS   10
#define DC   8
#define RESET  9

#define up 5
#define down 6

TFT TFTscreen = TFT(CS, DC, RESET);
const int menuSize = 4;
String menuItems(menuSize);

bool upLastState = HIGH;
bool downLastState = HIGH;

int currentMenu = 0;
String temp;
char currentPrintOut(10);

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

  pinMode(up, INPUT_PULLUP);
  pinMode(down, INPUT_PULLUP);

  menuItems[0] = ":)";
  menuItems[1] = ":(";
  menuItems[2] = "X(";
  menuItems[3] = ":S";
  menuItems[4] = ":T";

  //initialize the library
  TFTscreen.begin();

  MenuChanged();
}

void loop() {
  if (digitalRead(up) != upLastState) {
    upLastState = !upLastState;
  }

  if (!upLastState) {
    if (currentMenu > 0) {
      currentMenu--;
    } else {
      currentMenu = menuSize - 1;
    }
    MenuChanged();
  } else {
  }

 if (digitalRead(down) !=downLastState) {
  downLastState = !downLastState;

  if (!downLastState) {
    if (currentMenu < menuSize - 1) {
      currentMenu++;
    } else {
      currentMenu = 0;
    }
    //Serial.printIn(menuItems[currentMenu]);
    MenuChanged();
  } else {
    //Release
  }
 }

   delay(50);
 }

 void MenuChanged() {
  Serial.println(menuItems[currentMenu]);

// clear the screen with a black background
  TFTscreen.background(0,0,0);
  TFTscreen.setTextSize(9);
  TFTscreen.stroke(255,255,255);

  temp = String(menuItems[currentMenu]);
  temp.toCharArray(currentPrintOut, 10);

  TFTscreen.text(currentPrintOut, 40, 32);
}

Edited back to original as per request

remove #define up 5 and #define down 6, we already defined pin 5 for the button. also remove TFTscreen.text(":)", 40, 32); which is in front of defualt:. the serial.begin() and serial.println() and delay(100) are just for testing the code, you can remove them as well.

Hi! I've done all that now. It's still racing through every single face so I'm going to try the de bounce and see if it's that. I can't even press a button, it just does it itself haha.  Sorry I wasn't sure if I needed to write anything for default! After this I only have one major thing left to do in my code (that you'll probably wind up helping me again im so sorry I'm so new at this). I'll try my best to fix the face speed through

Please revert back your original code so others can see what was the problem, you basically cleared the question...

sure thing, I also had another problem now though haha. I tried to debounce but the faces are even faster now. It's going inbetween faces and won't actually stop on one and still wont let me click the button to activate it :/

updated the answer with de-bounce, if your questions in this site got an answer which solved your problem please pick them as correct answer by clicking on the "tick" next to the answer. is your push-button normally open or is it normally close?

Sorry to bother you so much. I guess it wasn't the debounce (I wasnt wrong for once! I did it right go me), it's still going through all the cases just slower. Is there a way to stop on that face if the button is actually pressed? I'm trying to work it out on my own but it just keeps repeating going through the faces and not actually pausing on the one I want when the button is pressed :/

i suspect it's because you have a normally close push-button, which means push-button is connected until you press it. link. is it a normally close push button?

Ah I see that makes sense. I guess I can try to make the space wider with resistors etc? Even thought that's still the electrical current but can't hurt to try

change the push button with a normally open push button OR change this line: if (buttonStatus == LOW) {} to if (buttonStatus == HIGH) {}

Hey newbie, I put the button in the middle of the board (like originally) and put both the wires on each end. It somewhat works! I need to double tap the button because sometimes it decides to do it again but I'll try your way too. I'll leave you be for now <3. Thank you so much for your help. I appreciate it more than you know. Here is my victory photo.

you're welcome.

Edit: I managed to fix my problem by putting the wires diagonally (ground left pin, 5 right side) if anyone in future has my problem. Back to the victory dance =)

You can make things much simpler:
int count = 0;
int button = 5;
int buttonStatus;
unsigned long timer = 0;

void setup() {
  Serial.begin(9600);
  pinMode(button, INPUT_PULLUP);
}

void loop() {
  buttonStatus = digitalRead(button); // read the button status
  if (buttonStatus == LOW) {
    if (millis() - timer > 200) { //de-bouncing the button
      count++; // increase +1 each time button is pressed
      // clear screen function should be here
      timer = millis();
    }
  }
  if (count > 3){ // if count is bigger than 3 start over.
    count = 0;
    // clear screen function should be here
  }
  switch (count){
    case 1: // if count == 1
    // show charecter :)
    break; // break out of this case!
    case 2:
    // show charecter :(
    break;
    case 3:
    // show charecter :D
    break;
    default: // if none of above cases is valid
    count = 0;
    // clear screen function should be here
  }
  Serial.println(count);
  delay(100);
}

simulate this circuit – Schematic created using CircuitLab
So each time button is pressed count value will increase by 1. you can also add another button to decrease this value...
You might also notice when pushing the button it'll count more than once, you'll also need to De-Bounce the button. tutorial.
Edit: added de-bounce function.

Hi again newbie. So with this, I say like Case 1: TFTscreen.stroke(0,0,0);
TFTscreen.text(":)"); with all my colour settings? Do I also put in void set up that I want the background to be black? I just want to make sure this is what you meant by your thing you sent me, or do you mean to still have the button in the middle but the wires on the other side? link. My TFT is just blank and wont show up anything before so I wan't to clarify before I start. Thanks again

@Ijustneedtopassprobs Only two wire goes to the button (what's the third wire in that picture?), ground and pin 5 in this case. yes define your libraries at top like you did in your original code and the sittings you want in void setup. also read the comments in the code that i posted.

I did remove that one after, sorry I figured that out eventually. It's going through all the faces at the moment. I made up to 5 cases. It's pretty much spamming. I haven't touched the button yet. I'm going to edit my code so you can see my new code to see if I'm extra dumb or not =), once again ty for this


text:
counting revolution of incremental encoder
I'm doing a project which requires me to use an faulhaber encoder,and the one i have is a 2channel 16lines per revolution.
I haven't worked with encoders before and based on what i found the lines per revolution mean how many pulses i get for each revolution and so in my code i used an interrupt and counted the times my channel A changed till it got to 32 counting once for every high to low and once for every low to high for my 16 pulses which then by my belief means that I've had one revolution but when i test the code after around like 1/6 of a spin my counter reaches 32 and I'd appreciate if someone can tell me where I'm going wrong with this .
This is the datasheet of the encoder I'm using IE2_16 .
here is the code :
volatile long int ticks = 0 ;
unsigned long int rev = 0 ;
const int channelA = 2 ;
void setup(){
   Serial.begin(9600);
   pinMode(6,OUTPUT);
   pinMode(7,OUTPUT);
   pinMode(8,OUTPUT);
   pinMode(channelA,INPUT);
   attachInterrupt(digitalPinToInterrupt(channelA), numCunts,  CHANGE);
   digitalWrite(7,LOW);
   digitalWrite(8,HIGH);
   analogWrite(6,15);
}
void loop(){
       Serial.println(rev);

    if(ticks>=32){
       ticks = 0;
       rev++;

      }
}

void numCunts(){
  ticks+=1 ;
  }

No, there are several problems with your decoding. First, you are detecting every change. You want to detect only rising or falling edge changes.
Second, the changes are likely noisy, so you need to write your decoder to "debounce" the readings. With a 2-channel encoder like you're using, the usual way to do that is to only respond to rising edge changes on channel A after you've seen a rising edge change on channel B, and visa-versa.
See this link for a description of how they work: http://www.creative-robotics.com/quadrature-intro
I tried my hand at writing my own decoder, but it's harder than you might think to get it right. I'd suggest using somebody else's rotary encoder library.
And a quick google search revealed this library on github: https://github.com/PaulStoffregen/Encoder
(I don't know if it's any good or not. It's the first hit I found.)


text:
What can cause an Arduino to "disconnect" from Windows?
I bought a DFrobot Beetle and it worked fine for probably an hour, then it just stopped working with Windows.
When I connect it to the computer I hear the "connect" sound, then within 5-7 seconds I hear the disconnect sound again.
I didn't do anything special with it. I connected a RDM6300 rfid reader and used an example code from a library.
I think the last thing I did was to change a string output message in the console.
From then on it just disconnects.
I tried to email DFrobot but didn't get a reply.
What could have caused this?
What can I do to make it work again?
The reset pin didn't work.
There is not enough time to replace the code on the board before it disconnects.

What's the USB chip? is it CH340 or CP2102? if it's CH340 try installing the windows driver for it. Link.

I don't know. How can I see that? On the chip it says "MEGA32U4"  \n "-MJ" \n "1812E PH" \n "1812E81"

Can you please post a link to the actual product?

This is the place I bought it from https://www.tme.eu/en/details/df-dfr0282/programmable-controllers/dfrobot/dfr0282/ . DFrobot product page https://wiki.dfrobot.com/Beetle_SKU_DFR0282

Seems it don't a have USB chip on it but read the Introduction section. Link. Did you select Arduino Leonardo in Arduino IDE before programing it? Also read This. and the AtMega32u4 Driver.

Yes I had Leonard selected, and it worked fine for an hour with probably 10 different codes. I will try the driver, but not today. Going to bed soon. Thanks!

do a double reset and the upload some working sketch. the USB is handled by the sketch