text:
Bipolar LEDs flicker when sensors are polled
Or at least that's what I believe is the problem.
I had to add a bipolar LED library to my sketch to get them to work.
As it is now I only have it activated by a specified bit so it can properly drive yellow. Green and Red were working fine (the flickering problem not withstanding) without the bipolar library.
If I have no sensors enabled in the software (java model railroad interface) I'm using with the sketch, then the bipolar LEDs work fine.
The second I add a sensor, then the arduino starts polling the inputs, at which time the bipolar LEDs (all colors) go all wonky. Their flickering coincides with the flickering of the tx/rx lights on the board, so I'm assuming that the polling of the sensors is what is causing it.
Note that the bipolars are the only LEDs attached to another output pin instead of the ground. It's almost like it's polling any pin that's low at the time, which we obviously don't need/want with the pins for the LEDs.
I even changed the order of the sketch which seemed to slightly effect the flickering, but not enough not to be annoying. Keep in mind my level of understanding programming this is at the level of being able to combine sketches...which conflict led us here.
#include <CMRI.h>
#include <CrossingFlasher.h>
#include <BiColorLED.h>

CMRI cmri; // defaults to a SMINI with address 0. SMINI = 24 inputs, 48 outputs
CrossingFlasher crossing(10, 11); // crossbucks
BiColorLED led=BiColorLED(46,47); // (pin 1, pin 2)
BiColorLED led2=BiColorLED(48,49); // (pin 1, pin 2)
BiColorLED led3=BiColorLED(50,51); // (pin 1, pin 2)
BiColorLED led4=BiColorLED(52,53); // (pin 1, pin 2)

void setup() {
  Serial.begin(9600); // make sure this matches your speed set in JMRI
  for (int i=34; i<=53; i++) { pinMode(i, OUTPUT); }
  for (int i=22; i<=33; i++) { pinMode(i, INPUT); digitalWrite(i, HIGH); }
  for (int i=10; i<=11; i++) { pinMode(i, OUTPUT); }
}

void loop() {
  // 1: build up a packet
  cmri.process();

  // 4: update crossing lights. Reads bit 0
  if (cmri.get_bit(0) == true)
    crossing.on();
  else
    crossing.off();

  // 5: update crossing lights
  crossing.update();

  // 6: update Yellow lights. Reads bit 1
  if (cmri.get_bit(1) == true)
    led.setColor(3);
  else
    led.setColor(0);

  led.drive();

  // 7: update Yellow lights. Reads bit 2
  if (cmri.get_bit(2) == true)
    led2.setColor(3);
  else
    led2.setColor(0);

  led.drive();

  // 8: update Yellow lights.
  if (cmri.get_bit(3) == true)
    led3.setColor(3);
  else
    led3.setColor(0);

  led.drive();

  // 9: update Yellow lights.
  if (cmri.get_bit(4) == true)
    led4.setColor(3);
  else
    led4.setColor(0);

  led.drive();

  // 2: update outputs
  digitalWrite(34, cmri.get_bit(5));
  digitalWrite(35, cmri.get_bit(6));
  digitalWrite(36, cmri.get_bit(7));
  digitalWrite(37, cmri.get_bit(8));
  digitalWrite(38, cmri.get_bit(9));
  digitalWrite(39, cmri.get_bit(10));
  digitalWrite(40, cmri.get_bit(11));
  digitalWrite(41, cmri.get_bit(12));
  digitalWrite(42, cmri.get_bit(13));
  digitalWrite(43, cmri.get_bit(14));
  digitalWrite(44, cmri.get_bit(15));
  digitalWrite(45, cmri.get_bit(16));
  digitalWrite(46, cmri.get_bit(17));
  digitalWrite(47, cmri.get_bit(18));
  digitalWrite(48, cmri.get_bit(19));
  digitalWrite(49, cmri.get_bit(20));
  digitalWrite(50, cmri.get_bit(21));
  digitalWrite(51, cmri.get_bit(22));
  digitalWrite(52, cmri.get_bit(23));
  digitalWrite(53, cmri.get_bit(24));

  // 3: update inputs (invert digitalRead due to the pullups)
  cmri.set_bit(0, !digitalRead(22));
  cmri.set_bit(1, !digitalRead(23));
  cmri.set_bit(2, !digitalRead(24));
  cmri.set_bit(3, !digitalRead(25));
  cmri.set_bit(4, !digitalRead(26));
  cmri.set_bit(5, !digitalRead(27));
  cmri.set_bit(6, !digitalRead(28));
  cmri.set_bit(7, !digitalRead(29));
  cmri.set_bit(8, !digitalRead(30));
  cmri.set_bit(9, !digitalRead(31));
  cmri.set_bit(10, !digitalRead(32));
  cmri.set_bit(11, !digitalRead(33));
}

I tried all the suggestions and more, same results.
My uneducated guess is the problem is probably with the CMRI.h library.
Because I FINALLY managed to actually get the native support for yellow in the software I was using (JMRI)
working without any extra bipolar libraries, and guess what? STILL flickers, though this native JMRI
support tends to make it more orange/red in color than the bipolar library did (I prefer the later).
The cmri library is actually attempting to make the arduino emulate another piece of hardware, so for all
I know it might not even be possible to get it to act right.
I've included both cpp and h scripts.
If no one actually figures this out, thanks anyway.
The CMRI.cpp file:
/*
CMRI - a small library for Arduino to interface with the C/MRI
computer control system for model railroads
Copyright (C) 2012 Michael Adams (www.michael.net.nz)
All rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

#include "CMRI.h"
#include <Arduino.h>

CMRI::CMRI(unsigned int address, unsigned int input_bits, unsigned int output_bits, Stream &serial_class)
    // store details
: _address(address)
, _rx_length((output_bits + 7) / 8)
, _tx_length((input_bits + 7) / 8)
, _serial(serial_class)

    // set state
, _rx_buffer((char *) malloc(_rx_length))
, _tx_buffer((char *) malloc(_tx_length))

    // parsing state
, _mode(PREAMBLE_1)
, _rx_index(0)

{
    // clear to zero
    for(int i=0; i<_rx_length; i++)
        _rx_buffer[i] = 0;
    for(int i=0; i<_tx_length; i++)
        _tx_buffer[i] = 0;
}

void CMRI::set_address(unsigned int address)
{
    _address = address;
}

// reads in serial data, decodes packets
// automatically responds to POLL requests
// returns packet type so if we got a SET request you know to update your outputs
bool CMRI::process()
{
    while (_serial.available() > 0)
    {
        if (process_char(_serial.read()))
        {
            return true;
        }
    }
    return false;
}

bool CMRI::process_char(char c)
{
    // if it's a SET that's fine do nothing
    // if it's an INIT that's also fine, we don't really care
    // if it's a GET, well, do nothing since it must be someone else replying
    // if it's a POLL then reply straight away with our data
    switch (_decode(c))
    {
        case POLL:
            transmit();
            return true;

        case SET:
            return true;

        default:
            return false;
    }
}

// public methods

bool CMRI::get_bit(int pos)
{
    // 1: divide index by 8 to get byte offset
    char c = get_byte(pos / 8);
    // 2: return bit at that location
    return (bool) ((c >> (pos % 8)) & 0x01);
}

char CMRI::get_byte(int pos)
{
    if (pos > _rx_length)
        return 0; // out of bounds
    else
        return _rx_buffer[pos];
}

bool CMRI::set_bit(int pos, bool bit)
{
    if ((pos + 7) / 8 > _tx_length)
        return false; // out of bounds
    else
    {
        int index = pos / 8;
        _tx_buffer[index] = bit
            ? _tx_buffer[index] | 1 << pos % 8      // if bit=1, then OR it
            : _tx_buffer[index] & ~(1 << pos % 8) // if bit=0, then NAND it
        ;
        return true;
    }
}

bool CMRI::set_byte(int pos, char b)
{
    if (pos > _tx_length)
        return false; // out of bounds
    else
    {
        _tx_buffer[pos] = b;
        return true;
    }
}

void CMRI::transmit()
{
    delay(50); // tiny delay to let things recover
    _serial.write(255);
    _serial.write(255);
    _serial.write(STX);
    _serial.write(65 + _address);
    _serial.write(GET);
    for (int i=0; i<_tx_length; i++)
    {
        if (_tx_buffer[i] == ETX)
            _serial.write(ESC); // escape because this looks like an STX bit (very basic protocol)
        if (_tx_buffer[i] == ESC)
            _serial.write(ESC); // escape because this looks like an escape bit (very basic protocol)
        _serial.write(_tx_buffer[i]);
    }
    _serial.write(ETX);
    _serial.flush();
}

// Private methods
uint8_t CMRI::_decode(uint8_t c)
{
    switch(_mode)
    {
        case PREAMBLE_1:
            _rx_index = 0;
            if (c == 0xFF)
                _mode = PREAMBLE_2;
            break;

        case PREAMBLE_2:
            if (c == 0xFF)
                _mode = PREAMBLE_3;
            else
                _mode = PREAMBLE_1;
            break;

        case PREAMBLE_3:
            if (c == STX)
                _mode = DECODE_ADDR;
            else
                _mode = PREAMBLE_1;
            break;

        case DECODE_ADDR:
            if (c == 'A' + _address)
                _mode = DECODE_CMD;
            else if (c >= 'A')
                _mode = IGNORE_CMD;
            else
                _mode = PREAMBLE_1;
            break;

        case DECODE_CMD:
            if (c == SET)
                _mode = DECODE_DATA;
            else if (c == POLL)
                goto POSTAMBLE_POLL;
            else
                _mode = POSTAMBLE_OTHER;
            break;

        case IGNORE_CMD:
            _mode = IGNORE_DATA;
            break;

        case DECODE_DATA:
            if (c == ESC)
                _mode = DECODE_ESC_DATA;
            else if (c == ETX)
                goto POSTAMBLE_SET;
            else if (_rx_index >= _rx_length)
                { }
            else
                _rx_buffer[_rx_index++] = c;
            break;

        case DECODE_ESC_DATA:
            if (_rx_index >= _rx_length)
                { }
            else
                _rx_buffer[_rx_index++] = c;
            _mode = DECODE_DATA;
            break;

        case IGNORE_DATA:
            if (c == ESC)
                _mode = IGNORE_ESC_DATA;
            else if (c == ETX)
                goto POSTAMBLE_IGNORE;
            break;

        case IGNORE_ESC_DATA:
            _mode = IGNORE_DATA;
            break;

        case POSTAMBLE_OTHER:
            _mode = PREAMBLE_1;
            break;
    }
    return NULL;

POSTAMBLE_SET:
        _mode = PREAMBLE_1;
        return SET;

POSTAMBLE_POLL:
        _mode = PREAMBLE_1;
        return POLL;

POSTAMBLE_IGNORE:
        _mode = PREAMBLE_1;
        return NULL;
}

The CMRI.h file:
    /*
    CMRI - a small library for Arduino to interface with the C/MRI
    computer control system for model railroads
    Copyright (C) 2012 Michael Adams (www.michael.net.nz)
    All rights reserved.

    Permission is hereby granted, free of charge, to any person obtaining a
    copy of this software and associated documentation files (the "Software"),
    to deal in the Software without restriction, including without limitation
    the rights to use, copy, modify, merge, publish, distribute, sublicense,
    and/or sell copies of the Software, and to permit persons to whom the
    Software is furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included
    in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
    OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    SOFTWARE.
*/

