text:
Can not find the download Zip button in the GitHub Page
I want to download a zip file for the following code from the GitHub. I am pretty new in the GitHub. Can anyone help me how to download the Zip folder for the following code from the GitHub library? I need the folder named StopWatch.Zip to include in the Arduino Zero library.
 #ifndef StopWatch_h
#define StopWatch_h
//
//    FILE: StopWatch.h
//  AUTHOR: Rob Tillaart
// PURPOSE: Simple StopWatch library for Arduino
// HISTORY: See StopWatch.cpp
//     URL: http://playground.arduino.cc/Code/StopWatchClass
//
// Released to the public domain
//

#define STOPWATCH_LIB_VERSION "0.1.5"

#if ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif

class StopWatch
{
public:
  enum State      { RESET, RUNNING, STOPPED };
  enum Resolution { MILLIS, MICROS, SECONDS };

  explicit StopWatch(const enum Resolution res = MILLIS);
  void start();
  void stop();
  void reset();

  uint32_t value();
  uint32_t elapsed()            { return value(); };

  bool isRunning()              { return _state == StopWatch::RUNNING; };
  enum State state()            { return _state; };
  enum Resolution resolution()  { return _res; };

private:
  enum State _state;
  enum Resolution _res;

  uint32_t _starttime;
  uint32_t _stoptime;

  uint32_t (*_gettime)(void);
  static uint32_t seconds()          { return millis() / 1000; };
};

#endif
// END OF FILE

In case, I have attached the link for this Code below.
Link for the StopWatch.h file

How is this an Arduino question? And this is surely nothing, that you couldn't have found out through googling.

go to https://github.com/RobTillaart/Arduino and click the "Clone or download" button.
The repository contains many small libraries, not only the StopWatch library.


text:
Arduino due dying after connection, gets hot
I have an Arduino Due (made in Italy) which suddenly (after working nicely for some time) started a new behavior: If I connect it to my computer via USB it is recognized and connects. The "On"-led is turned on but gets darker within seconds until it's off and the connection breaks. This happens with both USB ports. The area around the usb ports gets hot and especially the "504L" next to the reset buttons. (I just have my finger to measure the temperature, so it could also be something else in this corner).
What could have happened to the board? And is there anything I can try to revive it?
Update:
@GuitarPicker: It's the object labelled "0105" in your image, so it's probably the F1 fuse. If I connect the top USB, F1 gets hot, if I use the lower usb, F2 is activated.

There is nothing connected to the board. Before that, I used it to send SPI commands where I might have connected some of the SPI pins in the 6 pin group.
The board is placed on wood, so there should be no external connection
No smoke or visible damage.

I'm having trouble locating your "504L" part.  One sheet says it's a tiny resistor about 1mm x 0.5mm  Perhaps it's a different revision.  Near the reset button, I see a resettable fuse (F1), and a pair of capacitors (C25, C27).  Please check the layout below and see which part number corresponds to the hot one.  I suspect it may be the fuse.
Links: Layout, Schematic,
Photo

The board is using too much current. This will trip the polyfuse, which will gradually increase resistance. Which explains the power led fading out. Is there anything connected to the board?

The "504L" is a 500mA polyfuse.  If more than 500mA is attempted to be drawn through the USB port it will get hot which causes the fuse to "trip".  When it cools down again it will "reset".
Why is too much current being drawn through the USB port?  Well, that's what needs answering to know just why your board is misbehaving:

Do you have lots of things plugged into the board - like LED strips, motors, etc?
Is the board sat on something metal causing a short circuit? (I did that by having some loose change on my desk once).
Have you physically damaged the board and caused some pins of one of the chips to short together?
Has the Magic Smoke™ escaped from one of the chips rendering your board broken?

source: Stack Exchange

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

sort: votes


text:
Variable updated in ISR is miscounting
I'm using a timer to fire a interrupt in configurable time periods.
In that ISR, a pin is toggled, and a uint32_t variable is incremented.
In the main program, a while loop waits until that variable has reached a certain threshold - to then disable the timer via its clock source selection.
while(stepcounter <= threshold) {
}
disablecounter();

Sometimes - depending on optimization level, whether I put a small delay in the while loop, etc., this check seems to fail - advancing to disablecounter() even though stepcounter has not reached threshold.
If I stack the while loop like this:
while(stepcounter <= threshold) {
}
while(stepcounter <= threshold) {
}
disablecounter();

it runs just fine. This also works:
while(stepcounter <= threshold) {
  while(stepcounter <= threshold) {
  }
}
disablecounter();

I'm assuming there's some odd behaviour when comparing rapidly changing 32-bit numbers against a threshold.
This issue also occurs when using a uint16_t for stepcounter, but after a higher number of cycles.
For analysis, I'm simply running this loop over and over again; setting stepcounter back to 0 and restarting the timer. With uint32_t, it usually fails after the 5th or so loop. For uint16_t, it fails after around 25 loops.
Using a tempstepcounter like this also seems to work, but only when comparing against both counters at the same time:
while(tempstepcounter <= threshold || stepcounter <= threshold) {
  tempstepcounter = stepcounter;
}
disablecounter();

Any ideas on this? It this because 32-bit numbers take longer to read from the registers than the time from ISR to ISR?
ISR frequency should be around 32 kHz during this.
ISR code:
ISR(TIMER1_COMPA_vect) {
  PORTF ^= (1 << PORTF0));
  stepcounter++;
}

Hint: Please add the declaration of the variable. It is volatile? And it is protected by a critical-section (i.e. no interrupts) when reading and writing? Operations on 32-bit integers are not atomic on the AVR MPU. Not even 16-bit integers.

stepcounter is declared as volatile.
It it only written to (when the timer is running) inside the ISR, but not during the while()-loop - honestly not sure how I'd protect it there.

What does the ISR code look like?

@ElliotAlderson Updated the question

Possible duplicate of Can arduino interrupts occur in a middle of if statement?

You need to protect the read as well.

