text:
STM32f4 Warning: The core is locked up
I built a custom board that uses a STM32F411CEU6. My problem is that tried to upload a simple blink sketch (I'm using Arduino IDE with STM32 libraries) and I get the error:
ST-LINK SN  : 57FF72067166535645342467
ST-LINK FW  : V2J37S7
Board       : --
Voltage     : 3.23V
SWD freq    : 4000 KHz
Connect mode: Under Reset

Reset mode  : Hardware reset
Device ID   : 0x431
Revision ID : Rev A

Device name : STM32F411xC/E
Flash size  : 512 KBytes (default)
Device type : MCU
Device CPU  : Cortex-M4

Memory Programming ...
Opening and parsing file: Blink.ino.bin
  File          : Blink.ino.bin
  Size          : 11256 Bytes
  Address       : 0x08000000

Erasing memory corresponding to segment 0:
Erasing internal memory sector 0
Error: failed to erase memory

Error: failed to erase memory

RUNNING Program ...
  Address:      : 0x8000000
Warning: The core is locked up
Start operation achieved successfully
the selected serial port Start operation achieved successfully
 does not exist or your board is not connected

I'm using an ST-LINK V2 USB pen that works fine. I have a Black Pill with the same STM32 to use as a control and everything works ok.
Also, when I try to check the custom board with STM32CudeProgrammer, I get the error:
  22:16:27 :   Size          : 1024 Bytes
  22:16:27 :   Address       : 0x8000000
  22:16:27 : Read progress:
  22:16:27 : Error: Data read failed

How solve the "The core is locked up" issue and upload the sketch.

Fix the problem with your board. Whatever that may be.

https://www.stm32duino.com

The solution:

Open STM32CubeProgramer and click connect
Click Option Bytes (OB) located in the left bar
Select Read Out Protection and choose AA option
Then select PCROP and uncheck the box
Click apply


text:
Pyfirmata util.Iterator causes serial communications issues with more than one Arduino
I'm using two Arduino Megas in a project to read data from a bunch of analog sensors and then output PWMs on digital pins according to their value. These analog signals are also being plotted on a dash app.
I'm using pyfirmata, and the program runs perfectly with either one of the two boards connected. However, when I connect both boards, The second board (second in terms of its pyfirmata.util.Iterator object being instantiated second), will always report nonetype objects when calling board2_some_analog_pin.read()
I found essentially the exact same problem here
Putting the iterators on separate processes fixed the nonetype issue for me too. However I want to know why this would fix things, because I want to be confident there isn't a threading-based solution to the nonetype problem before I start reprogramming everything to work with processes.
My instinct tells me it has to do with this code:
class Iterator(threading.Thread):

    def __init__(self, board):
        super(Iterator, self).__init__()
        self.board = board
        self.daemon = True

    def run(self):
        while 1:
            try:
                while self.board.bytes_available():
                    self.board.iterate()
                time.sleep(0.001)
            except (AttributeError, serial.SerialException, OSError):
                # this way we can kill the thread by setting the board object
                # to None, or when the serial port is closed by board.exit()
                break
            except Exception as e:
                # catch 'error: Bad file descriptor'
                # iterate may be called while the serial port is being closed,
                # causing an "error: (9, 'Bad file descriptor')"
                if getattr(e, "errno", None) == 9:
                    break
                try:
                    if e[0] == 9:
                        break
                except (TypeError, IndexError):
                    pass
                raise
            except (KeyboardInterrupt):
                sys.exit()

found on the pyfirmata github repo here
I've been searching around for days, but still have no clue why this would cause whichever board is tied to the second instance of the iterator object to only give nonetype objects as analog reads. It's not a serial communications problem, because some_digital_pin.write(pwm) works for both boards when both plugged in.
Any help or insight into this issue would be greatly appreciated, as well as tips on how to bypass this issue to allow both boards to read without using multiprocessing.

Doesn't seem like it'd be this code if it's not a serial comms problem, rather something relating to how values are read or stored locally (if they are). No access to machines at the moment but I may take a look this evening. Does reading a digital pin show the same behavior?

Also, did you try via get_pin? And did you try the solution in the linked post? My current guess is that the issue is solvable with some minor tweaks to pyfirmata but I'll need to get a test env set up.

It is not a serial comms problem, I'm pretty sure. Both arduinos are detected fine. When either one is plugged in, they analog read fine. Only when both are plugged in and I run a program that has two pyfirmata.utils.iterator objects, does the arduino with the second iterator only report nonetypes. It's not an arduino issue either because I can swap the arduinos and it's always the one with the second iterator instance that gives nonetypes. Furthermore, setting PWMs on output pins work fine, suggesting no comms issue.

@DaveNewton I did not try get_pin, but I did try the solution in the linked post. It worked. However, for my application, just printing values to console is insufficient, so I'll have to either rework my entire code + modules to work with multiple processes, or, which I'm really hoping might be the case, there's some threading options or functions I can use to solve whatever is causing this issue with the two arduino iterator threads.

source: Stack Exchange

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

sort: votes


text:
Has anyone had issues when trying to download the "CE_ARDUINO_LIB" from Github?
Hello all: I am very new to all of this and suspect that I am doing something wrong. I try to download the library using the IDE (Version 1.8.15) and get the error messageArduino: 1.8.15 (Windows Store 1.8.49.0) (Windows 10), Board: "Arduino Uno"
Error downloading https://downloads.arduino.cc/packages/package_index.json
Specified folder/zip file does not contain a valid library
Specified folder/zip file does not contain a valid library
I am trying to use a 4-20mA current loop board from NCD.io and this is the library that they say to use.
Thank you for your time

The file is the standard Arduino boards management package file that to be setup via Arduino -> Preferences, and you probably already have it under "Additional Boards Manager URLs". To download an Arduino Library from IDE, go to "Tools" -> "Manage Library..." to search for the library you want to download.

I have searched the Arduino Library Manager several times but the "CE_ARDUINO_LIB" is not on it. I can find it on Github but for some reason when I download it and try to add zip file from the IDE that is when the error message appears.

Sometime the library does not have the proper setup of library.properties file  or registered with the Arduino library that  Arduino Library Manager used to find the library. Just down the library from the github and add it to the library directory(if not available, create one) inside your Arduino/ directory, or use git clone <the_library>.git to download it.

Thank you for the advice. I will give it a try and let you know

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


text:
How fast does the Arduino execute code?
I am using the Arduino Nano every. Take this example where I am measuring two things A and B.
Loop{// this loop runs once every second
    //Read A,B
    //Change something using analogueWrite which would effect A,B values
    //Read A,B
}

Would the analogueWrite values have changed fast enough such that the third line would read the new and changed A,B values?

yes the data should be able to change if you are using the analog write function it will change the waves immediately so you will see a change immediately  .

The Arduino Nano Every does not have analog outputs. The function
analogWrite() uses PWM as an ersatz of analog output. As soon as the
function returns, you know that the timer registers controlling the PWM
feature have been set to the proper duty cycle. The timer, however, will
complete the current PWM cycle using the previous settings. Only when
this cycle is over will it use the updated settings for the next one.
Completing the current cycle can take up to 2 ms.
Now, I wonder how the PWM cycle can have any effect on what you are
measuring. If you expect to measure something that depends on the
apparent “analog” value you are outputting, this can only work if your
circuit contains (or behaves like) a low-pass filter. In order to
convert the PWM to an analog value, the filter's time constant has to be
significantly longer than the PWM period. This in turn will cause a
corresponding lag, so your readings will take roughly one filter's time
constant to catch up with the value you are outputting.
Note that all this has absolutely nothing to do with how fast the
Arduino executes code.

the PWM sets the duty cycle on an SMPS device, this in turn would effect the voltage and currents I am measuring. I am worried that the duty cycle would not change in time and hence this means the third line of the code there would not read the changed current and voltage values( A,B)

I am unable to find timing information to be able to investigate this or find anything to draw an accurate conclusion.


text:
Can't access SD card when running timestamps.ino from sdfat.h lib on arduino MKRZero
Im trying to run Timestamps.ino (an example sketch) from the sdfat.h lib into a mkrzero arduino.
This is the code I am running:
/*
 * This program tests the dateTimeCallback() function
 * and the timestamp() function.
 */
#include <SPI.h>
#include "SdFat114.h"
#include "sdios.h"

SdFat sd;

SdFile file;

// Default SD chip select is SS pin
const uint8_t chipSelect = 28;

// create Serial stream
ArduinoOutStream cout(Serial);
//------------------------------------------------------------------------------
// store error strings in flash to save RAM
#define error(s) sd.errorHalt(F(s))
//------------------------------------------------------------------------------
/*
 * date/time values for debug
 * normally supplied by a real-time clock or GPS
 */
// date 1-Oct-14
uint16_t year = 2014;
uint8_t month = 10;
uint8_t day = 1;

// time 20:30:40
uint8_t hour = 20;
uint8_t minute = 30;
uint8_t second = 40;
//------------------------------------------------------------------------------
/*
 * User provided date time callback function.
 * See SdFile::dateTimeCallback() for usage.
 */
void dateTime(uint16_t* date, uint16_t* time) {
  // User gets date and time from GPS or real-time
  // clock in real callback function

  // return date using FAT_DATE macro to format fields
  *date = FAT_DATE(year, month, day);

  // return time using FAT_TIME macro to format fields
  *time = FAT_TIME(hour, minute, second);
}
//------------------------------------------------------------------------------
/*
 * Function to print all timestamps.
 */
void printTimestamps(SdFile& f) {
  dir_t d;
  if (!f.dirEntry(&d)) {
    error("f.dirEntry failed");
  }

  cout << F("Creation: ");
  f.printFatDate(d.creationDate);
  cout << ' ';
  f.printFatTime(d.creationTime);
  cout << endl;

  cout << F("Modify: ");
  f.printFatDate(d.lastWriteDate);
  cout <<' ';
  f.printFatTime(d.lastWriteTime);
  cout << endl;

  cout << F("Access: ");
  f.printFatDate(d.lastAccessDate);
  cout << endl;
}
//------------------------------------------------------------------------------
void setup(void) {
  Serial.begin(9600);
  // Wait for USB Serial
  while (!Serial) {
    SysCall::yield();
  }
  cout << F("Type any character to start\n");
  while (!Serial.available()) {
    SysCall::yield();
  }
  // Initialize at the highest speed supported by the board that is
  // not over 50 MHz. Try a lower speed if SPI errors occur.
  if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) {
    sd.initErrorHalt();
  }

  // remove files if they exist
  sd.remove("callback.txt");
  sd.remove("default.txt");
  sd.remove("stamp.txt");

  // create a new file with default timestamps
  if (!file.open("default.txt", O_WRONLY | O_CREAT)) {
    error("open default.txt failed");
  }
  cout << F("\nOpen with default times\n");
  printTimestamps(file);

  // close file
  file.close();
  /*
   * Test the date time callback function.
   *
   * dateTimeCallback() sets the function
   * that is called when a file is created
   * or when a file's directory entry is
   * modified by sync().
   *
   * The callback can be disabled by the call
   * SdFile::dateTimeCallbackCancel()
   */
  // set date time callback function
  SdFile::dateTimeCallback(dateTime);

  // create a new file with callback timestamps
  if (!file.open("callback.txt", O_WRONLY | O_CREAT)) {
    error("open callback.txt failed");
  }
  cout << ("\nOpen with callback times\n");
  printTimestamps(file);

  // change call back date
  day += 1;

  // must add two to see change since FAT second field is 5-bits
  second += 2;

  // modify file by writing a byte
  file.write('t');

  // force dir update
  file.sync();

  cout << F("\nTimes after write\n");
  printTimestamps(file);

  // close file
  file.close();
  /*
   * Test timestamp() function
   *
   * Cancel callback so sync will not
   * change access/modify timestamp
   */
  SdFile::dateTimeCallbackCancel();

  // create a new file with default timestamps
  if (!file.open("stamp.txt", O_WRONLY | O_CREAT)) {
    error("open stamp.txt failed");
  }
  // set creation date time
  if (!file.timestamp(T_CREATE, 2014, 11, 10, 1, 2, 3)) {
    error("set create time failed");
  }
  // set write/modification date time
  if (!file.timestamp(T_WRITE, 2014, 11, 11, 4, 5, 6)) {
    error("set write time failed");
  }
  // set access date
  if (!file.timestamp(T_ACCESS, 2014, 11, 12, 7, 8, 9)) {
    error("set access time failed");
  }
  cout << F("\nTimes after timestamp() calls\n");
  printTimestamps(file);

  file.close();
  cout << F("\nDone\n");
}