#ifndef CMRI_h
#define CMRI_h

#define _CMRI_VERSION 1.5 // version of this library
#include <Arduino.h>

class CMRI
{
    public:
        CMRI(unsigned int address = 0, unsigned int input_bits = 24, unsigned int output_bits = 48, Stream& serial_class = Serial);
        void set_address(unsigned int address);

        bool process();
        bool process_char(char c);
        void transmit();

        bool get_bit(int n);
        char get_byte(int n);

        bool set_bit(int n, bool b);
        bool set_byte(int n, char b);

        enum {
            MAX  = 258, // max packet length in bytes (64 i/o cards @ 32 bits each + packet type and address bytes)
            INIT = 'I', // PC is telling us stuff we don't really care about
            SET  = 'T', // as in TX from the PC => Arduino, PC is SETing our status
            GET  = 'R', // as in TX from Arduino => PC, PC is GETing our status
            POLL = 'P', // PC wants to know our status
            STX  = 0x02, // start byte
            ETX  = 0x03, // end byte
            ESC  = 0x10, // escape byte
        };

private:
        enum {PREAMBLE_1,PREAMBLE_2,PREAMBLE_3,DECODE_ADDR,DECODE_CMD,DECODE_DATA,DECODE_ESC_DATA,IGNORE_CMD,IGNORE_DATA,IGNORE_ESC_DATA,POSTAMBLE_SET,POSTAMBLE_POLL,POSTAMBLE_OTHER};

        int   _address;
        int   _rx_length;
        int   _tx_length;
        char    _rx_packet_type;
        char* _tx_buffer;
        char* _rx_buffer;

        Stream& _serial;

        // parsing state variables
        int     _mode;
        int     _rx_index;

        uint8_t    _decode(uint8_t c); // process one character received from serial port
};

#endif

The yellow color is make by very quickly alternating between red and green. If you do this fast enough your eyes won't notice. This alternating is done inside led.drive();. If you are polling the sensors, led.drive(); isn't called and the leds aren't alternating for a moment.
Best way would be to use a timer to call led.drive(); every 9ms or less. You could use the timerOne library. I've never used that library, but I think you should use the following code.
#include "TimerOne.h"

...

void setup {
    Timer1.initialize(9000);// call every 9ms
    Timer1.attachInterrupt(callback);

...

void callback()
{
    led.drive();
}

remove all other led.drive calls

Thank you, I will try that. The place I got the bipolar library from did mention the 9ms drive thing, but never actually showed how to do it.

Alternatively you could put a few led.drive() commands in between the digitalWrites and digitalReads at the end of the loop.
I also see your only calling led.drive(). not led2.drive() etc.. The library might not need that, so if it works now, don't change it.

Author of the library here. Sorry for the late reply; hopefully someone else will find this helpful.
Yes, you need to call .drive() on each instance of BiColorLED individually; the library doesn't know about multiple instances. (Thus you need to write led.drive(); led2.drive(); etc.)

The documentation doesn't say how to call .drive() in the right timeframe because it's up to you. My code style tends to rely heavily on cooperative multitasking, where the loop() function calls subroutines that are expected to do a very small amount of work and then return quickly. Thus for me it is sufficient to stick led.drive() right in the main loop() function, as loop() runs quite fast. If you have slower functions you can either attach it to an interrupt with the Timer1 library or the like; or intersperse calls at strategic points inside the slow functions.

You have your LED's across one of the serial I/O lines (Pin 1). Use different pins.


text:
Mac won't detect Serial Port for Leonardo
EDIT: The problem was the cable I was using (see answer below).

I have a MacBook Pro running OS X Yosemite (10.10.1). I connected my Arduino Leonardo to my computer for the first time today (using a Micro USB to USB cable), but my computer isn't detecting it.
When I opened the Arduino IDE I selected Tools > Board > "Arduino Leonardo", but when I try to choose a Serial Port the only options are:

/dev/tty.Bluetooth-Incoming-Port
/dev/cu.Bluetooth-Incoming-Port
/dev/tty.Bluetooth-Modem
/dev/cu.Bluetooth-Modem

I have tried closing and relaunching the Arduino IDE, disconnecting and reconnecting my Arduino Leonardo, and restarting my computer, but I still only see the four Bluetooth ports.
System Information (aka System Profiler) doesn't show anything connected to any of my USB ports.
Thanks in advance!

Have you tried another cable? Another computer?

@IgnacioVazquez-Abrams I don't have any other Micro USB cables, but I tried it with my roomate's PC (Windows 7) and it didn't work there either. Then I realized that the cable I have is only for charging Android phones. It doesn't do any data transfer. I'm going to buy a new cable. Thanks!

I have the same problem but its not cable's fault. I have dual boot with windows and on windows everything works. Any ideas?

@IgnacioVazquez-Abrams's comment made me realize that the problem was the Micro USB cable I was using. It gave the Arduino 5V power from my computer, but didn't support any data connection. I'm buying a new cable.

source: Stack Exchange

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

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

sort: votes


text:
SAM3X8E Maximum Serial Speed
Does somebody know which is the maximum serial speed one can achieve by using the Microchip SAM3X8E microprocessor with Serial Communication between other uC with a RS485 module?
The Arduino Due seems to be limited up to 115kbps, the USB (UOTGHS) should reach 1.5Mbps (low speed) without trouble, but I am not sure about the UART
From Microchip SAM3X8E Datasheet section 34.5.1 Baud Rate Generator, the UART baud rate should be the Master Clock MCK divided by 16, the maximum value given by setting the clock divisor UART_BRGR to 1, the minimum value after 0 (UART disabled).
Hence the Master Clock MCK should be around 84MHz (its Maximum Possible Clock?), and then the Maximum Baud Rate should be 5.25Mbps?
Is this right?
Thanks in advance

Quoting: "The maximum allowable baud rate is Master Clock divided by 16." from the SAM3X8 datasheet... However the maximum speed of RS485 bus transciever would be probably main bottleneck...

@KIIV Hence which is the MCK maximum value? Should it be 84MHz and then the maximum UART datarate should be 5.25Mbps?

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


text:
Configure Arduino Portable IDE
I am following this page (among others similar) about creating a portable Arduino IDE.
Though the steps are declared as easy...

Downloading the v.1.8.13 Windows ZIP file for non admin install,
Creating the portable folder,
Executing the arduino.exe file.

...I got stuck with this error:

This application was configured to use a bundled Java Runtime Environment but the runtime is missing or corrupted

I uninstalled v.1.8.13, then installed v.1.6.0, and never had any problems with JRE, until now.
What I am missing?

I'm using zip files since forever without issues. JRE is packed in subdirectory, so it should be working without it installed on OS level. That portable directory is great, never heard about it before.

@KIIV So, how shoud I use a packaged JRE in the Arduino Unzipped folder? What am I missing?

Just unpack arduino ide, jump into its directory and start Arduino.exe. It's expecting to have java in subdirectory. Btw, when I renamed java subdirectory, I've got exactly the same error message. (another way might be creating symlink to the system java instalation directory, or find out how to create Arduino.exe without that java bundling)

These instructions are interesting. Mainly section "Issues / Solution #1" - "When I used default Windows 'extract all' it didn't create half the folders which included java.".


text:
HardwareSerial Indexing Array
How should I index HardwareSerial ports into a single array?.
This compiles, but do not work.
HardwareSerial Serials[]={Serial,Serial1,Serial2,Serial3};

void setup(){
    for (int i=0;i<=3;i++){
        Serials[i].begin(38400);
        while (!Serials[i]);
    }
}

char s;
void loop(){
    for (int i=0;i<=3;i++){
        if (Serials[i].available()){
            s=Serials[i].read();
            Serials[i].write(s);
        }
    }
}

please, next time provide code that compiles

your code makes copies of Serials into items in the array of HardwareSerials. To use the original Serial objects, store and use pointers.
HardwareSerial* Serials[]={&Serial,&Serial1,&Serial2,&Serial3};

void setup(){
    for (int i=0;i<=3;i++){
        Serials[i]->begin(38400);
        while (!*Serials[i]);
    }
}

void loop(){
    for (int i=0;i<=3;i++){
        if (Serials[i]->available()){
            char s=Serials[i]->read();
            Serials[i]->write(s);
        }
    }
}


text:
Arduino Due SerialUSB Resetting
Having this basic example for using the SerialUSB function on the Arduino Due under Windows:
// ARDUINO DUE BLINK LED
void setup(){
  pinMode(13,OUTPUT);
  SerialUSB.begin(2000000);
  while(!SerialUSB){
    digitalWrite(13,HIGH);
    delay(100);
    digitalWrite(13,LOW);
    delay(100);
  }
}

void loop(){
  SerialUSB.println("Hello, World!");
  digitalWrite(13,HIGH);
  delay(100);
  digitalWrite(13,LOW);
  delay(900);
}

I am having trouble understanding which shall be the operating sequence for this use. Normally I follow these steps:

Open Arduino IDE, select Arduino Due (Programming Port) at COM 01, and connect it to PC USB,
Compile and Upload the code,
Open a Serial Monitor App, with COM 02, 2000000 bps or 9600 bps, 8b data, 1b stop, no parity, RTS|CTS flow control.

If I keep the Arduino connected to the Programming Port after trying the Native USB Port, I have to disconnect and connect everything to program it again (??), or disable it through the windows Device Manager.
Which is the proper sequence (and perhaps the code) for doing this the right way?.

You have to have flow control set to hardware for the Arduino to know the port has been opened.

Thanks @Majenko. That solved a big part of the problem. I have updated the question.

Assume the Arduino is already programmed and energized, i.e. from the Barrel 5V Power Source or from a USB Charger (as minimum) at Programming USB Port.
The following should be the proper steps:

If not Programmed: Program the Arduino, either through the Programming USB Port, Native USB Port, etc.
If Native USB Cable to PC is Plugged: Unplug Cable, or Reset Arduino,
Plug Native USB Cable to PC,
Check COM Number for the Native USB Port, i.e. COM01,
If Serial Monitor Connected: Disconnect Serial Monitor,
Connect through a Serial Monitor App, with COM01, any bps, 8b data, No parity, 1b stop, RTS|CTS flow control.

Done. The data flow should start immediately as soon as you Reset.
Check this for a deeper post with another example for debugging.


text:
Can Arduino Due be programmed with both USB ports connected?
It seems, due SAM-BA (SAM Boot Assistant) inside ATSAM3X8E being listening to both Native USB and UART USB ports after a Reset for programming, allowing talking with SAM-BA, this time from your PC, through BOSSA (bossac.exe, Basic Open Source Sam boot Assistant), then it would make not possible to program an Arduino Due while having both USB port connected to a PC.
Can somebody confirm, this is the reason?

Do you get a particular error when you try this?

It should be possible to do because when you flash the microcontroller needs to be in the flashing mode that only works with the Native port, to enable that mode you have to press the erase button for around 2 seconds and then press Reset...
I made a guide on how to do this here


text:
smooth DC motor control with millis
So the task is to control 12v DC motor.
With first button, you can add up motor speed by certain speed step.
With second button, you can slow down motors speed by certain speed step.
With third button you cant speed up motor to its max, but problem is there that i must be done smoothly. For example i press third button and in motor starts to spin faster and faster till it reaches max speed. But now when i press this button motor jumps to it max, and i don't know why. There is no smoothness.
I cant use delay, must be done by millis
[code]
int speed = 0;
int motor = 5,
    fasterbutton = 7, slowerrbutton = 4, tillmaxbutton = 2;
unsigned long previousMillis = 0;
const long interval = 100;
const long smoothinterval = 5000;
boolean faster, slower, tillend;
int begginingspeed;
const int step = 3;
const int maxspeed = 255;

void setup() {
  pinMode(2, INPUT_PULLUP);
  pinMode(4, INPUT_PULLUP);
  pinMode(5, OUTPUT);
  pinMode(7, INPUT_PULLUP);
  Serial.begin(9600);
}
void loop() {
  tillend = digitalRead(2);
  slower = digitalRead(4);
  faster = digitalRead(7);

  //button Nr 7 start DC motor and festens up
  if (faster == !HIGH && begginingspeed < maxspeed) {
    unsigned long currentMillis = millis();
    if (currentMillis - previousMillis >= interval) {
      begginingspeed += step;
      if (faster == !HIGH && speed < 1 ) {
        Serial.print('\n');
        Serial.print("MOTOR ON" );
      }
      analogWrite(motor, begginingspeed);
      Serial.print('\n');
      Serial.print("Speed = " );
      speed = begginingspeed * 100 / maxspeed;
      Serial.print(speed, DEC);
      previousMillis = currentMillis;
    }
  }

  //button Nr 4 slows down  DC motor
  else if (slower == !HIGH && begginingspeed > 0) {
    unsigned long currentMillis = millis();
    if (currentMillis - previousMillis >= interval) {
      begginingspeed -= step;
      analogWrite(motor, begginingspeed);
      Serial.print('\n');
      Serial.print("Speed = " );
      speed = begginingspeed * 100 / maxspeed;
      Serial.print(speed, DEC);
      if (slower == !HIGH && speed < 1 ) {
        Serial.print('\n');
        Serial.print("MOTOR OFF" );
      }
      previousMillis = currentMillis;
    }
  }

  //button Nr 2 for smooth fastens up DC motor till max
  if (tillend == !HIGH && begginingspeed > 0) {
    unsigned long currentMillis = millis();
    if (currentMillis - previousMillis <= interval) {
      for (begginingspeed = begginingspeed; begginingspeed <= 255; begginingspeed += step)
        analogWrite(motor, begginingspeed);
    }
    previousMillis = currentMillis;
  }

}
[/code]

you need more state, 1 more boolean, say, is_accelerating. You set this true when the button is pressed, and set it false when speed is max. It basically replaces faster == !HIGH so you don't have to hold down the button.

@dandavis in my code i don't need to hold button to reach max speed.

the for loop in if (tillend == !HIGH runs instantly. kill the for loop, then hold the tillend button to ramp up smoothly. then make my mod so you don't have to hold the button.

@dandavis you need more state, 1 more boolean, say, is_accelerating. You set this true when the button is pressed, and set it false when speed is max. It basically replaces faster == !HIGH so you don't have to hold down the button. SO could you explain me this part, i din't get it how to declare all of this.

@dandavisint   so i made changes, yes now i don't need to hold button, but speed still jumps up, there are no smoothnes

else if (tillend ==!HIGH && begginingspeed > 0) {
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= 5000) {                                                                              if (tillend==!HIGH){ is_accelerating= true; }                                                           begginingspeed += step; }  if (begginingspeed=maxspeed){ is_accelerating= false; } analogWrite(motor, begginingspeed); previousMillis = currentMillis; } }