You need to declare it volatile in both places and shut off interrupts while reading it. The mainline  has to read it byte-by-byte, and an interrupt could otherwise occur between any two byte-reads, rendering the result of the 4-byte read as garbage.
'volatile' informs the compiler that the variable might not contain what it did last time (which the compiler might otherwise expect if the code being compiled doesn't change it. Turning off the interrupts protects the variable being changed while it's being read.
An even better way to protect the reads than turning off interrupts, is for the ISR to update the counter, then set a single-byte flag to indicate that there's a new count. The mainline would monitor that flag and read the counter only when the flag gets set, then clear the flag. This can work as long as the mainline checks the flag frequently enough that it will never not notice the flag until just before the next update by the ISR. But if you can keep to that constraint, this is a better idea than turning off interrupts.
If too many sub-tasks resort to turning off interrupts, it can have a negative effect on response time or even cause missed interrupts in some cases. This is less likely to be a problem for the relatively simple programs most of us write and run, most of the time. But when you get to tracking and controlling more complex processes and make heavier use of the interrupt system, bad habits have a way of coming back to bite you.

Yep, that was pretty much the issue.
I implemented your suggestion of a single-byte flag, which the ISR sets and the while loop queries. If it has been set, tempstepcounter is updated while protected by cli() and sei().

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


text:
How to set time for 15 seconds
When user used one password after close the servo the password will valid for 15 seconds then it will not work. Other 9 will be same process
Here is code I need just this to set
int locker = 13;
int lockerState = 0;
const int buzzer = 49;
String readString;

#include <Servo.h>
Servo myservo;
int pos = 0;

void setup() {
  Serial.begin(9600);
  pinMode(locker, OUTPUT);
  pinMode(buzzer, OUTPUT);
  myservo.attach(9);
}

void loop() {
  lockerState = digitalRead(locker);
  while (Serial.available()) {
    delay(3);
    char c = Serial.read();
    readString += c;
  }

  if (readString.length() >0) {
    Serial.println(readString);
    if ((readString == "2028") || (readString =="1234") || (readString =="1294") || (readString =="4795") || (readString =="5651") || (readString =="7616") || (readString =="5648") || (readString =="1487") || (readString =="7095") || (readString =="2554"))
    {
      digitalWrite(locker, HIGH);
      for (pos = 0; pos <= 180; pos += 1) {
      myservo.write(pos);
      delay(30);
      }
      delay(5000);
      digitalWrite(locker, LOW);
      /* for (pos = 180; pos >= 1; pos -= 1) {
      myservo.write(pos);
      delay(30);
      } */
      readString="";
    }
      /* else if (readString == "proceed") {
        digitalWrite(locker, HIGH);
        for (pos = 0; pos <= 180; pos += 1) {
        myservo.write(pos);
        delay(30);
        }
      digitalWrite(locker, LOW);
      readString="";
      } */
      if (readString == "decline") {
         digitalWrite(locker, HIGH);
         for (pos = 180; pos >= 0; pos -= 1) {
         myservo.write(pos);
         delay(30);
         }
      digitalWrite(locker, LOW);
      readString="";
      }

    else {
      tone(buzzer, 500);
      delay(1000);
      noTone(buzzer);
      delay(1000);
      readString="";
  }
 }
}

In programming, there are many cases where designing data structures is
more important than the code itself. Once you have a data structure that
makes sense, the code flows very naturally. I think this is one of those
cases, so let's start by looking at what data you have to store for each
of your passwords:

the password itself (let's call it the code)
whether it has ever been used and, if so, whether it has expired
if it has been used but has not expired yet: when it was used for the
first time

This can be saved in an object with the following data fields:
const char * const code;
enum { UNUSED, USED, EXPIRED } status;
uint32_t first_use;  // valid if status == USED

Now think about what kind of actions you want to perform on such a
password:

you want to be able to test whether it matches some user entry
you want check whether it can be used and, if so, take note that it is
being used

Based on these requirements, I propose the following class:
const uint32_t PASS_LIFE_TIME = 15000;

class Password {
public:
    Password(const char *c)
        : code(c), status(UNUSED) {}
    bool matches(const char *entry) {
        return strcmp(code, entry) == 0;
    }
    void update() {  // expire if it needs to be
        if (status == USED && millis() - first_use > PASS_LIFE_TIME) {
            status = EXPIRED;
        }
    }
    bool use() {  // returns true on success
        if (status == UNUSED) {
            status = USED;
            first_use = millis();
        }
        update();
        return status != EXPIRED;
    }
private:
    const char * const code;
    enum { UNUSED, USED, EXPIRED } status;
    uint32_t first_use;  // valid if status == USED
};

Now you need to store all the passwords in an array, and a couple of
functions to operate on the password collection as a whole:
const int PASS_COUNT = 10;

Password passwords[PASS_COUNT] = { "2028", "1234", "1294",
    "4795", "5651", "7616", "5648", "1487", "7095", "2554" };

void update_all_passwords()
{
    for (int i = 0; i < PASS_COUNT; i++)
        passwords[i].update();
}

// Returns true on success, and uses the matching password.
bool try_entry(const char * entry)
{
    for (int i = 0; i < PASS_COUNT; i++)
        if (passwords[i].matches(entry))
            return passwords[i].use();
    return false;  // no match found
}

The function update_all_passwords() is meant to be called on each
iteration of loop(). It may seem superfluous, as a password is updated
whenever you try to use it. However, without regular updating, a used
password could be reused 49.7 days later, because of the millis()
rollover.
Now, in your program, you just need to:

Put a call to update_all_passwords() at the beginning of loop()
Replace the big condition that tests for a valid password by
if (try_entry(readString.c_str()))

Good answer! I would add, that it is not a good practice to use delay(). I think it's worth mentioning, that the coding style from the BlinkWithoutDelay example is way better (which you already used in your code, but the OP didn't), and will help especially when adding more functions to the code.

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


text:
What happen to the counter value if I do not input the statement (if previous state!=current state)
I refer to the code from this page: http://www.toddholoubek.com/classes/pcomp/?page_id=58 :
int ledPin = 13; // choose the pin for the LED
int switchPin =2; // choose the input pin (for a pushbutton)
int val = 0; // variable for reading the pin status
int counter = 0;
int currentState = 0;
int previousState = 0;

void setup() {
  pinMode(ledPin, OUTPUT); // declare LED as output
  pinMode(switchPin, INPUT); // declare pushbutton as input
  Serial.begin(9600);
}

void loop() {
  val = digitalRead(switchPin); // read input value
  if (val == HIGH) { // check if the input is HIGH (button released)
    digitalWrite(ledPin, HIGH); // turn LED on
    currentState = 1;
  }
  else {
    digitalWrite(ledPin, LOW); // turn LED off
    currentState = 0;
  }
  if(currentState != previousState) {
    if(currentState == 1) {
      counter = counter + 1;
      Serial.println(counter);
    }
  }
  previousState = currentState;
  delay(250);
}

I do not have the Arduino device so couldn't test the result currently but am Interested to know if I omitted this line:
if(currentState != previousState)

, using the command line
if(currentState == 1) {
counter = counter + 1;

only and lets say I using a FS-V21 fiber optic sensor to count the quantity of products of 1m long each and on a conveyer belt of speed 0.1m/s so the stat will be true of t=1/0.1=10second for each product.
Will the counter value increase one unit only for each product (happen on the transition edge only), or increase indefinitely in the 10 second duration?

Because of the line
delay(250);

towards the end of the loop() function it will count up once every quarter of a second all the time the "state" is 1.
That means over a 10 second period it will count 40 objects.

No, it will increment as long as there is a product and at the frequency your loop runs at. So, when the light is interrupted, it will count several objects within a second.
The line you want to ommit is very essential, it makes the sketch only detect edges rather than levels.


text:
How to implement a tilt compensated compass?
So i was trying to implement a tilt compensated compass, using HMC5883L and MPU6050. The problem i am facing is, there are 2 equations for tilt compensation
Tilt Compensated X:   X,Y,Z are compass output (raw output)
new_X =  X*cos(pitch) + Y*sin(roll)*sin(pitch) – Z*cos(roll)*sin(pitch)
Tilt Compensated Y:
new Y =  Y*cos(roll) + Z*sin(roll)
Final Heading :
Azimuth =  atan2(Y, X) * RAD_TO_DEG
The angles which i am getting from the mpu are gyro-drift corrected angles which are coming through a kalman filter. Those angles are fed to these above equations and after atan2 i get the tilt compensated heading. But the issue/observation here is, when i rotate the body(on which the compass and mpu are) along the Z axis (YAW axis) the heading doesn't change(sort of locked on), but changes when i tilt the body in X/Y.
I searched for thorough references, but wasn't able to find any!
Here is my code snippet (uses compass part form adafruit library):
double HEADING(double r, double p){
  sensors_event_t event;
  mag.getEvent(&event);
  r = r * (PI/180);
  p = p * (PI/180);
  double x = (event.magnetic.x)*cos(p) + (event.magnetic.y)*sin(r)*sin(p) - (event.magnetic.z)*cos(r)*sin(p);
  double y = (event.magnetic.y)*cos(r) + (event.magnetic.z)*sin(r);

  float heading = atan2(y,x);

  float declinationAngle = 0.366667 * (PI/180);// (0°22')positve declination
  heading += declinationAngle;

  if(heading < 0)
    heading += 2*PI;

  if(heading > 2*PI)
    heading -= 2*PI;

  heading = heading * 180/PI;

  return heading;
}

The HMC5883L data acquisition I wrote :
// i just need a direction reference not actual heading, just to keep my drone
// steady on yaw axis with reference to that direction reference but it shall be Tilt compensated
#include<Wire.h>

#define MAG 0x1E

#define R 0
#define P 1
#define Y 2

float mag_raw[3],h;
float CMP_DEC = 0.36667 * (PI/180);

void setup(){
  Serial.begin(115200);
  Wire.begin();
  Wire.setClock(400000);

  Wire.beginTransmission(MAG);
  Wire.write(0x02);
  Wire.write(0x00);
  Wire.endTransmission(true);

}

void loop(){
  Wire.beginTransmission(MAG);
  Wire.write(0x03);
  Wire.endTransmission(false);
  Wire.requestFrom(MAG,6,true);

  mag_raw[R] = Wire.read() << 8 | Wire.read();
  mag_raw[P] = Wire.read() << 8 | Wire.read();
  mag_raw[Y] = Wire.read() << 8 | Wire.read();

  h = atan2(mag_raw[P],mag_raw[R]);

//  h += CMP_DEC;

  if(h < 0) h+= (2*PI);
  if(h > (2*PI)) h -= (2*PI);
  h *= (180/PI);

//  Serial.print("X : ");
//  Serial.print(mag_raw[R]);
//  Serial.print(" Y : ");
//  Serial.print(mag_raw[P]);
//  Serial.print(" Z : ");
//  Serial.print(mag_raw[Y]);

  Serial.print(" H : ");
  Serial.println(h);

}

Some guidance will be very helpful!

Are you writing all the code?  (Not using libraries?)  I ask as you did not mention how you were compensating the magnetometer's output for hard and soft iron errors.
Creating a tilt compass is hard enough.  But I find it better, if writing most or all of the code from scratch, to create a normal (use it flat on a table) compass 1st.

@st2000 I tried writing my own code (the general approach for i2C Wire lib). Sometimes i got a solid output (no change in data even if i move in different axis), sometimes data came but the range remained almost around 170 for X , 65000 for Y and 56 for Z axes. I didn't understand what was going on so i started using libraries :(    can you give me some relevant references ?

Are the pitch and roll angles small when the body sits flat on a table? Do the raw values of the magnetic field components change when you rotate it?

@EdgarBonet i'll answer according to what i understood; So the R&P angles coming from the MPU are 0±0.1° when kept on the flat surface. Now when I rotate the compass along Z axis, there is no change in the values(actually it is there but it changed about 3 points when i rotated it 90°!). For X,Y axes, the values change a lot !almost ±120 units. ill just add my from scratch written code in the question. Have a look to it, maybe something wrong can be seen...

@Sajil, start simple!  Just stick to getting the magnetometer working.  Forget about the accelerometer. That said, I have yet to see a magnetometer output useful information with out compensating for range (add or subtract a number so that the maximum and minimum of a given axis is the same) and magnitude (multiply by a number so that the maximum and minimum of all 3 axes are the same).  Until you do that, performing math on the output of a magnetometer will give you garbage.

@st2000 yeah let me work more on magnetometer thoroughly. Can you send me some references for it ? Possibly not using the libraries (I find it easy without libraries ).

Inspecting your code, it does not appear you are compensating the raw magnetometer values for soft and hard iron effects.  These terms roughly refer to adjusting the range and magnitude of each of the individual magnetometers (X, Y and Z).  Some magnetometer manufactures allow writing these compensation values into the chip.  Even then the developer and user will still need to perform some form of calibration as the magnetometer can not predict under what conditions the magnetometer will be used.  Here is another explanation using matrices of hard and soft iron compensation.
Once the compass produces expected results on a flat surface parallel to the surface of the earth (in a place on earth where the magnetic lines roughly align with true north).  Consider adding tilt compensation.  Accelerometers usually do not need to be compensated as extensively as magnetometers.
This can be done using trigonometric math and Euler angles.  However, as with physical gambles, this can lead to a situation similar to gimbal lock.  Where the trigonometric math goes to infinity.
To avoid a gimbal lock like situation, most tilt compensated compasses use quaternions.  Quaternions use imaginary numbers and matrix math to describe 3 dimensional rotation.


text:
Chrome-sandbox error in Arduino IDE 2.3 in Ubuntu 24.04
I'm trying to setup an installation of the IDE 2.3 in a Ubuntu 24.04 LTS (beta) environment, and am facing an issue I'm unable to resolve. The IDE gets to the GUI for accepting terms and conditions, and just crashes if I try to proceed.
What I tried from the internet
The App Image complains about Chrome Sandbox. Someone has had this issue in the past, but in their case, they got a path for chrome-sandbox in /home/username/... so it was always the same, and they could chown it. I'm getting a random path in /tmp and it always vanishes after the App Image crashes.
Source: https://forum.arduino.cc/t/linux-install-issues/880034/4
CLI output
username@username-e14:/opt$ ./arduino-ide_2.3.2_Linux_64bit.AppImage
[14059:0413/233905.813890:FATAL:setuid_sandbox_host.cc(158)] The SUID sandbox helper binary was found, but is not configured correctly. Rather than run without sandboxing I'm aborting now. You need to make sure that /tmp/.mount_arduinGsNYxm/chrome-sandbox is owned by root and has mode 4755.
Trace/breakpoint trap (core dumped)
username@username-e14:/opt$ ll
total 185608
drwxr-xr-x  9 root  root              4096 Apr 13 23:32 ./
drwxr-xr-x 23 root  root              4096 Apr 12 10:14 ../
-rwxrwxr-x  1 username username  190013338 Apr 13 23:16 arduino-ide_2.3.2_Linux_64bit.AppImage*
drwxr-xr-x  8 root  root              4096 Apr 12 20:18 arm-gnu-toolchain-13.2.Rel1-x86_64-arm-none-eabi/
drwxr-xr-x  3 root  root              4096 Apr 12 11:07 google/
drwx------  2 root  root             16384 Apr 12 10:15 lost+found/
drwxr-xr-x  5 root  root              4096 Apr 12 21:10 .pio-env/
drwxr-xr-x  3 root  root              4096 Apr 12 20:21 STMicroelectronics/

I've tried these ownership combinations for the App Image, and all three give the same issue:
$ sudo chown username:username arduino-ide_2.3.2_Linux_64bit.AppImage
$ sudo chown root:username arduino-ide_2.3.2_Linux_64bit.AppImage
$ sudo chown root:root arduino-ide_2.3.2_Linux_64bit.AppImage

How do I proceed?

You can run Arduino IDE by adding --no-sandbox in the command line when starting it.
This is a workaround for a real problem with Ubuntu Noble 24.04 beta. Also other appimage files, like the one for Cider, have the same issue and solution.

Yeah, that does work... But I'm not comfortable overriding what seems to be a security feature. Also, the IDE just isn't supposed to need that flag, right? Let's wait for Canonical and OSS devs to fix it, thanks!

You can disable the new restriction in Ubuntu 24.04 for all applications using sanboxes (all those using chromium internally, AppImage apps, etc.) by adding kernel.apparmor_restrict_unprivileged_userns=0 to /etc/sysctl.conf (or a new file in /etc/sysctl.d/). Or you can create an AppArmor profile to disable the restriction to only the Arduino IDE (for examples, check any profile defined in /etc/apparmor.d/ that uses the "userns" override).

Adding this line in /etc/sysctl.conf indeed solves the issue. The --no-sandox is no longer needed. But is this a safe adaptation? Or only a temporary fix until a better solution becomes available?

@BertRAMAerts, using the sysctl change returns Ubuntu to the behavior of previous Ubuntu versions. I suggest better to configure AppArmor to except only the Arduino IDE. Check the following github report: https://github.com/arduino/arduino-ide/issues/2429

I miss a proper solution, which does not involve bypassing or disabling new or improved security features. (AppArmor is not exactly new, but gets improved)


text:
character input for an integer variable?
Im trying out the code found here , let me quote the section of code that bothers me.
// set pin numbers for switch, joystick axes, and LED:
const int switchPin = 2;      // switch to turn on and off mouse control
const int mouseButton = 3;    // input pin for the mouse pushButton
const int xAxis = A0;         // joystick X axis
const int yAxis = A1;         // joystick Y axis
const int ledPin = 5;         // Mouse control LED

xAxis is a variable that is defined as an integer , however, it is being assigned a character(A0), How is this possible? I tried to compile and run the code and everything works well. I'm quite surprised!

The clue is this comment:
// set pin numbers for switch, joystick axes, and LED:

and the fact that xAxis is declared a const int. Because the declaration promises that this variable will not (must not) be changed once it has been initialized, it will not be assigned any memory at run time. The compiler will treat it much like the macro:
#define xAxis A0

and do a compile-time replacement of xAxis with A0, wherever xAxis appears.
A0 is an analog channel, defined in the board-specific Arduino libraries to the Arduino pin# corresponding to it.
It is a somewhat recent idiom in C and C++ - since the inclusion of "const" in the language - to use "const int" declarations for this purpose instead of "#define" statements. The intent is the same.

A0 and A1 are not characters or what you mean probably: strings.
Because it would be written as "A0" and "A1".
The types of A0 and A1 are probably integers or another numeric type.
However, these are probably defined as (constant) integers, e.g.:
const int A0 = 100;
const int A1 = 101;

(note 100 and 101 are random numbers)
or defined by a macro. e.g.:
#define A0  100
#define A1  101

So the variables A0 and A1 are actually integers (or assigned as numeric values by a define).

Actually they are static const uint8_t

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


text:
Arduino with HC 08 bluetooth module
I am connecting Arduino Uno R3 with HC 08 module lie following
Arduino 5v -> HC 08 Vcc
Arduino gnd -> HC 08 gnd
Arduino Pin 5 -> HC 08 RXD
Arduino Pin 6 -> HC 08 TXD

Then I connected two LEDs to 9 and 10 pins
Then loading following sketch.
#include <SoftwareSerial.h>

int availableLEDpin = 9;
int notAvailableLEDpin = 10;
SoftwareSerial hc_08(5, 6); // RX-5, TX-6
void setup() {
  pinMode(availableLEDpin, OUTPUT);
  pinMode(notAvailableLEDpin, OUTPUT);
  Serial.begin(9600);
  hc_08.begin(9600);

}

void loop() {
  hc_08.listen();
  if (hc_08.available()) {
    Serial.println(hc_08.read());
    digitalWrite(availableLEDpin, HIGH);
    digitalWrite(notAvailableLEDpin, LOW);

  }
  else {
    digitalWrite(availableLEDpin, LOW);
    digitalWrite(notAvailableLEDpin, HIGH);
  }
  delay(100);
}

I am trying to connect to bluetooth from y iOS application. The application is searching and connecting to the HC 08 correctly. And sending data successfully - Swift code log showing sent successfully.
But back in Arduino, always led connected to pin notAvailableLEDpin is glowing and nothing is printing in serial monitor. What is wrong with my implementation?

You have the receive port on your arduino connected to the receive port on your bluetooth module. Connect pin 5 to the Tx on your module and connect pin 6 to the Rx on your module.

it's better to use digital pin 8/10 as RX, digital pin 9/11 and TX as your softwareserial pins since these pins are dedicated for softwareserial knowing you use the generic softwareserial library and mind your supply to only use 3v3 volts as much as possible, specially for the TX softwareserial pin of your arduino going to RX pin of HC08, you need to lessen the voltage output of that arduino pin into 3v3 volt also, using voltage divider. It will harm your HC08 module and might not work properly.


text:
Using PWM signal to decrease power of laser over time
I'm trying to turn a laser on and off with an external button. When I press the button, the laser should turn on. When I release the button the laser should turn off. However, I don't want the laser to turn off immediately. I want it to turn off linearly over 500 ms. I'm using PWM to alter the strength of the laser over time. However, will my laser power increase and then decrease in the extremely short time segments due to PWM fluctuation? Will it even be able to execute this reduction of power?

I dont know your circuit but...
Do you effectively want to use an RC filter to reduce PWM fluxuations so that the laser sees an analog voltage which will translate to a power (presumably)? - that will avoid the pulsing of the laser, but I did believe that the pulsing at full voltage was neccersary in most laser drivers - please post a schematic... Anyway if you want this to be less of an issue if an RC filter is not for you you could increase the PWM frequency (google is your friend) on the arduino...
To have it turn of slowly if your using analog, the RC filter could possibly have large enough capacity to slow the laser turn off. It will also effect rise time so suitable values for R and C will need to be found to suit. Otherwise you could dial down the PWM gradually before hard power off in the arduino software, by initiating a loop which gradually reduces power with time.
Somewhere to start anyway :)

This is my code to gradually reduce power over time:
void loop() {
int stateButton = digitalRead(onButton);
if(onButton ==1){
digitalWrite(Laser, HIGH);

}
else{
for(int i = 255; i>=0; i--){
analogWrite(Laser, i);
  delay(500/255);
}

}           Would this loop through continuously? Would the power descend always loop through the descent even though I didn't press the power button?
}

Sorry my coding is not great so without formatting I find it hard to read your code.
I would do it differently myself, using an if statement which ran the pwm loop when you have activated its variable.


text:
Module that can both detect Voltage (12V) and Control current
I need a module for ARDUINO that can both detect Voltage (12V) and Control current between 2 pins (12V), like a relay on another device
I have found relay modules to control pins and another module for 4-channel Voltage detection, but it seems like a lot of components and wiring.
Is there any module that can do both?

are you detecting "control current" or are you controlling current? ... how much current are you talking about?

DC or AC current?

Just opening/closing the connection between two pins. My bad for poor expl.

You don't need another module to detect voltage on an Arduino.  The UNO, which I assume you are using, has 6 analog inputs (A0-A5) that can directly read voltage.  The only problem is that you want to measure a voltage up to 12V and the Arduino can only handle 5V.  So the solution is to DIVIDE that using two resistors in a voltage-divider configuration so that you only see 5V at the Arduino when there is 12V on the signal.
From here: https://www.electroniclinic.com/what-is-a-voltage-divider-or-potential-divider-formula-and-practical-uses/
you can see how to make one:

As far as controlling a "current" that is usually done with a relay.  There are no on-board relays but there are the digital outputs that can drive a small relay or can be connected via some other circuitry like a couple of transistors to drive just about any size relay.

I just want to detect hi/lo. Sorry for poor expl. And also connect/disconnect between two (other) pins, lile a relay

I would suggest opto-isolators for both directions.

simulate this circuit – Schematic created using CircuitLab
For the Ardiuno sending control signal you have to know which way round to connect to the inputs of your controller. Chances are one will be ground - that's "CTL Low".

Would this component do the same https://www.adafruit.com/product/1875 ?

No. If you read that page you will see it says 3.3v to 5v not 5v to 12v.

I meant as a priciple, not the exact numbers :o). Im looking for a component and as little how brewed as possible. It will be used on a lock, so I prefer components