void loop() {}

And this is the error I get when I press any key into the serial.
Type any character to start
Can't access SD card. Do not reformat.
SD errorCode: 0X30,0X2

It's not and sd format problem, and I know that the chipselect pin for the SD is 28.
I have no idea what is wrong. Is it maybe a samd21 limitation with this library? is it there a samd21 lib for sd card?
I have written data in the sd card with other avr so I dont think the sd card is the problem.
Thanks

the SDFat library doesn't know that MKR Zero doesn't have the on-board SD card on SPI, but on SPI1. the Arduino SD library uses defines from variant.h of MKR Zero

So is it possible to make it to work by changing the variant.h? I was doing this test but I actually want to make it work with arduino zero. Do you know if arduino Zero has two spi also? if so, how can I know which one I am using? They both run the same atsamd21

you have to configure or change the SdFat library. but I don't know it. I use the Arduino SD library


text:
ESP-01 OTA Error uploading
Im trying to do OTA upload from Arduino IDE.
Uploaded BasicOTA to ESP-01 with flash size set to (FS:2mb, OTA 1019kb).
ESP-01 connects and shows up in Port selection, but when trying to upload I get
Uploading.................................................

14:40:35 [ERROR]: Error Uploading

Thats the only output I get.
Anyone had similar issue?
Thx

Does your ESP-01 have that much flash?

nop, read wrong the chip info value. It said 4Mbit and I read 4mb. Dumb me

The ESP-01 comes in two variants: blue, with 512KiB flash, and black, with 1MiB flash.
You have chosen an arrangement that needs 4MiB flash.  It won't fit.
Choose a suitable flash size for your board.

Im using Blue variant. Read the chip info using espressifs flash tool and it read 4MBit. In my haste I read 4MB not Mbit :) I have a black variant, will try with it


text:
SHT30 giving wrong humidity
I have an SHT30 sensor which is feeding to my Arduino via an RS485 connection. The readings are coming in as they should be for both temperature and humidity. The problem, however, is that the relative humidity I get from the SHT30 sensor is currently 45%, whereas the calculation of humidity from dry and wet bulb readings in the same conditions is 75%.
How can it be that my SHT30 reading differs by 30% from the actual calculated reading?
I confirm that all of the charts I have looked at place my relative humidity (given dry and wet bulb readings that I know are accurate) to be in the region of 75%. I know for certain, therefore, that it is my humidity sensor that is wrong.
Have you experienced this issue and, if so, how have you fixed it?
Many thanks in advance!

There's really nothing here to go on. The performance of an SHT30 over time depends on several factors. I've never had one go too far out of its published specs except when damaged (too-high humidity for too long) but even then it wasn't that far off. You'll likely need to supply details beyond "it's wrong" though :)


text:
Accessing Physical Pins in Arduino Due from Arduino IDE
It is possible to access the Physical Pin 93, Pin PC11 on ATSAM3X8E in Arduino Due  from the Arduino IDE?
I am programming a Barebone ATSAM3X8E, and it do not seems to be allocated by Arduino Due nor by ATSAM3X8E for any other purpose than the PC Port.

you can configure your own board for Arduino IDE https://arduino.stackexchange.com/questions/54484/adding-a-custom-board-to-the-arduino-ide/60660#60660

Modifying/Making a variant
If you wanted to do it in an Arduino-like way it would require editing the Arduino Due variant.cpp or copying the making your own variant, say from a copy of the Due, and editing the extern const PinDescription g_APinDescription[] array to include an entry that matches for PC11.
Example changes
As an experiment I made the following changes to files in the packages/arduino/hardware/sam/1.6.12/variants/arduino_due_x under the arduino15 directory.
In variant.cpp, an entry for in the g_APinDescription array is insert an index number 79, between the existing two entries (shown for context):
  { PIOB, PIO_PB23B_SPI0_NPCS3,ID_PIOB,PIO_PERIPH_B,PIO_DEFAULT, PIN_ATTR_DIGITAL,                  NO_ADC, NO_ADC, NOT_ON_PWM,  NOT_ON_TIMER }, // NPCS3
  // Addition line here VVVV (this is the line for PC12, copied with PIO_PC12 changed to PIO_PC11
  { PIOC, PIO_PC11,          ID_PIOC, PIO_OUTPUT_0, PIO_DEFAULT, PIN_ATTR_DIGITAL,                  NO_ADC, NO_ADC, NOT_ON_PWM,  NOT_ON_TIMER }, //
  // 79 .. 84 - "All pins" masks

  // 79 - TWI0 all pins
  { PIOA, PIO_PA17A_TWD0|PIO_PA18A_TWCK0, ID_PIOA, PIO_PERIPH_A, PIO_DEFAULT, (PIN_ATTR_DIGITAL|PIN_ATTR_COMBO), NO_ADC, NO_ADC, NOT_ON_PWM, NOT_ON_TIMER },

This is a copy of the entry for PC12, with PIO_PC12 changed to PIO_PC11.
In variant.h, PINS_COUNT changes to 80u, because we've inserted  the pin:
#define PINS_COUNT           (80u)

and later in the file the pin number associate with CAN are bumped up by one also because they're all numbered after the point of insertion:
/*
 * Complementary CAN pins
 */
static const uint8_t CAN1RX = 89;
static const uint8_t CAN1TX = 90;

// CAN0
#define PINS_CAN0            (91u)
// CAN1
#define PINS_CAN1            (92u)

I programmed a sketch the blinks PC11 by way of digitalWrite(79, state); and carefully placed a logic probe on the the unrouted pin on the Due board, and it "blinks" just fine.  That's as far as I've tested.
Direct control
Alternately you could control the pin in your code manually, doing what digitalWrite or digitalRead would normally do.  In other words, you could read the description of something like digitalWrite here and substitute all of the references that it would have gotten from g_APinDescription with hard-coded values.

If I get a chance I will try altering the variant here.  It looks like the new pin would have to be inserted before the PINS_COUNT index, which would need to be made larger by one.  And then PINS_COUNT and a few other named values for pins would have to change to reflect all their indices increasing by one.

I made the six line changes indicated, for some reason the 93 physical pin, PC11, in our sketch at 79, it stays at 3.3V. I will keep trying

You remember to pinMode(79, OUTPUT); ?

Yes... as all other pins. As reference, it is the 93 physical pin in ATSAM3X8E, it is located close to the A0 connector, in the Arduino Due board.

I gather from the that and the update that you're concern we're not talking about the same pin, but I'm pretty sure we are.  Here is the contact I'm making to probe.

Right... perhaps i am omitting some step. I will keep checking.


text:
I have a problem with this code where the buzzer won't work
const int buzzerPin = 7;
const int flamePin = 10;
int Flame = HIGH;
int redled = 8;
void setup()
{
  pinMode(buzzerPin, OUTPUT);
  pinMode(redled, OUTPUT);

  pinMode(flamePin, INPUT);
  Serial.begin(12000);
}

void loop()
{
  Flame = digitalRead(flamePin);
  if (Flame== HIGH)
  {
    digitalWrite(redled, HIGH);
  int i=0;
  do {
    digitalWrite(buzzerPin, HIGH);
    tone(buzzerPin,450);
    delay(200);
    noTone(buzzerPin);
    delay(200);

  }while (i<2);
  }
  else
  {
    digitalWrite(buzzerPin, LOW);
    digitalWrite(redled, LOW);
  }
}

test the buzzer with the simplest code possible

We don't know anything about your buzzer or circuit, so there's little to offer in the way of help. Please make sure when posting code that it's formatted as code so people can actually read it. It's also helpful to include what does work, e.g., there are other factors in your code that could make it seem like the buzzer isn't working.

450 is too low frequency for a piezo. use 3000

Here are the modifications I have done

I changed the Piezo Buzzer frequency to 3000 Hz
The green Button simulates the Flame signal
Change the RED LED from pin 8 to Pin 13 so that I don't have to use an external LED

Here is the simulation output

Observe the onboard LED going HIGH and the buzzer going off. You can find the project link here where you can test with different Piezo buzzer frequency.
Code
const int buzzerPin = 7;
const int flamePin = 10;
int Flame = HIGH;
int redled = 13;
void setup()
{
  pinMode(buzzerPin, OUTPUT);
  pinMode(redled, OUTPUT);

  pinMode(flamePin, INPUT);
  Serial.begin(12000);
}

void loop()
{
  Flame = digitalRead(flamePin);
  if (Flame== HIGH)
  {
    digitalWrite(redled, HIGH);
  int i=0;
  do {
    digitalWrite(buzzerPin, HIGH);
    tone(buzzerPin,3000);
    delay(200);
    noTone(buzzerPin);
    delay(200);

  }while (i<2);
  }
  else
  {
    digitalWrite(buzzerPin, LOW);
    digitalWrite(redled, LOW);
  }
}

Disclaimer: I am not the Wokwi creator but I support it since it is open source and free to use

@Juraj fixed it

@Juraj I Doubt it. if the flame signal is high, he is triggering the alarm


text:
NEMA 17 Stepper motor + Arduino Mega + driver doesn't move using GRBL and UGS
3x NEMA 17 Stepper Motors: https://www.amazon.com/gp/product/B00PNEQKC0/ref=ppx_yo_dt_b_asin_title_o01_s00?ie=UTF8&psc=1
3x DM542T Stepper Driver: https://www.omc-stepperonline.com/download/DM542T.pdf
Power supply: 12V, 30A
Arduino Mega: https://www.amazon.com/ARDUINO-MEGA-2560-REV3-A000067/dp/B0046AMGW0/ref=sr_1_3?dchild=1&keywords=arduino+mega&qid=1623258848&sr=8-3

