text:
How to increase life of EEPROM?
I want to store a few (8 as of now) IR codes into my Board's EEPROM.
It would be great if someone could suggest a few tips to maximize the lifetime.
The IR codes in my sketch are saved in array of unsigned longs.
I know that the count of times that I will be writing to EEPROM will << 100,000 times, but still would like to optimize my sketch. + would help in future projects

Just out of interest, I tried to "wear out" my EEPROM a while back. It took something like 1.5 million writes before it started to fail.

@NickGammon, what were the failures like?  Random data?

One bit failures, from memory.

It's possible that if you exceed the specifications the memory might become less reliable. I didn't test that. Conceivably you might find that, after a month, a bit would change. My own findings were that you could exceed the recommended ratings by a substantial amount, and still read back the byte you wrote, a moment later.

I can think of a few:

don't power it on unless you have to;
don't write to it unless you have to;
write as little data to you as you can - compress the data; only write to it during brown out or power down, ...;
level the writes to as many cells as possible - increment the write address with subsequent writes;
use a big eeprom;
use fram;
use sram + battery back-up;

...
3 - 7 are really examples of implementating #2.

The other answer mentioned some general ideas; here are a couple of more-specific notes.
• You can direct your writes of single bytes through a routine that reads the EEPROM cell before writing to it, and if its value isn't changing, doesn't write.
• For load-leveling, you can divide the EEPROM address space into k buckets, where k =⌊E/(n+1)⌋, with n = data array size and E = EEPROM size.  Initialize a directory, an array of m bytes all set to k, with m = E-n·k.  When your device starts up, it reads through the directory until it finds current entry, a byte not equal to k. [If all directory entries equal k, initialize the first to 0, and go on from there.]  If the current directory entry contains j, then bucket j contains current data.  When you need to write new data, you store j+1 into the current directory entry; if that makes it equal to k, initialize the next directory entry to 0, and go on from there.  Note that directory bytes get about the same amount of wear as bucket bytes because 2·k > m ≥ k.

Thanks, I will try and implement load-leveling to my sketch also. Great explanation.
I do check if the values are same before writing, so that part is taken care of.

If your data occupies only a small fraction of your EEPROM, you could use one of the wear leveling algorithms. The essence of these algorithms is to write to a different location each time, so writes are spread across several locations while each location stays below the 100,000 writes limit.
There are several such algorithms discussed here, which you could implement yourself. Alternatively, you could just use a library like this one.

These are great links Dmitry! Thanks.
Anyways, now I am using ~the entire EEPROM for data. Write operations are rare in my code and only happen during the start of the lifecycle (configuration period of my device). The lifecycle mostly consists of only read operations.
As the size of my config-files is increasing I am now looking for memory-optimization techniques to fit all that in the EEPROM and no go for any additional storage.

I believe there's a simple way to use only n cells and a single dedicated bit pattern to achieve n/2 increase in durability.
The dedicated bit pattern (e.g. 0xffff) is a marker which indicates an unused cell, and in normal operation at most one cell at a time has this value:
uint16_t readWord (const uint16_t *address);
void writeWord (uint16_t *address, uint16_t value);

#define CELL_COUNT   42
#define BASE_ADDRESS 12
#define MARKER       0xffff  // Best to use EEPROM default for this

static uint8_t curCell = 0;

static void wlInit (void)
{
  for ( uint8_t ii = 0 ; ii < CELL_COUNT ; ii++ ) {
    if ( readWord (BASE_ADDRESS + ii) != MARKER ) {
      curCell = ii;
      // No early return/break here to keep init() execution time
      // constant.  Could also check for corruption here by checking for
      // > 1 cells with MARKER (see below).
    }
  }
  // If we didn't find a non-marker cell we'll end up with curCell = 0
  // per the initial value of curCell
}

static uint16_t wlRead (void)
{
  return readWord (BASE_ADDRESS + curCell);
}

static void wlWrite (uint16_t value)
{
  assert (value != MARKER);   // Storing marker value is big no-no

  uint8_t nextCell = (curCell + 1) % CELL_COUNT;
  writeWord (BASE_ADDRESS + nextCell, value);
  writeWord (BASE_ADDRESS + curCell, MARKER);
  curCell = nextCell;
}

The same approach can be used with structured data provided a bit pattern can be reserved (either in a dedicated byte or from some other field that has a spare pattern).
This approach also has a useful property with respect to interrupted (e.g. power drop) writes: if there are ever two cells without the MARKER value an incomplete (i.e. corrupted) write has occurred. This seems useful, because e.g. the ATmega328P datasheet contains the following unclear and not-particularly-reassuring paragraph about using brown-out detection to avoid corruption:

Keep the AVR RESET active (low) during periods of insufficient power
supply voltage. This can be done by enabling the internal Brown-out
Detector (BOD). If the detection level of the internal BOD does not
match the needed detection level, an external low V CC reset
Protection circuit can be used. If a reset occurs while a write
operation is in progress, the write operation will be com- pleted
provided that the power supply voltage is sufficient.

authors: Александр Ломанов


text:
Need assistance decyphering agriculture systems control code created by absent team member
I'm working on an agriculture system and one of my partners (who was taking care of the automation side of things) has gone MIA and we are left with arduino code running our systems that we have a basic understanding of. We're in a bit of a pickle until we can get another person on board who has this kind of expertise and would greatly appreciate any help from anyone who can assist us in modifying a few parameters of the program.
The arduino is controlling one of the generic 8 relay boards hooked up to mains voltage and 8 outlets. The outlets control lights, cO2, water pumps, and fans (which are programmed to activate when temp/humidity reaches certain levels).
We presently understand how to alter how long the relays are activated for, but what we are trying to understand is how to modify the interval at which these relays are activated (cO2/water is every 150 minutes, we would like to alter this). So for example, how would I alter the code to release cO2 every 90 minutes and activate the water pump every 5 minutes?
Any help on this matter would be greatly appreciated! Thank you so much!
#include <dht.h>
#include <dht.h>

dht DHT;
#define dataPin 7
//#define DHT11_PIN 7

#define CH1 1   // Connect Digital Pin 8 on Arduino to CH1 on Relay Module
#define CH2 2   // Connect Digital Pin 7 on Arduino to CH3 on Relay Module
#define CH3 3   // Connect Digital Pin 8 on Arduino to CH1 on Relay Module
#define CH4 4   // Connect Digital Pin 7 on Arduino to CH3 on Relay Module
#define CH5 5   // Connect Digital Pin 8 on Arduino to CH1 on Relay Module
#define CH6 6   // Connect Digital Pin 7 on Arduino to CH3 on Relay Module
#define CH7 9   // Connect Digital Pin 8 on Arduino to CH1 on Relay Module
#define CH8 8   // Connect Digital Pin 7 on Arduino to CH3 on Relay Module
int seconds = 0;
int minutes = 1;
int hours = 0;
int days = 0;
int temp = 28; // not used
int tempset = 25; // turn on fan temp
int minmil = 1000; //clock 60000
int watertime = 8000; //water for 8 seconds =8000
int co2time = 8000; //water for 8 seconds =8000

void setup() {
  //Setup all the Arduino Pins
  pinMode(CH1, OUTPUT);//Lights
  pinMode(CH2, OUTPUT);//Water
  pinMode(CH3, OUTPUT);// CO2
  pinMode(CH4, OUTPUT);//FAN
  pinMode(CH5, OUTPUT);//FAN
  pinMode(CH6, OUTPUT);//FAN
  pinMode(CH7, OUTPUT);//FAN
  pinMode(CH8, OUTPUT);
}

void loop() {
  int readData = DHT.read11(dataPin); // Reads the data from the sensor
  float t = DHT.temperature; // Gets the values of the temperature
  float h = DHT.humidity; // Gets the values of the humidity
   Serial.print(minutes,2);
 Serial.print(" minutes  ");
 Serial.print(hours,2);
 Serial.print(" hours ");
 Serial.print(days,2);
 Serial.print(" days ");
 Serial.println();

//int chk = DHT.read11(DHT11_PIN);
 seconds=seconds+1;
   if (seconds >= 59) {
 minutes = minutes + 1;//adds to count
    seconds = 0;
  }
  if (minutes >= 59) {
    hours = hours + 1;
    minutes = 0;
  }
  if (hours >= 23) {
    days = days + 1;
    hours = 1;
  }
  if (days >= 31) {
    days = 1;
  }
  if ((days <= 3) && (hours < 19)) {

    digitalWrite(CH1, LOW);//Lights on for first 3 days 12 hours per Day

  }
  if ((days <= 3) && (hours >= 19)) {

    digitalWrite(CH1, HIGH);//Lights on for first 3 days 12 hours per Day

  }

  if ((days > 3) && (hours < 16)) {

    digitalWrite(CH1, LOW);//Lights on for first 3 days 12 hours per Day

  }
  if ((days > 3) && (hours >= 16)) {

    digitalWrite(CH1, HIGH);//Lights on for first 3 days 12 hours per Day

  }

  if (tempset < t) { // TURN ON FANS IF ABOVE TEMP SET POINT
    digitalWrite(CH4, LOW);//Lights on for first 3 days 12 hours per Day
    digitalWrite(CH5, LOW);//Lights on for first 3 days 12 hours per Day
    digitalWrite(CH6, LOW);//Lights on for first 3 days 12 hours per Day
    digitalWrite(CH7, LOW);//Lights on for first 3 days 12 hours per Day
  }
  if (tempset >= t) { // TURN ON FANS IF ABOVE TEMP SET POINT
    digitalWrite(CH4, HIGH);//Lights on for first 3 days 12 hours per Day
    digitalWrite(CH5, HIGH);//Lights on for first 3 days 12 hours per Day
    digitalWrite(CH6, HIGH);//Lights on for first 3 days 12 hours per Day
    digitalWrite(CH7, HIGH);//Lights on for first 3 days 12 hours per Day
  }

 // if (( (hours % 2) == 0) && (minutes == 30)) { //Water every 2 hours @ 30 minute Mark
if (minutes == 3) { //Water every 2 hours @ 30 minute Mark
    digitalWrite(CH2, LOW);//
    delay(watertime); //how long water pump is engaged
    minutes = minutes + 1;
  }
  else {
    digitalWrite(CH2, HIGH);//
  }
 // if (( (hours % 2) == 0) && (minutes == 45)) { //CO2 Released every 2 hours @ 45 minute Mark
 if  (minutes == 5) { //CO2 Released every 2 hours @ 45 minute Mark
    digitalWrite(CH3, LOW);//CO2
    delay(co2time); //how long CO2 is released
    minutes = minutes + 1;
  }
  else {
    digitalWrite(CH3, HIGH);// no CO2
  }
  delay(minmil);  // (60000) - 1 minute Delay
}

Question:  how could we alter the code in order to release co2 every 90 minutes?

Do a counter for minutes and every 90 minutes you release co2 and reset the counter.