text:
Generate 1.7 Mhz with PWM in Uno?
I have this code:
void setup() {
  pinMode(11, OUTPUT);
  TCCR2B = 0;
  TCNT2 = 0;
  TCCR2A = _BV(WGM21);
  TCCR2A |= _BV(COM2A0);
  OCR2A = 249;
}

void loop() {
  soundBuzzer();
}

void soundBuzzer() {
  TCCR2B |= _BV(CS21);
}

void silenceBuzzer() {
  TCCR2B &= ~_BV(CS21);
  TCNT2 = 0;
}

(Got it from here).
And I have an ultrasonic water atomizer that works in a frequency of 1.7 Mhz.
Writing another number instead of 249 in the line "OCR2A = 249;", the frequency generated changes. With 249 it generates a frequency of 4 Khz. So, my question is: Which number do I have to write to get approximately 1.7 Mhz?

You can only divide the clock by an integer, so with a 16 MHz clock the closest you can achieve is 2 MHz.  The data sheet will show you how to find the divider ratio register setting (specifically, if the division will be one more than the loaded count, and if there is a prescaler upstream of what you get to divide).  If there is no perscaler it would seem like switching the board to a 12 MHz crystal and dividing by 7 might be a fit, but you'll need a custom bootloader.

More realistically, to operate this usefully you'll need the power and voltage amplifier from the intended driver circuit, so why not just take the entire original driver circuit, frequency generator and all, and figure out a way to enable/disable it from the Arduino?  Do take appropriate precautions for the voltages which it may generate!

You cannot generate 1.7 MHz on an Uno. The closest you can get is 16 MHz / 9 = 1.778 MHz.

You need to set the CS20 bit, not CS21. That way you have no prescaler. Then have it count to 9, like Edgar calculated. So set OCR2A to 8.

Wow, how did I miss 16/9?  That's not much worse than 12/7, for a lot less trouble.

Expanding from my comment... any signal level generated by this kind of
microcontroller can only last for an integer number of CPU cycles. In
order to generate it, you first have to compute the timing
characteristics of the desired signal in terms of CPU cycles:
period = 16 MHz ÷ 1.7 MHz = 9.412 cycles

The closest you can get is 9 cycles, which gives the frequency
frequency = 16 MHz ÷ 9 = 1.778 MHz

Assuming this is acceptably close to your target, you can configure a
timer to do it. The example code you provided uses Timer 2 with the
OC2A output set to toggle mode. This approach can only give periods
which are an even number of cycles, thus I am using the regular
“non-inverting fast PWM” mode instead in the solution below. In this
mode, the pin OC2A cannot be used with a controlled frequency, then I
changed it to OC2B (pin 3 on the Uno). Here is the code:
const uint8_t OUTPUT_PIN = 3;  // = OC2B
const uint8_t PERIOD = 9;      // 9 CPU cycles ~ 1.778 MHz

void setup()
{
    pinMode(OUTPUT_PIN, OUTPUT);
    TCCR2B = 0;           // stop timer
    TCNT2  = 0;           // reset timer
    TCCR2A = _BV(COM2B1)  // non-inverting PWM on OC2B
           | _BV(WGM20)   // fast PWM mode, TOP = OCR2A
           | _BV(WGM21);  // ...ditto
    TCCR2B = _BV(WGM22);  // ...ditto
    OCR2A = PERIOD - 1;
    OCR2B = PERIOD/2 - 1;
}

void soundBuzzer() {
    TCCR2B |= _BV(CS20);  // F_CPU / 1
}

void silenceBuzzer() {
    TCCR2B &= ~_BV(CS20);
    TCNT2 = 0;
}

The generated signal is slightly asymmetric: it stays HIGH during
4 cycles and LOW for 5 cycles. If you want a symmetric signal
(50% duty cycle), you can set PERIOD to 10 (5 cycles HIGH
and 5 cycles LOW), but then the frequency drops to 1.6 MHz.
Edit: You could also replace your Arduino Uno by a cheap ATtiny85
microcontroller, or maybe an Arduino-compatible dev board based on it,
like the Trinket or the Digispark.
This microcontroller has a built-in PLL which allows it to run one of
its timers at 64 MHz, even though the CPU is running much slower.
A 64 MHz timer allows you to hit the target 1.7 MHz frequency
to within 1%:
64 MHz ÷ 38 = 1.684 MHz