I am currently trying to use the GRBL (Mega version 1.1f - https://github.com/gnea/grbl-Mega) and Universal G-code sender (UGS classic version 2.0.7 - https://github.com/winder/Universal-G-Code-Sender) to program my 3 NEMA 17 Stepper motors, but none of the motors move. I have tried powering just one NEMA motor using a simple arduino code successfully.
I successfully uploaded the GRBL Mega software onto the arduino and connected that with the UGS. Upon using the toggle buttons, the status shows that the coordinates are jogging, but my stepper motor does not move. I probed the pins with an oscilloscope as well and read a continuous 5V on pins 11 and 12, which I don't exactly understand. Shouldn't there be pulses sent to the pins used, not continuous voltage?
Here are my current connections:
V+ on driver is connected to V+ on power supply
V- on power supply is connected to GND on arduino and GND, DIR-, PUL- on the driver
The other four wires are connected from motor to driver.
DIR+ is connected to pin 5, and PUL+ is connected to pin 2
Please suggest anything I can try!

There's... a lot of things you could try. There's at least two layers of troubleshooting: circuit (which we can't see) and GRBL config, which includes both the GRBL compilation itself, e.g., everything custom required for the driver, and the customization doable once it's loaded (neither of which we can see).

Solved! I mistakenly assumed pinouts were the same on the Arduino Uno vs. Mega configurations. Changing the pins worked!

can you please provide pinouts that has to be changed.


text:
Digispark Rev.3 Kickstarter ATTiny85 using all 6 pins
i have some trouble to use i2c and the other pins at the same time.
im tring to control the attiny over i2c with a arduino and the attiny should control a 28byj-48 stepmotor.
i started to setup the i2c connection pin 0 and pin 2 is use for that. it is working fine but then i connected the stepmotor driver on pin 1,3,4,5 after connecting the 5 pin i lose my i2c connection.
here is the code from the attiny, nothing special
#include <TinyWireS.h>                // wrapper class for I2C slave routines

#define I2C_SLAVE_ADDR  0x29            // i2c slave address (38)
#define A 1
#define B 3
#define C 4
#define D 5
#define NUMBER_OF_STEPS_PER_REV 512

void setup(){
  pinMode(1,OUTPUT);
  pinMode(3,OUTPUT);
  pinMode(4,OUTPUT);
  pinMode(5,OUTPUT);
  TinyWireS.begin(I2C_SLAVE_ADDR);      // init I2C Slave mode
}

void loop(){
  byte byteRcvd = 0;
  if (TinyWireS.available()){           // got I2C input!
    byteRcvd = TinyWireS.receive();     // get the byte from master
    //Blink(byteRcvd);           // master must wait for this to finish before calling Wire.requestFrom
    //byteRcvd += 10;                                                    // add 10 to what's received
    //TinyWireS.send(byteRcvd);           // send it back to master

    //             Blink(1);                  // show we transmitted
  }
}

There is no such Digispark board as the Rev 3. There was going to be, but there was a mistake, so they went straight from Rev 2 to Rev 4. However unscrupulous Chinese counterfeiters are making "Rev 3" boards.
So... your mileage may vary since the components used on there could be of any dubious quality.
But to your problem: P5 is also the RESET pin.  If the fuses on that chip are set correctly then it can be used as an IO port. But being a counterfeit, who knows what they set the fuses to?
But if you do change the fuses you will have to rely on the power-on reset (plugging it in) to trigger uploads.

As an addition to Majenko's answer I can report having used many of the "Rev.3" counterfeits, every single one came with chip default fuses thereby reset enabled.
You can set the RSTDISBL fuse with your Arduino, plus update the micronucleus bootloader in the process (freeing 0.4k).
Keep in mind setting this fuse will disable ISP programming, so you will need a working bootloader to reprogram the chip unless you revert it via HV programming.


text:
How can I pause serial transfer and then un-pause it?
So I am running a USB (UART) connection from my Arduino UNO (using the serialtransfer.h library) to my pc (using the pyserial transfer library).
This how the INTENDED cycle of code goes:
I receive the list_ packet and save it to a list on the Arduino . Then the elements in the list are checked and used to control parameters of motor a using GPIO pins. Finally a return message is sent to acknowledge each transfer.
I was hoping to make the return message from Arduino as sort of a flag ; whether to wait or move onto the next transfer, this is on the python side of things.
However this is not the case as the sending of packets from Arduino is almost instantaneous even with delay functions and before the Arduino can process the information the transfer is done.
1)Why doesn't delay() work ?
2) Why isn't code sequential ?
This is the Arduino side of things
#include "SerialTransfer.h"

SerialTransfer myTransfer;
int motor1 = 13;
int motor2 = 10;

int obj_cordinates[9];
char reply [16] = {"Packet Recieved"};
void setup()
{
  Serial.begin(115200);
  pinMode(motor1,OUTPUT);
  pinMode(motor2,OUTPUT);

  myTransfer.begin(Serial);
}

void loop()
{
  if(myTransfer.available())
  {
    // use this variable to keep track of how many
    // bytes we've processed from the receive buffer
    uint16_t recSize = 0;
    uint16_t sendSize = 0;

    recSize = myTransfer.rxObj(obj_cordinates, recSize);
    sendSize = myTransfer.txObj(reply, sendSize);

     if( obj_cordinates[4] == 15)
    {
      digitalWrite(motor1, HIGH);
      digitalWrite(motor2, LOW);

      delay(5000);

      digitalWrite(motor1, LOW);
      digitalWrite(motor2, HIGH);
      delay(5000);
    }

    myTransfer.sendData(sendSize);
  }

}

The python side of things
import time
from pySerialTransfer import pySerialTransfer as txfer

def Ser_tran_list (list_):

    try:
        link = txfer.SerialTransfer('COM6')
        link.open()
        time.sleep(2) # allow some time for the Arduino to completely reset

        to_transfer = True
        while to_transfer:
            send_size = 0

            # Send a list

            list_size = link.tx_obj(list_)
            send_size += list_size

            # send a character
            str_ = 'Sending data Packet'
            str_size = link.tx_obj(str_, send_size) - send_size
            send_size += str_size
            link.send(send_size)

            while not link.available():
                if link.status < 0:
                    if link.status == txfer.CRC_ERROR:
                        print('ERROR: CRC_ERROR')
                    elif link.status == txfer.PAYLOAD_ERROR:
                        print('ERROR: PAYLOAD_ERROR')
                    elif link.status == txfer.STOP_BYTE_ERROR:
                        print('ERROR: STOP_BYTE_ERROR')
                    else:
                        print('ERROR: {}'.format(link.status))

            # Parse response string

            rec_str_   = link.rx_obj(obj_type=type(str_),
                                     obj_byte_size=16,
                                     start_pos=0)

            # Display the received data

            print('SENT: {} {}'.format(list_,str_))
            print('Recieved: {}'.format(rec_str_))

            to_transfer = False

Probably because obj_cordinates[4] != 15 You can't use delay() for something that needs  eventually some unpausing ...

The delay() function uses the milliseconds interrupt. Inside an interrupt handler, all other interrupts are suspended so the millis() counter doesn't count and delay() never ends. delayMicroseconds() will work in the interrupt routine because it just sits in a busy loop. Rewrite the code to eliminate the delay function, you can use millis if you want. This is telling you while in the delay function just about everything stops until it is finished.

There are several protocols that will do what you want. There is hardware handshaking and serial handshaking.  This link explains a lot about both and how flow control works. https://stackoverflow.com/questions/7578812/serial-port-handshake-what-the-difference-between-hardware-and-none-handshaking


text:
receives 0 0 instead of "hello"
I receive the following:
09:27:10.618 -> 0 0
09:27:12.589 -> 0 0
09:27:14.616 -> 0 0
09:27:16.622 -> 0 0
09:27:18.576 -> 0 0
09:27:20.577 -> 0 0
09:27:22.583 -> 0 0
09:27:24.606 -> 0 0
09:27:26.571 -> 0 0
09:27:28.612 -> 0 0
09:27:30.585 -> 0 0
09:27:32.582 -> 0 0
09:27:34.564 -> 0 0
09:27:36.563 -> 0 0
09:27:38.587 -> 0 0

When I use the following codes:
For sending:
#include <SPI.h>
#include <SoftwareSerial.h>
SoftwareSerial Serial1(0, 1);
char mystr[6] = "Hello"; //String data

void setup() {
  // Begin the Serial at 9600 Baud
  Serial1.begin(9600);
}

void loop() {
  Serial1.write(mystr,6); //Write the serial data
  delay(1000);
}

For receiving:
    char mystr[10]; //Initialized variable to store recieved data

void setup() {
  // Begin the Serial at 9600 Baud
  Serial.begin(9600);
}

void loop() {
  Serial.readBytes(mystr,6); //Read the serial data and store in var
  Serial.println(mystr); //Print data on Serial Monitor
  delay(1000);
}

Why don't I get my hello string?
NOTE: When I changed to Serial1 for the receiver code I now receive nothing. Not sure why it doesn't work.

pins 0 and 1 are hardwareserial. don't use them with SoftwareSerial. you have to terminate the buffer with 0 to use it with print

I want to use it between my rx/tx from a custom made circuit based on nano board to my adafruit feather m0. The feather supports serial1, the other board does not; yet I want to send the message on a hardware level, how would I do this without softwareSerial? As Serial1 won't work on its own as its "not declared in scope". When you say terminate the buffer with 0, should i do "Hello0"?

why not use Serial if you don't use it for USB? not '0', but 0. int l = Serial.readBytes(buff, len); buff[l] = 0;

The Receiver log looks like some SerialMonitor output, which receives via USB. The text to report there should come from feather's Serial1 ? I'd guess on the feather you should do if (Serial1.available()) Serial.write(Serial1.read());


text:
Recover .ino file from tmp files?
Is it possible to recover an .ino file/sketch in/for Arduino? I really need my file back, but ones i uploaded it to my device it vanished from the sketch folder, nor can I find it in the build folder; however, a ton of TMP files are left. Is it possible to use those to recover my .ino file?
They're named something like filename.ino1238437381212.TMP

Have you looked in them to see what they contain?

It would seem that all the 20 files contains the old code I was looking for... Do you know why I get so many tmp files with the same code in?

I would strongly encourage using some form of source control.

Well, stupidly enough, the missing code was inside of the TMP files... in all of them...

I gather that you solved your problem.  I'm guessing someone reading this with the same probably would want to know more though.  You must have learned something useful between the question and answer, what was that?


text:
Fader OOP Problem
This code works and it can fade three LEDs without any problem, obviously you can even add more of them : )
// Pins Definition
const int button1 = 13;
const int button2 = 12;
const int button3 = 11;
const int redled = 2;
const int greenled = 3;
const int blueled = 4;

// Timing States
unsigned long ElapsedLoopTime;
unsigned long Now;

class LED
{
    // Parameters
    unsigned long ParamStartFeed = 300;
    unsigned long ParamDebounce = 50;
    float ParamMinLux = 25.5;
    float ParamMaxLux = 255.0;
    float ParamFeedRamp;

    // Pins
    int led;
    int buttonpin;

    // Status Variables
    bool INDownFront;
    bool LastINValue;
    bool LedStatus;
    float Lux = 127.0;
    bool Direction = true;
    unsigned long LastPressed;
    bool INStatus;
    bool Pressed;
    float Delta;

  public:

    void Initialize(int pin, int ledpin)
    {
      led = ledpin;
      buttonpin = pin;
      pinMode(led, OUTPUT);
      pinMode(buttonpin, INPUT);
      LastINValue = digitalRead(buttonpin);
      LastPressed = millis();
      ElapsedLoopTime = millis();
    }