I suggest using a different logic in your program. I would first divide up the different parts of the project:

A code part, which reads the 3 buttons and sets/increments/decrements a variable based on the button clicks, and
a code part, which takes a variable as set point and ramps the PWM (analogWrite()) output up or down, until the set point is reached. (So the setpoint is the target speed/PWM value)

This division between "input code" and "output code" is rather common, since it often makes your code better structured and makes it possible to easily add new inputs for one single output.

Let us first look at the second part (ramping the PWM signal up and down). We need a variable, that holds the current PWM value, and one, that holds the current set point (for both we are starting with zero, thus the motor stands still here:
int current_speed = 0;
int speed_setpoint = 0;

We also need a timestamp variable for using millis() to regularly setting the PWM output according to the set point and the corresponding interval (here as a define). Additionally we also define the increment, with which the PWM value should be incremented on each sample:
unsigned long motor_timestamp;
#define MOTOR_SAMPLE_INTERVAL  100
#define MOTOR_SAMPLE_INCREMENT 3

We are doing all this in the global scope. Now in the loop function we first check for millis() and the timestamp (which gives us a regular sample interval for the motor speed) and then check, if the current speed is higher or lower than the setpoint and change the current_speed accordingly. At the end we write the value of current_speed to the output:
if(millis() - motor_timestamp > MOTOR_SAMPLE_INTERVAL){
    if(current_speed < speed_setpoint){
        current_speed += MOTOR_SAMPLE_INCREMENT;
    } else if(current_speed > speed_setpoint){
        current_speed -= MOTOR_SAMPLE_INCREMENT;
    }
    analogWrite(motor, current_speed);
    motor_timestamp += MOTOR_SAMPLE_INTERVAL;
 }

So now we current_speed of the motor will follow the speed_setpoint, but will only increment or decrement with the speed you set with the MOTOR_SAMPLE_INTERVAL and the MOTOR_SAMPLE_INCREMENT. The new target speed is simply set by giving the variable speed_setpoint a new value. The above code will take care of reaching it.

Now lets look at the first part (reading the buttons for changing a variable). At your current code, you need to hold the button down for the value to change. From your text is guess, that you want a click behavior (1 step in speed for 1 button click, meaning button press and release). For that I suggest using the Bounce2 library, which will handle the buttons - especially the debouncing - for you:
#include <Bounce2.h>
Bounce bounce = Bounce();

void setup(){
    bounce.attach( BOUNCE_PIN, INPUT_PULLUP );
    // DEBOUNCE INTERVAL IN MILLISECONDS
    bounce.interval(5); // interval in ms
}

void loop(){
    bounce.update();
    if(bounce.fell()){
        // Handle the button click here
    }
}

Inside the if(bounce.fell()) statement, you would handle the action for the button click, in this case: updating the speed_setpoint variable. Define an increment value for the buttons and do the increment/decrement in the if statements. In global scope:
#define BUTTON_SPEED_INCREMENT 4

In the loop() function:
if(slower_bounce.fell()){
    speed_setpoint -= BUTTON_SPEED_INCREMENT;
}
if(faster_bounce.fell()){
    speed_setpoint += BUTTON_SPEED_INCREMENT;
}
if(tillend_bounce.fell()){
    speed_setpoint = maxspeed;
}

Now you need to put all this together. I will leave that to you. You can then tune the behavior to your liking by changing the defines.

Note the following points:

The motor will accelerate linear. That should be fitting for you.

The code will restart the PWM wave at every MOTOR_SAMPLE_INTERVAL. That is ok for a motor when the interval is significantly higher than the PWM interval. When you choose the interval too low (like single digit milliseconds), you need to put the analogWrite() call into the if statements with the increment of speed_setpoint. That will take 1 more statement, but will solve the problem.

If you choose the MOTOR_SAMPLE_INTERVAL too low, the speed change will get stuttery

If not delay then you'll probably have to use something like an H-Bridge. L298N is a good place to start. You can use PWM to control its speed and its gradual too.
https://www.browncountylibrary.org/wp-content/uploads/2018/03/arduino_dc_motors.pdf
Here's the relevant documentation

i just did CTRL+T, hope it will help. 3 button most smoothly add speed to dc motor, so then i press it, it must go to max speed (255) from current speed.

Yeah thanks, so when programming keep the variable names short and simple and try not to use redundant variables. It'll help debug the process much faster and it'll be a less burden to your compiler too.

thanks for advice, i'm new to coding, so yeah :D thanks in advance

yes button works, but its not smooth, it just "jumps" to max, that's the deal. I know how to make that dc motor goes to max speed, but i don't know, how to make it smoothly increase speed after pushing 3rd button

Did you try increasing the delay, to say 100? from my code above delay(50)

and i cant use delay, sadly

Did you try increasing the delay, to say 100? from my code above delay(50)--Yes, didn't work, just jumped to max

yeah, schematic is correct.It must be done with diode,transistor and push buttons.

@N0m4d why exactly should a H-bridge be necessary to do smooth speed changes?


text:
Remove unwanted characters from char type
I'm working on an ESP8266 module that needs to fetch date data from worldtimeapi, everything works fine but the problem is How do I strip of the time field off the datetime JSON response without loop.
Note: Arduino JSON library was used in deserializing the response data and it seems the library only supports char data type.
void loop ()
{
  // Initialize the request object
  HTTPClient request;

// Make a http request
  request.begin(dateTime);
  delay(2000);

  // Check the request status code.
int  responseCode = request.GET(); //Get the api host response code.
  Serial.print("Response code is: ");
  Serial.println(responseCode);
  if (responseCode == 200); // If the server returned OK
  {
      String responseData = request.getString();
      Serial.println("Response from the server is:");
      Serial.println(responseData);
        // Deserialize the JSON response data
       StaticJsonDocument<715> result; // Declare data storage to stack

      //Check for error during data deserialization
      DeserializationError error = deserializeJson(result, responseData);

      if (error)
      {
        Serial.print(F("Response deserialization failed with reason: "));
        Serial.println(error.f_str());
        return;
      }

      else
      {
        char abbreviation = result["abbreviation"];  // Returns the current time zone abbreviation
        char timezone = result["timezone"]; // Returns the current time zone
        char datetime = result["datetime"]; // "2021-03-12T17:04:0
        char date = datetime.remove(9,22); // This line throws error : request for member 'remove' in 'datetime', which is of non-class type 'char'

        Serial.print("Current time is ");
        Serial.print(datetime);
        Serial.print(" ");
        Serial.print(abbreviation);
        Serial.print(" ");
        Serial.println(timezone);
        delay(2000);
      }

  }

}

why without loop?

You can use strtok to split the string on the T character:
char *datepart = strtok(datetime, "T");
char *timepart = strtok(NULL, "T");

Serial.print("The current date is: ");
Serial.println(datepart);
Serial.print("The current time is: ");
Serial.println(timepart);

An alternative is to just find the T and turn it into the NULL terminating character:
char *T = strchr(datetime, 'T');
*T = 0;

If you need to copy the string data into a temporary string first you can do:
char temp[strlen(datetime)+1];
strcpy(temp, datetime);

Then operate on temp instead of datetime.

I need to get rid of T17:04:0.

Then just use datepart.

How do I do that in C++, I think datepart is a SQL syntax.

I have shown you how to do it.

Followed the ALT but seems the the Arduino Json library has some const definition. New error message: path/to/arduino/libraries/ArduinoJson/src/ArduinoJson/Variant/VariantAs.hpp:94:27: error: invalid conversion from 'ArduinoJson6172_91::enable_if<true, const char*>::type {aka const char*}' to 'char*' [-fpermissive]    return variantAs<T>(data);

You may need to copy the string content to a temporary work string first then.

Seems to work but the Arduino Json library won't allow that, I'll use NTP Client lib to get the date data. Thank You Majenko.

What @Majenko suggested works just fine. Define an appropriate sized character array (with an extra for the null terminator) and just strncpy() to it.

@Ruby, esp8266 has built in NTP


text:
Grounding issues Arduino Ethernet Shield makes WS2811 LEDs flicker
I have an Arduino Due with an Arduino Ethernet Shield V2 that I use to control multiple daisy-chained WS2811 LED strips.
When I turn on most of the LEDs the Arduino and attached wires seem to become an antenna, picking up fluctuations that make the LEDs flicker, by messing with the data on the WS2811 data line. Touching the data cable, touching the ethernet plug on the shield, or simply hovering my hand over the Arduino adds noise that causes flickering in the lights.
When I pull out the ethernet plug, it stops. (The Arduino continues to update the WS2811 chips, even without network connection)

The flickering is especially strong when I set the first couple of LEDs in the chain to White (biggest draw of current), while having red or green colored LEDs at the beginning causes milder flickering (even if there are LEDs set to White further back in the chain).
Some more observations:

The LED strips are powered from both sides. It doesn't seem to be a power issue.
I tried with a different Arduino Due, a different Ethernet shield, a different router and Ethernet cable, and a different power supply.
The router the Arduino is plugged into, is positioned on the same table, and powered from the same power bar as the LED/Arduino power supply.
I tried running the Arduino and the LEDs from different power supplies but that didn't help. Rather the opposite (which makes sense)
This happens no matter how long the equipment has already run or how hot it is.

Another mystery:
You might notice the lose ground cable from the LED strip connector. When I plug that into the Arduino Due, the LEDs don't get turned on at all. When I plug that ground cable into the Ethernet shield sitting on the Due, then some lights turn on wrong. No matter if Ethernet is plugged in or not (though there's a difference in the 'wrongness' of the lights when Ethernet is plugged in). Note, that the Arduino and the LED strips already share ground 1 foot away as they are both fed by the same 12V power supply.
Where are all these grounding issues coming from and how do I get rid of them? What else could I try?

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