Ditto for SAMD21-based Arduinos; a built-in PLL lets you run a timer at 96MHz.

That’s a great answer, thank you, and I could follow the process in the ATmega328P datasheet. However, I don’t understand why it’s not possible to output the frequency on the OC2A pin. Indeed, there seems to be the same mode for OC2A in table 17-3: Clear OC2A on compare match, set OC2A at BOTTOM, (non-inverting mode). I tried and it doesn’t work, as you said, but I can’t find the part of the docs that say why.

@Olivier'Ölbaum'Scherler: In this mode (Waveform Generation Mode 7) the register OCR2A is used to set the pulse period (via the “TOP” value). You cannot use the same register to set the pulse length. If you set the pulse length with OCR2B, then the PWM signal can only be output on pin OC2B.


text:
Strange results trying to count pulses
I am now hopelessly stuck and need help please.
I am building an automated observatory and now at the stage of trying to control the observatory dome rotation. The dome is rotated using a step motor and it works fine. The rotation of the dome also turns a rotary encoder to give an independent verification that the dome is moving. Although the RE is a quadrature type I am simply counting RE ticks from both channels as I don't need direction information.
What I am trying to do now is to count how many motor driving pulses occur between each pair of RE ticks. The reasoning behind this is to monitor the dome movements and detect jamming. The actual motor pulses will be used for all dome position calculations.
To achieve this, I have built a small board with a ULN2803A inverting buffer and an Arduino Nano. The Nano uses Pin Change interrupts on pins D11 and D12 to count the RE ticks. Pin D7 will also be used to monitor a Home Position sensor although this doesn't exist at present. The motor pulses are sent via the buffer to Pin D2 (INT0) and the motor direction is sent via the buffer to pin D3 (INT1). The external interrupts are then used to count the motor pulses, up or down depending on the motor direction.
For information, there is another board present, a Velleman VM110 USB breakout board, that also receives the rotary encoder ticks. This gives me a simple way to check that my board gives the same answer when I rotate the rotary encoder shaft by hand.
OK - sorry this is so long winded but now it gets weird.
When I rotate the RE without the motor running everything is fine. I get four times as many pulses as the Velleman board as I am using Pin Changes, triggering on each rise and fall, not on full cycles of the encoder. This does happen as predicted and everything is nice and stable.
BUT - when I start the motor running, I get hundreds of RE ticks every time I move the encoder and sometimes I get increasing RE ticks without touching the encoder at all.
The obvious answer is some form of RFI but I have done everything I can to eliminate this. The motor driver and the Nano board that powers it are in a shielded enclosure, the cable to the motor is a shielded cable and I have 10uH chokes on each of the four motor leads. Finally, I have fitted a filter to the incoming power supply to the motor box to minimise any RFI going back down the power lines.
The use of the ULN2803A buffer was my latest attempt to make this work. Previously the signals went direct to the Nano pins. With the buffer, I have used 20k pull-ups on the input side and 10k pull-ups on the outputs. This was a direct copy of the Velleman board input circuit that I knew worked without problems.
I have looked at the motor pulses at the input pin to the Nano on my scope and they are nice looking, sharp edged pulses of duration 70 uS and a frequency of 497 Hz. Not bad as I set the pulse rate using the Accelstepper library to 500Hz.
I now suspect that this is a software problem. This wouldn't surprise me as I am very new to all this, just trying to learn enough at each stage to do what I need. I have attached the code - this is a stripped down version without a lot of I2C stuff that is not relevant to my problems.
Again, for information. I have tried using the attachInterrupt() function and by directly setting the relevant registers - no difference!
Anyway, I really really hope someone can help me sort this out.
Regards, Hugh
/*
ABoard3
ROTATION MONITORING AND POSITION
Version AB3_stripped
*****************************PURPOSE*****************************************
This sketch is used on an Arduino Nano to count the motor pulses from ABoard1
and the Rotary Encoder ticks. The motor pulse count between encoder ticks is
used to detect dome jamming.
****************************INPUTS*******************************************
PIN CHANGE INTERRUPTS
**********ROTARY ENCODER INPUT*********
The rotary encoder is a Bourns ENA1J-B28 L00064L 1139M MEX 64 cycle per turn
optical encoder. This is connected to ABoard3 Pins D11 and D12. These pins
connect to Channel A and Channel B respectively. Pin change interrupts are used
to receive the rotary encoder output.
(The output pulses from the rotary encoder is also sent to the Velleman board
for use by LesveDomeNet for finding dome position)
*********HOME POSITION INPUT*********
The home position sensor is an Omron EESX671 Optical Sensor.
The sensor output is connected to ABoard3 Pin D7.
Pin change interrupt PCINT21 records activation/deactivation of the sensor.
EXTERNAL INTERRUPTS
*********MOTOR PULSE INPUT***********
The pulses sent to the G251X stepper driver are also sent to Aboard3 Pin D2.
This pin is the External Interrupt pin, vector INT0
*********MOTOR DIRECTION INPUT********
Motor direction is input to ABoard3 from ABoard2. ABoard2 pin, pnVmInRotMotor
(AB2:A0{54}) is connected to Velleman pins DI4 and DO2 and also to AB3:D3.
AB3:D3 is an External Interrupt pin, vector INT1.
*/

#include <Wire.h>
#include "streaming.h"
#include "I2C_AnythingHEG.h"
#include <EEPROMex.h>

//CONSTANTS
//PIN ASSIGNMENTS For ABOARD3
const uint8_t pnMotorPulse = 2;      //Port PD2, INT0, ISR(INT0_vect){}
const uint8_t pnMotorDirection = 3;  //Port PD3, INT1, ISR(INT1_vect){}
const uint8_t pnDomeAtHome = 7;      //Port PD7, PCINT23,ISR(PCINT2_vect){}
const uint8_t pnREChanA = 11;        //Port PB3, PCINT3, ISR(PCINT0_vect){}
const uint8_t pnREChanB = 12;        //Port PB4, PCINT4, ISR(PCINT0_vect){}

//*****************EXPERIMENTAL STUFF FOR PULSE COUNTING*******************************
uint16_t volatile myTest = 0;
int32_t volatile ratioCount = 0L;
int32_t volatile totalCount = 0L;
int32_t volatile tickCount = 0L;
uint8_t volatile halftickCount = 0;
int32_t volatile addPulse = 0L;

void setup() {
  //**********************************SERIAL FOR DEBUG ONLY************************
  Serial.begin(115200);
  //*************************INPUT PIN MODE SETUP**********************************
  //NOTE Set all UNUSED PCINT0:5 pins (D8, D9, D10, D11) to OUTPUT.
  //and set the value to LOW
  //The actual pins used to receive interrupts have external 10k pull-ups.
  //This is to reduce susceptibility to interference causing false triggering.
  pinMode(pnMotorPulse, INPUT); //D2
  pinMode(pnMotorDirection, INPUT); //D3
  pinMode(pnDomeAtHome, INPUT); //D7
  pinMode(pnREChanA, INPUT); //D11
  pinMode(pnREChanB, INPUT); //D12
  pinMode(4, OUTPUT); //D4
  digitalWrite(4, LOW);
  pinMode(8, OUTPUT); //D8
  digitalWrite(8, LOW);
  pinMode(9, OUTPUT); //D9
  digitalWrite(9, LOW);
  pinMode(10, OUTPUT); //D10
  digitalWrite(10, LOW);
  //******************SET UP AddPulse According to Motor Direction******************
  //This is needed to make sure the pulse counting starts in the correct direction
  //as the direction is only checked in the ISR after a change has occurred.
  //If Motor Direction is AntiClockwise, change to Subtract a pulse
  if( digitalRead(pnMotorDirection)) {
    addPulse = 1L;
  } else {
    addPulse = -1L;
  }
  //**************************SET UP PIN CHANGE INTERRUPTS**************************
  //Set the Pin Change Interrupt Masks
  //Clear all bits to start with
  PCMSK0 &= 0b00000000; //Clear all bits
  PCMSK1 &= 0b00000000; //Clear all bits
  PCMSK2 &= 0b00000000; //Clear all bits
  //Mask for PCINTs 0 through 7 is PCMSK0 (Rotary Encoder Pulses)
  //Need to allow interrupts on PCINT3 and PCINT4, so set bits 3 and 4
  //PCINT3 is Nano  pin D11 and PCINT4 is Nano pin D12
  //Use a compound bitwise OR to set the bits
  PCMSK0 |= 0b00011000; //Enable PCINT3 ONLY (bit 3)
  //Interrupt on pins 11 and 12, RE Ticks
  //Mask for PCINTs 16through 23 is PCMSK2 (Home Position)
  //Need to allow interrupts on PCINT23 so set bit 7
  PCMSK2 |= 0b10000000; //Interrupt on pin 7, Home Position Sensor activated
  //Now enable the interrupts (TURN THEM ON) by setting bits in PCICR
  //PCICR is Pin Change Interupt Control Register.Set bit 0 (PCIE0)
  //to enable interrupts PCINT0:7 This catches PCINT3 and 4 - RE Ticks
  //Set bit 2 (PCIE2) to enable interrupts PCINT16:23. Catches PCINT21 - Home Position Sensor
  PCICR &= 0b00000000; //Clear PCICR register
  PCICR |= 0b00000001; //Set bit 0 - Catches PCINT3 & PCINT4 - RE Ticks
  PCICR |= 0b00000100; //Set bit 2 - Catch PCINT21 - Home Position Sensor
  //**************************SET UP 'EXTERNAL INTERRUPTS'**************************
  //Interupts on External Interrupt Pins D2 (INT0) and D3 (INT1).
  //INT0 (Nano pin D2)occurs when a stepper motor driver pulse is received
  //INT1 (Nano pin D3)occurs when the ABoard2 pin, pnVmInRotMotor toggles
  //indicating a motor direction change.
  //To use the 'External Interrupts' the following registers need to be set-up:
  //EICRA External Interrupt Control Register A
  //Need to set Interrupt Sense Control bits ISC11 .. ISC00 (bits 3:0 in EICRA)
  //ISC01     ISC00 (INT0)    Interrupt
  //ISC11     ISC01 (INT1)    Generated by
  //  0         0             Low level on Pin
  //  0         1             Any Logical Change
  //  1         0             Falling Edge
  //  1         1             Rising Edge
  //First clear all bits, then set as follows:
  //For INT1 - Motor Direction - Generate on ANY LOGICAL CHANGE
  //bit 3 ISC11 0
  //bit 2 ISC10 1 This combination = Any logical change causes interrupt
  //For INT0 - Stepper Motor Pulses  - Generate on RISING EDGE
  //bit 1 ISC01 1
  //bit 0 ISC00 1 This combination = Rising edge of pulse causes interrupt
  //NOTE: To provide some immunity to RFI, Aboard3:Pins 2 & 3 are pulled high
  //using 10k resistors.
  //So, code is
  EICRA &= 0b00000000; //Clear EICRA register
  EICRA |= 0b00000111; // Set bits 0,1 and 2 in EICRA register
  //EIMSK External Interrupt Mask Register
  //Need to set External Interrupt Request Enables INT1 & INT0  (bits 1:0)
  //First clear both bits, then set as follows:
  //bit 1  INT1  1 External interrupt pin (D3) enabled
  //bit 0  INT0  1 External interrupt pin (D2) enabled
  //So, code is
  EIMSK &= 0b00000000; //Clear EIMSK register
  EIMSK |= 0b00000011; // Set bits 0 and 1 in EIMSK register
  //NOTE: Setting EIMSK TURNS ON THE EXTERNAL INTERRUPTS
  //************VARIABLE INITIALISATION*********
  myCommand = 0;
  myTest = 0;
  tickCount = 0L;
  totalCount = 0L;
} //END of setup