    void Execute(float ParamFeedRamp)
    {
      INStatus = digitalRead(buttonpin);

      INDownFront = LastINValue && !INStatus;
      Pressed = ((Now - LastPressed) > ParamStartFeed) && INStatus;

      if (INDownFront && (Now - LastPressed  < ParamStartFeed) && (Now - LastPressed  > ParamDebounce))
      {
        LedStatus = !LedStatus;
      }

      if (!INStatus) LastPressed = Now;
      LastINValue = INStatus;

      if (Pressed && LedStatus)
      {
        Delta = (ParamMaxLux - ParamMinLux) * ElapsedLoopTime / ParamFeedRamp;

        if (Direction)
        {
          Lux += Delta;
        }
        else
        {
          Lux -= Delta;
        }

        if  (Lux > 255) {
          Lux = 255;
          Direction = false;
        }
        if  (Lux < 25) {
          Lux = 25;
          Direction = true;
        }

      }
      analogWrite(led, Lux * LedStatus);
    }
};

LED ledblue;
LED ledgreen;
LED ledred;

void setup()
{
  Serial.begin(115200);
  ledred.Initialize(button3, redled);
  ledgreen.Initialize(button2, greenled);
  ledblue.Initialize(button1, blueled);
}

void loop()
{
  Now = millis();
  ledred.Execute(3000); // 3000ms
  ledgreen.Execute(3000); // 3000ms
  ledblue.Execute(3000); // 3000ms
  ElapsedLoopTime = millis() - Now;
}

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

I don't really know about the
// Pins
byte led;
byte buttonpin;

but maybe you can try
// Pins
int led;
int buttonpin;

I changed them to integers but there's no change in the speed of the program, but I saw that if I change the position of Now and ElaspedLoopTime in the main Loop it will get faster but it doesn't completely work

I don't agree that it isn't an answer. It looks like an answer. I just happens to not solve the problem.

@NickGammon I fixed everything right now so I changed the title to [Solved], this is my first time in a forum so I don't really know if i can close the question or not

@alessandromrc For example see https://meta.stackexchange.com/questions/116101/is-it-ok-to-add-solved-to-the-title-of-a-question

@DaveNewton Thanks!

I have a tutorial similar to this: https://www.instructables.com/How-to-Create-an-Arduino-Library/


text:
Arduino (line follower + ultrasonic sensor + servomotor)
I am making a line follower car that follows the line when push button is pressed. And by using ultrasonic sensor I want the car to stop when object ahead distance is closer than 100 and then make servo motor turn to 180 degrees.
Used:

Arduino UNO
2 DC motor
cytron maker line sensor
1 servo motor
1 ultrasonic sensor
1 push button.

Got stuck coding, I would like some help please.
int E1 = 4;
int M1 = 5; // Right
int M2 = 6; // Left
int E2 = 7;
int trigPin = 4;
int echoPin = 5;

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

  pinMode(E1, OUTPUT);
  pinMode(M1, OUTPUT);
  pinMode(E2, OUTPUT);
  pinMode(M2, OUTPUT);

  digitalWrite(E1, HIGH);
  digitalWrite(E2, HIGH);

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

void loop() {
  float duration, distance;

  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH);
  distance = ((float)(340 * duration) / 1000) / 2;

  Serial.print("\nDIstance:");
  Serial.print(distance);
  Serial.println("mm\n");
  delay(200);

  int D1 = digitalRead(8);
  int D2 = digitalRead(9);
  int D3 = digitalRead(10);
  int D4 = digitalRead(11);
  int D5 = digitalRead(12);

  if (D1 == 0 && D2 == 0 && D3 == 1 && D4 == 0 && D5 == 0) {
    analogWrite(M1, 100);
    analogWrite(M2, 100);
  }
  else if (D1 == 0 && D2 == 1 && D3 == 1 && D4 == 0 && D5 == 0) {
    analogWrite(M1, 80);
    analogWrite(M2, 100);
  }
  else if (D1 == 0 && D2 == 1 && D3 == 0 && D4 == 0 && D5 == 0) {
    analogWrite(M1, 60);
    analogWrite(M2, 100);
  }
  else if (D1 == 1 && D2 == 1 && D3 == 0 && D4 == 0 && D5 == 0) {
    analogWrite(M1, 30);
    analogWrite(M2, 100);
  }
  else if (D1 == 1 && D2 == 0 && D3 == 0 && D4 == 0 && D5 == 0) {
    analogWrite(M1, 0);
    analogWrite(M2, 100);
  }
  else if (D1 == 0 && D2 == 0 && D3 == 1 && D4 == 1 && D5 == 0) {
    analogWrite(M1, 100);
    analogWrite(M2, 80);
  }
  else if (D1 == 0 && D2 == 0 && D3 == 0 && D4 == 1 && D5 == 0) {
    analogWrite(M1, 100);
    analogWrite(M2, 60);
  }
  else if (D1 == 0 && D2 == 0 && D3 == 0 && D4 == 1 && D5 == 1) {
    analogWrite(M1, 100);
    analogWrite(M2, 30);
  }
  else if (D1 == 0 && D2 == 0 && D3 == 0 && D4 == 0 && D5 == 1) {
    analogWrite(M1, 100);
    analogWrite(M2, 0);
  }
  else if (D1 == 0 && D2 == 0 && D3 == 0 && D4 == 0 && D5 == 0) {
    analogWrite(M1, 0);
    analogWrite(M2, 0);
  }
  else if (D1 == 1 && D2 == 1 && D3 == 1 && D4 == 1 && D5 == 1) {
    analogWrite(M1, 00);
    analogWrite(M2, 00);
  }
  else {
  }
}

Stuck how? What's the specific issue?

(Unrelated, but consider naming things to be a bit more descriptive, e.g., if you have to comment M1 with right just name it rightMotor or something :) Might also be convenient to move some of the code out of loop into separate functions to help figure out what's going on.)

this coding doesn't detect the distance it prints 0 everytime I'm guessing if it is in the wrong order

int M1 = 5; // Right
...
int echoPin = 5;

You appear to be trying to use one of your motors on the same pin as your return signal from the ultrasonic range finder.  When analogWrite(M1, whatever), the internals of analogWrite will set the pin to output, overriding your own pinMode(echoPin, INPUT) in setup().
Later when you pulseIn(echoPin, HIGH), you're just seeing whatever analogWrite is doing with it.  If you're not touching any buttons, your code is executing analogWrite(M1, 0);, so no "distance".
For more fun:  If all of this is correct, if you hold down the buttons to execute analogWrite(M1, 100), pulseIn should report a value of about (1.0/980) * 100/256 or 399.  The 980 being the frequency pin 5 uses on the UNO for analogWrite.  This should cause your code to print something around 66.


text:
Proper Micro SD card schematic
I am using a micro sd card shield with an arduino zero, and I am not sure I am using a proper circuit with it. This is the circuit I am using right now:

That is all it is there, just a capacitor for the power and a pullup resistor for the chipselect. The tags just go to the processor.
I have seen a lot of schematics out there with resistors in series to the processor, some times with pull up resistors, some times with pulldown resistors...
I'm not sure the pullup resistor I am using is a good idea, and I am unsure about the value.
To me something like this makes more sense:

Can someone teach me a proper circuit for this? what is best and why?
Right now I am not very happy with the performance of the micro SD card socket. That's why I want to improve it.
EDIT: Turns out I didnt really understand very well the second schematic, it was just voltage dividers to lower the 5v os arduino uno to 3V. But what about the pullup resistor of the MISO?

As per the SD card specification:

When an SD card is operating in SPI mode or 1-bit SD mode, the CMD and DATA (DAT0 - DAT3) lines of the SD bus must be pulled up by 10 kOhm resistors. Slaves should also have pull-ups on all above-mentioned lines (regardless of whether these lines are connected to the host) in order to prevent SD cards from entering a wrong state.

Basically you need to ensure that "everything is off" until the Arduino actively drives the SD card. Without them the SD card's inputs will be floating and doing anything they like until the Arduino starts communicating.
Resistors in-line with the signals are there really just to increase the impedance and prevent damage when hot-swapping a card.
If you have a 5V Arduino you will require logic level translation. This is a separate thing to the resistors. While resistors are OK for UART or simple IO logic level translation they are not suitable for use with an SD card. This is because the clock frequencies involved are too high and the resistors will corrupt the signal (through low pass filtering). Instead you require an active logic level translation system, such as a dual voltage, or TTL input, buffer, or active MOSFET level shifters.

I think those are not a good idea. They are actually voltage dividers from 5V to 3V.

@Espada86 What are not a good idea? And what is a voltage divider between 5v and 3v?

Arduino UNO works with 5V, but SD Socket works with 3V. Thats the reason they put 3 voltage dividers.

@Espada86 Logic level translation is a completely separate issue. The resistors are still required even if you have level translation. And using resistors as logic level translation for SD cards is not practical - the frequencies involved are too high.

After a lot of testing and investigating it seems that the pullup resitor on miso is the key. I tried a lot of things and this one is the single thing that did the job for me. I finally managed to make it work in a reliable way. I am thinking about putting it on every SPI device connected. Do you think it is usefull to put pull up resitors on al lines? I mean miso, mosi, sck, and CS. Or just miso?

There's an excellent tutorial on Instructables I recommend one to read.
here's the link
https://www.instructables.com/Select-SD-Interface-for-ESP32/

Thanks for sharing that link, it is really usefull

There are a couple of "do and don't" when designing an SPI interface.
Do add pull-up resistors on SS or set SS HIGH for multiple-slave system
SPI is a bus system, means that your device might not be the only one using the interface. When designing an SPI interface, you therefore has to consider the scenario where multiple SPI devices are used, and especially when some of the slaves are not coded by your system.
Without a pullup resistor, the SS line might be neither LOW nor HIGH, this might caused some of the devices on the bus to “hear” the communication on its MISO that was not intend for the device. This might explained why some of the Arduino shields or breakout boards with SPI works when used alone, but fail when used together with other SPI boards, causing by some of those boards lack of pullup resistor or the user didn't pull the SS lines in the system HIGH at the setup() before calling the SPI.begin()!
Do ensure MISO can be tri-state in multiple-slave system
Most SPI chips will be at tri-state on their MISO pin (but there are some chips out there requires extra external tri-state buffer chip) when their chip select signal is HIGH. Tri-stage means that it is neither HIGH nor LOW (i.e. floated) and effectively disconnect. However, A SPI device without tri-state MISO could caused potential problem on a SPI bus where multiple SPI devices are connected. If the MISO is unable to be at tri-state, it will be either HIGH or LOW, this will affect other devices connected on the same bus in receiving data.
With this in mind, it is not a good idea to add a pull-up resistor on MISO line.

Noted, Thank you


text:
Anyone know why my pushbutton is always returning HIGH?
Been trying to figure this out for a couple hours, despite how ridiculously simple it should be. I have no idea why it's always returning 1, even when i'm pushing the button. Fritzing sketch:

My code:
#include <Servo.h>
#define button 3

Servo myservo1;
Servo myservo2;
Servo myservo3;