text:
Arduino Leonardo keyboard
I use Arduino Leonardo board for virtual keyboard. Everything work fine, but when my local keyboard layout is russian it's not work how I want. This is my code
Keyboard.print("cmd");
typeKey(KEY_RETURN);
delay(2000);
Keyboard.print("powershell iwr -outf %TEMP%\\index.html http://google.com");
typeKey(KEY_RETURN);

Otput in English US keyboard layout:
cmd
powershell iwr -outf %TEMP%\index.html http://google.com

Output in Russian keyboard layout
сьв
зщцукырудд шцк -щгеа %ЕУЬЗ%\штвучюреьд реезЖ..пщщпдуюсщь

Is there a way to make Arduino Leonardo to write every time in English US keyboard layout no matter what keyboard layout uses my computer?

This is not really an Arduino question.  This is a Windows operating systems question about switching between keyboard layouts.  Should be close this question?  Or ask to have it moved to a more appropriate forum?

The Arduino Leonardo, in the same way as any keyboard, just sends keystroke data. It is down to your computer's operating system to translate those into individual letters and symbols. The Leonardo (and indeed any keyboard) has no say over how the operating system does that translation.
A brief google search (which led back to Stack Exchange) found me this project which may be of some interest. It allows you to automatically change the selected keyboard language depending on which keyboard is being used at any one moment in time.

But how to add this in Arduino Leonardo ?

You didn't quite grasp what I said, did you? It's down to your operating system which is windows, and that is where you have to do everything.

I understand you. But if I want to test arduino leonardo keyboard on different pc with russian layout I have to download this and use them. I want  to configure Arduino to send keystrokes everytime in US layout in every pc no matter which keyboard layout they uses.

@Desole you don't send keystrokes in any layout. You send keystrokes that, to a certain extent, describe the physical location of the key on they keyboard. There is no language. Only a location. Only the operating system can convert that location to a character. There is nothing you can do from the Arduino. No matter how much you beg and moan.

Think about it: if the keyboard could define the layout why would the operating system even have the ability to select a layout? It'd be pointless. Keycodes do not equate to characters directly. True, a Unicode keyboard is technically possible, but no operating system supports such a thing because there is no standard for it.


text:
What is the maximum frequency input signal that I can accurately track on a GPIO pin?
This all started with me wanting to use an Arduino to make a tachometer. This is all now working fine, but it got me wondering what the highest frequency digital signal that I could read?
So I built a simple test sketch and have run this on both a Nano and an ESP32. The result was about 6300Hz on both. Anything above this gives chaotic results. This is somewhat lower than I expected.
Has anybody done better than this?

Doing it all in software, yes, it'll be slow. There's hardware built in to most MCUs that will do it for you that can measure MHz ranges.

could use a cheap 8 bit counter ic as a frequency divider; just feed the last bit into the MCU where your tach is now, and feed the tach into the clock/tirgger of the IC.

As Majenko wrote, when you only rely on software to measure the frequency on a IO pin, it will always be rather slow. And it also depends on the code, that you use. Functions like digitalRead() are always slower than directly working with the control registers of the pin (Reference). As you didn't show your code, we cannot say more about that.
If you need to measure higher frequencies or you want to do other things in between (like outputting the data somewhere), it is better to use the microcontrollers buildin hardware. There are multiple ways to measure the frequency. 2 immediately come to my mind:

You could assign an ExternalInterrupt or a PinChangeInterrupt to the signal pin (limited choice of pins here), which triggers each time you see a rising (or falling) edge on the signal. In the ISR (Interrupt Service Routine) you could count up a variable. That value is the number of rising (or falling) edges, thus periods of the signal. The frequency is this value divided by the duration of the measurement. Every time you calculate the frequency, you reset the counter; reading it again after a defined duration. This should be better than just polling, but its not the best. (Note that a PinChangeInterrupt triggers on every edge, so you have to divide the frequency by 2)

You could configure an unused Hardware Timer/Counter to use your signal as external clock source. Let it count up until it overflows (or up to a value defined by you) and let it trigger an interrupt. Since the Arduino framework already uses Timer0 for timekeeping, you could divide the max value of the Timer/Counter by the time passed and you will get the frequency. I think this can get you in the MHz range.(As with PinChangeInterrupt, the Counter will increment on every edge, so again a factor of 2 here)

Both ways will calculate the frequency as a mean over a specific time. If you have a changing frequency, you might wanna manipulate measurement frequency. In the first case you can change the interval, in which you read the counter variable. In the second case you can change the max value, to which the Timer/Counter will count.

what the highest frequency digital signal that I could read?

(I assume you just want to read the frequency of the signal) That depends on many factors. If we use the second case from above (configuring a Hardware Timer as Counter connected to the signal) we have a limit on the maximum frequency, that we can provide. I found the relevant part in the datasheet of Atmega328p (which is the microcontroller on the Nano):

Each half period of the external clock applied must be longer than one system clock cycle to ensure correct
sampling. The external clock must be guaranteed to have less than half the system clock frequency (f ExtClk < f clk_I/O /2) given a 50/50% duty cycle. Since the edge detector uses sampling, the maximum frequency of an
external clock it can detect is half the sampling frequency (Nyquist sampling theorem). However, due to
variation of the system clock frequency and duty cycle caused by Oscillator source (crystal, resonator, and
capacitors) tolerances, it is recommended that maximum frequency of an external clock source is less than
f clk_I/O /2.5.

So we should stay below the controllers clock frequency divided by 2.5, which would be 16MHz / 2.5 = 6.4MHz for the Nano. But before you reach that, your code might introduce further delays, which make the measurement less accurate. That depends on the implementation.

Dear Chris and Majenko, Thanks for the excellent answers. I have tried the approach of using the signal to trigger an interrupt. That helped a bit. I have not tried to feed the signal into a hardware counter. I don't need to do this at the moment but it is a useful thing to know.

My DaquinOscope https://www.daqarta.com/dw_rroo.htm can use burst sampling to grab 1024 samples at high sample rates, then send them to a host computer over USB for display and analysis. For digital-only inputs it can acquire over 400,000 samples per second on an UNO, with each sample being a reading of 8 pins to make one byte in the record.  It does this by reading a digital port (PIND or PINB) in a tight loop, with an optional delay on each read for slower sampling. DaquinOscope is free, and it uses the open-source DaqPort https://www.daqarta.com/dw_rraa.htm, both included with Daqarta, complete with code that you can modify as desired.

Oh Wow! - I've just had a surf through your site - lots of interesting stuff. Many thanks, but you should have warned me - I could easily lose weeks of my life here. I do have a vague aspiration to build myself an arduino based 'scope but I want to be able to use an Android device (phone/tablet) for the UI.