void loop() {
  //******************************COMMAND ACTIONS******************************
  if (myTest == 3) (
    //RE tick
    Serial << "Tick Count = " << tickCount << "  totalCount = " << totalCount << "\n";
    myTest = 0;
  }
}
//*************************FUNCTIONS / ISRs FROM HEREON*************************
ISR(INT0_vect) {
  //Triggered by stepper motor drive pulse from ABoard1
  totalCount = totalCount + addPulse;
}
ISR(INT1_vect) {
  //Triggered by a change in motor direction
  if(digitalRead(pnMotorDirection)) {
    addPulse = 1L;
  } else {
    addPulse = -1L;
  }
}
ISR(PCINT0_vect) {
  //Triggered by a ROTARY ENCODER TICK
  halftickCount++;
  if (halftickCount == 2) {
    //Make count same as Velleman
    tickCount++;
    halftickCount = 0;
    myTest = 3;
  }
}
ISR(PCINT2_vect) {
  //Triggered by activation of Home Position Sensor
  myTest = 4;
}

PCMSK0 &= 0b00000000; //Clear all bits - wouldn't PCMSK0 = 0; be a lot clearer? Meanwhile I agree with Gerben's answer. Try "guarding" your access to multi-byte variables set by interrupts. See Interrupts.

You have a scope, you used it to look at the motor pulses. Did you look at the encoder pulses also? How do they look like? 2) On a quadrature encoder, I would expect at most one channel to be “bouncy” at any given time. Then, if you use the encoder in the usual way, you should get a sequence of +1, −1, +1, −1... adding up to zero. 3) The standard idiom for setting the AVR I/O registers is PCMSK0 = _BV(PCINT3) | _BV(PCINT4);, which looks clearer than PCMSK0 &= 0b00000000; PCMSK0 |= 0b00011000;, at least to those familiar with AVR programming.

Do you have a proper shared ground between quadrature encoder outputs and the Arduino? If so, then @EdgarBonet is right. Quadrature encoders can bounce like crazy, so you really do need to read the encoder properly, determining the step direction and all from each and every read. This way, if it bounces +1 and then -1, or any other sequence, 100 times in a row, you end up knowing what the new location is, and thereby you've debounced it too. Try adding a 2.2uF cap on each quadrature output too, to help a little bit with hardware debouncing.

Properly reading the encoder is the software debouncing you really need.

Is your rotary encoder electrical or optical?  I ask as I wonder if you have issues with switch bounce or possibly the optical receiver swithing on and off at a boundary. If this is the case, one way that may help solve it is to properly decode the quad encoded pulses.  This blog post shows a reliable way of decoding quad encoded pulses: https://thewanderingengineer.com/2014/08/11/rotary-encoder-on-the-attiny85-part-2/  Regads,

An alternative to doing the debounce in the processor is to use an chip designed for the purpose.  Here's one that may be suitable:  https://www.elmelectronics.com/ic/elm402/  Regards,

There is no need to use int32_t for some of the variables. The problem with using variables that are more than 8 bits on a 8-bit processor, is that the processor needs 4 reads to get the value. In the middle of those reads an interrupt might occur, resulting in a value that has some bits of the old value, and some bits of the new.
Some variable only need 8 bits.
uint8_t volatile myTest = 0;
int32_t volatile totalCount = 0L;
int32_t volatile tickCount = 0L;
uint8_t volatile halftickCount = 0;
int8_t volatile addPulse = 0L;

The next thing is to make the reading of the value atomic.
void loop()
{
//******************************COMMAND ACTIONS******************************

if (myTest == 3)   //RE tick
{
    noInterrupts();
    int32_t tickCountCopy = tickCount;
    int32_t totalCountCopy = totalCount;
    interrupts();
    Serial << "Tick Count = " << tickCountCopy << "  totalCount = " << totalCountCopy << "\n";
    myTest = 0;
}
}

PS. this is not necessarily an answer, but it didn't fit in the comments.

Hi, and thanks Gerben and Nick. I made the changes you recommended but they actually seemed to make things worse, not better, in that even without the step motor running I was getting multiple triggering on each of  the RE channels.

Oops - wanted a new line and pressed return but that sent the comment before I had finished. So, excuse the lack of formatting from now on. I have now reached the conclusion that I need to debounce the Rotary Encoder. I had ASSUMED that as it's an optical encoder it wouldn't require debouncing but I now think my assumption was wrong. I am going to make a small hardware debouncer using RC timing and a 74HC14 hex inverting Schmitt trigger IC. Hopefully hat will solve the problem. The good news is that the actual step motor pulses are  counted without any problems. Thanks, Hugh.

There's no real bounce here, but probably not as clear a transition as you'd expect. My guess is a schmitt trigger alone will work. Even though my answer doesn't solve your problem, it still point to a problem you might account with your code.

Hi, I tried to use my scope to look at the encoder outputs but I don't know how to use it properly and couldn't get meaningful results. I have made the debouncer board, using ca 5 mS delay on each encoder channel and, finally, it all works as it is supposed to. I first had this problem in early December so it has taken all this time to get it solved. Actually bought my scope to help with this specific problem. Thanks again to everyone who answered and commented. Regards Hugh

@HughGilhespie, if the problem is solved now, please post an answer to your own question and mark it as solved.


text:
Error while updating ThingSpeak using SIM808
im trying to update ThingSpeak from a SIM808 but I'm getting a network error. Please check below and let me know if there is anything wrong in my methodology.
I'm using terminal.exe to send commands via RS232.
AT
OK
AT+CREG?
+CREG: 0,5 //connected in roaming
AT+SAPBR=3,1,"Contype","GPRS"
OK
AT+SAPBR=3,1,"APN","www" //VODAFONE INDIA "www" is APN (as per the operator)
OK
AT+SAPBR=3,1,"USER","" //blank (as per the operator)
OK
AT+SAPBR=3,1,"PWD","" //blank  (as per the operator)
AT+SAPBR=1,1
OK
AT+HTTPINIT
OK
AT+HTTPPARA="CID","1"
OK
AT+HTTPARA="URL","https://api.thingspeak.com/update?api_key=MY_KEY&field1=VALUE"
OK
AT+HTTPACTION=0
+HTTPACTION: 0,603,0

Note: while I'm typing in the browser url box, https://api.thingspeak.com/update?api_key=MY_KEY&field1=VALUE, I can update my field. I can make calls, send SMS. I have an internet pack.
Please help.

You're using HTTP commands to perform an HTTPS request. You need to use the HTTPS commands instead. Read the SIM808 manual for the right commands.

https://stackoverflow.com/a/69513173/8119511

It worked with changing AT+HTTPARA="URL","http://api.thingspeak.com/update?api_key=MY_KEY&field1=VALUE" (from https:// to http://)

You have to send this command: AT+HTTPSSL=1


text:
Detecting if a push button was pressed and released
I want to detect if a push button was pressed and released again. So I thought the right approach would be to first wait while the pin yields LOW and then wait while the pin yields HIGH:
void push(int pin) {
  // wait until button was pushed down...
  while (digitalRead(pin) == LOW);
  // ... and released again
  while (digitalRead(pin) == HIGH);
}

That function can be easily reused. The code works fine, but I am just wondering if that solution is considered clean and a good practice.

it only supports one button, so that's kind of weak.

No, I wouldn't consider that good practice - for one good reason: it's blocking.
Your system can't be doing anything else at all while you're waiting on the button. That may be fine for some situations, but far from ideal for 99% of others.
It is better to remember the state of the button and detect that change of state.
Personally, to make it properly portable, I would implement a class to contain all the state information.  Something like:
class Button {
    private:
        bool _state;
        uint8_t _pin;

    public:
        Button(uint8_t pin) : _pin(pin) {}

        void begin() {
            pinMode(_pin, INPUT_PULLUP);
            _state = digitalRead(_pin);
        }

        bool isReleased() {
            bool v = digitalRead(_pin);
            if (v != _state) {
                _state = v;
                if (_state) {
                    return true;
                }
            }
            return false;
        }
};

Then you can do something like:
Button myButton(3);

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

void loop() {
    if (myButton.isReleased()) {
        Serial.println(F("Released"));
    }
}

Every time myButton.isReleased() is called the current button state is compared against the state it was last time it was called. If it's changed then the button must either have been pressed or released. So you remember that change. If it's been released then you return a true, otherwise return a false.
You can now easily have it work with many buttons:
Button myButton(3);
Button myOtherButton(4);

void setup() {
    myButton.begin();
    myOtherButton.begin();
    Serial.begin(115200);
}

void loop() {
    if (myButton.isReleased()) {
        Serial.println(F("Released 1"));
    }
    if (myOtherButton.isReleased()) {
        Serial.println(F("Released 2"));
    }
}

Thank you, the blocking might clearly be an issue, however not in my specific use case (a reaction time game). I didn't use C++ features yet, but for abstracting a state, it's clearly a good idea.

I concur with Majenko, although your code would work, the code is blocking, meaning that your code stops at that point until the button is released again. The remaining code in your loop does not execute until the button is resolved.
A much better method is to check the state of the button in each passing of the loop. If the state changes (ie goes low) you can set a flag. Then when you read that the button is high again and the flag has been set then you execute the appropriate code. For example:
const int buttonPin = 2;     // the number of the pushbutton pin
boolean buttonWasLow = false;         // variable flag for when the pushbutton goes low

void setup() {
    pinMode(buttonPin, INPUT);    // initialize the pushbutton pin as an input:
}

void loop() {
    // read the state of the pushbutton and set a flag if it is low:
    if (digitalRead(buttonPin) == LOW)  {
        buttonWasLow = true;
    }

    // This if statement will only fire on the rising edge of the button input
    if (digitalRead(buttonPin) == HIGH && buttonWasLow)  {
        // reset the button low flag
        buttonWasLow = false;

        // Button event here
    }
}

My favorite way to detect a rising edge of an input is actually much simpler:
void loop() {
    button = digitalRead(buttonPin);

    // If the button is pressed
    if (button && !buttonLast)
    {
        // Button event here
    }

    // Update button flag
    buttonLast = button;
}

user8886193 brings up the very good point about button debounce.

Bouncing is the tendency of any two metal contacts in an electronic device to generate multiple signals as the contacts close or open; debouncing is any kind of hardware device or software that ensures that only a single signal will be acted upon for a single opening or closing of a contact.

I prefer to debounce the pushbutton inputs through hardware by adding a 100nF (or larger) from the input pin to ground. Note that this requires a 10K (or larger) resistance in series with the button circuit in order for the capacitor to charge/discharge.
Alternatively, in software, the most common debounce for beginners is adding a delay such as delay(100);, which would look something like this:
void loop() {
    button = digitalRead(buttonPin);

    // If the button is pressed
    if (button && !buttonLast)
    {
        // Button event here
        delay(100);  // <---- Delay inserted after the button event
    }

    // Update button flag
    buttonLast = button;
}

This has the downside that it is blocking for 100ms while the delay executes. A better method is to debounce without a delay. One of the built in examples demonstrates button debounce. The main loop is shown below:
void loop() {
    // read the state of the switch into a local variable:
    int reading = digitalRead(buttonPin);

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

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

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

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

            // only toggle the LED if the new button state is HIGH
            if (buttonState == HIGH) {
                ledState = !ledState;
            }
        }
    }

    // set the LED:
    digitalWrite(ledPin, ledState);

    // save the reading. Next time through the loop, it'll be the lastButtonState:
    lastButtonState = reading;
}