char incomingByte = "";
int timer;
int timer2;
int interval;
int numservo = 3;
int press1 = 90;
int letup = 0;
int val = 0;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  myservo1.attach(9);
  myservo1.write(0);
  myservo2.attach(7);
  myservo2.write(0);
  myservo3.attach(5);
  myservo3.write(0);
  pinMode(button, INPUT_PULLUP);

}

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

  val = digitalRead(button);
  Serial.println(val);

  //checkerthing();

    while (Serial.available() > 0) {
      incomingByte = Serial.read();
      timer  = incomingByte - '0';
      Serial.println(timer);
      timer2 = timer * 60;
      interval = timer2/numservo;

     motor1_control(press1, letup, interval);
     checkerthing();
     motor2control(press1, letup, interval);
     checkerthing();
     motor3control(press1, letup, interval);
     checkerthing();

     timer = 0;
     timer2 = 0;
     interval = 0;
    }

  }

void checkerthing() {
  val = digitalRead(button);
  if (val == LOW){
    Serial.println("Stopped");
    timer = 0;
    timer2 = 0;
    interval = 0;

  }
  if (val == HIGH){
    Serial.println("Still going");
  }

}
void motor1_control(int angle, int originalangle, int lengthoftime){
    myservo1.write(angle);
    delay(1000);
    myservo1.write(originalangle);
    delay(lengthoftime * 1000);

}

void motor2control(int angle, int originalangle, int lengthoftime){
    myservo1.write(angle);
    delay(1000);
    myservo1.write(originalangle);
    delay(lengthoftime * 1000);

}

void motor3control(int angle, int originalangle, int lengthoftime){
    myservo1.write(angle);
    delay(1000);
    myservo1.write(originalangle);
    delay(lengthoftime * 1000);

}

Basically, the point of this is to have the servo motors go off at specific intervals as given by the user in the serial monitor. The button exists so that the user can restart the timer at any point in the code. But the problem is, I can't even get it to register the button being pushed. It always returns "HIGH", which leads me to believe there's something wrong with the circuits. I've tried using some different methods, but no luck. Can anyone tell me what the issue here is?
Edit: ...I hadn't pushed the pushbutton all the way into the breadboard. I'm gonna go cry in the corner for a bit. And then get back to coding I guess lol. Thanks for the answers.

Is your breadboard one of the "split power rail" variety?

@Majenko no, it's a full power one

Well, if your real schematic is the same as the drawing then it should work.

Hade you checked you're using the correct terminals on the push button and it's making proper contact with the breadboard ?

What Bra1n said. I have to check those 4-lead pushbuttons every... single... time... because they're like Micro USB connectors; takes three tries to get the orientation right. Check continuity to make sure you're using the correct leads.

@Bra1n Oh god, I hadn't pushed the button in all the way. Ugh. Thank you.

@Crystal For those pushbuttons I flatten the leads; they ship with a "bump" which is great for PCBs, not so much for breadboards--squoosh 'em with pliers.

For people with trouble with those switches, I've seen it suggested to just always connect them by opposite (diagonal) corners.

@DaveNewton To be honest, all USB connectors have 3 sides...

you have INPUT_PULLUP so it should return HIGH if the button doesn't connect the pin to ground

You can try to ise a simple wire to pull the pin down to ground (connecting it to GND on the arduino board); if it works, then it's the wiring or the button, if it doesn't it's something else.

"I hadn't pushed the button in all the way." - You can write this as an answer and accept it. That will show that it has been solved, plus it will keep the question from being resurrected forEVER, waiting for an accepted answer that's never going to arrive.

https://meta.stackexchange.com/questions/116101/is-it-ok-to-add-solved-to-the-title-of-a-question

Hadn't pushed the button all the way in lol

it has happened to me. sometimes, I had forgotten to power on UNO or connect USB!!


text:
Dealing with USB Unplugging?
The following code, debugs SerialUSB Native Port, plugged to a PC, and connected through a Terminal Monitor (such as Termite, with any bps, 8N1, RTS/CTS).
At start, the ports seeks for communication, and you see fast blinks.
If SerialUSB, Plugged and Connected, communication happens, a.k.a. slow blinks.
But if USB is Unplugged after SerialUSB, even if you Disconnect it before, the code turn into an Halt state, a.k.a. no blinks.
If you Plug back the USB, it returns to !SerialUSB, so if you Disconnect (if it were connected) and Connect back the terminal, it recovers the SerialUSB state, not without a reset() line to react.
Seems the same happens for Serial.
Any clue about why the Arduino goes into that Halt state after a USB disconnect?
How should we deal with that? How one should prevent this state?
Most people asserts this is a power source problem. This happens with and without the 5V Barrel Power Source.
// ARDUINO DUE BLINK LED
void setup(){
  pinMode(13,OUTPUT);
  Serial.begin(115200);
  SerialUSB.begin(115200);
  while(!Serial){
    digitalWrite(13,HIGH);delay(500);
    digitalWrite(13,LOW);delay(500);
  }
  Serial.println("System Reset");
}
void loop(){
  int n=0;
  while(!SerialUSB){
    Serial.println("USB Unplugged or Terminal Disconnected");
    digitalWrite(13,HIGH);delay(50);
    digitalWrite(13,LOW);delay(450);
    n=n+1;
    if (n>=5){
      Serial.println("Resetting to Connect if Disconnected");
      digitalWrite(13,HIGH);delay(450);
      digitalWrite(13,LOW);delay(50);
      rstc_start_software_reset(RSTC);
    }
  }
  SerialUSB.println("USB Plugged and Terminal Connected");
  Serial.println("USB Plugged and Terminal Connected");
  digitalWrite(13,HIGH);delay(50);
  digitalWrite(13,LOW);delay(50);
}

This is not possible to do because the protocol CDC/ACM don't send that type of information so you can't detect if the Arduino is connected or not, that's why it halts. (You could make a keep-alive function but I don't know if this is possible with what you're doing)


text:
Higher than 12V Arduino Uno
On many tutorials I have looked at, they say that you should power your Arduino with a 5 - 12V external power supply, but on the Arduino, there is a voltage regulator. Is there anything wrong with powering your Arduino with power outside this range?
Solved

it won't work very well below 5 V ... the regulator has to dissipate too much power when the input voltage is high .... this sort of question has been asked before

Thank you for your answer.

it is 7 to 12 V

Let me just give you an example of what happens even with 12V: One time I was working on a claw machine that I made for the Arduino and when I plugged in 12V while the 5V USB port plugged into the computer, guess what happened. Well, I'll tell you: the Arduino burned up and it was broken. I couldn't even put in the code because it was so cooked. I don't think it turned on either. You see, 7-12V is just a range. You typically want to use what is in between the voltage rating. Even with 12V, you have to be careful. So, hopefully that clarifies. Basically, it will burn up your Arduino into hot plastic, sort of like a hot glue gun. The datasheets agree if you don't believe us. You can try it, but just be aware that I warned you not to. This is the datasheet for the Mega 2560 rev3 It's all because of voltage, which is a sort of pressure for electricity. You could say the same for the water specifications. What happens when you add too much pressure to a water container? It bursts, right? In a way, this can be applied to the Arduino. Thanks for reading, hopefully this helped.

Well, things are a bit more complicated. For the MEGA, if you use the barrel jack the power is fed by the LD1117 IC. It has a roughly 1x1cm heatsink, but in order to be more conservative I'll ignore it. Consequently the thermal resistance is 110°C/W. If the arduino remains at 30°C, the maximum power the 1117 can dissipate is about 860mW. Let's remove 10% to be a bit safer (so 780mW). When the mega is idle with no external devices, it draws 73mA; consequently the 1117 can bear a 10.5V drop, which puts the maximum input voltage at 15.5V. If, on the other hand, you [...]

[...] want to add two bright LEDs (20mA each), the current jumps to 113mA, lowering the voltage drop the 1117 can withstand to 6.9V (and so a maximum input voltage of 11.9V). As you can see, the maximum input voltage highly depend on what you are building...

This sounds more like a power supply or board issue; there should be zero issues with powering through the barrel jack and having USB plugged in at the same time; that's a very common scenario when, e.g., you're directly connected to a 3D printer or CNC machine through USB.

Well, it is a clone. I am not sure if that has to do with anything, if you want I can delete my answer, if it doesn't make sense.

You could use a step-down converter to lower the voltage and also stabilize it to 12V or even lower and you wouldn't have any problem even if you power supply isn't really stable and outputs higher voltage.
(Instead of buying one you can even build it, it isn't really hard to make one)


text:
Using External Power Supply Arduino Uno
I have an AA battery holder for 9V. Two wires come out of it, one for positive and another for negative. How can I wire it up to my Arduino Uno? It kind of looks like this.

I would suggest a barrel jack, you know, ones on eBay. For instance, those 2.1 x 5.5mm barrel jack connectors. Just solder the positive and negative wires respectively with barrel jack. Here is a link: eBay Barrel Jack
Make sure the red or the positive goes with the red on the Barrel Jack and that the black or negative goes with the black of the Barrel Jack. Like in the image.

(Making sure to match the polarity of the Arduino connector; which IIRC is center-positive.)


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:
Battery for WS2812 Strip? (Something's not right)
I have posted this in a few places, so sorry if you have seen it somewhere else
Im working on a battery powered led strip project,
iv put the project together and have been testing with a mains power supply
Iv run some tests and found at max I'd be pulling 4.5 amps
Averaging around 2 ish

I rounded out to about 3.5 amps, and said for 90 mins run time id be looking at the 7ah battery
7/2 = 3.5 so 2 hours runtime
I got a 7ah SLA 12v battery, running though a 12v to 5v converter to power the led strips
(Arduino is running off a usb battery pack)
However after about 45 mins I tested the battery and it said 10.9 v
Which I understand to be too low for SLA batteries (11 should be the minimum?) so I shut it off
My question is did I mess up somewhere and get my math wrong?
Many thanks in advance

What kind of 12V to 5V converter are you using?

Its listed as a Step Down buck converter regulator
9-35v input, 5v 5A output

In that case 4.5A at 5V will only be around 2A to 2.5A at 12V.

So based on that my battery should have lasted longer? not shorter?

Yep. If indeed there was even a problem.

There are a few things that may contribute to your lower than expected battery lifetime.
Effective capacity: you should aim to never use more than 50% of the capacity of a lead acid battery or you will shorten its lifespan considerably.
Also, note that lead acid battery capacity is usually given for a discharge time of 20 hours (C20 rating). The “C” rating could be different but its value should be on the label of the battery.
In the case of a stated capacity of 7Ah at C20, this means the capacity has been calculated at a discharge rate of 7Ah/20h = 350mA. For higher discharge rates, such as in your application, the effective capacity will be much lower.
Battery voltage: measuring battery voltage under load does not say much. Measure the battery voltage “at rest”, when completely disconnected from the load for about 1 hour.
Charging: Are you charging the battery with a proper charger?

I cant see anything about a C rating?
I think my understanding ( or at least what i was told ) is wrong, as i was going off the understanding that 7AH means 7 amps over an hour, so 3.5 amps would be 2 hours etc
I had no mention of C ratings when researching this
For the load, iv charged the battery back up now, but i did check when i was pulling the battery out (would have been about 30 mins after) and was still showing 10.8V more or less
and I have a charger which is marked as being for SLA batteries

okay so i have done some reading on C values, and can understand what you mean now. my next question would be how do I fix this? EG what battery type would I need,

Next step up in terms of common SLA battery sizes would probably be 17Ah. If you keep to 50% maximum discharge you should probably be able to reach 90 minutes with some spare capacity left, but YMMV.


text:
Pulsing 3v into a capacitor to create custom Voltages
I was wondering if it is possible to create diffrent voltages by just pulsing power into a capacitor,
Im using an esp32 which can only output 3v or nothing on its GPIO pins, and i need to make it possible for it to adjust the amount of voltage without anyone touching the device, so i thought maybe you could pulse 3v into a capacitor and the capacitor would only unload what ever the pulses would give in voltages combined, so e.g. 50% 3v 50% 0v, then it gives 1.5v, i have no idea how this would work or the physics behind it
all help would be appreciated

Yes. That's basically PWM through a Low Pass Filter.
Use PWM to set the "duty cycle", which is the percentage of voltage. Then ise a low-pass filter (an inductor + capacitor, or resistor + capacitor) tuned to filter out the carrier frequency (should be around 500Hz if it's the same as an Arduino) to give you a voltage that is proportional to the duty cycle.

simulate this circuit – Schematic created using CircuitLab
That should filter at about 150Hz. The bigger the capacitor the smoother your output will be, but the slower it will be to respond to changes in the specified voltage.  Note that this is not going to give you large currents, but is fine for using as a reference voltage. To boost the current you can feed it into a voltage follower:

simulate this circuit

Just a question: why the resistor is just 100 Ohm? I think having it around 10k is better; this way you can have a smaller capacitor and lower currents. According to your experience is having <1k resistor an advantage?

The smaller the resistor the lower the impedance and the higher the current it can supply. If you x10 the resistor you can /10 the capacitor and the frequency response will be the same, but current in and available current out is reduced. 100r is just the default value in the schematic editor and I sized the capacitor accordingly. The choice is entirely yours what values you use.

BTW, this is a very handy low-pass filter calculator.

ok thanks ;) yes, the output current is directly related to the resistor, but since you put an op-amp just after (so current is virtually 0) I did not understand it. Honestly I did not consider the first schematic, where the lower resistor makes more sense ;) Thank you


text:
Select pin to connect RF receiver
I use the RCSwitch library receive signals with a RF receiver. I really need to change the pin the receiver is connected to on my Arduino Uno.
What should I change in my sketch?
What pins can I connect the receiver to?
This is my code:
#include <RCSwitch.h>

RCSwitch receiver = RCSwitch();

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

  receiver.enableReceive(0);
  pinMode(1, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);

  Serial.println("READY");
}