text:
Nextion Display not getting updated data
I am using an Arduino Mega to display the readings of 4 pots on a Nextion Display as well as store them on an SD Card with a time stamp. I keep getting:
recvRetCommandFinished err
on the serial monitor and the display does not update with time.
I have attached my code below:
#include "Nextion.h"
#include <SPI.h>
#include <SD.h>
#include <Wire.h>
#include "RTClib.h"

RTC_DS1307 rtc;
char daysOfTheWeek[7][12] = {"Sunday","Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

// Declare your Nextion objects - Example (page id = 0, component id = 1, component name = "b0")
NexText tDate = NexText(0, 1, "tDate");
NexText tPot1 = NexText(0, 6, "tPot1");
NexText tPot2 = NexText(0,7, "tPot2");
NexText tPot3 = NexText(0, 8, "tPot3");
NexText tPot4 = NexText(0, 9, "tPot4");

File myFile;

void setup(void) {
  Serial1.begin(9600);
  // Open serial communications and wait for port to open:
  Serial.begin(9600);

  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }

  if (! rtc.isrunning()) {
    Serial.println("RTC is NOT running!");
    // following line sets the RTC to the date & time this sketch was compiled
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
    // This line sets the RTC with an explicit date & time, for example to set
    // January 21, 2014 at 3am you would call:
    //rtc.adjust(DateTime(2016, 11, 19, 19, 45, 0));   // <----------------------SET TIME AND DATE: YYYY,MM,DD,HH,MM,SS
  }

  delay(100);

  // You might need to change NexConfig.h file in your ITEADLIB_Arduino_Nextion folder
  // Set the baudrate which is for debug and communicate with Nextion screen
  nexInit();

  SPI.begin();

  int pot1 = 0;
  int pot2 = 0;
  int pot3 = 0;
  int pot4 = 0;

  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.print("Initializing SD card...");
  if (!SD.begin(53)) {
    Serial.println("initialization failed!");
    while (1);
  }
  Serial.println("initialization done.");

  // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
}

void loop(void) {
  myFile = SD.open("testpot1.csv", FILE_WRITE);
  // if the file opened okay, write to it:
  if (myFile) {
    Serial.print("Writing to testpot1.txt...");

    while(1) {
      DateTime now = rtc.now();
      myFile = SD.open("testpot1.csv ", FILE_WRITE);
      int pot1 = analogRead(A0);
      int pot2 = analogRead(A1);
      int pot3 = analogRead(A2);
      int pot4 = analogRead(A3);
      myFile.print(now.hour());
      myFile.print(":");
      myFile.print(now.minute());
      myFile.print(",");

      myFile.println(pot1);
      myFile.println(",");
      tPot1.setText(pot1);

      myFile.println(pot2);
      myFile.println(",");
      tPot2.setText(pot2);

      myFile.println(pot3);
      myFile.println(",");
      tPot3.setText(pot3);

      myFile.println(pot4);
      myFile.println(",");
      tPot4.setText(pot4);

      Serial.print(pot1);
      Serial.print(",");
      Serial.print(pot2);
      Serial.print(",");
      Serial.print(pot3);
      Serial.print(",");
      Serial.print(pot4);
      Serial.print(",");

      delay(2000);
      myFile.close();
    }
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }
}

How do I get the pot values on my display? Any help or tips would be helpful!

I changed the text components to number components on the Nextion GUI Editor. That worked as I primarily wanted to show numerical readings from the pot.

recvRetCommandFinished err means something is wrong with the serial communication between the Arduino and the Nextion display; it is what recvRetCommandFinished() prints when there is an error.
Check if you are using the right pins (TX1 and RX1 for Serial1) for the serial connection to the display, the actual connections you made (RX1 to TX, TX1 to RX), the baud rate, and the cable.

Thanks. This worked and also, I changed the text components to number components on the Nextion GUI Editor.

Great! Please accept the answer (if you accept the answer), so the question doesn't stay open.


text:
Arduino freezing frequently
I'm using an Arduino Nano for programing an automatic hand sanitizer that has a thermometer. But after running for some time the board freezes and only restarting can solve the issue. While checking the serial monitor it suddenly stops working.
The program includes reading distance from an ultrasonic sensor and temperature from an IR thermometer (distance and ambient temperature are read continuously and the serial monitor will constantly display values). At random when the temperature is read and is displayed on the OLED screen, the board freezes (board freezes only at this time) and restarting can make it work 1 more time and then freezes again.
Question 1
Is it something to do with the code or is it a hardware issue?
Question 2
Does a clone version of NANO cause such problem? (I'm using a clone version)
This is my code:
#include <Wire.h>
#include <Adafruit_MLX90614.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

Adafruit_MLX90614 mlx = Adafruit_MLX90614();
Adafruit_SSD1306 display(-1);
//Adafruit_SSD1306 display(128, 64, &Wire, -1);

#define trigPin 12 // Trigger pin
#define echoPin 11 // echo pin

float roomTemp; // ambient temperature
float objectTemp, stemp; // object temperature

int readcount = 0;
float threshold= 3.5 ;

int maximumRange = 15; // Maximum range needed
int minimumRange = 3; // Minimum range needed
long duration, distance; // Duration used to calculate distance
int dtime;
unsigned long rememTime;

// motor coding
int set_time;
float distance_cm;
unsigned long ultra_time;
int set_cm = 20;
int motor = 2; // Output for Motor drive
int flag = 0;

void setup() {
  Serial.begin(9600);// initialize serial communication at 9600 bits per second:

  pinMode (trigPin, OUTPUT);
  pinMode (echoPin, INPUT);
  pinMode(motor, OUTPUT);

  display.begin(SSD1306_SWITCHCAPVCC, 0x3C) ;
  delay(200);
  display.clearDisplay();
  display.setTextColor(WHITE);
}

void loop() {
  // temperature sensor coding
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH);
  //Calculate the distance (in cm) based on the speed of sound.
  distance= duration * 0.034/2;

  // reading object and ambient  temperature
  objectTemp = threshold + mlx.readObjectTempC() ;
  roomTemp = mlx.readAmbientTempC() ;

  // print to Serial port
  Serial.println("Object:" + String(objectTemp) + ", Ambient:" + String(roomTemp));
  Serial.println(distance);

  // display on OLED
  display.clearDisplay();
  display.setTextSize(1);
  display.setCursor(0, 25);
  display.print("Dis:" + String(distance) + "cm");
  display.setCursor(65, 25);
  display.print("Room:" + String(roomTemp).substring(0, 4) + "C");
  display.display();
  display.setTextSize(2);
  display.setCursor(0, 0);

  if (distance < minimumRange) {
    display.print("TOO CLOSE!");
  }
  if ((distance >= minimumRange) && (distance <= maximumRange)) {
    if (readcount == 5) { // after reading 5 consecutive time
      disptemp();
    } else {
      display.print("HOLD ON"); // when in range, ask user to hold position
      stemp = stemp + objectTemp;
      readcount++; // until approx. 5 x 200 ms = 1 sec
    }
  } else { // if user is out of range, reset calculation
    dtime = 100;
    readcount = 0;
    stemp = 0;
  }
  display.display();
  delay(dtime);
  Serial.println("count  :"+String(readcount));
}

void disptemp() {
  objectTemp = stemp / 5; // get the average reading of temp
  display.setTextSize(1);
  display.print("YOUR TEMP:");
  display.setTextSize(2);
  display.setCursor(60,5);
  display.print(String(objectTemp).substring(0, 4) + "C");
  display.display();
  readcount = 0;
  stemp = 0;
  if (objectTemp >= 38) {
    play_alert();
  } else {
    play_ok();
  }
  ultrasonicRead();
  dtime = 5000; // wait for 5 seconds
}

void play_ok() {  // play three sequential notes when object temperature is below 37.5C
  tone(3, 600, 1000);  // pin,frequency,duration
  delay(200);
  tone(3, 750, 500);
  delay(100);
  tone(3, 1000, 500);
  delay(200);
  noTone(3);
}

void play_alert() { // beep 3x when object temperature is >= 37.5C
  tone(3, 2000, 1000);
  delay(1000);
  tone(3, 3000, 1000);
  delay(1000);
  tone(3, 4000, 1000);
  delay(1000);
  noTone(3);
}

void ultrasonicRead() {
  if (distance < set_cm) {
    digitalWrite(motor, HIGH);
    Serial.println("Motor On");
    delay(500);
    digitalWrite(motor, LOW);
    Serial.println("motor off");
  }
}

Remove all the String objects from your code.

You may want to consider using the watchdog timer to cause the board to automatically reset for this sort of thing.  To be clear, I'm not proposing this as a solution; you should still address the actual problem.  But the watchdog is often used to add a layer of protection against freezing up when deployed.

It should be a fun project. Since you did not give us a schematic (not a frizzy thing) I can only guess. It appears to me you are using the I2C interface and may be week on the pull up resistors. Also the early 1 wire library would hang up if a device missed an ACK. There are many small programs that display the amount of free memory, include that in your code and see if it is stable or slowly leaking memory.

You can put the following two lines at the top your sketch: void got_to_line(int n) {Serial.print(F("[Line:")); Serial.print(n); Serial.println(']'); Serial.flush();}  and #define GOT_HERE() got_to_line(__LINE__)   You can then litter your code with GOT_HERE(); moving them around until you find the exact line (or lines) where the freeze is happening.  If you do that, let us know the exact line (or lines) that it is freezing on.

Any allocation / de- or re-allocation of memory[1] during run time, will cause the heap (the pool of memory from which those allocations are made) to expand until the heap and the stack grow toward each other enough to collide, at which point one overwrites part of the other with unpredictable results.
Strings are allocated from the heap. Strings that are built up little by little, as with:
Serial.println("Object:" + String(objectTemp) + ", Ambient:" + String(roomTemp));
 cause allocation several allocation / de-allocations.
As a simple-to-implement test, comment out the statements that use the String object and just print the raw data. Your program should run without crashes.
To recreate what you're now doing with Strings, I'd suggest using snprintf() to build up your output into a fixed-size output buffer, which can be a local character array (allocated on the stack and de-allocated when the containing function exits). This should be equally stable as the abbreviated experiment I proposed above.
[1] *Unless allocated memory is de-allocated most-recent-first. And even that assumes foreknowledge of the memory allocation algorithm in use, and so, is non-portable).
One way around this is to write one's own memory allocator/de-allocator, which has a pre-assigned pool of fixed-length blocks, one of which it supplies for any memory request of any size, so long as:

there is a free block to allocate; and
the requested size can fit in (the data-space of) a pre-assigned block.

why not a series of Serial.print()?

A series of Serial.print() is perfectly acceptable; I suggested snprintf() as being semantically closer to concatenation of Strings as the OP had written.