I usually put a capacitor next to my push button in order to get a clean up/low signal right away.

@sa_leinad could you comment on why you chose the capacitor value (100nF) you did?

The values come from the RC timing constant t = RC. You want to aim for a few milliseconds to get any reduction in the button switching noise. A good article is from the Embedded with Elliot blog: https://hackaday.com/2015/12/09/embed-with-elliot-debounce-your-noisy-buttons-part-i/

The voltage across the capacitor rises slowly in spite of the bouncing switch, and increasing the component values will make it even slower to reach the logical high. Component values could be changed about until the ideal charge and discharge rates cause a delay that outlasts the bouncing and a stable interval has passed. - Excerpt from Debouncing switches in hardware and software

"I usually put a capacitor next to my push button"
Yep, a 1uF capacitor across the button. No need to fiddle with code. See Nick Gammon's excellent switch tutorial http://www.gammon.com.au/switches that covers all kinds of conceivable situations (high or low, GND or +5V, internal pull-up or pull-down, capacitor debounce or software debounce, etc.)

@sa_leinad Well, the OP (Mr. Bucher) already received a complex answer to a simple problem and accepted it as best answer ; )

@Systembolaget Please still put it as an answer. It will help others who have the same problem as the OP. Plus sometimes a simple and concise answer is more helpful than a long wordy answer (at least to some people).

"I usually put a capacitor next to my push button"

A 1uF capacitor across the button is easy, cheap and means no need to fiddle with debouncing codes. See Nick Gammon's excellent switch tutorial that covers almost any conceivable situation when using switches with Arduinos and clones (high or low, GND or +5V, internal pull-up or pull-down, capacitor debounce or software debounce, etc.). In any case, Nick Gammon has many great explanatory examples on his site and where else he comments online.

+1 for the link to Nick Gammon's tutorial, it is indeed excellent!


text:
Always 255-response in I2C between ATTiny85 (8MHz) and Arduino Uno
I tried to set up an I2C conversation between ab ATTiny85 (8MHz) and an Arduino Uno. However I always get a 255 response from my I2C slave. I am using Arduino 1.8.5.
What am I doing wrong?
ATTiny85-Slave Code:
#include "TinyWireS.h"  // wrapper class for I2C slave
routines
#define I2C_SLAVE_ADDR  0x26 // i2c slave address (38)

byte t=10;

void setup() {
  TinyWireS.begin(I2C_SLAVE_ADDR);  // init I2C Slave mode
  TinyWireS.onRequest(requestEvent);
}

void loop() {
}

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

Arduino Uno-Master Code:
 #include <Wire.h>
 #define I2C_SLAVE_ADDR  0x26 // i2c slave address (38)

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

void loop() {
  byte num;
  // read 1 byte, from address 0x26
  Wire.requestFrom(I2C_SLAVE_ADDR, 1);
  while(Wire.available()) {
    num = Wire.read();
  }
  Serial.print("num = ");
  Serial.println(num,DEC);
}

Where is the TinyWireS_stop_check ? The value of 255 is when the Wire.read() returns -1 which means that you did not receive valid data from the slave. You could run a i2c scanner and keep it running on the Uno, while trying to fix the wiring or the slave sketch. If that is working, then try to receive or send data.

@Jot - can you explain why Wire.read() would yield -1 when wire.available() is nonzero?

@ChrisStratton you are right, when wire.available shows that there is data, then -1 is not returned. I didn't think that through. I was trying to tell it in a common way, because there is an other possibility: when the slave behaves badly, perhaps the slave aknowledges with a ack to its address, but fails to send data so the sda stays high resulting in 255. Maybe there are even more possibilities when the slave does weird things.

Seems that  am not the only one. https://forum.pjrc.com/threads/48887-HELP-Teensy-3-5-I2C-ATTiny85-20PU-(TinyWireS-OnRequest-not-triggering!) ...strange :-(

It may seem that the current commit of January 2018 from the TinyWire library is corrupt. Try using an older version from 2017, for example this one: https://github.com/rambo/TinyWire/tr...72a13504bbfc4e
This solves the problem for me as well.
Source: Teensy 3.5 - I2C - ATTiny85-20PU (TinyWireS.OnRequest not triggering!) - Post #11


text:
Iteed SD card breakout info for Arduino
I got an SD card breakout from an online shop, its the iteed kind without the level shifter, it has the 3.3 / 5 V switch. I cannot find any libraries or write example for it.
Has anyone dealt with it before with Arduino? I have tried finding info but I only get the level shifter kind that has the MOSI pins!
enter image description here

Use standard Arduino SD library or the SdFat library. All SD card 'modules' are only a holder and eventually level converters. The SPI device is the SD card itself.
Set the SD adapter to the voltage of your board, connect it to power and SPI bus, choose some pin as SS pin, insert SD card and it must work.
Pins: MISO is master in slave out, MOSI is master out slave in. DO is data out, DI is data in. SD card is slave, so MISO to DO and MOSI to DI

Thanks, do you by any chance know how to connect it as all the examples show mosi and miso pins but i dont have those on this breakout, even in the data log example it asks for mosi and miso pins but i only have DO, CLK, DI, CS, i can only find CLK and CS in examples

MISO is master in slave out, MOSI is master out slave in. DO is data out, DI is data in. SD card is slave, so MISO to DO and MOSI to DI

So, a quick google for "Itead SD card breakout" comes up with their website/wiki where there is a schematic.  Can't believe you did not try this.  It is just that - a breakout board.  It will allow you to connect Arduino to an SD card.  You can look up any generic example for SD + Arduino on the web.
They explicitly say

It can work with 5V or 3.3V power supply, and both 5V/3.3V IO operation level. It can be controlled directly by a wide range of microcontrollers such as Arduino, AVR, PIC, ARM and MSP430.

Alrighty, For anyone else struggling with this in the future.
Using arduino mega and iteed sd breakout withoit level shifter
G-Ground
DO-50
CLK-52
DI-51
CS-53
+-5V
then in the code before setup specify chip select to 53
Thanks for all the help.


text:
Nano & Ethernet will not write to PushingBox on a workplace network (but will at home)
I have a Nano+ENC28J60 and I'm using Pushingbox which I have setup to write data to a GoogleDrive spreadsheet which works perfectly at home. However when I take it to my workplace it no longer works.
At work, serial tells me that the

Ethernet connection is good;
I get a client connection OK too.

However, [edit] even with 5 attempts at a response client.read(); it reports nothing at all. Serial shows
OK connected! Written. Checking response: + + + + +

I assume it is to do with some firewall or other restriction, but if I can get a connection that should be enough, no?
[edit] note: i have also tried connecting to port 443 instead of port 80 in case it was an HTTPS issue - same results, though]
How I can write to GDrive on my work network?
The code [edit#2 modified client.connect() to try 5 times and a response check via client.read() to try 5 times and Serial.print("+ "); each time] :
#include "DHTesp.h"
#include <SPI.h>
#include <UIPEthernet.h>

DHTesp dhtA; DHTesp dhtB;

const int ledPin =  LED_BUILTIN;
int ledState = LOW;
int interval = 20; // this is the num seconds between reads (120=2mins) ***************************
int numReads = 2;   // Amount of reads between posting to Gdocs.  ***************************

byte mac[] = {0xAA, 0xF0, 0xDE, 0xDE, 0x06, 0xAF };  // Ethernet shield MAC addy
byte ip[] = { 10, 10, xx, yy };
char devid [] = "vXXXXXXXXXXXXXXXX";  //  device ID from Pushingbox

char server[] = "http://api.pushingbox.com";
EthernetClient client;

int c = '\0';

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

  Serial.print(F("dB_CoSdataV3.  Establishing..."));
  if (Ethernet.begin(mac) == 0) {
    Serial.println(F("Failed to configure ethernet"));

    //while (true); // no point in carrying on, so do nothing forevermore
  }
  else {
    Serial.println(F("Ethernet OK."));
    // print the Ethernet board/shield's IP address:
    Serial.print(F("local IP addy: "));
    Serial.println(Ethernet.localIP());
  }

  // give the Ethernet shield a second to initialize:
  delay(3000);

  Serial.println("____________________________________________");  Serial.println();

  dhtA.setup(3); //  sensor A
  dhtB.setup(4); //  sensor B
  //dhtC.setup(7); dhtD.setup(7);

  pinMode(ledPin, OUTPUT);

}

void loop(){

  int Ahumidity = 0;   int Atemperature = 0 ;
  int Bhumidity = 0;   int Btemperature = 0;

  int j = 0;
  for (j = 1; j <= numReads ; j++ ) {
    int p = 0;
    for (p = 1; p <= interval ; p++) {
      delay (1000);
      // if the LED is off turn it on and vice-versa:
      if (ledState == LOW) {        ledState = HIGH;       }
      else {        ledState = LOW;      }
      Serial.print (F("."));
      digitalWrite(ledPin, ledState);
    }

    Serial.print (" reading: ");
    Ahumidity += 10 * dhtA.getHumidity();  Atemperature += 10 * dhtA.getTemperature();
    Bhumidity += 10 * dhtB.getHumidity();  Btemperature += 10 * dhtB.getTemperature();

    Serial.print (j);     Serial.print (F("/"));     Serial.print (numReads);
    Serial.println();
  }

  Serial.print (F("Show the averaged val.s : "));
  Serial.print(F("\t\tA:")); Serial.print(Atemperature/(numReads)); Serial.print(F("\t")); Serial.print(Ahumidity/(numReads));
  Serial.print  (F("\tB:")); Serial.print(Btemperature/(numReads)); Serial.print(F("\t")); Serial.print(Bhumidity/(numReads));

  // now connect + write to Gdrive....................
  boolean connected;
  int counter1 = 0;
  do {
      connected = client.connect(server, 80);
      if (connected) { break; }
      client.stop();
      delay(1000);
      Serial.println("retry");
      counter1++;
  } while (!connected && counter1 <5);

//------------------
//if (client.connect(server, 80)) {

if (connected){
    Serial.println();
    Serial.print(F("OK connected! "));

      String buf;

      buf += F("GET /pushingbox?devid=");
      buf += String(devid);

      buf += F("&tempA=");  buf += String(Atemperature/numReads);
      buf += F("&tempB=");  buf += String(Btemperature/numReads);
      buf += F("&tempC=0&tempD=0&tempE=0&tempF=0&tempG=0&tempH=0"); // null data needed

      buf += F("&humidA=");  buf += String (Ahumidity/numReads);
      buf += F("&humidB=");  buf += String (Bhumidity/numReads);
      buf += F("&humidC=0&humidD=0&humidE=0&humidF=0&humidG=0&humidH=0"); //null data needed

      buf += F("&submit=Submit");
      buf += F(" HTTP/1.1");
      //client.println(F("Host: api.pushingbox.com"));
      buf += F("Host: http://api.pushingbox.com"); // trying the addition of http://...
      buf += F("Connection: close\r\n");
      //client.println();

      client.print(buf);
      Serial.print(F(" Written. "));
      delay(1000);
      int counter2 = 0;
      Serial.print ("Checking response: ");

      do {
          if (client.available()) {
              Serial.print("Y ");
              c = client.read();
              Serial.print((char)c);
          }
          delay(2000);
          Serial.print("+ ");
          counter2++;
      } while (counter2 < 5);

      Serial.println ();       Serial.println ();
      //client.stop();
  }

}