Straight answer to the question as asked:
To make it do this every 90 minutes would be
if ((hours / 60 + minutes) % 90) == 0) {

If you want something to happen every 5 minutes you would write it like this:
if ((minute % 5) == 0) {

I hope you can find someone who can make some improvements on this.  There are much better ways to do it, beginning with a DS3231 Real-Time Clock module.
Good luck with this.

Just about all the comments are lying, mostly from copy paste-code-edit where the comment wasn't edited. It's a great example of why comments should not be used to explain code.
The timing code is full of off-by-one errors. The seconds go from 0 to 58, minutes also goes from 0 to 58, hours goes from 1 to 22, and days goes from 1 to 30.
The comments say that it runs the loop() once every minute but instead it's once a second.
There is no hysteresis on the fan control. Which means that in the worst case the fans can cycle on and off every time it runs through loop().
The CH1, CH2, etc. can be named much better like RELAY_LIGHT, RELAY_WATER, RELAY_CO2, etc. After you do that you won't need the comment on each digitalWrite.
Turning off the water and CO2 after they have been activated can be done by setting a timestamp of when to turn it off in the globals and then checking that:
if (((hours % 3 == 0 && minutes == 0)  ||
    (hours % 3 == 1 && minutes == 30)) && seconds == 0) {
    digitalWrite(RELAY_CO2, LOW);
    CO2RelayOffDays = days;
    CO2RelayOffHours = hours;
    CO2RelayOffMinutes = minutes
    CO2RelayOffSeconds= seconds + CO2_ON_TIME;
    if(CO2RelayOffSeconds >= 60){
        CO2RelayOffSeconds -= 60;
        CO2RelayOffMinutes++;
    }
    if(CO2RelayOffMinutes >= 60){
        CO2RelayOffMinutes -= 60;
        CO2RelayOffHours++;
    }
    if(CO2RelayOffHours >= 24){
        CO2RelayOffHours -= 24;
        CO2RelayOffDays++;
    }
    if(CO2RelayOffDays >=30){
        CO2RelayOffDays -= 30;
    }
}

if(days == CO2RelayOffDays && hours == CO2RelayOffHours && minutes == CO2RelayOffMinutes && seconds == CO2RelayOffSeconds){
    digitalWrite(RELAY_CO2, HIGH);
}

Every 90 minutes means when hours:minutes (modulo 3 hours) is equal to 0:00 or 1:30. But another option is keeping a timestamp of when to turn it on next by adding 1 hour and 30 seconds each time to it you turn it on.
Every 5 minutes is when minutes%5 == 0.
You can collect the various timestamps I suggest into a struct each and then provide a function that will wrap everything appropriately.
void wrapTimestamp(TimeStamp *timestamp){
    if(timestamp->seconds >= 60){
        timestamp->seconds = timestamp->seconds%60;
        timestamp->minutes += timestamp->seconds/60;
    }
    if(timestamp->minutes >= 60){
        timestamp->minutes = timestamp->minutes%60;
        timestamp->hours +=timestamp->minutes/60;
    }
    if(timestamp->hours >= 24){
        timestamp->hours = timestamp->hours%24;
        timestamp->days +=timestamp->hours/24;
    }
    if(timestamp->days >=30){
        timestamp->days = timestamp->days%30;
    }
}

You should consider adding a real-time-clock module that will have much less drift than delay.

@SDsolar they are nearly all wrong. I wanted strong language to emphasize that they should be taken with a large grain of salt.

I agree with nearly everything you said.  If it were me I would indeed do what you said:  add a DS3231 clock module and start over.  But the OP says this is inherited code and that a rewrite is beyond their capability, alas.

There is nothing that happens every 150 minutes!
The (hours % 2) == 0 would be true every 2 hours.
NOTE this is terrible code! I hope nothing is to dependent on things happening at a definite time, because the internal clock will drift and no allowance is made for the time other code takes to execute.

There was something that happened every 2 hours at the 30 minutes mark (which is not 150 minutes, but easily confused for it), however that was commented out.

source: Stack Exchange

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

sort: votes


text:
esp32 pico kit - actual clock speed vs crystal vs max_speed etc
I am trying to understand how the clock speed in the esp32 works.
I am running arduino ide 1.8.12 with 1.04 board definition - on a pico kit 4 module .
The device datasheet says it has a 40mhz crystal.
getCpuFrequencyMhz() reports 240mhz
But the following code is generating 1sec interrupts with 80mhz as a base i.e., as if the clock speed is 80mhz.
If I explicitly set the clock speed to 80 mhz then getCpufrequency correctly reports it as 80, and the code still keeps generating 1sec interrupts (as it should at 80). If I set the clock to 40mhz then I finally see interrupts at 2 secs as would be expected. What is the deal with the 240 report for what is actually 80 and where is 80 coming from on a supposedly 40 mhz part?
I am sure that the explanation is somewhere in expressif's docs, but I have been unable to glean it. Can anyone quickly explain what is going on or point me to some resource that explains this particular circumstance?
---------------
Sample output
getCpuFrequencyMhz() = 240
interrupts so far = 1 - : - mills() = 1018
interrupts so far = 2 - : - mills() = 2018
interrupts so far = 3 - : - mills() = 3018
interrupts so far = 4 - : - mills() = 4018
interrupts so far = 5 - : - mills() = 5018

----------------Sample code
#include "esp32-hal-cpu.h"

volatile int interruptCounter;
int totalInterruptCounter;

hw_timer_t * timer = NULL;
portMUX_TYPE timerMux = portMUX_INITIALIZER_UNLOCKED;

void IRAM_ATTR onTimer() {
  portENTER_CRITICAL_ISR(&timerMux);
  interruptCounter++;
  portEXIT_CRITICAL_ISR(&timerMux);

}

void setup() {

  Serial.begin(115200);

  Serial.printf("getCpuFrequencyMhz() = %d\n",getCpuFrequencyMhz()); //Get CPU clock

  timer = timerBegin(0, 80, true);
  timerAttachInterrupt(timer, &onTimer, true);
  timerAlarmWrite(timer, 1000000, true);
  timerAlarmEnable(timer);

}

void loop() {

  if (interruptCounter > 0) {

    portENTER_CRITICAL(&timerMux);
    interruptCounter--;
    portEXIT_CRITICAL(&timerMux);

    totalInterruptCounter++;

    Serial.printf("interrupts so far = %d - : - mills() = %d \n", totalInterruptCounter, millis());

  }
}

look at the link in section 3.3.3 of this ... https://www.espressif.com/sites/default/files/documentation/esp32_datasheet_en.pdf ... section 4.2 in that link

@jsotola Thanks that is definitely helpful. I am not sure yet if it explains everything, but it does appear to have some of the key missing elements.

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


text:
sent commends by bluetooth to sd card as one line of string
 void loop() {

  if (Bluetooth.available() > 0) {
           dataIn = Bluetooth.readString();
   //the problem is here
           while(dataIn !=""){
                   dataSd += dataIn;
                   dataSd += "," ;
           }

 if (dataIn.startsWith("s1")) {-----------}
 if (dataIn.startsWith("save"){ save to sd card }

// what I want is to sent command by bluetooth to variable dataSd as a line
of string seperated by commas
like ("left,right,up,down,left,stop,right") and  when i send command save, it
will save to sd card, but this code didnt work

while loop didnt work does not mean anything useful ... what did happen?

And please provide a full compilable code, which is formatted correctly

sorry this is the first time i posted something here now i modified the code

What's the reason for that while ? It won't ever stop repeating

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


text:
Arduino Due power supply
I have an Arduino Due.  It communicate to the computer with the native usb port. It is also powered by the native port. Anyway, the connected sensors are pretty sensitive to the current, thus I would like to use a power supply (as a portable smartphone charger) in order to provide the current at the Arduino.
How can I say to the Arduino to get the current from another 'port' (e.g. the serial programming) and use the native port only for the communications?

You can't really fiddle with the power circuitry of the Due. If external sensors need more power than the due can provide through its internal 5V connection, whatever you choose that to be (dictated by the USB connection used) then you will either have to use a higher voltage to feed the barrel jack, or better, power the sensors separately to the Due. Just remember to connect the grounds.

beside, the USB power selector on the Arduino 2 is pretty crappy. The serial programming port has a pMOSFET connected as an "ideal diode" (gate grounded, drain toward the power). The other port has a similar connection, except that the gate is driven by a comparator circuit. However if Vin=0, the comparator outputs 0, and drives the gate low. The problem is that a mosfet connected as an "ideal diode", once it's on, it also conducts backwards, as long as VGS > VTH. Therefore current can flow between the VDD of two USB ports... Yes, the same can occur with external VIn and the serial USB.

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


text:
Arduino Uno as USB to Serial converter (bypass 328p)
I'm trying out computer to computer serial communication using 2 Arduino Unos (both connected to different computers).
Right now, I use the Software Serial library, which redirects data from the SoftwareSerial ports to the hardware Serial (over USB to the PC).
Is there any way to bypass the 328p chip, and only use the 16U2, which works as a USB to Serial converter?
Will the circuit in the diagram work? By connecting the GND to RST on both the Unos, the 328p gets disabled, which in theory should all me to directly tap into the serial line of the 16U2.

Have you tried it?

Just tried it, it works fine. Tried 1 mega-baud, but there were a few errors

That's to be expected.

I'd probably add some resistors in between, in case the ground potential of both PC is a bit off. Not sure if this adequate, or if this is even a problem to begin with.

i don't think you want a resistor on the ground, if that's what you're getting at...

You may want a smallish (220ohm should be fine) resistor on each TX line in case the other device is accidentally configured as an output, but this is less of an issue on "known good" devices such as two Arduino Unos.

If your Arduino board has the Atmega328p in DIP format (not SMD), the best way is to extract it and you will have a pretty USB-UART so your schematic must work.

As per your diagram, ground the reset pin on both Arduinos and connect TX to RX on the one to RX to TX on the other. Alternatively, if your Unos have a socketed 328P, you can remove it.
(This answer summarized from the comments above in order to take it off the "unanswered" list.)

The circuit you have drawn will work for PC to PC coms. Essentially your connection diagram looks like this:
PC1 -(USB)- Arduino1 -(TTL serial)- Arduino2 -(USB)- PC2
To answer your second question, you can bypass the 328p chip by removing them both as they are not needed. The 16U2 converts the USB to TTL serial which it provides to the Arduino on pins 0 and 1. Since the ATmega328p microcontrollers aren't being used (ie in reset state) then you may as well remove them and use them on another project.

authors: Антон Якубович


text:
Linking Arduino and Matlab
My project is based on controlling a moving fan using different hand gestures. I am using image processing toolbox from matlab to detect and identify various hand movements.I want to link my matlab codes to arduino for hardware implementation. How to link these two?

this may help: arduino support from matlab. Firmata may also be what you need to link matlab to arduino.

Seems like Serial is often used but then you need a protocol. You can use everything from textual or binary blocks to more advanced parsing. To give you more advice you would need to describe what you want to communicate and how often (for the bandwidth and response time calculation).

This block of code can give you some idea...
% create an arduino object

a = arduino('com3', 'uno');

% start the loop to blink led for 10 seconds

for i = 1:10

    writeDigitalPin(a, 'D11', 1);

    pause(0.5);

    writeDigitalPin(a, 'D11', 0);

    pause(0.5);

end

% end communication with arduino

clear a

For more details on this code and working of it you can visit....
Here


text:
Data sent via UART Bluetooth different than SerialMonitor
I am using a 9-axis accelerator on an Arduino Uno (Atmega 328P processor) with a BLE Nordic rRF8001 chipset.
I am trying to send the accelerometer data via bluetooth to a smart phone (android).
The problem I am having is that the data shown on the serial monitor (which is correct, is not the data that is received via bluetooth. I think it has something to do with either the casting of the variables or that I am screwing up when converting the formats. Below is where I'm currently at and what I have tried.
The error I'm having is that the accelerometer data shown on the serial monitor screen (which is correct):

A_x: -0.12 A_y: 0.53 A_z: 0.83
A_x: -0.12 A_y: 0.53 A_z: 0.83
A_x: -0.12 A_y: 0.53 A_z: 0.83

Does not agree with what the smart phone receives: (See image 1)

If I hard code in the x,y,z values in the arduino sketch

float x = (float) 0.52;
float y = (float) 0.52;
float z = (float) 0.52;

I get the following results (see image 2):

And here is the Arduino sketch I am working with:
//-------------------------------------------------------------------------------
//  TinyCircuits 9 Axis and Nordic BLE TinyShield Example Sketch

#include <Wire.h>
#include "RTIMUSettings.h"
#include "RTIMU.h"
#include "RTFusionRTQF.h"
#include <SPI.h>

#include "lib_aci.h"
#include "aci_setup.h"
#include "uart_over_ble.h"
#include "services.h"

#if defined (ARDUINO_ARCH_AVR)
#define SerialMonitorInterface Serial

#elif defined(ARDUINO_ARCH_SAMD)
#define SerialMonitorInterface SerialUSB
#endif

#define DISPLAY_INTERVAL 100

RTIMU *imu;                                           // the IMU object
RTFusionRTQF fusion;                                  // the fusion object
RTIMUSettings settings;                               // the settings object

unsigned long displayInterval = 50;
unsigned long lastDisplay;
unsigned long lastRate;
int sampleCount;

#define BLE_DEBUG false
uint8_t ble_rx_buffer[21];
volatile uint8_t ble_rx_buffer_len = 0;
volatile uint8_t ble_can_sleep = false;
volatile uint8_t ble_connection_state = false;

#ifdef SERIAL_POR_MONITOR
  #define SerialMonitor SERIAL_PORT_MONITOR
#else
  #define SerialMonitor Serial
#endif

void setup(void)
{
//  SerialMonitorInterface.begin(230400);
  SerialMonitor.begin(230400);

  int errcode;

  while (!SerialMonitor);

  Wire.begin();
  imu = RTIMU::createIMU(&settings);                        // create the imu object

  SerialMonitorInterface.print("ArduinoIMU starting using device "); SerialMonitorInterface.println(imu->IMUName());
  if ((errcode = imu->IMUInit()) < 0) {
    SerialMonitorInterface.print("Failed to init IMU: "); SerialMonitorInterface.println(errcode);
  }

  if (imu->getCalibrationValid())
    SerialMonitorInterface.println("Using compass calibration");
  else
    SerialMonitorInterface.println("No valid compass calibration data");

  lastDisplay = lastRate = millis();
  sampleCount = 0;

  // Slerp power controls the fusion and can be between 0 and 1
  // 0 means that only gyros are used, 1 means that only accels/compass are used
  // In-between gives the fusion mix.

  fusion.setSlerpPower(0.02);

  // use of sensors in the fusion algorithm can be controlled here
  // change any of these to false to disable that sensor

  fusion.setGyroEnable(true);
  fusion.setAccelEnable(true);
  fusion.setCompassEnable(true);
  BLEsetup();
}

void loop() {
  aci_loop();//Process any ACI commands or events from the NRF8001- main BLE handler, must run often. Keep main loop short.
  unsigned long now = millis();
  unsigned long delta;

  if (imu->IMURead()) {                                // get the latest data if ready yet
    fusion.newIMUData(imu->getGyro(), imu->getAccel(), imu->getCompass(), imu->getTimestamp());
    sampleCount++;
    if ((delta = now - lastRate) >= 1000) {
      /*SerialMonitorInterface.print("Sample rate: "); SerialMonitorInterface.print(sampleCount);
        if (imu->IMUGyroBiasValid())
        SerialMonitorInterface.println(", gyro bias valid");
        else
        SerialMonitorInterface.println(", calculating gyro bias - don't move IMU!!");
      */
      sampleCount = 0;
      lastRate = now;
    }
    if ((now - lastDisplay) >= displayInterval) {
      lastDisplay = now;
      RTVector3 accelData = imu->getAccel();
      RTVector3 gyroData = imu->getGyro();
      RTVector3 compassData = imu->getCompass();
      RTVector3 fusionData = fusion.getFusionPose();
      char sendBuffer[30] = " ";
      uint8_t sendLength = 0;
      //displayAxis("Accel:", accelData.x(), accelData.y(), accelData.z());        // accel data
      //displayAxis("Gyro:", gyroData.x(), gyroData.y(), gyroData.z());            // gyro data
      //displayAxis("Mag:", compassData.x(), compassData.y(), compassData.z());    // compass data
      //displayDegrees("Pose:", fusionData.x(), fusionData.y(), fusionData.z());   // fused output
      float x = (float)(accelData.x() );//* RTMATH_RAD_TO_DEGREE);
      float y = (float)(accelData.y() );//* RTMATH_RAD_TO_DEGREE);
      float z = (float)(accelData.z() );// * RTMATH_RAD_TO_DEGREE);
//      float x = (float) 0.52;
//      float y = (float) 0.52;
//      float z = (float) 0.52;
      sendLength = sprintf(sendBuffer, "% 2.3d % 2.3d % 2.3d", x, y, z);
      if (sendLength > 20)sendLength = 20;
      if (!lib_aci_send_data(PIPE_UART_OVER_BTLE_UART_TX_TX, (uint8_t*)sendBuffer, sendLength))
      {
        SerialMonitorInterface.println(F("TX dropped!"));
      }
      SerialMonitorInterface.println();

      SerialMonitor.print(" A_x: "); SerialMonitor.print(x);
      SerialMonitor.print(" A_y: "); SerialMonitor.print(y);
      SerialMonitor.print(" A_z: "); SerialMonitor.println(z);

    }
  }
}

Any thoughts on why the data sent over BLE is incorrect?

The problem has nothing to do with the bluetooth. It is purely down to how you are formatting the data:
% 2.3d % 2.3d % 2.3d

d is a signed integer. You can't format a floating point value as a signed integer, it just messes up.
Also I don't think the Arduino's sprintf even has floating point support by default (it makes it all too big).
So you will need to find another way to format your data. Maybe use dtostrf() instead.

Thank you for the response. Using what you said as a starting point, I was able to piece together the solution.
Your statement about sprintf not having sprintf floating point support was also seen because the number recieved was really large compared to the value it should have been.
So my solution was to convert the floating point numbers to strings using dtostrf:
Ex:
dtostrf( x, 5, 2, tempx);
which I repeated for the other two variables.
Then in sprintf I changed the format to read:
sprintf(sendBuffer, "% 3s % 3s % 3s", tempx, tempy, tempz);
And it works perfectly!


text:
Major difference between DTR signal and RTS signal?
I actually had a doubt about what is the difference between the RTS signal and DTR signal ?
I already know this that the DTR signal is used to auto reset when we use Arduino and similar MCUs. Can anyone say what is the major difference between these signals and what is their active state ?

Electrically they are both the same. The difference is what they are used for.
DTR means Data Terminal Ready and indicates that the connected device is ready to receive data.

Data Terminal Ready (DTR) is a control signal in RS-232 serial communications, transmitted from data terminal equipment (DTE), such as a computer, to data communications equipment (DCE), for example a modem, to indicate that the terminal is ready for communications and the modem may initiate a communications channel.

RTS means Request To Send and indicates to the connected device that it wants to send data.

The DTE asserts RTS to indicate a desire to transmit to the DCE, and in response the DCE asserts CTS to grant permission, once synchronization with the DCE at the far end is achieved.

Basically DTR is used to indicate the presence of some equipment, and RTS is one half of hardware flow control (along with CTS) to start and stop communication.
On USB communication (e.g., using FT232 USB to UART adaptor, etc) the meaning is less clear. DTR is asserted when the port is opened (usually) and RTS is most likely not asserted at all. It's at the whim of the operating system and/or the driver whether DTR is automatically asserted or not, and whether RTS is even implemented.

I'd only add that the FTDI cables (at least the ones I have, from two different vendors) bring out CTS and RTS and assert RTS when the port is opened.

@Majenko Some devices such as an ESP device really needs DTR and RTS signal so how do they communicate through UART ICs. Do they both work the same ?

Very few devices these days use RTS and CTS for anything. Many mcus don't even have them. They were used more when devices couldn't keep up with the speed of serial communication. Now everything is so fast and serial is so slow CTS and RTS are almost redundant.

DTS and RTS are used on esp8266 boards with USB (Wemos, NodeMcu) to reset the board and to set io 0 low for bootloader mode. You can see it in source code of esptool.py. Sometimes you want a reset without going to bootloader mode.
RTS = either CH_PD/EN or nRESET (both active low = chip in reset
DTR = GPIO0 (active low = boot to flasher)

As a counter point, industrial systems utilize the UART protocol at much higher rates - 10 Mbits for example.   RTS/CTS can prove very useful when a large data set is being received at a higher rate.  We have clients using LVDS and RS-485 IO types for the higher speeds. DTR/DSR is occasionally used to see if the other equipment is on-line but this signal pair is in the rare to use category.


text:
How to use ESP8266 for wireless communication?
I saw many tutorial explaining how to program ESP8266 but Specifically I didn't get any tutorials explaining how to use with Arduino or any other Microcontroller for Wireless Communication. I had a doubt how could I use it with Arduino for Serial Communication such that I could use with my handset ( using Blynk ) and with my PC.

http://www.blynk.cc/getting-started/

I'm not very clear on what you are asking but I think you are saying how do you connect an ESP8266 to an Arduino so the Arduino has wireless(WIFI) access.
I'm sure there are tutorials out there so I won't go in to detail (also I don't know the details), but hopefully you will get some better terms to search with.
The basic idea is you connect the serial connection of the ESP8266 to the serial of the Arduino (via a level shifter and connect Tx to Rx).  You then write a series of AT commands to configure the ESP8266 so that what ever is receives over the serial it sends to a TCP endpoint via WIFI (and what it receives is sent to serial).
You can program the ESP via the Arduino IDE, so you could write a 'smarter' version that did all the setup for you, etc.  In fact since the ESP8266 is a faster processor with more RAM you could do a lot more on it.
If you are using an UNO or Nano you might want to look at the software serial library to let you keep the main serial port for debug messages.  If you are using a Mega then you can use one of the secondary serial ports.

But how could I use it with Blynk ???????

All described in tutorial I linked. Please read it, ask then more if not clear.

You follow the instructions from blynk.cc/getting-started which include quite simple steps:

1 create auth id
2 download and install blynk library
3 replace auth id in some example you can find from arduino ide
4 run code

More details from tutorial.


text:
Can you make Arduino Uno send information through a WiFi module to a server?
A lot of tutorials are about how to control Arduino through WiFi, but I need my Arduino to send information about motion sensor activity to a server. Is that possible?

The key words to search are "web request" together with arduino. I think there is a client library, that you can use. Depending on your used hardware

What do you want the server to do with your sensor activity? Have you looked into things like IoT (“internet of things”)?

Can you make Arduino Uno send information through a WiFi module to a server?

Yes, I can.
The simplest way is through an HTTP "GET" request. Every time you request a web page (and there are plenty of examples of that) you are sending data to the server to tell it both what web page to get (/foo/bar.php) and what data to submit to that web page (?baz=4).
It's then up to you to craft that GET request, such as:
GET /foo/bar.php?baz=4 HTTP/1.1
Host: example.com
Content-length: 0

and write the PHP web page (or whatever language you prefer to write web pages in) to do something meaningful with the "baz = 4" parameter.


text:
ESP32 stops looping after 2 loops
My code: https://pastebin.com/UmdK33U2
I made a menu so I can send commands. First I connect to the wifi and then I send the command to send a request.
Then when it detects the key datos(); goes true, so the loop detects that and it starts sending requests.
After 2 requests it just doesnt continue.
What I can do?
Btw im using a ESP32.
Thank you!
boolean datos = false;

#include <WiFi.h>
#include <HTTPClient.h>

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

//removed the password and ssid for security, it was there before.
void setup() {
  pinMode(2, OUTPUT);
  Serial.begin(115200);

  while (!Serial)
    ;
  Serial.println("===================================================");
  Serial.println("Welcome to the menu, choose what do you want to do:");
  Serial.println("1º Connect to the Wifi | W");
  Serial.println("2º Scan Wifi | S");
  Serial.println("3º Send data to Website | D");
  Serial.println("===================================================");
  Serial.println("Made by Francine and Javi.");
  Serial.println("===================================================");
}

void scanwifi() {
  int n = WiFi.scanNetworks();
  Serial.println("===================================================");
  Serial.println("Scan have been finished.");
  Serial.println("===================================================");
  if (n == 0) {
    Serial.println("===================================================");
    Serial.println("No networks have been found.");
    Serial.println("===================================================");
  } else {
    Serial.print(n); // imprimir en el puerto serial el # de redes encontradas
    Serial.println(" networks have been found.");
    for (int i = 0; i < n; ++i) {
      // SSID: Nombre de la red; RSSI: Potencia de la red en dBm
      Serial.print(i + 1); //iniciamos en la red # 1...
      Serial.print(": ");
      Serial.print(WiFi.SSID(i)); //Imprime el nombre de la red
      Serial.print(" (");
      Serial.print(WiFi.RSSI(i)); //Imprime la potencia de la señal en dBm
      Serial.print(")");
      byte encryption = WiFi.encryptionType(i); // en la variable encryption, guardamos el tipo de encriptación de la red
      Serial.print(" Encryption Type: ");
      Serial.println(encryption, HEX); // imprimimos el tipo de encriptación: 2: WPA, 5: WEP, etc.
      delay(10);
    }
  }
}

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

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);

    Serial.println("Connecting to WiFi..");
  }

  Serial.println("Connected to the WiFi network");
  delay(1000);
  setup();
}

void loop() {
  if (Serial.available()) {
    char ch = Serial.read();
    if (ch == 'w' || ch == 'W') {
      conectarsealwifi();
    }
    if (ch == 'S' || ch == 's') {
      scanwifi();
    }
    if (ch == 'd' || ch == 'D') {
      datos = true;
      Serial.println(datos);
    }
    if (datos == true) { // si esta habilitado el sending de datos haz
      //randomN = random(200);
      if (WiFi.status() == WL_CONNECTED) {
        digitalWrite(2, HIGH);
        HTTPClient http;

        http.begin("removedtheurl"); //Specify the URL
        int httpCode = http.GET();                            //Make the request

        if (httpCode > 0) { //Check for the returning code

          String payload = http.getString();
          Serial.println(httpCode);
          Serial.println(payload);
          Serial.println("===================================================");

        } else {
          Serial.println(
              "Error on HTTP request, reminder maybe its cloudflare shit.");
        }
        http.end(); //Free the resources
        digitalWrite(2, LOW);
      }
      delay(2000);

    } else {

    }
  }
}

If you fix your indenting you'll soon find your problem.

@Majenko Hi, thank you for responding. I dont understand your response, im not a foreign speaker, mind explaining better the solution to my problem?

The basic layout (indenting) of your program is a mess. If you fix that and lay it out properly you will be able to follow the flow of your program better, and the reason for its behaviour will become apparant.

@Majenko What I checked is that if I type nothing and I send it the loops continues for 1 row then bakc to normal.

I know. I can see that by just looking at the flow of your program (after fixing the indenting). If you don't know how to indent properly then please use the auto-format facility in the IDE to do it for you.

Incidentally, I see that Juraj has fixed it for you in your post. Take a look at that version and tell me where the problem is.

You send from Serial Monitor a character followed by a new line character. This two characters are available. Nothing more to enter the if (Serial.available()) { block.

Thank you for your response. How can I apply it on my code?

by moving the if (datos) { block out of if (Serial.available()) { block?

Thank you, it is working. Have a good day.


text:
Burning bootloader and uploading sketch on ATMEGA328
I have a ATMEGA328-PU (not a atmega328P-PU) and managed to install the boot loader on it using an Uno as ISP, but now i can not upload any sketch, this are the steps I've done so far:
connected this pins:
reset to pin10
11 to 11
12 to 12
13 to 13
and 5V to 5V and ground to ground.
uploaded ArduinoISP from examples and then changed the programmer to Arduino as ISP.
Then i changed this line in avrdude.conf:
part parent "m328"
    id          = "m328p";
    desc        = "ATmega328P";
    signature       = 0x1e 0x95 0x0F;

    ocdrev              = 1;
;

to:
part parent "m328"
    id          = "m328p";
    desc        = "ATmega328P";
    signature       = 0x1e 0x95 0x14;

    ocdrev              = 1;
;

selected burn bootloader and uploaded the boot loader with success.
and then i removed pin 10 to 13 and connected reset to reset, RX to RX and TX to TX and removed the chip from Arduino UNO.
added this lines to boards.txt:
##############################################################

uno328.name=Arduino328

uno328.vid.0=0x2341
uno328.pid.0=0x0043
uno328.vid.1=0x2341
uno328.pid.1=0x0001
uno328.vid.2=0x2A03
uno328.pid.2=0x0043
uno328.vid.3=0x2341
uno328.pid.3=0x0243

uno328.upload.tool=avrdude
uno328.upload.protocol=arduino
uno328.upload.maximum_size=32256
uno328.upload.maximum_data_size=2048
uno328.upload.speed=115200

uno328.bootloader.tool=avrdude
uno328.bootloader.low_fuses=0xFF
uno328.bootloader.high_fuses=0xDE
uno328.bootloader.extended_fuses=0xFD
uno328.bootloader.unlock_bits=0x3F
uno328.bootloader.lock_bits=0x0F
uno328.bootloader.file=optiboot/optiboot_atmega328.hex

uno328.build.mcu=atmega328
uno328.build.f_cpu=16000000L
uno328.build.board=AVR_UNO
uno328.build.core=arduino
uno328.build.variant=standard

Selected that from board menu changed the programmer to AVRISP mkll and tried to upload the blink sketch but it stuck on "uploading" and after a while says "an error occurred during upload".
I triple checked the wiring!

Is your chip set up with a crystal/caps, or a resonator?  The chip needs an external clock source since that's your fuses are set up for.  "changed the programmer to AVRISP mkll" This will do nothing unless you have a Programmer connected to the ICSP pins.   What is connected to what here: "connected reset to reset, RX to RX and TX to TX and removed the chip from Arduino UNO."?

@CrossRoads yes it have a crystal and two capacitors, i wanna use the Arduino as programmer... WIRES connected those pines together.

newbie, use the https://github.com/MCUdude/MiniCore to burn the bootloader and serial upload. btw: you can put the 328 in the socket on Uno

"managed to install the boot loader on it" How did you do that? Do you have another board you are using as a Programmer? Or do you have a Programmer?

@CrossRoads, it started here https://arduino.stackexchange.com/questions/66694/atmega328p-u-vs-atmega328-pu this question make more sense if you put the informations together. but you should read this question again

Not really. There is no indication of how the bootloader was installed.

@Juraj thanks i'll try that and let you know what happened.

@Juraj i placed the 328 on arduino and installed that library from github then followed the instruction but i'm still getting this error: "An error occurred while uploading the sketch"!

@Juraj the led on pin 13 is blinking tho... i have no clue...

sorry, you should burn a 328 bootloader from that package first

the instruction didn't say anything about that, how do i do that? @Juraj

same way like before, only with MiniCore. choose the right settings in Tools menu

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

Use the https://github.com/MCUdude/MiniCore for ATmega328. It has Boards Manager installation. Choose the right options in Tools menu for your ATmega328.
First burn the bootloader using programmer or "Arduino as ISP". Then you can do serial upload as usual.
You can put the ATmega328 on Uno if you want.


text:
Arduino IDE 2.0 Beta doesn't start
Yesterday i downloaded the new version of the IDE to take advantage of all the new features, but it just won't open. I tried installing it to different paths, different PC's, i deleted the package_index.json and the cache folder, but nothing. It stucks in the opening screen (see image below), any other ideas?

Run it from the command line and see what errors you get? Maybe raise an issue on the github repo. It's beta software. Don't expect it to work, and if you want to use it, be prepared to debug it.

I've used v1.9 beta for 2 years; it has been stable and lots faster than 1.8 which was miserably slow to launch (macOS). 2.0 beta is described as "Experimental Software". Based on that, and your experience, I'd probably call it 2.0 alpha. But, yeah, if it's not a released version, somebody doesn't feel it's ready for prime time.

Arduino IDE 2.0 is a very slow start up. How long did you wait? I've since uninstalled it. I recall the start up splash screen being there at least a minute, which is longer than most people would normally wait for a splash screen.

FWIW, I'm running Beta 7 on a 2019 MBP w/ 16G and it's ready to go in about 7 sec, and that's w/ a hefty suite of Docker microservices running and RubyMine and DataGrip in the throes of a large project.

I have a very slow internet connection and the Arduino IDE seems to depend a lot on it. When I launch it, I shut down internet and it opens in a breeze.

About the only time arduino-cli cares about your connection is when you're downloading new board definitions or libraries.

Perhaps you meant "and the Arduino IDE 2.0 seems to depend a lot on it." ?

Noted. I guessed it was the cli the one blocking it from the notification pop-up you get when you start it offline.


text:
Multiple arduino connections problem
I have 2 Arduino Mega 2560 connected via USB to my Ubuntu 18.04 machine. When I boot, one connects to /dev/ttyACM0 and the other connects to /dev/ttyACM1.
Communication works perfectly. However, randomly on boot, the Arduino boards connect to the opposite port of what is coded into the script. I use Python 3.6 to communicate with the boards.
Is there any way to force these boards to always connect to the same port? Or is there a way for Python to detect the board that it's talking to?

https://majenko.co.uk/blog/making-your-boards-unique-linux

Thanks. Simpler solution found here. raspberrypi.org/forums/viewtopic.php?t=216907


text:
Http request change delay
i'm noob in coding i try to make some led blink ( with succes ) and now i would like to add http request to change delay.
i have no error compiling the code but it dont work any idea ?
Thanks
 include SPI.h
 include Ethernet.h

unsigned long maxTime = 4000;

EthernetServer arduinoServer(81);
EthernetServer httpServer(80);

// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
IPAddress ip(192, 168, 8, 60);

// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(80);

////CODE IS 11001010
int led1 = 6;  // = 0
int led2 = 7;  // = 1

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

  // Setup the 3 pins as OUTPUT
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);

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

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

  // start the Ethernet connection and the server:
  Ethernet.begin(mac, ip);

  // Check for Ethernet hardware present
  if (Ethernet.hardwareStatus() == EthernetNoHardware) {
    Serial.println("Ethernet shield was not found.  Sorry, can't run without hardware. :(");
    while (true) {
      delay(1); // do nothing, no point running without Ethernet hardware
    }
  }
  if (Ethernet.linkStatus() == LinkOFF) {
    Serial.println("Ethernet cable is not connected.");
  }

  // start the server
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());

}

void loop()
{
  digitalWrite(led1, LOW);
  digitalWrite(led2, HIGH);
  delay(maxTime);
  digitalWrite(led2, LOW);
  delay(maxTime);
  digitalWrite(led1, LOW);
  digitalWrite(led2, HIGH);
  delay(maxTime);
   digitalWrite(led1, HIGH);
   digitalWrite(led2, LOW);
  delay(maxTime);
  digitalWrite(led1, LOW);
   delay(maxTime);

   digitalWrite(led1, HIGH);
   digitalWrite(led2, LOW);
  delay(maxTime);
   digitalWrite(led1, LOW);
   digitalWrite(led2, HIGH);
  delay(maxTime);
   digitalWrite(led1, HIGH);
   digitalWrite(led2, LOW);
  delay(maxTime);
   digitalWrite(led1, LOW);
   digitalWrite(led2, HIGH);
  delay(maxTime);
   digitalWrite(led1, HIGH);
   digitalWrite(led2, LOW);
  delay(maxTime);
     digitalWrite(led1, LOW);
   digitalWrite(led2, LOW);
  delay(5000);

 // listen for incoming clients
}

void receiveHttpRequest() {
  EthernetClient client = httpServer.available();
  String requestInputString;
  boolean resetArduino = false;
  boolean forceSolved = false;
  client.setConnectionTimeout(50);

  if (client)
  {
    Serial.println("new client");
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;
    boolean firstLine = true;
    requestInputString = String("");
    while (client.connected())
    {
      if (client.available())
      {
        char c = client.read();
        if (firstLine)
        {
          requestInputString += String(c);
        }
        Serial.write(c);
        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
        if (c == '\n' && currentLineIsBlank)
        {

          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println("Connection: close"); // the connection will be closed after completion of the response
          client.println();
          client.println("<!DOCTYPE HTML>");
          client.println("<html><body>");

            int newMaxTime = requestInputString.substring(20).toInt();
            if (newMaxTime < 2000) {
              newMaxTime = 2000;
            }

            maxTime = newMaxTime;

            client.print(String("New maxTime is: "));
            client.println(maxTime);
          }
        }
      }
    }
  }

At no point do you call receiveHttpRequest(). Just making a function isn't good enough - you have to actually call that function.

Inside delay() no other code can run. Which also means that no clients can be serviced.
Change that delay-laden function to a state machine mirroring blinkWithoutDelay.
That is you test if(millis() - previousTimestamp < delay) and if true progress to the next state in your blinks and update previousTimestamp.
After that if you call receiveHttpRequest() to see if any clients are waiting and process the input.


text:
Millis () funtion fails to perform for extended period of time
I'm using millis () function to control the timer of my LED. It is a very basic code that I used from the example libraries. The code worked well for 6 hours (On for 6 h, Off for the following 6 h and continues), however, when I set it up for 12 hours, the light failed to turn off when I checked on it. The designed time should have fit into the 2^32 bits for unsigned long which I have defined beforehand.
Can someone please help on this issue? Thank you!
/*
  Blink without Delay

  Turns on and off a light emitting diode (LED) connected to a digital pin,
  without using the delay() function. This means that other code can run at the
  same time without being interrupted by the LED code.

  The circuit:
  - Use the onboard LED.
  - Note: Most Arduinos have an on-board LED you can control. On the UNO, MEGA
    and ZERO it is attached to digital pin 13, on MKR1000 on pin 6. LED_BUILTIN
    is set to the correct LED pin independent of which board is used.
    If you want to know what pin the on-board LED is connected to on your
    Arduino model, check the Technical Specs of your board at:
    https://www.arduino.cc/en/Main/Products

  created 2005
  by David A. Mellis
  modified 8 Feb 2010
  by Paul Stoffregen
  modified 11 Nov 2013
  by Scott Fitzgerald
  modified 9 Jan 2017
  by Arturo Guadalupi

  This example code is in the public domain.

  http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
*/

// constants won't change. Used here to set a pin number:
const int ledPin =  7;// the number of the LED pin

// Variables will change:
int ledState = LOW;             // ledState used to set the LED

// Generally, you should use "unsigned long" for variables that hold time
// The value will quickly become too large for an int to store
unsigned long previousMillis = 0;        // will store last time LED was updated

// constants won't change:
unsigned long interval = 12*60*60*1000UL;           // interval at which to blink (milliseconds)

void setup() {
  // set the digital pin as output:
  pinMode(ledPin, OUTPUT);
}

void loop() {
  // here is where you'd put code that needs to be running all the time.

  // check to see if it's time to blink the LED; that is, if the difference
  // between the current time and last time you blinked the LED is bigger than
  // the interval at which you want to blink the LED.
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }

    // set the LED with the ledState of the variable:
    digitalWrite(ledPin, ledState);
  }
}

please look at your post ... does the program listing look the way you intended it to look? ... please format your code ... use the {} button

use unsigned long interval = 1000UL*12*60*60*;

In C++, the multiplication operator is “left-associative”. This means
that the expression
12*60*60*1000UL

is interpreted as
((12*60)*60)*1000UL

The left factor, namely (12*60)*60, is computed using the int data
type, but the result overflows that format, resulting in the problem you
see.
The simple solution is to make one of the factors of the first product
be an unsigned long. For example
1000UL*60*60*12

Then, 1000UL*60 is computed with the unsigned long data type. Since
the result is itself an unsigned long, the next multiplication is also
done as unsigned long, and likewise for the last one.
If you find this technique somewhat obscure, you can also add the UL
suffix to every single factor. This would avoid implicit conversions by
the compiler, making all the types explicit.

The problem is panned out! Thank you sir! Programming is not my field at all and so I am clearly with no base. Your comment is very helpful and much appreciated.

Did you try to change your variables so that the calculations would be in seconds instead of milliseconds ? IOW add "/1000" after millis() and reduce your constants accordingly.
millis() is overflowing periodically, but it only happens every 49 days or so, and that even shouldn't play a role in the way you use it (the difference will also kind of overflow in the other direction).

Do not add /1000 after millis(), otherwise you will have a problem when millis() rolls over.


text:
Serial.println() not working in ISR
Please refer my below code,
const int led_pin = PB5;
const uint16_t t1_load = 0;
const uint16_t t1_comp = 43750;
int blinkcount;

void setup() {
  // put your setup code here, to run once:
  DDRB |= (1<< led_pin);
  TCCR1A = 0;
  //TCCR1B = 0X03;
 TCCR1B |= (1 << CS12);
 TCCR1B &= ~(1 << CS11);
 TCCR1B &= ~(1 << CS10);

  TCNT1 = t1_load;
  OCR1A = t1_comp;

  TIMSK1 = (1 << OCIE1A);
  Serial.begin(9600);
  sei();

}

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

}

ISR(TIMER1_COMPA_vect) {
  TCNT1 = t1_load;
  PORTB ^= (1 << led_pin);
  blinkcount = blinkcount + 1;
  Serial.println(blinkcount);
}

the Serial.println(blinkcount); not working or the serial window does not show up.
Apologies if it sound stupid as I'm new to programming.

please format your code .... you don't print inside ISR .... increment variable and set a second flag variable instead ... check for flag in loop() and print if the flag is set

thank you for support

@jsotola can you please review the changed code and share your suggestion?

ISR are simply not intended for this abuse.
If you want to use Arduino level functions, you must have good reasons why you need to mix them with direct arv-gcc hardware-accessing code (or vice versa).
If you're new to programming and to Arduino, simply ignore that level (for now).
DDRB |= BV(PB5);
is easier understandable if you write
pinMode(13,OUTPUT); ( or even use LED_BUILTIN instead of 13 )

const uint16_t t1_load = 0;
const uint16_t t1_comp = 43750;
int blinkcount;
int flag, flag_1, a, i;

void setup() {
  // put your setup code here, to run once:
  DDRB |= (1<< led_pin);
  TCCR1A = 0;
  //TCCR1B = 0X03;
 TCCR1B |= (1 << CS12);  //for 256 prescalar
 TCCR1B &= ~(1 << CS11);
 TCCR1B &= ~(1 << CS10);

/* TCCR1B &= ~ (1 << CS12);
 TCCR1B |= (1 << CS11);
 TCCR1B &= ~(1 << CS10);*/

  TCNT1 = t1_load;
  OCR1A = t1_comp;

  TIMSK1 = (1 << OCIE1A);
  Serial.begin(9600);
  sei();

}

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

/*  blinkcount = blinkcount + 1;
  if(blinkcount++)
  {
    flag = 1;
  }
  if(flag == 1)
  {
    Serial.println("ok");
  }*/

}

void loop_1()
{
  i = blinkcount;
  //for(i=0; i<=blinkcount; i++);
  //{
  i = i + 1;
  //if(i++)
  // {
    flag = 1;
    flag_1 = flag;
   //}
  if(flag_1 == 1)
  {
    Serial.println(flag_1);
  }
//  }
}

ISR(TIMER1_COMPA_vect) {
  TCNT1 = t1_load;
  PORTB ^= (1 << led_pin);
  //blinkcount = blinkcount + 1;
  //Serial.println(blinkcount);
  loop_1();

}```

I've changed the code according to your suggestion, the tx led on arduino blinks but serial monitor does not pop up

loop_1 is (logically) still part of the ISR. Serial.println() not working in ISR is a fact, not a question.  Don't use ISRs if you don't need OR understand it. In your case both conditions apply. Sorry.


text:
Serial Moniter is repeating output
I do apologize for the constant posts on here.  However I ran into an issue and I cannot seem to find any solution to it.  The goal is to enter a username, through the Serial.read function, and if the username matches it simply responds "Welcome Steven", and lights a green LED, when the wrong username is submitted it responds "Access Denied" and lights a red LED.  So far the code works in response to access granted, and access denied, while also lighting the appropriate LEDs.  However the Serial Monitor does not wait until there is a user input, it automatically starts repetitively "access denied" and lights the red LED.  When the username is entered the red LED turns off, the green LED turns on, and Serial Monitor repetitively responds "Welcome Steven".  I can do this multiple times, and each time it will change state.  I have looked at many tutorials and read many posts on here concerning issues, but so far nothing has worked out. Even tried making changes NickGammon suggested in another post.  Would like to get rid of the repetitive issue, and wait for user input before access denied or granted appears.
int led1 = 9;
int led2 = 10;
String user_name;

void setup()
{
  Serial.begin(9600);
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  Serial.println("Enter Username");
}

void loop()
{
 if(Serial.available())
   user_name = Serial.readStringUntil('\n');
{

if(user_name == "Grantham1")
{
  Serial.println("Welcome Steven");
  digitalWrite(led1, HIGH);
  digitalWrite(led2, LOW);
}
else if(user_name != "Grantham1")
{
  Serial.println("Invalid Input");
  digitalWrite(led1, LOW);
  digitalWrite(led2, HIGH);
}
else
{
  Serial.println("Waiting Pateintly");
  digitalWrite(led1, LOW);
  digitalWrite(led2, LOW);
}
}
}

your code is badly formatted .... indentation is not what it should be .... that makes it very difficult to follow the program flow ..... please correct the formatting and the cause of the problem may become apparent at first glance

@jsotola i edited the code, hope its better.  Also for some reason I tried a separate code (for some reason would only accept 4 char lines for an array instead of the 9) but when i tried to re-upload this one, it quit working on me.  Still repetitively saying "access denied" but when i enter "Grantham1" it will no longer read it,

i do not understand how you  are able to run this code .... it has errors and does not compile as a result

@jsotola That could be why it stopped working for me properly after I had uploaded a different code.  Every time I compile a new code now, my error window will flash orange, but complete the compile.  I managed to build a shorter and much more simpler code for this program, but still having the same issue with the Serial Monitor.  Ill update the code through edit.

Change
if(Serial.available())
    user_name = Serial.readStringUntil('\n');
{

to
if(Serial.available()) {
    user_name = Serial.readStringUntil('\n');

Edit: The reason why it didn't work properly was because all subsequent ifs were evaluated repeatedly regardless of whether there was anything new in the serial buffer or not. The modification fixes that problem.

It did work thank you. I thought I had all the necessary {} in there.  Im a little surprised it didnt give me a compiler error for lacking them while uploading.

@Steven The if (statement) command; is completely valid in C++ and the stand alone block { commands; } is also perfectly valid in C++

@Steven, accept the answer if it works now

@Juraj Accepted the answer, I apologize for taking so long to do so.

@KIIV Im intermediate in C++ probably why im having so many issues with coding in the Arduino.  Wish i could just write with Python that language made so much more sense to me.


text:
Where is my BUG?
Thank you everyone for help on my last post, i managed to make it work.  I still keep trying to craft my skill with the arduino.  This time I need to make a coffee hot plate simulation.  When the sensor is not up to temp an LED will blink, once the sensor gets up to temp the LED will blink but turn off (go to low) after five seconds. This is the code i am working on.  The sensor is at temp and the LED is still blinking instead of turning off.  When its low it blinks as should.  I think the bug is in the millis() portion of code.  Any ideas would be greatly appreciated.  I also ran the println screen, and the temp is consistantly around 210-220.
const int led         =  11;       // hot plate led on pin 11
const int sensor      =   9;       // temp sensor on pin 9
const int LOWER_BOUND = 174;       // lower temp
const int UPPER_BOUND = 220;       // upper temp

int val = 0;                       // analog reading

unsigned const long period = 5000; // time it takes to turn led off at temp

unsigned long startMillis;
unsigned long currentMillis;

void setup() {
    Serial.begin(9600);
    pinMode(led, OUTPUT);
    pinMode(sensor, INPUT);
    startMillis = millis();
}

void loop() {

    val = analogRead(sensor);      // temp recorder
    Serial.println(val);
    currentMillis = millis();

    if (val == UPPER_BOUND){
        digitalWrite(led, HIGH);
    }

    else if (val == UPPER_BOUND && currentMillis - startMillis == period) {
        digitalWrite(led, LOW);
    }

    else (val <= LOWER_BOUND); {
        digitalWrite(led, LOW);
        delay(200);
        digitalWrite(led, HIGH);
        delay(200);
    }
}

Sorry but im confused... Someone corrected my last post for me, i followed the instructions, indent than hit the space bar 4 times to activate the code block.  Ill try my best to edit it through.  my apologies.

so, learn how to indent the code properly .... it will help you a lot when you are debugging by showing the code in logical blocks ..... look at example code in the arduino IDE ..... your correction is a good attempt .... i'll fix it though

reformatted the code for you .... look at the end of the code and see if the correct number of closing braces } are there ..... the code reformat will be visible when it is accepted

I see what you are saying now.  It does look nicer and easier to follow for myself and others.  Ill be sure to follow this format in the future.  Thank you.

the code inside else if (val == UPPER_BOUND && currentMillis - startMillis == period) { can never run, since if (val == UPPER_BOUND){ will also be true - swap the order of the first two ifs

the last else is missing an if and has a stray ; it should be else if (val <= LOWER_BOUND) { - the way the code is written, the else now performs (val <= LOWER_BOUND); ... and the following block is always executed

what's also not clear is what the LED should do when the temperature is above LOWER_BOUND but not exactly equal to UPPER_BOUND

and one final flaw .. you set startMillis in setup ... so 5 seconds after power on, regardless of temperature, currentMillis - startMillis >= period will always be true (not that it matters with your current logic)

As Long as the temperature is below UPPER_BOUND the LED should just blink.  Once at or above the UPPER_BOUND temperature, the led should blink for 5 seconds than turn off.  I did make the changes suggested bu Jaromanda X, and right now when below UPPER_BOUND, it blinks, when at or above UPPER_BOUND LED stays steadily lit.

First, let me point out a few technical issues with your program:

const int sensor = 9; is wrong. On an Uno, you can only use
analogRead() on the pins labeled A0 through A5.
if (val == UPPER_BOUND). Never test an analog reading for exact
equality. The reading is noisy, and you shouldn't expect continuity.
It can very well jump from UPPER_BOUND-1 on one reading to
UPPER_BOUND+1 on the next one. Instead, test for
val >= UPPER_BOUND.
currentMillis - startMillis == period. Again, you should not test
for exact equality. This time it's for a more subtle reason that has
to do with the implementation of millis(): some values (roughly one
every 42) are skipped over. Here again, test for >= period.

There is also the issue, already pointed out by PhoenixRevealed, of
your code defining two thresholds, while your prose only mentions one.
This may well be just you being sloppy and not describing your
requirements precisely enough.
Next, and since you are interested in perfecting your learning process,
let me advise you on two techniques that are worth learning, because
they are extremely useful for mostly any Arduino project more complex
than just blinking an LED:

Avoid using delay(). While the Arduino is busy delaying, it can
do nothing else. For instance, it cannot monitor the temperature
changes on the hot plate. In this particular case, it may well be the
case that you don't care, because the hot plate is so slow that you
can afford to be 400 ms late. But if you get into the habit of
relying on delay(), it will bite you sooner or later. So the sooner
you learn to blink an LED without using delay(), the
better.
Learn to program a finite state machine. This is a programming
concept that is very well suited for describing reactive systems,
i.e. systems that have to react to external “events”. It is a very
useful concept for writing most programs that are meant to control
hardware. There are quite a few tutorials out there. I would
recommend The Finite State Machine, by Majenko.

Here is my interpretation of your requirements in terms of a finite
state machine: your Arduino can be in any of 3 states: COLD (initial
state, the plate has not reached the required temperature), WAITING
(the plate reached the temperature and we are delaying five seconds),
DONE (the five seconds have elapsed). The rules for changing states
are:

COLD → WAITING: when in the COLD state, if the temperature
reaches a specified threshold, go to the WAITING state.
WAITING → DONE: when in the WAITING state, once five seconds
have elapsed since we entered the state, go to the DONE state.
When we are in the DONE state... nothing more ever happens.

Here is the corresponding state diagram:

Notice that once we reach the DONE state, the system gets stuck. This
situation can only be recovered from by rebooting the Arduino. You may
want to revise your specification in order accommodate a DONE → COLD
transition in some way. But from your specification as written in your
question, I assume you are fine with the system getting stuck.
I tried to implement this state diagram in code, using the traditional
switch/case construct. But then I got lazy and noticed that calling
exit() is the easiest way of implementing the DONE state, as
this function is precisely designed to get the program stuck in a
do-nothing state. Then, since there are only two states left to care
about, a boolean can be used as a state variable. In the end, the code I
propose may not look like a finite state machine. However, it is
important to notice that, event if such case, the finite state machine
is a very useful concept for thinking about your program and writing
down its requirements.
// Pinout
const uint8_t LED = 11;
const uint8_t SENSOR = A0;

// Threshold temperature reading.
const int THRESHOLD_TEMP_READING = 220;

// Timing.
const uint32_t LED_TOGGLE_PERIOD = 200;
const uint32_t WAIT_TIME = 5000;

bool is_hot = false;
uint32_t last_led_toggle;
uint32_t wait_started;

void setup()
{
    pinMode(LED, OUTPUT);
    pinMode(SENSOR, INPUT);
}

void loop()
{
    // Read the time once per loop.
    uint32_t now = millis();

    // Toggle the LED state.
    if (now - last_led_toggle >= LED_TOGGLE_PERIOD) {
        digitalWrite(LED, !digitalRead(LED));
        last_led_toggle = now;
    }

    if (is_hot) {
        // If the plate is hot, keep blinking during WAIT_TIME.
        if (millis() - wait_started >= WAIT_TIME) {
            digitalWrite(LED, LOW);  // turn off the LED
            exit(0);                  // stop everything
        }
    } else {
        // If the plate is cold, take note when it gets hot.
        if (analogRead(SENSOR) >= THRESHOLD_TEMP_READING) {
            is_hot = true;
            wait_started = now;
        }
    }
}

So when using analogRead() I should never measure or read exact values?  I should probably know this by now, but does A0-A5 give off a sine wave compared to a square wave compared to the PWM pins?  I appreciate you all giving an explanation on what I am doing wrong.  It helps me understand what I need to look for and how to go about things in later projects.

@Steven: Please, rephrase the questions in your comment in a clearer way. As written, I cannot make any sense of them.

Does the A0-A5 pins output a sine wave instead of a square wave, like a PWM pin does? and Would that be the reason why we cannot measure exact values through analogRead()?

@Steven: 1. The A0 – A5 pins can serve as analog inputs. Otherwise you can use them as regular digital IO (i.e. output either HIGH or LOW). The Arduino Uno has no analog outputs. It cannot output a sine wave on any pin. 2. The reason you cannot measure exact values is that there is no such thing as an exact measurement in the physical world. But this is not quite the point I discuss in my answer. Instead, I am telling you to never compare a measurement with an expected value using the == operator. The key word here is “test” for exact equality.

So I did read up on the FSM, and it does seem to be better constructed, than some of what I have been doing.  And I get what your explaining now, with the A0-A5 pins.  It does make sense that nothing in the physical world has an exact measurement.  That is something I did not consider, and explains why with "==" I could not get the proper output i was expecting, even with making suggested edits.

I see a couple of issues with your code. The biggest problem is that you capture startMillis in setup() and then compare it with currentMillis in your loop. If it takes more than five seconds for the pot to get hot enough you will never match (currentMillis - startMillis) == period because (currentMillis - startMillis) will already be > period before you start testing it. Changing "== period" to ">= period" will fix this, but it still won't behave the way you want since you should be setting startMillis when the pot first reached the target temp, not at program startup.
Also, your code does nothing when the temp is between LOWER_BOUND and UPPER_BOUND, which I suspect is not what you want. You don't specify whether "up to temp" means at or above LOWER_BOUND or at or above UPPER_BOUND. I'm going to assume that you want the LED to flash when the temp is below LOWER_BOUND, go solid on while the temp is between LOWER_BOUND and UPPER_BOUND, and then turn completely off five seconds after the pot reaches UPPER_BOUND.
Personally I would rewrite it like this, both for functionality and readbility...
int val = 0;                       // analog reading

unsigned const long period = 5000; // time it takes to turn led off at temp

// ---We don't need this till later, zero it so the loop knows not to use it till then
unsigned long startMillis = 0;

void setup() {

    Serial.begin(9600);
    pinMode(led, OUTPUT);
    pinMode(sensor, INPUT);

}

void loop() {

    val = analogRead(sensor);      // temp recorder
    Serial.println(val);

    if ( val <= LOWER_BOUND ) {

        // ---Coffee temp is low, flash the LED
        digitalWrite(led, LOW);
        delay(200);
        digitalWrite(led, HIGH);
        delay(200);

    } else if ( val < UPPER_BOUND ) {

        // ---Coffee temp is medium, turn the LED solid on (assumes switched cathode)
        digitalWrite(led, LOW);

    } else {

        // ---Coffee is hot!
        if ( !startMillis ) {

            // ---Coffee just reached UPPER_BOUND... start timing (LED is already on)
            startMillis = millis();

        } else {

            // ---Has the period timed out yet?
            if ( ( millis() - startMillis ) >= period ) {

                  // ---More than 5 seconds has passed, make sure LED is off
                  digitalWrite(led, HIGH);

            }
        }
    }
}

A couple of points about this implementation...

I have not tested this code on a physical Arduino.
Notice that we don't care to start storing or watching millis() until the pot first reaches UPPER_BOUND. Until then all the program cares about is the temp of the coffee.
Like your original code, this implementation doesn't consider the wraparound of millis() every 50 days or so. It's unlikely a coffee pot will take over 50 days to reach the target temperature, so I wouldn't worry about it, but you should consider this situation when coding long-running applications (I refuse to call them "sketches").
I based this on your original code, so like yours, once the temp reaches at least LOWER_BOUND it continuously writes to the LED pin every pass through the loop, even though it likely hasn't changed since the last iteration. If I was doing this for real I would restructure it so it only writes to the pin when the state of the LED actually changes. This is only an efficiency issue though... writing the same value to a pin repeatedly will work fine, it just isn't very elegant.
If the coffee starts to cool down after reaching UPPER_BOUND then behaviour is undefined. I suspect that it would work normally when the coffee temp is low or medium, but if the coffee reached the UPPER_BOUND the second or more times I believe the LED would turn off immediately rather than after 5 seconds. It wouldn't be difficult to enhance the code to behave correctly no matter how many times the pot temp cycles up and down, but this solution was to the problem as you described it, which was a coffee pot warming up just once from cold to a target temperature.

I made a few changes to the code, I added the global variables for led, and sensor.  I also eliminated lower bound, and only kept to measure upper bound. It worked really well.  Between this code and my code, I noticed I am using a lot of unnecessary variables, and some that are useless.  I found that when using both an upper and lower bound, the code would only run the lower bound, im assuming this because, i gave lower bound a value, when it does not need it,  So in the program, although it kinda worked it would never work as intended because of that value.

I also believe I understand millis() a little better now, I thought millis() had to be started within the setup for it work properly.

You have received very valuable comments, all valid.However, to address your original question - once you reach upper bound and continue to apply heat - your  code have no means to detect greater then upper bound value.


text:
5 switches, 5 leds, 5 tones, in an Array
The idea is when a switch is pushed, the corresponding tone will be played as well as lighting up the corresponding LED. I have the circuit set up to where each array matches another, for example Switch one will play tone 1 and light LED 1. When the switch is released the LED turns off and the tone no longer plays.
However I have to use an Array for the sketch instead of declaring each individual switch, led, and tone.  My issue is when I compile the code, I get the error message "i" is not declared.  Not sure where my error is within the for loop in the setup portion of the sketch.
I tried following the example from the Exploring Arduino web page but it did not help.
#define NOTE_C   262 //HZ
#define NOTE_D   294 //HZ
#define NOTE_E   330 //HZ
#define NOTE_G   392 //HZ
#define NOTE_A   440 //HZ

const int SPEAKER = 9;   //speaker on pin 10
int LED[5] = {13, 12, 11, 10, 8};   //led pins
int ledcount = 5;
int buttonState;
int buttonState1;
int buttonState2;
int buttonState3;
int buttonState4;

//Button Array
int Buttons[5]= {3, 4, 5, 6, 7};
int ButtonCount = 5;
const int numButtons = sizeof(Buttons) / sizeof (Buttons[0]);

//Tone Note Array
int Notes[5] = {NOTE_C, NOTE_D, NOTE_E, NOTE_G, NOTE_A};

void setup()
{
  for (int i = 0; i < sizeof (Buttons) / sizeof(Buttons[0]); i++){
  pinMode(Buttons[], INPUT);
}
  for (int i = 0; i < sizeof (LED) / sizeof (LED[0]); i++);{
  pinMode(LED[], OUTPUT);
}
  for (int i = 0; i < numButtons; i++){
  pinMode(Buttons[i], INPUT);
  debouncer[i].attach(Buttons[i]);
  debouncer[i].interval(100);
}
  buttonState = digitalRead(Buttons[0]);
  buttonState1 = digitalRead(Buttons[1]);
  buttonState2 = digitalRead(Buttons[2]);
  buttonState3 = digitalRead(Buttons[3]);
  buttonState4 = digitalRead(Buttons[4]);
}

void loop()
{

  if (buttonState == HIGH)
  { tone(SPEAKER, Notes[0]);
  digitalWrite(LED[0], HIGH);
  }
  else if (buttonState1 == HIGH)
  {tone(SPEAKER, Notes[1]);
  digitalWrite(LED[1], HIGH);
 }
  else if (buttonState2 == HIGH)
  {tone(SPEAKER, Notes[2]);
  digitalWrite(LED[2], HIGH);
 }
  else if (buttonState3 == HIGH)
  {tone(SPEAKER, Notes[3]);
  digitalWrite(LED[3], HIGH);
 }
  else if (buttonState4 == HIGH)
  {tone(SPEAKER, Notes[4]);
   digitalWrite(LED[4], HIGH);
 }

  else
 {
  digitalWrite(LED[5], LOW);
  noTone(SPEAKER);
 }
}

I have to use an Array  .....  is this a school assignment?

@jsotola, It is a school assignment.Its why i ask for suggestions and not completed codes.  It doesnt help if someone does the work for me.  Can only learn through doing.  Millis() was a great thing to learn through here, millis() will not even be covered through the curriculum.  However I don't think ill need millis() in this code.  Im now using the Bounce2 library and it gives a debounce interval. Ill update my code for the changes made.

i ask for suggestions and not completed codes .... i do not see that

@jsotola I do apologize for not making that clearer in this post.

You have a rogue ; here:
  for (int i = 0; i < sizeof (LED) / sizeof (LED[0]); i++);{
  pinMode(LED[], OUTPUT);                                 ^------HERE
}

That is terminating the for, making it empty, and the following block is a completely different scope.
Another thing I spotted - you aren't putting i into your array index LED[] (should be LED[i]).  The same is true with Buttons[].
However, on a different subject, this:
buttonState == digitalRead(Buttons[0]);
buttonState == digitalRead(Buttons[1]);
buttonState == digitalRead(Buttons[2]);
buttonState == digitalRead(Buttons[3]);
buttonState == digitalRead(Buttons[4]);

is pretty meaningless.  You are comparing values and throwing away the result.
In a similar vein:
if (buttonState = Buttons[0])

stores the current value of Buttons[0] into buttonState and succeeds if Buttons[0] is anything other than 0.  The same goes for all the others.
You need to sort out your comparisons (==) and your assignments (=) and also sort out what you think you are doing with all those buttonStates at the top of loop.

I did not notice the extra semi colons which explains why it was not declared in the scope.  I made the changes as well, tone plays and led lights up just wont turn off.  Im assuming ill need to debounce the switches in order to get them to work.

I debounced the switches and im still having the same issue.  Its debounced via array for loop, through the bounce2 library.  I am still not getting the led or other switches to work properly.  It will not let me post the new code in a comment either.

Unless you fixed all the other issues with your code you have no hope of it working.

I got it working now thank you for your help.  The issue ended up being the two things you pointed out, and how i was calling on the array.


text:
Programming ATUC256L4U using only Arduino ISP
I heard that you can program any AVR Microcontroller by just using Arduino ISP Can I program ATUC256L4U by just hooking it up to Arduino ISP and Caps, Crystals and etc. Or do I need to do some more work like you know the fuses and all ?

You can set the fuses through your ISP programmer.

Only the fuses or anything more.


text:
Slackbot integration using ESP8266 gets "ssl->need_bytes=16432 > 6859"
I'm trying to use Uri Shaked Slackbot code using an Adafruit Feather Huzzah ESP8266 WiFi.
I have created the Slackbot integration and copied the API key. The code connects to the WiFi and does the time configuration but then hangs when connecting to slack with the error message in the serial monitor.

ssl-need_bytes=16432 > 6859

/**
   Arduino Real-Time Slack Bot
   Copyright (C) 2016, Uri Shaked.
   Licensed under the MIT License
*/

#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <ESP8266HTTPClient.h>
#include <WebSocketsClient.h>
#include <ArduinoJson.h>
#include <Adafruit_NeoPixel.h>

#define SLACK_SSL_FINGERPRINT "AC 95 5A 58 B8 4E 0B CD B3 97 D2 88 68 F5 CA C1 0A 81 E3 6E" // If Slack changes their SSL fingerprint, you would need to update this
#define SLACK_BOT_TOKEN "https://slack.com/api/rtm.start?token=[MY TOKEN]" // Get token by creating new bot integration at https://my.slack.com/services/new/bot
#define WIFI_SSID       "[My WIFI]"
#define WIFI_PASSWORD   "[WiFi Password]"

#define LEDS_PIN        2
#define LEDS_NUMPIXELS  8
#define WORD_SEPERATORS "., \"'()[]<>;:-+&?!\n\t"

ESP8266WiFiMulti WiFiMulti;
WebSocketsClient webSocket;

Adafruit_NeoPixel pixels(LEDS_NUMPIXELS, LEDS_PIN, NEO_GRB + NEO_KHZ800);

long nextCmdId = 1;
bool connected = false;

/**
  Sends a ping message to Slack. Call this function immediately after establishing
  the WebSocket connection, and then every 5 seconds to keep the connection alive.
*/
void sendPing() {
  DynamicJsonBuffer jsonBuffer;
  JsonObject& root = jsonBuffer.createObject();
  root["type"] = "ping";
  root["id"] = nextCmdId++;
  String json;
  root.printTo(json);
  webSocket.sendTXT(json);
}

/**
  Input a value 0 to 255 to get a color value.
  The colors are a transition r - g - b - back to r.
*/
uint32_t wheel(byte wheelPos) {
  wheelPos = 255 - wheelPos;
  if (wheelPos < 85) {
    return pixels.Color(255 - wheelPos * 3, 0, wheelPos * 3);
  }
  if (wheelPos < 170) {
    wheelPos -= 85;
    return pixels.Color(0, wheelPos * 3, 255 - wheelPos * 3);
  }
  wheelPos -= 170;
  return pixels.Color(wheelPos * 3, 255 - wheelPos * 3, 0);
}

/**
  Animate a NeoPixel ring color change.
  Setting `zebra` to true skips every other led.
*/
void drawColor(uint32_t color, bool zebra) {
  int step = zebra ? 2 : 1;
  for (int i = 0; i < LEDS_NUMPIXELS; i += step) {
    pixels.setPixelColor(i, color);
    pixels.show();
    delay(30 * step);
  }
}

/**
  Draws a rainbow :-)
*/
void drawRainbow(bool zebra) {
  int step = zebra ? 2 : 1;
  for (int i = 0; i < LEDS_NUMPIXELS; i += step) {
    pixels.setPixelColor(i, wheel(i * 256 / LEDS_NUMPIXELS));
    pixels.show();
    delay(30 * step);
  }
}

/**
  Looks for color names in the incoming slack messages and
  animates the ring accordingly. You can include several
  colors in a single message, e.g. `red blue zebra black yellow rainbow`
*/
void processSlackMessage(char *payload) {
  char *nextWord = NULL;
  bool zebra = false;
  for (nextWord = strtok(payload, WORD_SEPERATORS); nextWord; nextWord = strtok(NULL, WORD_SEPERATORS)) {
    if (strcasecmp(nextWord, "zebra") == 0) {
      zebra = true;
    }
    if (strcasecmp(nextWord, "red") == 0) {
      drawColor(pixels.Color(255, 0, 0), zebra);
    }
    if (strcasecmp(nextWord, "green") == 0) {
      drawColor(pixels.Color(0, 255, 0), zebra);
    }
    if (strcasecmp(nextWord, "blue") == 0) {
      drawColor(pixels.Color(0, 0, 255), zebra);
    }
    if (strcasecmp(nextWord, "yellow") == 0) {
      drawColor(pixels.Color(255, 160, 0), zebra);
    }
    if (strcasecmp(nextWord, "white") == 0) {
      drawColor(pixels.Color(255, 255, 255), zebra);
    }
    if (strcasecmp(nextWord, "purple") == 0) {
      drawColor(pixels.Color(128, 0, 128), zebra);
    }
    if (strcasecmp(nextWord, "pink") == 0) {
      drawColor(pixels.Color(255, 0, 96), zebra);
    }
    if (strcasecmp(nextWord, "orange") == 0) {
      drawColor(pixels.Color(255, 64, 0), zebra);
    }
    if (strcasecmp(nextWord, "black") == 0) {
      drawColor(pixels.Color(0, 0, 0), zebra);
    }
    if (strcasecmp(nextWord, "rainbow") == 0) {
      drawRainbow(zebra);
    }
    if (nextWord[0] == '#') {
      int color = strtol(&nextWord[1], NULL, 16);
      Serial.println("Color");
      Serial.print(color);
      if (color) {
        drawColor(color, zebra);
      }
    }
  }
}

/**
  Called on each web socket event. Handles disconnection, and also
  incoming messages from slack.
*/
void webSocketEvent(WStype_t type, uint8_t *payload, size_t len) {
  switch (type) {
    case WStype_DISCONNECTED:
      Serial.printf("[WebSocket] Disconnected :-( \n");
      connected = false;
      break;

    case WStype_CONNECTED:
      Serial.printf("[WebSocket] Connected to: %s\n", payload);
      sendPing();
      break;

    case WStype_TEXT:
      Serial.printf("[WebSocket] Message: %s\n", payload);
      processSlackMessage((char*)payload);
      break;
  }
}

/**
  Establishes a bot connection to Slack:
  1. Performs a REST call to get the WebSocket URL
  2. Conencts the WebSocket
  Returns true if the connection was established successfully.
*/
bool connectToSlack() {
  // Step 1: Find WebSocket address via RTM API (https://api.slack.com/methods/rtm.start)
  HTTPClient http;

  Serial.printf("Connecting to\n");
  Serial.printf(SLACK_BOT_TOKEN);
  Serial.printf("\n");

  http.begin(SLACK_BOT_TOKEN, SLACK_SSL_FINGERPRINT);
  int httpCode = http.GET();

  if (httpCode != HTTP_CODE_OK) {
    Serial.printf("HTTP GET failed with code %d\n", httpCode);
    return false;
  }

  pixels.setPixelColor(3, pixels.Color(0, 2, 0));
  pixels.show();

  WiFiClient *client = http.getStreamPtr();
  client->find("wss:\\/\\/");
  String host = client->readStringUntil('\\');
  String path = client->readStringUntil('"');
  path.replace("\\/", "/");

  // Step 2: Open WebSocket connection and register event handler
  Serial.println("WebSocket Host=" + host + " Path=" + path);
  webSocket.beginSSL(host, 443, path, "", "");
  webSocket.onEvent(webSocketEvent);

  pixels.setPixelColor(4, pixels.Color(0, 2, 0));
  pixels.show();

  return true;
}

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

  pixels.begin();
  drawColor(pixels.Color(2, 0, 0), false);

  pixels.setPixelColor(0, pixels.Color(0, 2, 0));
  pixels.show();

  WiFiMulti.addAP(WIFI_SSID, WIFI_PASSWORD);
  while (WiFiMulti.run() != WL_CONNECTED) {
    delay(100);
  }

  pixels.setPixelColor(1, pixels.Color(0, 2, 0));
  pixels.show();

  configTime(3 * 3600, 0, "pool.ntp.org", "time.nist.gov");

  pixels.setPixelColor(2, pixels.Color(0, 2, 0));
  pixels.show();
}

unsigned long lastPing = 0;

/**
  Sends a ping every 5 seconds, and handles reconnections
*/
void loop() {
  webSocket.loop();

  if (connected) {
    // Send ping every 5 seconds, to keep the connection alive
    if (millis() - lastPing > 5000) {
      sendPing();
      lastPing = millis();
    }
  } else {
    // Try to connect / reconnect to slack
    connected = connectToSlack();
    if (!connected) {
      delay(500);
    }
  }
}

they probably use "too strong" of a cert, according to https://github.com/esp8266/Arduino/issues/1375. you can use a server-side proxy to talk to both the ESP and the API, using a shorter key cert on the "proxy"

Yep, I read igrr's comment. I've downloaded the axTLS library and are trying to tweak it to get it working but no luck so far.

@mach I have this exact same issue.  I do get mine to connect sometimes, but it's very inconsistent (sometimes it works, sometimes it fails).  Once it connects and I get to the repeated pings it works perfectly.  Did you find a solution for the ssl-need_bytes error?

@mach @Axel
I replaced use rtm.start with rtm.connect as per April 2017 Slack Recent Updates https://api.slack.com/changelog
and this got rid of the error on my Wemos.
http.begin("https://slack.com/api/rtm.connect?token=" + SLACK_BOT_TOKEN, SLACK_SSL_FINGERPRINT);

OMG, going to test this tonight!


text:
Failing to write to SD card using SD.h
Using a knockoff Arduino Nano (pinout seems to be the same), I would like to record data to an external SD card. I have everything hooked up (correctly I think) but I continue to fail to initialize the card using SD.begin().
Here's a snippet of code that I'm running to do this:
//Wire and MS5803_I2C libraries for communicating with the pressure sensor.

#include <Wire.h>
#include <SparkFun_MS5803_I2C.h>
// For the SD card reader.
#include <SPI.h>
#include <SD.h>

const int chipSelect = 4;

void setup(void) {
  Serial.begin(9600); // Set baud rate.
  pinMode(10, OUTPUT); // Set data output pin for the SD card reader.
  digitalWrite(10, HIGH);
 // see if the card is present and can be initialized:
 if (!SD.begin(10)) {
   Serial.println("Card failed, or not present");
   // don't do anything more:
   return;
 }
 Serial.println("card initialized.");
  delay(500);  // Wait half a second before continuing.
}

void loop(void) {
  Serial.println("Hello Library!");
  delay(100000);
}

Here's the Nano pinout:

And a picture of the circuit.

Which version of the SD library are you using? This can be found at Sketch > Include Library > Manage Libraries... > Filter your search... > SD.

I was running 1.0.8, but I just noticed there was an update. I'll try that out now that the library is updated! Thanks - I didn't know how to do that.

I was asking because there was a bug in 1.1.0 that was causing this sort of problem and was fixed in 1.1.1 but since you were using 1.0.8 that wouldn't have been your issue.

The Sparkfun pressure sensor has a 3.3V chip and a SD memory card is also 3.3V. Your Arduino Nano is probably a 5V board. How did you connect those to the board ?
When your Nano board is 5V, you need a SD module with a level shifter for the signals.
To make it work, test either the SD or the sensor and try to make it work. When testing the SD, don't connect the sensor and don't even include the sensor library.

I've been trying to upload a picture, but it keeps failing on both this site and imgur. Any suggestions? - I might make a schematic later today and upload it. Also, no sensor is currently attached, and this code is much simplified from a larger code-base but you're probably right, I should take out the sensor library for now - good suggestion.

Alright, I added a photo of the setup currently.

Is it my eyes or there's nothing connected to D4...?
const int chipSelect = 4;

Your chipSelect/CS pin seems connected to D10.

Yes, that's a remnant of the previous code. !SD.begin(x) allows for chipSelect to be entered as x. Here I have it as 10, which as far as I can tell is the actual CS on the device. What I'm wondering is if it is !CS and if that is different from the regular Arduinos

authors: แดงเดช แนนเกี้ยง