In addition to some of the above comments;
Your Nano may not support the watchdog. Please check This post on the Arduino forum
If you are looking for "There are many small programs..." I'll just post the functions I use for getting free memory, heap and stack information below.

int freeRam()
{
    extern int __heap_start, *__brkval;
    int v;
    return (int)&v - (__brkval == 0 ? (int)&__heap_start : (int)__brkval);
}

uint8_t * stack()
{
  uint8_t * ptr;
  ptr = (uint8_t *)malloc(4);
  free(ptr);
  return ((uint8_t *)(SP));
}

uint8_t * heap()
{
       uint8_t * ptr;
       ptr = (uint8_t *)malloc(4);
       free(ptr);
       return(ptr);
}

"may not support the watchdog" is perhaps not the best way to put it.  Optiboot clears MCUSR and so WDRF, meaning you cannot tell that the watchdog timer was the cause of reset merely by inspecting MCUSR.  As a reset mechanism it otherwise works perfectly fine.  There are some ways to somewhat address the clearing of MCUSR also, beyond just fixing the bootloader that is.


text:
L293D motorshield with batteries doesn't power Arduino
Recently I came across a video about a guy building a remote Bluetooth-controlled Arduino car and I was quite amazed. So I decided I wanted to build it too. I have no Arduino or electronics experience at all other than being an IT professional.
So I bought the parts he used in the video (he advised a knockoff Arduino in the description).
After putting it all together the motors work through Bluetooth (yay!). But the issue is that the batteries connected to the motorshield don't give power to the Arduino at all (because the lights don't turn on).
When plugged in the laptop with the USB cable the Arduino gets powered and the motorshield light turns on just a bit, but not enough to make the motors and Bluetooth work.
So in short:
USB powered: Arduino works, motorshield light barely turns on, motors don't work, Bluetooth lights go on, but is not emitting a signal.
2x 18650 battery powered: motorshield light shines bright, Arduino doesn't work, Bluetooth lights don't flicker.
Both: everything works.
So for some reason, the batteries connected to the motorshield don't power the Arduino.
Video used:
https://youtu.be/Q36NbjPMV5k
Circuit diagram:

Knockoff arduino:

L293D motor shield (I'm aware that the ground of the power isn't plugged in)

Parts used:

Geekcreit UNO r3 ATmega16U2 AVR
L293D motor shield
Geekcreit HC-05 bluetooth
4 TT motor
2x 18650 3,7-4.2v 2200mah batteries

I really don't know what I did wrong, since I followed the video and did exactly what the person did. Maybe the batteries aren't powerful enough?

the yellow jumper is the first suspect ... remove it and short the pins with a screwdriver

@jsotola what would shorting the pins cause?

it would replace the jumper ... the yellow jumper itself may be missing the metal strip that shorts the two pins

That sadly didn't work.

Take your voltmeter and measure the voltage from the white wire to the black wire.  These are supposed to be +5V and GND.  But unless you measure them you won't know if they are or not.  Don't have a voltmeter?  It's time to get one.

@jwh20 i can get a voltmeter, but it'll take a while, cuz corona. What would my next steps be if it was correct or not correct?

If there is 5V present, then the problem is likely on the Arduino side.  If not, then your board may be the problem.

Would there be a way to rule the board or arduino out if said 5V is present or not?

After trying to short the pins again, i found out @jsotola was right. The jumper is a defect. It's working now

You're allowed to answer your own question.

The problem was that the 2 pins on which the jumper sits, the jumper or the board was broken (idk exactly). I might've caused that myself by turning on the batteries + powering it through usb at the same time.
I bought a new L293D board then made sure I didn't connect usb power to the arduino while the L293D was sitting on top of it. I uploaded the code, then disconnected the usb, put the L293D on top, powered it all and it works like a charm!

Nice project. The batteries are connected to the motor power which is correct but the motor shield does not output voltage to the 5V system.  Try connecting the batteries to the Vin on the board and all should work.


text:
Problems in calculating and printing long unsigned integers
I have this code which provides an erroneous unsigned long number.
CODE:
char buff[100];

int unsigned long bytes;

bytes = 48 * 70 * 144;

sprintf(buff,"%lu bytes\n", bytes);

BTPort.print(buff);

OUTPUT:
20088 bytes
BUT: The correct value is 483840

This is because the default numeric type is int, which on Arduino is just 16 bits (and signed).
So 48 * 70 * 144 is 0x76200 in hex, which truncated to 16 bits is 0x6200, or 25088. This calculation is done by the preprocessor, not the compiler, so doesn't know (or care) about the destination variable type.
You need to force the values to be calculated as unsigned long by appending UL to them:
bytes = 48UL * 70UL * 144UL;

Thank you for your time, this was extremely useful.

It's even sufficient to force one of the values to be unsigned long. bytes = 48UL*20*144;


text:
Wiring VCNL 4000 Proximity Sensor
I was looking for wiring the VCNL 4000 Proximity Sensor.
I found this one http://bildr.org/2012/11/vcnl4000-arduino/
but there is used a sensor on a red board, which has other pins like mine (which has a blue board) see http://www.adafruit.com/products/466?&main_page=product_info&products_id=466
as I see SCL,DSA,GRND on both
the red has IR+ which is connected to the 5V . mine (blue one) has VIN. Is this meant to be the same and should it be connected to the 5V ?
Any hints?
I tried the following wiring but the following call does not finish.
3,3V TO 3,3V POWER
SCL TO SCL (Last pin on the digital side)
SDA to SDA (Beside SCL)
GND TO GND on the Analog side
Vin to 5V
 readVCNLByte(0x81); is called

i used the example code from adafruiut

There seems to be a big difference between the Sparkfun and the Adafruit breakouts:

Sparkfun breadkout needs 3.3V and 5V power as inputs as shown in their wiring circuit (in the first link you mentioned)
Adafruit breakout needs only 5V as input but has a 3.3V regulator on it that provides the 3.3V to all its internal circuits that need it; it also has a 3.3V pin which is an output not an input as for the Sparkfun

Hence your wiring is wrong. The expected wiring is described in Adafruit sample sketch:
// Example sketch for talking to the VCNL4000 i2c proximity/light sensor
// Written by Adafruit! Public domain.
// To use: Connect VCC to 3.3-5V (5V is best if it is available), GND to
//         ground, SCL to i2c clock (on classic arduinos, Analog 5), SDA
//         to i2c data (on classic arduinos Analog 4). The 3.3v pin is
//         an ouptut if you need 3.3V
// This sensor is 5V compliant so you can use it with 3.3 or 5V micros

In comments, VCC should read as Vin on the breakout.
Note that the comments mention SDA and SCL pins on A4 and A5 respectively, this is correct on Arduino UNO, but your wiring on the 2 leftmost pins of the digital pin header is also correct, as these pins are now replicated there on UNO and Leonardo. On Leonardo, the real pins for SDA/SCL are pins 2 and 3. If you don't have a UNO or Leonardo though, you should check where SDA and SCL can be found (that's generally described on Arduino Product page for your board).
Although wiring SDA/SCL on these 2 replicate pins is correct, I would rather recommend using A4 and A5 instead, so that you don't get the illusion that you can both use SDA/SCL and A4/A5 for something else at the same time.
This circuit uses I2C which means you should normally add pullup resistors to SDA and SCL wires; however, it seems that the Adafruit breakout already integrates them, so no problem here.
To sum up, and provided that you have a UNO or Leonardo, your wiring is correct except that you should remove the wire between both 3.3V pins.
This is shown below for UNO (I used the real pins for SDA and SCL so that you don't use them for something else later):

Arduino UNO 5V  ---> Breakout Vin
Arduino UNO GND ---> Breakout GND
Arduino UNO A4  ---> Breakout SDA
Arduino UNO A5  ---> Breakout SCL
Breakout 3.3V left unconnected

For Leonardo it would be:

Arduino Leonardo 5V  ---> Breakout Vin
Arduino Leonardo GND ---> Breakout GND
Arduino Leonardo D2  ---> Breakout SDA
Arduino Leonardo D3  ---> Breakout SCL
Breakout 3.3V left unconnected

I show you both UNO and Leonardo since you did not mention which board you use.


text:
Arduino Analog Input Oscillating
I'm making a simple Infrared detector using a thermopile. I have a few extra capacitors than what that schematic says. I'm currently following another, but this is the gist.
Schematic and Breadboard-
I can add breadboard picture if needed. I don't have 10 points in this Stack so I can't post more than 2.
I'm using a 9V battery through a 24v - 5v regulator (had one around) to power my op amp and schematic. The signal from the OPAMP will be between 0-5V so voltage hasn't damaged the Arduino Uno. The final project will be something like: output > A then power green, A < output < B power yellow, B < output red.
The issue is that I'm getting an oscillating value from my Serial Monitor that goes from 0 to 1023 (or I have a conversion to change it back to output voltage. So 0V to 5V. See code).
It does this oscillation when I have the board connected to any of the AX pins (X=0-5) or nothing plugged in at all (I understand it will output weird numbers with the pin floating).
I had a picture of the serial monitor but I don't have 10 points to add more than 2 pictures. Please see image below
I know that the output from the OPAMP works because when I use a VoltMeter to read the output, it works fine. 0.3XXV when no flame, 5V when flame is directly on top of my theromopile.
Would anyone happen to have a suggestion to why the Arduino is acting this way? The volt meter reading is directly out of the Op amp pin 1. no more than 2 links. AD822 op amp
Here's my code before adding if statements for the LED's. It was incorrect.
int TP=A2; // Assign Thermopile to pin A2
int val; // Declare readValue Variable
float Voltage; // Declare real world voltage variable - Float = in between variable
int ledG = 11;
int ledY = 12;
int ledR = 13;

void setup() {
 pinMode(TP,INPUT); // Declare Thermopile pin as input
 pinMode(ledG, OUTPUT);
 pinMode(ledR, OUTPUT);
 pinMode(ledY, OUTPUT);
 Serial.begin(9600); // Start your Serial Port
}

void loop() {
  val = analogRead(TP); // Read Thermopile pin and place value into readValue

  Voltage = (5./1023.)*val; // To do "floating point math" have a "." //after the number. If not, it will return real number (5/1023 = 0) according to Arduino

Serial.println(Voltage); // Print readValue to Serial Monitor
  delay(100); // Delayed output to 1/4 a second
}

You can still workaround the limitation about pictures by combining them with some photo editing SW ;-)

To improve the precision of the calculation, I'd do
Voltage = val * 5. / 1023;

Good idea about combining images..... Updated the question.

LED in the bread board aren't expected to work.

Have you connected your circuit ground to the Arduino ground?