You should probably ask your local network administrator.  They are going to be the ones who know how they are blocking you.  You have given us absolutely zero information on the corporate network so there is very little chance of us being able to help you circumvent it.

sure, thanks @Delta_G. i'm happy to provide whatever information i can - what question should i ask the network administrator?

you use static IP?

Hi @ Juraj do you mean the question to ask is: "do we use a static IP here"? if yes/no what would that mean for the sketch? thx

I asked because you have byte ip[] = { 10, 10, xx, yy }; but I see ip is not used

I think you misunderstand what I meant.  Your fundamental problem isn't a problem with the Arduino code, it is a problem with the network at work.  You need to ask the network admins there to help you fix the network setting so that your device can connect.  They know what they're doing that's blocking you so they could unblock you.

you don't use available to check if the response is incoming. read returns -1 if nothing is available. See WiFiClient example on how to wait for the response and copy it to Serial Monitor

after next edit: if the server doesn't respond at all, connection is blocked. it is some restriction in the network at work

Your code for HTTP request has multiple issues.
After you connect to an HTTP server, it doesn't send anything until it receives your request. Your check for available bytes should always fail. Remove the if (client.available()) part, including the else part.
You make a POST request, but you put all parameters to URL and the request has no body. Change it to GET or put the parameters into request body and use "Content-type: application/x-www-form-urlencoded". Don't forget the Content-length parameter.
You send the request in very small parts. Every single print is send right away over network. Concatenate strings and print one or use buffered print.
And you should read the HTTP response and check the status.

some reading to content length and buffering https://github.com/jandrassy/StreamLib/blob/master/README.md