void loop() {
  if (receiver.available()) {

    int value = receiver.getReceivedValue();

    Serial.println(value);

    switch(value) {
      case 1:
        digitalWrite(1, HIGH);
        digitalWrite(9, HIGH);
        digitalWrite(10, HIGH);
        break;
      case 2:
        digitalWrite(1, LOW);
        digitalWrite(9, HIGH);
        digitalWrite(10, HIGH);
        break;
      case 3:
        digitalWrite(1, HIGH);
        digitalWrite(9, LOW);
        digitalWrite(10, HIGH);
        break;
      case 4:
        digitalWrite(1, HIGH);
        digitalWrite(9, HIGH);
        digitalWrite(10, LOW);
        break;
    }
  }
}

IIRC it needs an interrupt-capable pin, so 2 & 3 on an Uno. Why do you need to switch pins?

You can change
receiver.enableReceive(0);

which uses pin 2, to
receiver.enableReceive(1);

which is pin 3 on the Uno. These are the numbers of the external interrupt. The Uno only has two of them, which are tied to those two pins. So as long as you are using the Arduino Uno, you need to use one of these. The Arduino Mega for example has more external interrupts.
For reference also look at the github page of the RCSwitch library and it's wiki, especially the site about receiving, where this is described.

Besides that: As you are using Serial, you might want to change
pinMode(1, OUTPUT);

to a different pin, since pins 0 and 1 are used for the Hardware Serial interface (Serial, which is connected to USB). So the usage of that pin collides with the serial communication.

Isn't there another way to use a pin like 9?

@manarinian It needs an interrupt-capable pin: https://github.com/sui77/rc-switch/blob/7925dfb753c78bf22f6b8164995cac76fdaa97e1/RCSwitch.cpp#L561


text:
Help with understanding fuses for an embedded AVR project
I am planning to build a project, but it's something quite embedded and I have no need for the extra features or bootloader of a standard Arduino. At the same time, I think I want to use the ATmega 328P rather than an ATTiny, which is what I'm familiar with for this.
I'm running into confusion with the boot size bits and I'm not too sure about the clock setup bits either (normally I run an ATTiny with internal clock). I'm fairly sure I bought some 16MHz crystals and capacitors for this sort of thing a while back, but I'm also sure there will be times that the internal crystal will be fine.
Does anyone have a favored fuse config for this?
I am using an external programmer over the six-pin SPI/ISP port (well, the pins that would be the equivalent of that) for a "boarduino." I only care about the power filtering and external clock (in cases where I need the latter). I'm not bothering with auto-reset or UART since, again, I'm using a programmer.
I would appreciate both configs for 16 MHz (most Arduino-like, I believe) and internal clock at 8MHz. Thanks!
Edit: Here are my settings so far: http://eleccelerator.com/fusecalc/fusecalc.php?chip=atmega328p&LOW=FF&HIGH=D6&EXTENDED=FF&LOCKBIT=FF. I think that's normal for a "regular" Arduino (minus some stuff I may have messed up in the high fuse) but I'd like to not bother with any bootloader stuff and have my code run right away.
For the internal clock version I have this so far: http://eleccelerator.com/fusecalc/fusecalc.php?chip=atmega328p&LOW=E2&HIGH=D6&EXTENDED=FF&LOCKBIT=FF

The bootloader is entirely optional. If you don't want to use the bootloader then you don't need to install the bootloader, and you don't need to configure the chip to use a bootloader.

I think you need to deselect the Boot Reset vector, to disable the bootloader. That's what I do when I don't use a bootloader. Other than that, those fuses look fine to me. Though I'd enable brownout detection, unless you have a very good reason not to. Note that using the internal RC oscillator will give a less accurate clock, which I found only to be an issue when I was using high speed UART. Most of the time it doesn't matter. I like not having to add a crystal and caps to my PCBs.