I haven't. Since it was being powered by a battery, I wasn't sure if that would effect the Arduino board. I'll try it out.------- Just connected a wire from board ground to Arduino Ground (while keeping battery ground to bread board) and it seems to have fixed it. Great Suggestion!

@Majenko If you want to post that as a question answer, I'll select it for you.

It seems you haven't connected the circuit ground to the Arduino ground.  This is essential to complete the circuit between your breadboard and the Arduino.  Without the ground connection the electrons that you send to the Arduino have no way of getting back again.
Here's a couple of diagrams that I drew for another question which deals with the Arduino driving a remote device, but the theory holds true no matter which way around it is.

In that diagram the red arrows (not the aerial display team I hasten to add) represent the connection between your breadboard circuit and the Arduino.  Without the ground connection there is no circuit, and a circuit is always needed for current to flow (and hence your signal).  With the ground connection the red arrows become a loop which allows the current to flow and transfer your signal.

Perfect! Thank you for the extra description! It made understanding what I was missing a lot more clearer.


text:
Error while burning bootloader
I am trying to burn bootloader on Arduino UNO using MEGA2560 as the programmer,
I followed the steps stated here but still get the error below:
avrdude: Version 6.3-20190619
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "/home/arduino/arduino-nightly/hardware/tools/avr/etc/avrdude.conf"
         User configuration file is "/home/webdev/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyUSB0
         Using Programmer              : stk500v1
         Overriding Baud Rate          : 19200
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : STK500
         Description     : Atmel STK500 Version 1.x firmware
         Hardware Version: 2
         Firmware Version: 1.18
         Topcard         : Unknown
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000 (retrying)

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000 (retrying)

Error while burning bootloader.
Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.
         Double check connections and try again, or use -F to override
         this check.

avrdude done.  Thank you.

Note: The Arduino UNO stopped responding when I mistakenly short-circuited a connection, I mistakenly passed 12v to one of the header pins of sensor shield mounted on the board.
How it was connected

You note about short circuiting needs more explanation.  Depending on what you did the device may be damaged.

Clearly, however, the MEGA is not communicating with the Uno.  Please share how you have this hooked up.

@jwh20 I have included a connection diagram to the question.

Based on this:

Note: The Arduino UNO stopped responding when I mistakenly
short-circuited a connection, I mistakenly passed 12v to one of the
header pins of sensor shield mounted on the board.

There are no I/O pins on the Arduino that are 12V tolerant.  You have almost certainly "fried" your Uno board.  It's possible the only casualty is the ATMega chip itself and replacements are available from a number of sources or you can purchase a "raw" one from an electronics reseller and use your programmer setup above to burn your own boot loader.
It's also quite likely that your sensor board is damaged as well.
From the Microchip datasheet:

You want something like this:
Adafruit Pre-programmed ATMega168p
Buy several, accidents happen!

If it's any consolation, I've put 30VDC onto a pin of a Arduino Leonardo, just being sloppy with leads on a table.  Strangely, it "worked" after that, though not the GPIO pin. But, it was rather hot and bothered about it and so untrustworthy thereafter; I mean it ran code, but you could fry an egg on it while it was doing so.  I replaced the chip on it and now it's fine.  It is entirely possible that only the AVR on your UNO is dead and with some work may be replaced.  If it's a DIP based UNO as pictured, this is comparatively easy.

Anyone who has experimented with electronics for any length of time has experience "smoke".  I've lost track of how many expensive chips I've fried due to one oversight or another.

Or an Adafruit Pre-programmed ATMega328P rather.


text:
Arduino LED lamp circuit
I am working on a RGB LED lamp project and this is the schematic for the circuit I managed to come up with.

I am planning to integrate a 27V power supply that powers both the Arduino and a Bluetooth HC-05 module, so I calculated the required resistor values as seen on the schematic. Would this design work? Is 27V too much for the Arduino or does the LED setup balance everything out?
EDIT:
I made an attempt to fix my mistakes based on the answers I received here and this is the new schematic:

This new model would use a 5V power supply instead. Would this fix all issues?

the Arduino pins are 5 V. it will work with one LED, but not with 6 in series. every LED drops around 2 V so after 2 LEDs there is not enough voltage and nothing will light up.

No, this will not work. An Arduino works at 5V and 27V will destroy it. You cannot control the LEDs directly from the Arduino's pins. You need a transistor or MOSFET based circuit to be able to control the LEDs from a lower voltage digital output pin. What current do these LEDs run at?

This is not a software question, it's an electrical one.  Read the datasheet.  And then learn Ohm's Law.

in the updated schematics every LED must have its own resistor usually at least 100 Ohm. it is better to have the transistor after the LEDs

No. You will destroy the Arduino and the bluetooth module.
Firstly the Arduino needs no more than 20V absolute maximum - recommended no more than 16V.
Secondly a resistor is not a voltage regulator. It can only drop a fixed voltage when you have a fixed current. It only works with LEDs because they are themselves a fixed voltage.
Thirdly an Arduino output cannot power 6 LEDs in series. You get 5V out, but the combined forward voltage of 6 LEDs is between 12 and 18 volts depending on the colour.


text:
HC-05 voltage divider
I am currently testing a small Arduino Nano project (schematic below) and have encountered issues when communicating between a HC-05 Bluetooth module and the Arduino. I am using a simple LED bulb which I am trying to turn on and off from a phone which is connected to the HC-05. The HC-05 is powered separately by some batteries instead of being powered by the Arduino itself. The Bluetooth connection is functional, and so is the actual LED functionality on the Arduino, but there seems to be a problem when I am trying to send stuff through the RX/TX connection. I previously attempted this without a voltage divider and had the same problem. Am I using the right resistors for the voltage divider or should I step them up to 1k and 2k respectively? I measured the voltage on the RX/TX and for some reason it only amounts to around 1.5V (instead of the desired 3.3V). Is there any other issue I am not seeing?

Edit: I also measured the voltage on the RX/TX without the voltage divider and somehow it's straight up 0. Why would that be?

connect the grounds together

both the 200 ohm resistor branch and the HC-05 GND are connected to the cathode of my batteries

What about the ground of the Arduino...?

Arduino is plugged in (via mini USB)

Connect the grounds of the 2 boards together, like jsotola said!


text:
How to change avrdude parameter in Arduino status log when uploading a program? avrdude.conf
Recently I custom bootloader optiboot for Arduino Uno to my custom board called Ardunesia xst X1-02, with Cortex M3 processor. I set avrdude as bootloader upload tool = "X1-02_bootloader.upload.tool=avrdude" in board.txt. It work normal which my board pretends to be Arduino UNO. But I want to change this log status:
 Using Port                    : COM6
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

I want the status log to contain my custom board instead displaying atmega328. I changed and edit file in avrdude.conf which it seems the root of this problem. I added an inheritance in Atmega328 for my custom board, but It didn't work (still displaying atmega328). I know avrdude.conf is made for avr MCU, but I wonder there is a way to add our custom/non-avr mcu to display this status log? Thank You.
Edit: To make it clear I want to customing avrdude.config C:\Users\yourPC\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17\etc which its contain board ID for AVR device and I want to insert y device ID here, I inserted it on Atmega328 part parent like this:
part parent "m328"
    id          = "m328p";
    desc        = "ATmega328P";
    signature       = 0x1e 0x95 0x0F;

    ocdrev              = 1;
;

part parent "m328"
    id          = "m328pb";
    desc        = "ATmega328PB";     //another m328 version
    signature       = 0x1e 0x95 0x16;

    ocdrev              = 1;
;

part parent "m328"
    id          = "XST";
    desc        = "XST_X1_02";         //my board XST X1-02
    signature       = 0x1e 0x95 0x0F;

    ocdrev              = 1;
;

I set the signature so the bootloader recognize my board as Arduino UNO and its work well. But it keep reading as Atmega328P and not displaying XST X1-02. Should I create my own signature? any advice? Thank you
Problem Solved! I need to changes compile patterns in platform.txt from -DAtmega328_{build.board} to -DXST_{build.board} which XST is my MCU name. Thanks everyone!

why would you make an ARM MCU pretend to be an Uno?

Arduino Uno is running on ArduinoCore-avr while Microchip's ARM MCUs are using ArduinoCore-samd, ST's STM32 or PIC's 32 bits MCUs all have there own different Arduino Core. Are you sure you know what you are doing? Why you are trying to use an 8-bit AVR core for 32-bit ARM chip?

@juraj Thanks for asking, because I want to make 'optiboot' bootloader work on my ARM MCU. Optiboot by default design for AVR device. Next I modified my MCU's buffer and boot sector address to make the optiboot main program work. Its work fine, but I just wondering how to change the status log above to contain my Device ID.

@hcheung Yess I know that, I just assigned to make a bootloader for the new MCU. I found it easier to port a bootloader program from Optiboot which designed for AVR and used AVRdude as upload tool than using Bossac for ARM devices like arduino Due. Its works since I just porting the size of buffer and bootloader section address for it. Now it just likes the last step to display my Device ID in arduino verbose output. Or can you tell me how to make an arduino bootloader for arm devices? Because I found it more complicated than a bootloader from Optiboot

Arduino M0 uses avrdude for upload

@juraj Interesting, but I dont find ATSAMD21G18 was mentioned in avrdude.conf C:\Users\yourPC\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17\etc. This file contain all device ID that using avrdude for upload

I think it reports as ATmega2560

@juraj Just checked it, it's not. But since I don't have Arduino M0 so I can't  figure it out. Thanks for your response


text:
ESP32: interrupt error (The following tasks did not reset the watchdog in time)
My system includes 2 ESP32 devices, communicating over ESPnow protocol. The slave device (connected to a Joystick)  is transmitting only when a changes occur, yet there can be several changes in a short time. The Master receives the transmission and executes upon. It starts running OK, but from time to time the master gets the following error and reset:
6429) task_wdt: Task watchdog got triggered. The following tasks did not reset the watchdog in time:
The master loop is empty, so to my understanding it runs endlessly (like NOP?) until an interrupt is received. However, the function registered with
esp_now_register_recv_cb(OnDataRecv);

is not very short. So perhaps this is the cause for the error.
I guess I could use a handling routing to collect the messages from the slave, but in this case it doesn't matter if a packet of data will be lost from time to time. I prefer losing old data rather than responding to it late.
Any ideas how to solve this problem? perhaps stop registration of the OnDataRecv when the master is working on the service routine? and re-register it when ready?
the relevant code:
struct_message myData;
// callback function that will be executed when data is received
void OnDataRecv(const uint8_t * mac, const uint8_t *incomingData, int len) {
memcpy(&myData, incomingData, sizeof(myData));
my_tank.tank_go_vector(myData.x_val,myData.y_val,myData.button_state,range);
} // of OnDataRecv()
The registration within setup:
esp_now_register_recv_cb(OnDataRecv);