Thanks Juraj. i have 1. changed POST to GET (as it should have been:) 2. concatenated the separate client.print statements as a string and now client.print all in one go. Unfortunately same result :(  A question: where/how do i  read HTTP response? cheers

FYI i tried char c = client.read (); Serial.print (c); after the all-in-one client.print, and i get a backwards '?'

FYI#2 i also tried if (client.connect(server, 443) { in case it was a HTTPS issue... gives exactly the same results :(

see WebClient on example how to prin response. use available()

Thx Juraj. as i said in the comment above i just get a backwards '?' on the response. nothing else

add to code in Question the response read

you don't use available to check if the response is incoming. read returns -1 if nothing is available. See WiFiClient example on how to wait for the response and copy it to Serial Monitor/

code edited to incorporate @Juraj suggestions. Same result :( Any ideas from here?

if the server doesn't respond at all, connection is blocked. it is some restriction in the network at work

OK. i was really hoping to avoid IT who will just say "NO" because its easier for them.  Excuse the N00B question but would work WiFi end up at the exact same blockage?

it is not common to block port 80, so it will be something about known and temporary IP addresses. at my work we have a WiFi for guests which has Internet access but not intranet access


text:
ESP8266 Peer to Peer with AP and STA - Cache AP Clients, Flush Their Requests?
I'm fairly inexperienced with Arduino and entirely new to networking, so bear with me.
I've programmed a couple of NodeMCU devices to communicate the use of an instrument via activation of an LED. I have one set up as an access point and another as a client. I roughly followed the second answer from this question to set mine  up. I'll eventually shift this particular project to mqtt but I'd like to understand how to get the direct peer-to-peer working for other projects as well.
While it is partially working, I am having a couple issues that I assume are related to networking.
1. After plugging in the client ESP8266, the server only recognizes it for two loops (taking ~5 seconds each), then I have to restart the client, which is discovered instantaneously by the server.
2.  After the client connects, if I press the pushbutton on the client - while recognized - only once, the "toggle" command is repeatedly sent, resulting in the LED blinking for a handful of loops until it stops and the client has to be restarted again.
2.1. If I comment out the button debounce on the client, this happens more reliably. With debounce on, if I click the button immediately upon the first "client found!" message, the LED will typically toggle on the second (final) loop. Subsequent presses changing nothing.
Server sketch:
// Particle counter use server
// Place outside with LED

// load libraries
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>

// Set up variables
#define use_LED   D2

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

WiFiServer server(80); // set port to 80

int toggle = 0;
String request = "";

void setup() {
  Serial.begin(9600);
  pinMode(use_LED, OUTPUT);

  WiFi.mode(WIFI_AP);
  WiFi.softAP(ssid, password);
  digitalWrite(use_LED, HIGH);
  delay(1000);
  Serial.println(WiFi.softAPIP());

  digitalWrite(use_LED, LOW);

  server.begin();
}

void loop() {
  // Check for a client
  WiFiClient client = server.available();
  if (client) {
  // Wait until client is connected
//  while(!client.available()) { delay(1); }/
  Serial.println("client found!");

  // Parse commands
  String request = client.readString();
  Serial.println(request);

  // After pressing client switch once, this dances between on and off with every loop
  if (request == "toggle") {
    toggle = 1 - toggle; // switches to opposite on request reception
    digitalWrite(use_LED, toggle);
    delay(2000);
  }

  client.flush();
  }

}

Client sketch
// Particle counter use client
// Place in analysis room with button

#include <ESP8266WiFi.h>
#include <WiFiClient.h>

#define toggle_button D1 // make sure to use a pulldown resistor

int toggled = 0;

// Set up connection to server ESP
const char* ssid = "esp_server";    // ssid of server
const char* password = "password";  // password of server
const int port = 80;                // port of server

byte ip[] = {192,168,4,1};

WiFiClient client;

void setup() {
  Serial.begin(9600);
  pinMode(toggle_button, INPUT);
  Serial.println("active");

  WiFi.mode(WIFI_STA); // Setup as client
  WiFi.begin(ssid, password); // Connect to server ESP
}

void loop() {
  toggled = digitalRead(toggle_button);

  if (client.connect(ip, port)) { Serial.println("CONNECTED"); }

  if (toggled == HIGH) {
    // send command to toggle LED when button is pressed
    Serial.println("triggered");
    client.print("toggle");
  }

  client.flush();
}

Strangely, the slow recognition is only on the server side, the client spams its serial output with "CONNECTED", until stopping (I assume when the second loop completes on the server side, I can only monitor the serial of one at a time). But once found the following lines suggesting a WiFi or memory error in the output nestled among all the lines of "CONNECTED":
Exception (29):
epc1=0x40202a8f epc2=0x00000000 epc3=0x00000000 excvaddr=0x00000000 depc=0x00000000

ctx: cont
sp: 3ffefa30 end: 3ffefc40 offset: 01a0

>>>stack>>>
3ffefbd0:  3ffe8b70 3ffee9b0 3ffeebe4 40202a8d
3ffefbe0:  0104a8c0 00000000 3ffeebe4 4020328c
3ffefbf0:  00000000 3ffee9b4 3ffeebe4 3ffeec10
3ffefc00:  3fffdad0 3ffee9b0 3ffee998 40202107
3ffefc10:  401070a0 0104a8c0 00000001 40203519
3ffefc20:  3fffdad0 00000000 3ffeec08 40203544
3ffefc30:  feefeffe feefeffe 3ffeec20 40100710
<<<stack<<<

I have pulldown resistors on both the client switch and the server LED, I'm guessing that client.flush() does not clear the command? I'm baffled as to why the loop on the server only runs twice before I have to reset the client, and why upon resetting the client is instantly recognized, but takes so long to see it again. Does anyone have any advice?

You connect() and do not stop() the client. You get out of the 5 connections limit.
Use client in if (client.connect(...)), print and then do client.stop().
And also stop() the server's client object.
readString has one second timeout. you should send a delimiter and use readStringUntil
Edit: For permanent connection of multiple clients on server side see the WiFiTelnetToSerial example. At client side you can use one global client object. But check if it is connected and if not, call stop and then connect again.
void loop() {

    if (!client.connected()) {
      client.stop();
      if (!client.connect(ip, port)) {
        delay(1000);
        return;
      }
    }

    int toggled = digitalRead(toggle_button);

    if (toggled == HIGH) {
      // send command to toggle LED when button is pressed
      Serial.println("triggered");
      client.print("toggle.");
    }
}

Thanks, that solved the 2 loop problem!   Now I've got new client side issues, after sending the toggle once, I can't send it again without resetting the client esp; is there a way to maintain the connection as open?

do you stop the client on server side?

for permanent connection on server side see the WiFiTelnetToSerial example. at client side you can use one global client object. but check if it is connected and if not, call stop and then connect again

Yes, I stop on the server side. Client side I refactored to loop() {if (client.connect(...)) { while (client.connected()) { if(toggled) client.flush() } client.stop() } which solved all issues except it dumps a Soft WDT reset error every few seconds. I looked up the example, thanks!

remove flush() and while (connected()). do you use the latest release of esp8266 arduino core package? (2.4.2)

Removing the while(connected()) portion brings back the single-use issue. As for the library, after updating in the library manager, it shows it's version 1.0.0

Library Manager? this is a board package

make WiFiClient client global and use the loop() as loop

Ah, I'm on 2.4.1, just updated, it did not solve the client side error. WiFiClient client is global, and I am using loop() for the loop as far as I can tell.

2.4.1 had bugs.

I added client's loop to answer

Fantastic,  no more error, I must've been exceeding memory by trying to make a connection every time. Thanks a lot for all the help!

2.4.1 had a memory leak with reusing the WiFiClient object


text:
Arduino /dev/ttyUSB0 permission denied even when user added to group "dialout' on Ubuntu 18.04
I bought Arduino Mega board (CH341 usb) and I am able to connect to /dev/ttyUSB0 (upload to device) only by using sudo.
OS: Ubuntu 18.04
What I've tried:

I have downloaded Arduino IDE and added my user to dialout group. Logged out and logged in. Still nothing.
Installed Arduino by using apt
Installed Arduino by using snap

For all three cases it worked only by running as root (sudo actually). I saw couple of answers for Ubuntu 14.04 but none of answers didn't help.
I guess some other device access permissions are missing but I still didn't find any solution.

After some struggle I figured out that I need to add my user to "tty" group as well.
There's another approach that involves udev rules modification for certain vendor:device and update of device's ownership but this seems more sane approach.
To recap:

Add your standard user to the group "dialout'
sudo usermod -a -G dialout your-username

Add your standard user to the group "tty"
sudo usermod -a -G tty your-username

Logout/Login

Hope this helps

Sometimes a restart may be required. Logging Out / In may not be enough.


text:
Understanding heap fragmentation
I finally understand why people do not allocate memory when it comes to micro-controllers. The reason is because as you allocate different objects on the heap of various sizes and then you delete them you end up with holes. This is called heap fragmentation. Anyways I know what is heap fragmentation. I just want to know how it works. So that I know when I can use the new keyword to allocate memory and when not..
(1) To make things simple consider this example. Lets say my heap looks like this. The bottom numbers represent the addresses. In a real example I will be allocating structs with larger sizes but lets use bytes to make things simple.
0    0    0    0    0    0    0    0    0    0
1    2    3    4    5    6    7    8    9    10

(2)  I allocate a char with value 123 in memory. Now my heap looks like this
1    0   123   0    0    0    0    0    0    0
1    2    3    4    5    6    7    8    9    10

the first 2 bytes 1  0 store the size of the data being allocated followed by the byte 123 that has the actual value.
(3)  I allocate another char with value 111 in memory. Now my heap looks like this
1    0   123   1    0   111   0    0    0    0
1    2    3    4    5    6    7    8    9    10

(4) I delete the first object created on step 2 with value 123. It now looks like:
0    0    0    1    0   111   0    0    0    0
1    2    3    4    5    6    7    8    9    10

I now have a hole at the beginning (heap fragmentation)
Now my question is if I where to allocate another byte say 222 will it be allocated on the beginning like this?
1    0   222   1    0   111   0    0    0    0
1    2    3    4    5    6    7    8    9    10

Or will it be allocated at the end like this?
0    0    0    1    0   111   1    0   222   0
1    2    3    4    5    6    7    8    9    10

If arduino is smart enough to place that object at the beginning, then I will no be that afraid of using the new keyword as long as I am allocating objects of small sizes and never allocating to many of them.
Reason why I am asking this question is because I have a class Queue that I use in c++. Whenever I add an item to that queue it allocates the objects that I create. The objects that I pass to that queue are 10 bytes. The queue size is never larger that size 30. Will it be safe if that queue is constantly allocating (enqueing) and deleting (dequeing) items?

Edit
Sorry for the question I guess I asked this question when I should had done more research. Thanks to your comments and my previous question I now know that this only occurs when allocating memory of different sizes.

Heap fragmentation occurs specifically when you are allocating objects of different sizes and a smaller object is placed into a larger hole leaving a bit of left over memory too small for another object later on. With single bytes or always the same size objects you won't get that problem, since a hole will always be the right size.

When having always the same object size (in your example always only 3 bytes per object) you don't have that problem. I added a small paragraph about that in my answer to your previous question, because it fits good into the answer.

@chrisl thanks I just want to make sure I understand because I am allocating a lot of memory in my code. For example all the events that ocur on arduino of interest I place them on a queue. Then my library uses that queue to send the messages with the NRFL24L01 radio. Thanks for all the help!

I suggest you keep at that idea.  When you hit the wall and can’t understand why it sometimes just does weird things you can’t explain then come back and we can help you find a proper memory budget.  Doing what you’re doing on a microcontroller is like trying to live like a king on minimum wage.  You can use credit and pull it off for a while but eventually it catches up with you.  Unless you’re writing code to make sure each of these queued things fits neatly into memory eventually you’ll queue something that doesn’t fit.  And there will be no explanation for what happens next.

Your method is good thinking on a PC.  But on a microcontroller you’re asking for trouble.  It would be best to go ahead and set a limit for how many things can be queued and how big they can be.  And if you can set that limit then you no longer need dynamic allocation.  You don’t have anything to share memory with so why not just allocate what you need from the start.  You’ll see.

You may want to take a look at the source code of malloc() (this is the AVR version): it is very well documented in the comments. And maybe also at this answer to a related question.


text:
Is this circuit properly made?
I can't get to work a circuit that doesn't look that hard to copy.
This circuit was done for an Arduino extension of my DSC HS2032 system. I was trying the example "Status" on the Arduino's library DSC Keybus Interface v1.2.0.
On the example, we can see this circuit:
 *      DSC Aux(+) --- Arduino Vin pin
 *
 *      DSC Aux(-) --- Arduino Ground
 *
 *                                         +--- dscClockPin (Arduino Uno: 2,3)
 *      DSC Yellow --- 15k ohm resistor ---|
 *                                         +--- 10k ohm resistor --- Ground
 *
 *                                         +--- dscReadPin (Arduino Uno: 2-12)
 *      DSC Green ---- 15k ohm resistor ---|
 *                                         +--- 10k ohm resistor --- Ground

Here on the photos, I'm showing what I have done.

This is the HS2032 panel where (on the YEL and GRN) I connect the Arduino. I changed the Arduino's power source to be from my laptop so I could easily test it on the Serial Monitor. YEL->White/Green wire and GRN->Green wire
Now goes the Arduino's wiring.

Remember from the panel, the yellow is the white/green and the green is the green (they are coming from the right). First, each of both wires goes directly to 15kOhm resistor. Secondly, it splits between a 10kOhm resistor which then ends up into Arduino's ground, or it goes directly to the Arduino's pin 3 or 5, depending on the cable.
Results
The Serial Monitor shows "DSC Keybus Interface is online" and over.
If I connect green and white directly to 3 and 5, it will say sometimes "Keybus disconnected" and "Keybus connected" without any additional messages ever.
So my question is, am I missing something here? Why is the Serial Monitor not responding or what can I do to check where is the problem?
EDIT
This are the serial monitor readings, nothing from the Panel. I had to connect without resistances to get this output, otherwise, the only output would be "DSC Keybus Interface is online."
08:26:32.359 ->
08:26:32.359 -> DSC Keybus Interface is online.
08:26:35.345 -> Keybus disconnected
08:26:42.722 -> Keybus connected
08:26:47.838 -> Keybus disconnected
08:26:51.131 -> Keybus connected
08:26:54.937 -> Keybus disconnected
08:27:12.661 -> Keybus connected
08:27:17.122 -> Keybus disconnected
08:27:34.218 -> Keybus connected
08:27:41.697 -> Keybus disconnected
08:28:19.509 -> Keybus connected
08:28:22.487 -> Keybus disconnected
08:28:25.068 -> Keybus connected
08:28:28.053 -> Keybus disconnected
08:29:23.692 -> Keybus disconnected
08:29:31.175 -> Keybus disconnected
08:29:33.990 -> Keybus connected
08:29:37.005 -> Keybus disconnected

There's quite a lot of bare copper visible. Is that mains power?

I don't see the connection between AUX- and Arduino ground. You need common ground between them

@marcellothearcane if you are talking about the first photo, the RED, BLK, YEL and GRN are used for direct connections to the original keypad. More on the left, you can see the siren wiring. There is also one copper coming out of BLK, it is the blue wire bended to fit properly.

@chrisl excelent. I will take a wire from DSC Aux (-) (we can't see it on the images) to the breadboard's GND ground, finally going to the Arduino's GND ground through the black wire. Will tell you how it goes!

@chrisl I think it didn't work, but it is still something. I attached the Serial monitor result.

The blue wire on your breadboard doesn't seem to match anything in your circuit diagram -- is that right?

@RedGrittyBrick the blue wires come from YEL and GRN with 10kOhm. They join together with the black wire on the (-). The black wire ends in the Arduino's ground. Maybe I should make a neat diagram?

I added the circuit diagram that copies exactly what I made.

The schematic you drew does not match the ASCII circuit you copied. You need to swap the GND and Arduino wires on the resistors.

Is this circuit properly made?

No.
A lot of the problem is that you don't have a well-drawn schematic. I think that what you have is a couple of voltage dividers to interface a 5V arduino with a higher voltage device. I suspect a voltage divider isn't the best solution but presumably it works for someone else. So what you need is ...

simulate this circuit – Schematic created using CircuitLab
If I were you I'd pull your existing wiring apart completely and start again, arranging the components and wires so that they match this schematic as closely as possible in terms of position and orientation. Then trace the connections through carefully to make sure everything matches.


text:
dot matrix arduino turn off the intermittent led
I made a dot matrix that contain 10 row and 12 column , total 120 led.
I want to turn on the leds like this picture but when I open ground 1 , 2 and pin 0 , 1 , 2
6 leds light together.what kind of structure should I build?
Sheme :

I tried row by row like this:
 clear_cube();
 regWrite(cube[0][0], HIGH);
 set_array(4);
 //delay(10);

clear_cube();
regWrite(cube[1][0], HIGH);
set_array(3);
//delay(10);

clear_cube();
regWrite(cube[0][0], HIGH);
set_array(2);
//delay(10);                                                                                When I decrease the delay 5 leds blinking.

100  50  10  0 delay   Youtube

You can't just turn them on like that.
Instead you have to turn one row on. Then the next row. Then the next. Very fast.
So you first display:
O@OO
OOOO
OOOO

Then you display
OOOO
OO@O
OOOO

Then you display
OOOO
OOOO
O@OO

And you cycle through that very fast.  Usually using a timer to run it all.  The fact that you're using '595s will slow you down and make it harder to update fast enough to look non-flickery.

I will try that

I tried but it does not work .I update the code like above @Majenko♦

That code is completely meaningless.

No. regWrite turn on the positive and set array turning on the ground.I'm uploading a video 100 50 10 and 0 delay

That looks like it's working. But like i said, your use of '595s will make it hard to make it non-flickery. You need to refresh very fast. Ideally hundreds of times per second, though tens of times per second will be tolerable.

You want to multiplex them by rows or columns. If you do it by columns, then do the following: Set all columns to open circuit. (everything off.)
Set the row value pins for the first column, then
activate the column pin for the first column. The LEDs for the first column light up.
Now delay for a brief period (say 20 ms) and go on to the next column. (Obviously you'd use a loop for this.) Repeat.
You should write your code as a state machine using millis() rather than using delay, or you will paint yourself into a corner and you'll write code that totally blocks the machine just to display the LED grid. If you use millis() and a sate machine you'll be able to do other things at the same time you loop through the LEDs


text:
Implementing very slow external drive using ESP32 and TinyUSB
I want to implement a simple external drive with ESP32-S3 that would act like a normal USB enabled flash drive when connected to a computer.
The actual storage of the data is done mechanically (for educational purposes) and controlled via the esp pins. (the exact setup is not important now)
I am using the esp32TinyUSB library to implement the communication between the ESP and the Computer. However the problem is, that when I actually try to store the data using the mechanical system (which is very slow ~1 bit/s), the USB disconnects from the computer.
Is there a way to fix this issue? I don't know how exactly the USB and MSC protocol works but I am thinking some keep-alive messages?
Here is the setup() which is typical for this library:
void setup() {
  USB.onEvent(usbEventCallback);
  MSC.vendorID("myUSB");
  MSC.productID("myUSB");
  MSC.productRevision("1.0");
  MSC.onStartStop(onStartStop);
  MSC.onRead(onRead);
  MSC.onWrite(onWrite);
  MSC.mediaPresent(true);
  MSC.begin(DISK_SECTOR_COUNT, DISK_SECTOR_SIZE);
  USBSerial.begin();
  USB.begin();
}

and here is where the problem lies:
static int32_t onWrite(uint32_t lba, uint32_t offset, uint8_t* buffer, uint32_t bufsize){
  // this check is there to only use the mechanical system of storage for
  //one of the segments
  if (lba == 8) {
    for(int i = 0; i < bufsize; i++) {
      writeAt(offset + i, buffer[i]); // this function is slow and probably causing problems
    }
  } else {
    memcpy(msc_disk[lba] + offset, buffer, bufsize); // otherwise store in memory
  }
  return bufsize;
}

thank you in advance!
UPDATE:
I later found, that the reason for the drive disconnecting is probably the fact, that the esp32 is not dealing with the interrupts (events) as fast as they are coming from the USB (which is unfortunately unavoidable). This probably causes the ESP32 to be overwelmed with the events to the point that it crashes.
I will have to come up with a queue in memory that will be holding the waiting events. It seems like there is nothing like keep-alive messages on this layer - the Windows OS just waits patiently and displays the loading bar...