I don't want the chip configured to have a bootloader, even if I don't use one (not quite sure what happens if it is and I don't, either). It's as simple as turning off the boot reset vector? Like http://eleccelerator.com/fusecalc/fusecalc.php?chip=atmega328p&LOW=FF&HIGH=D6&EXTENDED=FF&LOCKBIT=FF ? Plus you get more pins without an OSC, admittedly it's less of an issue here. I'll set the BOD as needed, that part I do fortunately understand. Any idea if the internal clock is accurate enough to drive Neopixels or not? I like to use a few as indicators.


text:
Using BLE via NRF24L01 to communicate with Android phone
I have been going through a tutorial about this, based on the example code for the "BTLE" Arduino Library.
This is my program:
#include <SPI.h>
#include <RF24.h>
#include <BTLE.h>

RF24 radio(9,10);
BTLE btle(&radio);

void setup() {
  Serial.begin(9600);
  while (!Serial) { }
  Serial.println("BTLE advertisement receiver");
  btle.begin("");
}

void loop() {
  if (btle.listen()) {
    Serial.print("Got payload: ");
    for (uint8_t i = 0; i < (btle.buffer.pl_size)-6; i++) {
      Serial.print(char(btle.buffer.payload[i]));
    }
    Serial.println("");
  }
  btle.hopChannel();
}

I saw a video of a person running this code, and then sending advertising information via the "nRF Connect" Android app.
In that video (https://www.youtube.com/watch?v=DGgjdBSId4Y) they would receive output in the Serial Monitor very regularly, as I would expect.
When I run my code, and start advertising, then I see the name of my phone only every other minute in the output, and between that time, there is a lot of garbage. I cannot copy the output because of too many special characters.
I would expect the string that I am advertising to show up approximately every 100ms, as that is the rate of the advertisement.
Any idea what I could be doing wrong, or how to debug this better?


text:
Can Arduino take 19.5 V
I have a 19.5 V power adapter, can I safely connect it to my Arduino? I don't want to damage it. It is very simple, just lights some LEDs, and I don't want to burn the LEDs either.

probably not, but 19.5 V is not enough information ... what is written on the power adapter label?

You may want to say which Arduino you have, because there is some variation in a specific answer based on that.

45 W 19.5 V = 2.31 A
thats exactly what it says

I have a Arduino Uno Rev3

https://store.arduino.cc/arduino-uno-rev3 see the Tech Specs tab

You can do it but you will have nothing left from the regulator for LEDs etc. The best solution is to invest in a buck converter, they are only a few dollars from your favorite china supplier, sometimes even less then a buck. While you are at it purchase two or three you can then use them to generate other voltages as you progress with the Arduino. I use this method a lot, it is a way to use my old laptop power supplies. If you do not have one your next purchase should be a multimeter, even a cheap one is better than none. Then a logic analyzer, again less than $10.00 US. You could also purchase a 8 to 12V wall wart with maybe about 2 amp output and be safe while probably costing less then the buck converter. Have fun!

The Arduino Uno has a maximum voltage range of 6 to 20 v and a recommended range of 7 to 12 v
Using it at 19.5 v may work if the power supply is well regulated but it is uncomfortably close to the limits and dropping nearly 15v across the linear regulator on the Uno may cause it to get fairly hot.


text:
Can at least one Arduino emulate a USB hub?
What I'd like to do is have some kind of compact (and preferably inexpensive) Arduino-compatible device emulate a USB hub, and simulates plugging in a USB keyboard, pressing a key, then simulates unplugging the keyboard.
The goal here being a USB-connected device with media-control buttons for an Android device, but since plugging in a device that acts as a keyboard disables the on-screen keyboard, the idea is that it only acts like a keyboard when a button is pressed, but keeps a connection going while it's plugged in.
Is this at all possible with any Arduino-compatible device, do I need to look for a different embedded architecture, or do I need a particular kind of USB converter chip?

Since an Arduino is "just" a microcontroller with some specific bootloader and commonly programmed via the Arduino IDE, you can also program it like any other microcontroller.
There are several projects offering USB functionality as a library, in the Arduino world or outside of it. Use your favorite web search engine to find them. With such a library you should be able to tackle your task.
However, this is not a beginner's task. Please note that you might need to learn a lot.
I'd say that even the simplest AVR based Arduino should suffice.

Given I don't have much experience with USB terminology, what should I be searching for? Would "USB composite library" be an accurate description of this set of features?

You could start with "avr usb library" and see what comes up. The interesting projects pop up quite early, and many of them link to other projects of the same subject. Use the keywords you find there to refine your search. -- But do I really have to tell you how to search?


text:
Arduino Keypad: the following key does not respond
I was wondering, by the time I press the following key, it does not return to the main_screen() function. How can I fix my code?
void loop()
  {
    int exit = 0;
    char input = customKeypad.getKey();

    main_screen();
     if (input=='A')
        {
          delay(100);
          lcd.clear();

          do{

           lcd.setCursor(1,0);
           lcd.print("Enter minutes: ");

             if (input=='B')
               {
                break;
                lcd.clear();
               }
           }
           while(1);
       }

}

can you also share the complete code?

You need to read the input again after you get input == 'A'.  At the moment, when you enter the do ... while loop, the input is always 'A', so input == 'B' is never true, and the loop never exits.


text:
Arduino PID Library
I hope you're doing well. I have some questions regarding the PID functions.
Can you please explain to me the following commands? I shall be very thankful to you.

PID myPIDX(&InputX, &OutputX, &SetpointX, Kpx, Kix, Kdx, REVERSE);
What is meant by reverse and why we used & with input, output and setpoint?

myPIDX.SetMode(AUTOMATIC);
What is meant by automatic/manual?

myPIDX.SetOutputLimits(80, 110)
What is meant by the values 80, 110 and what is range 0-255?

myPIDX.SetSampleTime(45);
What is meant by this command? is the time in milli-seconds?

myPIDX.Compute();
How is this function working? I mean what is happening at the back end of the compute function?

Best Regards!

The library documentation and/or code would be the best place to start. At the very least a link to the library you're asking about would be helpful.

https://playground.arduino.cc/Code/PIDLibrary

This is the link to this library I'm talking about

Can you guide me related to this? My project is 2 DOF Ball Balancing using a PID controller

The documentation seems to explain at least some of these fairly well. The code for each is available as well.

Yea ive done the code

I need to understand the backend work being done behind these

Then you'll need to read the code?


text:
PID Arduino UNO
I want to implement a PD controller in Arduino using the PID library. Should I put Ki=0 and the rest of the constants as desired?
/*
BALL BALANCING USING A PID CONTROL with 6" resistive Touchscreen
*/
//////////////////////////////////////////////////////
///Libraries///
#include <PID_v1.h>
#include <stdint.h>
#include <TouchScreen.h>
#include <Servo.h>

//______________________________________________________________
// Definitions TOUCH PINS
#define YP A1 //brown
#define XM A2 //black
#define YM 7  //yellow
#define XP 6  //red

//______________________________________________________________
// For better pressure precision, we need to know the resistance
// between XP and XM Use any multimeter to read it
// For the 6" its 273 ohms across the X plate
#define Rx 273 //  Resistance in Ohm of Touchscreen measured in X-Direction
TouchScreen ts = TouchScreen(XP, YP, XM, YM, Rx);

// Coordinates Touchscreen
TSPoint p;
double xmin = 146.0;  //154
double xmax = 854.0;   //851
double xLength = 160.0; //Width of Touchscreen in mm at 6.0" 158

double ymin = 63.0;    //63.0
double ymax = 953.0;    //950.0
double yLength = 96.0; //Length of Touchscreen in mm at 6.0" 94

double convertX = xLength / (xmax - xmin);   // converts raw x values to mm. found through manual calibration  0.2295   0.225988
double convertY = yLength / (ymax - ymin);   // converts raw y values to mm. found through manual calibration  0.1082   0.107865

//______________________________________________________________
//Center-Position
double x0=74.35; double y0=42.71; //center  Correct: 0.5//-7     double x0=74.35; double y0=42.71
//______________________________________________________________

int state = 0;

// servos variables
Servo servoX; //X axis
Servo servoY; //Y axis

/////TIME SAMPLE
int Ts = 45;  //Delay between taking samples/measurements

unsigned long Stable=0;
unsigned int noTouchCount = 0; //variable for noTouch
//______________________________________________________________

double Kpx = 0.08;  //Kpx = 0.08; //Proportional (P) Get the ball to set point
double Kix = 0.02;  //Kix = 0.02 0.022 //Integral (I)
double Kdx = 0.035;  //Kdx = 0.035; //Derivative (D)  Stop the ball at set point

double Kpy =0.08;  //Kpy = 0.08
double Kiy =0.02; //Kiy = 0.02 0.022;
double Kdy =0.035;  //Kdy = 0.035;

//______________________________________________________________
//INIT PID
double SetpointX, InputX, OutputX; //for X
double SetpointY, InputY, OutputY; //for Y
PID myPIDX(&InputX, &OutputX, &SetpointX, Kpx, Kix, Kdx, REVERSE);
PID myPIDY(&InputY, &OutputY, &SetpointY, Kpy, Kiy, Kdy, REVERSE);
//______________________________________________________________

void setup(){
servoX.attach(9);
servoY.attach(10);

  OutputX=92;
  OutputY=100;
  servoX.write(OutputX); // Make Plate flat in X-Direction
  servoY.write(OutputY); // Make Plate flat in Y-Direction

  //INIT OF TOUSCHSCREEN
   p = ts.getPoint();

  //INIT SETPOINT, Center of Plate
  SetpointX = 0.0;
  SetpointY = 0.0;

  //Setup PID Controller
  myPIDX.SetMode(AUTOMATIC);
  myPIDX.SetOutputLimits(77, 107); // 83 107
  myPIDY.SetMode(AUTOMATIC);
  myPIDY.SetOutputLimits(85, 115); // -- 81 105

  // TIME SAMPLE
  myPIDX.SetSampleTime(Ts);
  myPIDY.SetSampleTime(Ts);
  delay(100);

  state=0;
  setDesiredPosition();

} // end of setup

void loop()
{
  while(Stable < 15)    //REGULATION LOOP
  {
   p = ts.getPoint();   //measure pressure on plate
   if (p.x > 0 ) //ball is on plate
   {
      servoX.attach(9); servoY.attach(10); //connect servos
      setDesiredPosition();
      noTouchCount = 0;
      p = ts.getPoint(); // measure actual position
      InputX = (p.x - xmin) * convertX;  // read and convert X coordinate
      InputY = (p.y - ymin) * convertY;  // read and convert Y coordinate
      if((InputX == SetpointX && InputY == SetpointY ))

          { Stable = Stable + 1;}

       myPIDX.Compute();  // action control X compute
       myPIDY.Compute();  // action control  Y compute
  }
   else //if there is no ball on plate
  {
    noTouchCount++; //increment no touch count
    if(noTouchCount == 150)
    {
     noTouchCount++;
     OutputX=92; OutputY=100;  //make plate flat
     servoX.write(OutputX); servoY.write(OutputY);
    }
    if(noTouchCount == 300) //if there is no ball on plate longer, detach servos
    { servoX.detach(); servoY.detach(); }
  }
  servoX.write(OutputX); servoY.write(OutputY);  //control

  } // END OF REGULATION LOOP

servoX.detach(); servoY.detach(); //detach servos

///STABILITY////
 while(Stable==15)    //if is stable
 { //still measure actual postiion
    setDesiredPosition();
    p = ts.getPoint();
    InputX = (p.x - xmin) * convertX;  // read and convert X coordinate
    InputY = (p.y - ymin) * convertY; // read and convert Y coordinate
    if(InputX < SetpointX || InputX > SetpointX || InputY > SetpointY || InputY < SetpointY  ) //if ball isnt close to setpoint
    {
      servoX.attach(9); //again attach servos
      servoY.attach(10);
      Stable=0; //change STABLE state
    }

  }//end of STABLE LOOP
}//loop end

//______________________________________________________________
//#### DESIRED POSITION ####
void setDesiredPosition(){
 switch(state){

// Start-Sequence
     case 0:  SetpointX = x0;
              SetpointY = y0;
              p = ts.getPoint();
              if (p.x > 0)
              {
                state = 1;
              } // if ball is on plate
              else if (p.x <= 0)
              {
                state = 0;
                setDesiredPosition();
               } // if no ball is on plate
              break;

// Center-Position
      case 1:  SetpointX = x0;
               SetpointY = y0;
               state = 1;
               break;

    default : state = 0; break;

 }  //end of switch state
}   //end of setDesiredPosition()

//______________________________________________________________

Maybe? Without any context it's impossible to help.

I'm doing a project on ball balancing using a PID controller in arduino UNO
My plant is of type-2 and fifth order system.

you can check the code above

Yes, you can use the PID library with Ki=0; to get a PD controller.


text:
Understanding HC-05 and HC-06 usage
I am looking to make some wireless motor controllers, and am going to use an Arduino connected to an HC-05 module as a master controller, with a potentiometer as the speed controller input. There will then be another arduino connected to an HC-06 module as a slave, with the arduino outputting to a PWM motor controller.
I am happy with programming of a single arduino with a potentiometer and the PWM motor controller as an all in one device, however what I would like to understand is how the HC-05 and HC-06 devices are spliced into the scheme. I want to be clear that I don't want someone to come up with the sketch for me as I will not learn anything that way!
I have studied lots of online tutorials about using these devices, and unfortunately they all go straight into using it for an LED blink or something like that, and as a result to my 54 year old brain I am unable to deconstruct the sketch sufficiently to understand which bits of the sketch pertain ONLY to the HC06/05 usage.
For me to understand it I am hoping that someone can point me to (or maybe do) a step by step tutorial that takes the process in three steps;
Firstly a sketch that does something (say you press a button and a buzzer sounds, all on one arduino
Secondly, a completely basic sketch that shows the minimum necessary to connect the master and slave without any actions, buttons, LED's buzzers etc.
Lastly, a sketch that combines the two, where the button is on the master, the buzzer is on the slave, and the sketches that show where those spliced in bits of code go.
In that way, I will be able to differentiate in my head which bits belong to which part of the system. I know it is not a conventional way to learn, but for me it will then allow me to attempt to construct the correct master / slave sketches required for my project. I used this method successfully for making sketched for LCD displays so I am hoping it will work again!
Happy to explain more but as I say, I want to learn for myself and would appreciate tutorials an old git can follow!
Cheers
Les

Any button tutorial should resolve the first ask--it's a common button tutorial topic. Most HC05/06 examples/tutorials firat show how to send or receive data as their first step. It might be helpful to include info on what specific issues you're running in to or provide links to the tutorials/examples you're looking at that are causing confusion. IIRC there should be examples of both buttons and comms included in the IDE examples as well.

I think you misunderstand - yes, I can get an individual button / buzzer sketch, but as for the basic HC-05 / HC06 sketches, I am not certain that they are just 'blank' sketches. The third part is that I want the first sketch to be integrated with the second sketch so that I can see the logical progression from one to another - if those sketches are not all in the same site, I can't be sure that the last sketch is indeed an amalgam of the two.

please add a program listing of the 'blank' HC05 sketch that you are talking about

Hi all, I had someone external to this site direct me to this link http://www.martyncurrey.com/connecting-2-arduinos-by-bluetooth-using-a-hc-05-and-a-hc-06-easy-method-using-cmode/ which has some follow on pages that progress the use, so I am going to go through that and see if this is what I need


text:
CPP Function param use function with multi params
I want to specify a function with parameters for a function parameter, but it doesn't come together.
////////////////////////////////////////////////////////////////////////

// Example funch...
void fileLoad(String path, String type) {
  file = SD.open(path.c_str(), FILE_READ);
  server.streamFile(file, type) != file.size();
  file.close();
}

// This is how I want to use it, but it's not possible:
server.on("/homepage", fileLoad("app/homepage.html", "text/html") );

////////////////////////////////////////////////////////////////////////

// Currently, as it works, you need 1 extra funch...:
void homepage() {
  fileLoad("app/homepage.html", "text/html");
}
server.on("/homepage", homepage);

How you want it isn't how C++ works. Depending on how "on" is written, and what you're actually using, you might be able to use a lambda, or you could start playing C++ games a la https://stackoverflow.com/a/41528436/438992. But I wouldn't.

@DaveNewton, it does support std::function and so lambdas of the type that would be needed, so you could make that an answer.

@timemage I don't remember enough C++ to be coherent ;)

Well, I need more coffee, but I took a stab at it anyway. =)

You can find examples of this sort of thing in the library's examples.
The on() function does support std::function as a parameter, which in turn, means you can use a C++11-onwards lambda expression (which Dave Newton mentioned in comments) to proxy your two-argument function call through a no-argument function:
server.on("/homepage", [] () {
    fileLoad("app/homepage.html", "text/html");
});

The [] ("capture list") is something that would be used if you wanted to copy or refer to things within the scope of the on function call.  Since you're not doing that you could also just write a no-argument function which turns around and calls fileLoad with your two compile-time-known values.  But it is common for people using this webserver library to need to make references things in scope.

As as side note, I'd consider not using String as your received parameter type in void fileLoad(String path, String type).  When passing in a string literal, you're just causing dynamic allocation for no particularly good reason.

Thank you!!! :)


text:
Can't transfer information from esp8266 to arduino
I have esp8266. Which I am trying to set up to be a self-contained access point and server (tcp).
ESP8266 is connected to ports 2,3 of Arduino Uno. On Arduino, I want to process all information coming into esp8266.
Here is my current connection diagram:

And a simple code like this:
ESP8266
/* Create a WiFi access point and provide a web server on it. */
#include<SoftwareSerial.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>

/* Set these to your desired credentials. */
const char *ssid = "JP_TestAP";

int status = WL_IDLE_STATUS;
boolean alreadyConnected = false; // whether or not the client was connected previously

WiFiServer server(23);
WiFiClient client;

void setup()
{
   delay(1000);
   Serial.begin(9600);
   Serial.println();
   Serial.print("Configuring access point...");
   /* You can remove the password parameter if you want the AP to be open. */
   WiFi.softAP(ssid);
   delay(200);
   IPAddress myIP = WiFi.softAPIP();
   Serial.print("AP IP address: ");
   Serial.println(myIP);

   Serial.println("\nStarting server...");
  // start the server:
  server.begin();
}

void loop()
{
  // wait for a new client:
  if (!client) {
      client = server.available();
  }
  else
  {
     if (client.status() == CLOSED) {
      client.stop();
      Serial.println("connection closed !");
    }
    if (!alreadyConnected) // when the client sends the first byte, say hello:
    {
      // clead out the input buffer:
      client.flush();
      Serial.println("We have a new client");
      client.println("Hello, client!");
      alreadyConnected = true;
    }

    if (client.available() > 0) {
      // read the bytes incoming from the client:
      char thisChar = client.read();
      // echo the bytes back to the client:
      server.write(thisChar);
      // echo the bytes to the server as well:
      Serial.print(thisChar);
    }
  }
}

Arduino Uno
#include<SoftwareSerial.h>
SoftwareSerial esp8266(2,3);
String message = "";
bool messageReady = false;
void setup() {
  // put your setup code here, to run once:
 Serial.begin(115200);
esp8266.begin(9600);
}

void loop() {
  while(esp8266.available() > 0) {
    message = esp8266.readString();
    messageReady = true;
  }
  if(messageReady) {
    Serial.println(message);
    messageReady = false;
    return;
  }

}

Unfortunately, I am not receiving any information from the ESP8266 (just a clear log on monitor port). I don't understand where the mistake.

ESP Rx to Uno 3, ESP Tx to Uno 2.

@hcheung what did you mean?

i think i already have same connection, which you mention

@hcheung okay, sorry. I tested. now it works. (i tested many variants, how i can miss that?, maybe when i tested "right version" smth whent wrong with Arduino IDE)


text:
ESP32 Partition size and maximum program size
From an ESP32 example code, I extracted the following part, that just prints the flash partition list to the console.
#include <string.h>
#include <assert.h>
#include "esp_partition.h"
#include "esp_log.h"

static const char *TAG = "example";

void setup(void)
{
    Serial.begin(115200);
    delay(200); // Otherwise, the first log entries get lost
    ESP_LOGI(TAG, "Start test");
    esp_partition_iterator_t iter = esp_partition_find(ESP_PARTITION_TYPE_APP, ESP_PARTITION_SUBTYPE_ANY, NULL);
    ESP_LOGI(TAG, "Name, type, subtype, offset, length");
    while (iter != nullptr)
    {
      const esp_partition_t *partition = esp_partition_get(iter);
      ESP_LOGI(TAG, "%s, app, %d, 0x%x, 0x%x (%d)", partition->label, partition->subtype, partition->address, partition->size, partition->size);
      iter = esp_partition_next(iter);
    }

    esp_partition_iterator_release(iter);
    iter = esp_partition_find(ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_ANY, NULL);
    while (iter != nullptr)
    {
      const esp_partition_t *partition = esp_partition_get(iter);
      ESP_LOGI(TAG, "%s, data, %d, 0x%x, 0x%x (%d)", partition->label, partition->subtype, partition->address, partition->size, partition->size);
      iter = esp_partition_next(iter);
    }

    esp_partition_iterator_release(iter);

}

void loop()
{
}

In the project folder, I also have a custom partitions.csv file as follows:
nvs,        data, nvs,      0x9000,  0x6000,
phy_init,   data, phy,      0xf000,  0x1000,
factory,    app,  factory,  0x10000, 512k,
storage,    data, ,         ,        0x40000,

If I run the code, it correctly shows the custom partitions with the above sizes, everything like it should be.
However, the build output says the program uses 207278 Bytes from a maximum of 1310720. If I change the partition scheme selection in the tools menu, the second number changes. I would expect the maximum size to be equal to the size of the factory partition from the custom partition scheme.
If I change the factory partition to be only 100k in size, the ESP32 fails to boot and enters a core-dump-restart-loop.
Is this a compiler bug or am I overlooking something?

This appears to be a limitation of the toolchain. The output of processing the partitions.csv file doesn't make it back to the compiler to generate the correct message. The different partition schemes available in the menu come from boards.txt of the ESP32 package. They can be updated, but would be overwritten when the toolchain is updated. For the compiler input, the setting in the menu is relevant, but the actual size of the partitions comes from the partitions.csv file (if it exists).
This means that one has to manually make sure that the size of the factory partition in the csv file is larger or equal to the actual code size. Ideally, it is also equal to the selected partition size from the menu (to get the correct message and eventually error if the binary size exceeds the allocated space).
Some testing shows that if the actual size of the factory partition is smaller than the code size (and smaller than the compiler size limit) the application will successfully build and upload, but fail to run. The chip will enter a startup-reboot-forever loop and not execute any user code. However, whether that is always the case is not guaranteed.


text:
Get time as 24 hour format from RTC
I have a DS3231 RTC module.
I would like to get the time from the RTC as 24 hour format not 12 hour. The library that I'm using requires that I pass in 2 Boolean values into Clock.getHour(), however changing these values does not change the returned time format.
Code;
/*
DS3231_test.pde
Eric Ayars
4/11

Test/demo of read routines for a DS3231 RTC.

Turn on the serial monitor after loading this to check if things are
working as they should.

*/

#include <DS3231.h>
#include <Wire.h>

DS3231 clock;
bool century = false;
bool h12Flag;
bool pmFlag;
byte alarmDay, alarmHour, alarmMinute, alarmSecond, alarmBits;
bool alarmDy, alarmH12Flag, alarmPmFlag;

void setup() {
    // Start the I2C interface
    Wire.begin();

    // Start the serial interface
    Serial.begin(57600);
}

void loop() {
    // send what's going on to the serial monitor.

    // Start with the year
    Serial.print("2");
    if (century) {          // Won't need this for 89 years.
        Serial.print("1");
    } else {
        Serial.print("0");
    }
    Serial.print(clock.getYear(), DEC);
    Serial.print(' ');

    // then the month
    Serial.print(clock.getMonth(century), DEC);
    Serial.print(" ");

    // then the date
    Serial.print(clock.getDate(), DEC);
    Serial.print(" ");

    // and the day of the week
    Serial.print(clock.getDoW(), DEC);
    Serial.print(" ");

    // Finally the hour, minute, and second
    Serial.print(clock.getHour(h12Flag, pmFlag), DEC);
    Serial.print(" ");
    Serial.print(clock.getMinute(), DEC);
    Serial.print(" ");
    Serial.print(clock.getSecond(), DEC);

    // Add AM/PM indicator
    if (h12Flag) {
        if (pmFlag) {
            Serial.print(" PM ");
        } else {
            Serial.print(" AM ");
        }
    } else {
        Serial.print(" 24h ");
    }

    // Display the temperature
    Serial.print("T=");
    Serial.print(clock.getTemperature(), 2);

    // Tell whether the time is (likely to be) valid
    if (clock.oscillatorCheck()) {
        Serial.print(" O+");
    } else {
        Serial.print(" O-");
    }

    // Indicate whether an alarm went off
    if (clock.checkIfAlarm(1)) {
        Serial.print(" A1!");
    }

    if (clock.checkIfAlarm(2)) {
        Serial.print(" A2!");
    }

    // New line on display
    Serial.println();

    // Display Alarm 1 information
    Serial.print("Alarm 1: ");
    clock.getA1Time(alarmDay, alarmHour, alarmMinute, alarmSecond, alarmBits, alarmDy, alarmH12Flag, alarmPmFlag);
    Serial.print(alarmDay, DEC);
    if (alarmDy) {
        Serial.print(" DoW");
    } else {
        Serial.print(" Date");
    }
    Serial.print(' ');
    Serial.print(alarmHour, DEC);
    Serial.print(' ');
    Serial.print(alarmMinute, DEC);
    Serial.print(' ');
    Serial.print(alarmSecond, DEC);
    Serial.print(' ');
    if (alarmH12Flag) {
        if (alarmPmFlag) {
            Serial.print("pm ");
        } else {
            Serial.print("am ");
        }
    }
    if (clock.checkAlarmEnabled(1)) {
        Serial.print("enabled");
    }
    Serial.println();

    // Display Alarm 2 information
    Serial.print("Alarm 2: ");
    clock.getA2Time(alarmDay, alarmHour, alarmMinute, alarmBits, alarmDy, alarmH12Flag, alarmPmFlag);
    Serial.print(alarmDay, DEC);
    if (alarmDy) {
        Serial.print(" DoW");
    } else {
        Serial.print(" Date");
    }
    Serial.print(" ");
    Serial.print(alarmHour, DEC);
    Serial.print(" ");
    Serial.print(alarmMinute, DEC);
    Serial.print(" ");
    if (alarmH12Flag) {
        if (alarmPmFlag) {
            Serial.print("pm");
        } else {
            Serial.print("am");
        }
    }
    if (clock.checkAlarmEnabled(2)) {
        Serial.print("enabled");
    }

    // display alarm bits
  Serial.println();
    Serial.print("Alarm bits: ");
    Serial.println(alarmBits, BIN);

    Serial.println();
    delay(1000);
}

How do I make this happen?

The library that I'm using requires that I pass in 2 Boolean values
into Clock.getHour(), however changing these values does not change
the returned time format.

You appear to be talking about the parameters here, which the second is for getting the current state of the AM/PM flag and configuration and not altering the kind of value you get in the return.
There's a setClockMode function you can call which will configure the chip to report in 24-hour mode.  If you call that passing in false, getHour should begin returning 24-hour time.