The routine that executes:
void tank_go_vector(int _x, int _y,int _button,int _range) {

    Serial.print("  >> in tank_go_vector: x/y/button/range ");
    Serial.print(_x);
    Serial.print("..  ");
    Serial.print(_y);
    Serial.print("..  ");
    Serial.print(_button);
    Serial.print("..  ");
    Serial.print(_range);
    Serial.print("..  ");

    // go by vector recieved from joystick;

    int x_speed = abs(_x);
    int y_speed = abs(_y);

    x_speed = map(x_speed,0,_range,0,SERVO_RANGE); // 255 for 8 bits
    y_speed = map(y_speed,0,_range,0,SERVO_RANGE);

    Serial.print("   x_speed / y_speed: x/y ");
    Serial.print(x_speed);
    Serial.print("..");
    Serial.print(y_speed);

    if (_x==0 && _y==0) {
      Serial.println("  stop");
      left_motor.stop();
      right_motor.stop();
      return;
    }

    if (_x==0 && _y>0) {
      Serial.println("  forward");
      Tank_forward(y_speed);
      return;
    }

    if (_x==0 && _y<0) {
      Serial.println("  backward");
      Tank_backward(y_speed);
      return;
    }

    if (_x>0 && _y==0) {
      Serial.println("  Right Pivot");
      Tank_right_pivot(x_speed);
      return;
    }

    if (_x<0 && _y==0) {
      Serial.println("  Left Pivot");
      Tank_left_pivot(x_speed);
      return;
    }

  // now deal with vector moves TBD

  } // of tank_go_vector

Or maybe just kick the dog during long looping operations. Without your code it's impossible for us to help you.

@Majenko I added the code.

I did some trials and found out that if the number of transmissions is reduced, the system is working well. Since it is OK to lose some packages, as long as the master is handling the latest package, How can I program the ESP32 master to stop receiving ESPnow messages while handling the current message? and enable it afterwards?


text:
Is this circuit connected right?
I want to create something similar to an article I read a few months ago about the effects of Dopamine. Dopamine is known as the feel-good neurotransmitter; the brain releases it when we eat food that we crave, contributing to pleasure and satisfaction as part of the reward system. I want to use this reward method for breaking habits and creating new ones. I saw someone on youtube make a Dopamine box, very similar to what I was thinking (I left it down below), but I think it had a few design flaws.
So how it works, the lights will be dimmed (so it’s not annoying) and default red, the screen in the center will read the list of activities you have set for yourself that you want to be completed. When you complete a task, you will flip a switch on the housing side; this will toggle some lights to go from red to green and give you the reward system. Along with the lights turning green, the box will play a sound, similar to when you win a game or get a kill, again triggering the dopamine release.
The LCD will display a message, something like "keep going"  or "Don't quit."
The LED is for the green and red lights mentioned above, and the piezo is for a buzzer to play a sound to congratulate you for finishing a task.
Down below, I left a circuit I made in TinkerCad. I am very new to this, and I would like if someone could look at my connections and tell me if I have connected them correctly.
TinkerCad Link- https://www.tinkercad.com/things/9EYfcPv1XsX

Please provide a normal link to your tinkercad circuit, not an embed link. Also please put an image of the circuit directly in your question. That way the question will stay valid, even when the link becomes invalid

Have you tested the circuit in tinkercad? Does it work? If everything works as intended, then the circuit should be correct

if the circuit works, then it is probably connected correctly

Ah, I see 1 problem: Your code doesn't use the Neopixel ring, but why did you connect its data pin to D2 together with the LCD. The data pin of the Neopixel ring needs an own digital output pin.

@chrisl sorry, I added the link in the post, and I left it down below in this reply. Thanks again!
link- https://www.tinkercad.com/things/9EYfcPv1XsX

@chrisl I am very new with TinkerCad; how do I test it?


text:
Using a Encoder Feedback to control a 360 degree servo
I pieced together a sketch to control a servo that turns an encoder. Eventually I plan to build this up to a DMX input, so I have the input range from 0 - 255.
Basically, it's supposed to ask you to input range from 0 to 255 and then it changes that value to 0 -180 for servo control. Then it's supposed to compare that to the encoder and rotate the correct direction until the encoder value and requested values match. I'm just learning arduino so I'm sure I've made some mistake. Here is the code:
// Rotary Encoder Inputs
#define inputCLK 22
#define inputDT 24

#include <Servo.h>

Servo myservo;
int pos = 90;
int counter = 90;
int currentStateCLK;
// Setup Serial Monitor

// Read the initial state of inputCLK
// Assign to previousStateCLK variable
int previousStateCLK;

String encdir ="";

void setup() {
  Serial.begin (9600);
  previousStateCLK = digitalRead(inputCLK);
  // Set encoder pins as inputs
  pinMode (inputCLK,INPUT);
  pinMode (inputDT,INPUT);
  myservo.attach(9);

void loop() {
  Serial.println("Enter a number from 0 to 255");
  while (Serial.available() == 0); {}
  int val = Serial.parseInt(); // read int or parseFloat for ..float...
  long Pos = val;
  Pos = Pos * 180 / 255;
  Serial.println(val);
  Serial.println(Pos);
  if (Pos > Counter) {
    myservo.write 0;
  }
  if (Pos < Counter) {
    myservo.write 180;
  }
  if (Pos = Counter) {
    myservo.write 90;
  }

  // Read the current state of inputCLK
  currentStateCLK = digitalRead(inputCLK);

  // If the previous and the current state of the inputCLK are different then a pulse has occured
  if (currentStateCLK != previousStateCLK) {
    // If the inputDT state is different than the inputCLK state then
    // the encoder is rotating counterclockwise
    if (digitalRead(inputDT) != currentStateCLK) {
      counter --;
      encdir ="CCW";
    } else {
      // Encoder is rotating clockwise
      counter ++;
      encdir ="CW";
    }
    Serial.print("Direction: ");
    Serial.print(encdir);
    Serial.print(" -- Value: ");
    Serial.println(counter);
  }
  // Update previousStateCLK with the current state
  previousStateCLK = currentStateCLK;
}

So when I run the program, I'm not getting any movement on the servo.
Thanks.

reduce your code to only turn the servo in one direction ... nothing more ... it is pointless to even look at your code until you verify that the servo actually works

Your initial problem is here:
  if (Pos = Counter) {

If the result (fall through) of assigning Counter to Pos is non-zero then stop.
That's not right.  You're assigning, not comparing. In C == is comparison and = is assignment.  Instead it should read:
  if (Pos == Counter) {

However there is another, more sneaky, problem with your code - the usage of Serial.parseInt().
If you send the string 56\r\n as you typically would (with the CR+LF line ending typical of serial communication) then parseInt will read the first portion of the string up to and including the first non-digit character and parse it as a number. That is, the 56\r and return the value 56.  Then on the next pass it will see there is still data in the serial buffer and parse it, up to and including the first non-digit character - which is just \n. So it will return 0.
That means the first pass through loop() you get 56, and then immediately after in the next pass through loop() you get 0.
And then, looking at your code a third time, there is another bigger problem: you block waiting for serial input, and your Pos variable is local and will be lost each iteration. I think you meant to use pos, which is a global variable, and not create a new long Pos variable each iteration. And where is Counter defined? That surely should be the global counter variable?
If you're blocking waiting for serial input then how can you be controlling the servo to get it to the desired location?
So, in short, there are so many errors and problems with your code that you need to go back to basics and re-think / re-write many portions of it.


text:
Arduino Nano IoT 33 Char Array size constraints
I would like to save data that I am receiving from API calls in a char array. The problem is that the data is around 80 kB, and my Arduino IoT 33 only has 32 kB of memory.
It will save data in a char array up to 25000 bytes, but when I go to 30000 bytes or above the Arduino freezes. When I copy-paste the entire data to a char array without specifying the size it works fine, but when receiving data over the API in chunks of 10 kB it won't save the entire 80 kB. Is there a way around this?

why do you want to store all that data? process it right away.

well, it is basically a hexadecimal array to update an E-Ink Display. I need all of it at the same time.

then use a SD card or save it to flash memory (if it is not to many writes)

well, my Arduino has a CPU Flash Memory of 256KB can use that somehow?

you can, but it has only 10000 writes

wait so what do you mean by 1000 writes? Can't I save 80kb in CPU flash?

you can but flash memories have limited count of write-erase cycles

I will be updating my display probably 5 to 6 times a day. That should be enough right?

I will try that. Thanks a lot :)

what do you mean by hexadecimal array? ... are you storing text, not bytes?

You can use the flash memory of the SAMD21 MCU used on the Nano 33 IoT, if you don't write too often. Flash memories have a limited count of write-erase cycles. It is guarantied for 10000 writes.
For Arduino SAMD boards like the Nano 33 IoT you can use the FlashStorage library. The library is in the Library Manager.


text:
Where can I store secret keys?
I want to store a password in my ESP8266 program, but I can't figure out a way to do it that makes it inaccessible to hackers. Even if I encrypt it, I'd still need to store the private key for the encryption process somewhere. I only have two ideas and both have issues:

As a const in program code
The compiled binary will be publicly available, so anyone who is able to spend some time interpreting the compiled file would eventually be able to find the password stored in it.
In EEPROM
This is at least safe from people who aren't users, but any user would still be able to upload their own program and read the EEPROM to find the password.

Surely this is a common issue, especially in commercial products. What is the solution that I'm not thinking of?

Maybe you should tell us what you are trying to do that requires you to store a password.

If it is that important, then you probably need a TPM module/chip for storing and using the private key. Though you then should only send the password in encrypted form. If you just decrypt the password with the TPM and then use it directly, someone might be able to extract it. This seems to be a use case of public key authentication involving a TPM.

As @the busybee already said, the ESP8266 is the wrong chip for such applications. Since you always have the possibility to change the firmware. You could write your own bootloader that only accepts your firmware, but this is a huge project by itself.
Encrypting the data should normally be totally ok, if the encryption algorithm is sufficiently strong.
But since you have a ESP8266, you could also transfer the data encrypted to a cloud server which manages/holds the data for you.
But with the hardware you have, it's going to be difficult to lock or hide the data in the EEPROM.
Regards
Dario

The ESP8266 is the wrong device for this. You cannot store anything inside it with protection against read-out.
Any user software is in external memory, so even hobbyists can read all of it. If you provide the binary for download (because of updates, or a DIY build), it even simplifies the read-out.
If you apply asymmetric encryption, for example via a key from an external server, you cannot stop a hacker to apply the same algorithm.
Final note: There is no such thing as absolute security. You can reach some degree, but it is hard.