text:
Counting the number of pulses in a second
For my speedometer application, I want to count the number of pulses occurring every second and convert it to speed. So for that, I need to count the number of pulses occurring at a given input pin for one second. This count is used to convert to speed. The count should go to zero and start over after every second. But I don't get how to set a limit of one second and start over every second. So far I have come up to this:
int count = 0;
float lasttime = 0;
float currenttime = 0;
const int speedpin = 52;

void setup()
{
    Serial.begin(115200);
    pinMode(speedpin, INPUT);
}

void loop()
{
    currenttime = millis();
    if (currenttime - lasttime <= 1000)
    {
        if (digitalRead(speedpin == HIGH))
        {
            count = count + 1;
        }
        else
        {
            count = count;
        }
    }
    else
    {
        count = 0;
    }
    Serial.println(count);
}

You may want to have a look at attachInterrupt(), which is often used for these things, because with this you will not miss a pulse. Then you should also read more about interrupts, so that you understand, what you are coding with it.

@chrisl It starts missing pulses much faster than using external clock source to the counter. Depends on how many mcu cycles takes to handle whole ISR.

@KIIV: if  the pulses do not bounce (as mechanical switches do), attachInterrupt() is rather convenient and the counting itself is very fast. If there are less than 256 pulses/sec to expect, handling of this byte counter in the main loop is super easy as well.

How are you planning to display the output from your speedometer application? Will you use the serial monitor, a 7 segment display module, or maybe a 16 x 2 LCD?

Right now am seeing in the serial monitor. But in the application, I will display it in an LCD screen

What type of vehicle will you be using the speedometer app on?

Actually, this is for a project on electric bikes

As already explained in Michel Keijzers' answer, instead of counting how
many times you find the input HIGH, you should count the LOW →
HIGH transitions. This requires saving the previous input state and
counting a transition only when the input is HIGH while it was LOW
last time you saw it:
static int last_pin_state = LOW;
int pin_state = digitalRead(SPEED_PIN);
if (pin_state == HIGH && last_pin_state == LOW) {  // rising edge
    count++;
}
last_pin_state = pin_state;

For displaying the count every second, use the technique explained in
the Blink without delay Arduino tutorial:
static uint32_t last_time = 0;
if (millis() - last_time >= PERIOD) {
    Serial.println(count);
    count = 0;
    last_time += PERIOD;
}

Note that you have to reset the count every time you print it.
VE7JRO suggests using interrupts. Interrupts save you the pain of
writing the edge detection. On the other hand, they also make things
slightly more complicated, because you now have to worry about
atomicity, race conditions, volatile variables and such. There is no
need to use interrupts unless the pulses are so fast (or your loop()
is so slow) that you may miss a pulse. If your loop() gets bigger and
slower, and you risk missing pulses, then interrupts can really help.
But the proper way to use them is to count the pulses in the ISR. If you
use the ISR only to rise a flag, you loose the speed advantage of the
interrupts, which is the whole point of this approach.
The interrupt service routine would then be like this:
volatile unsigned int count;

void count_pulse()
{
    count++;
}

Then, the loop only has to print and reset the count:
void loop()
{
    // Periodically print and reset the count.
    static uint32_t last_time = 0;
    if (millis() - last_time >= PERIOD) {
        noInterrupts();
        unsigned int count_copy = count;
        count = 0;
        interrupts();
        Serial.println(count_copy);
        last_time += PERIOD;
    }
}

Note that the variable count is shared between the ISR and the main
loop. That's why it has to be declared volatile. Also, its access
within loop() has to be protected within a critical section delimited
by a noInterrupts()/interrupts() pair, otherwise you would have a
race condition. Also note that, in order to keep the critical section as
short as possible, the value of count is only copied within the
critical section, and the actual printing is deferred to after the
critical section is finished.

First align your code:
int count = 0;
float lasttime = 0;
float currenttime = 0;
const int speedpin = 52;

void setup()
{
  Serial.begin(115200);
  // put your setup code here, to run once:
  pinMode(speedpin, INPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  currenttime = millis();
  if(currenttime - lasttime <= 1000)
  {
    if (digitalRead(speedpin == HIGH))
    {
      count = count + 1;
    }
    else
    {
      count=count;
    }
  }
  else
  {
    count=0;
  }
  Serial.println(count);
}

Than the statement count = count assigns a variable to itself which is not needed, and for increment you can use count++, so you get:
int count = 0;
float lasttime = 0;
float currenttime = 0;
const int speedpin = 52;

void setup()
{
  Serial.begin(115200);
  // put your setup code here, to run once:
  pinMode(speedpin, INPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  currenttime = millis();
  if(currenttime - lasttime <= 1000)
  {
    if (digitalRead(speedpin == HIGH))
    {
      count++;
    }
  }
  else
  {
    count = 0;
  }
  Serial.println(count);
}

In the loop, you do not count pulses, but only the measurements where a pin is HIGH and when the pin is LOW anywhere within the second, it is set to 0.
What you instead want to do is (assuming you want to count the LOW -> HIGH transients: Make a global variable called e.g. previousState. Now, if the previousState == LOW and the current state of the GPIO is HIGH, only than increase count with one. Also, within the loop, each time update the previousState with the current state.
I leave the implementation to yourself.

But for one second I have to count the pulse. And after that one second is over count should go to zero and start counting again. Thus I need the number of pulses for each second.

Than you store after one second the number of measured pulses (count) in a separate variable to be processed in the next second (while count already measures the new pulses for that second).

If 'count' comes from a counter or device register, or is kept by an interrupt service routine, you don't ever want to zero the count. If a pulse arrives between the time you read the variable and the time you clear it, you will have failed to count that pulse.
Instead, make sure 'count' is of a suitable length to contain the largest number of pulses you could ever receive in one interval. Then, at each interval, save count to a temporary, say, 'tempCount'. Subtract the current 'tempCount' from the previous count, 'prevCount', in which you stored 'count' the previous time through. The difference will be the number of pulses counted in this interval. Use it or save it or whatever you need to do with it. Then store 'tempCount' into 'prevCount', and you're done.
No missed pulses, no overflow errors.

If count comes from an ISR, you can safely read it and clear it in the same critical section. Unless it's only 8 bits, you need that critical section just to read it anyway. If count comes from a hardware counter, then you are right, it should never be cleared.

Yes, if done in a critical section. But if background (ISR) code is collecting pulses and foreground code is calculating the counts, there would still be an opportunity for errors. Using a continuous counter (and it's only 1 byte wide), you could avoid the need to turn off interrupts again.


text:
(Arduino Uno reflashed as USB HID) How to send Scroll Lock key?
I am having a hard time finding documentation on how to properly use USB HID buffers, so the issue may lie there instead of with my code.
To get 0x47, I used this table: https://www.usb.org/sites/default/files/documents/hut1_12v2.pdf
Here's code that is loosely based off of http://mitchtech.net/arduino-usb-hid-keyboard/
    /* Arduino USB Keyboard HID demo
 * Cut/Copy/Paste Keys
 */

#define SCRLCK  0x47
//#define KEY_LEFT_SHIFT  0x02
//#define KEY_RIGHT_CTRL  0x10
//#define KEY_RIGHT_SHIFT 0x20

uint8_t buf[8] = {
  0 };  /* Keyboard report buffer */

#define PIN_PTT 2
//#define PIN_CUT 6
//#define PIN_PASTE 7

int state = 1;
int prevState;

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

  pinMode(PIN_PTT, INPUT);
  //pinMode(PIN_CUT, INPUT);
  //pinMode(PIN_PASTE, INPUT);
  // Enable internal pull-ups
  digitalWrite(PIN_PTT, 1);
  //digitalWrite(PIN_CUT, 1);
  //digitalWrite(PIN_PASTE, 1);

  delay(200);
}

void loop()
{
  state = digitalRead(PIN_PTT);
  if (prevState != state) {
    buf[0] = SCRLCK;   // Scroll Lock
    // buf[2] = 27;    // Letter X
    // buf[2] = 123;    // Cut key: Less portable
    Serial.write(buf, 8); // Send keypress
    prevState = state;
    releaseKey();
  }
}

void releaseKey()
{
  buf[0] = 0;
  Serial.write(buf, 8); // Release key
  delay(100);
}

Using a keyboard testing application, the green keys (minus mouse) are the buttons that appear to be pressed when the Arduino is using the USB HID firmware:
Upon using Passmark Keyboardtest, it looks like it's pressing Shift, Ctrl, Left alt, and right alt when I press the button.
My assumption is that I am writing to the 'modifier key' buffer instead of the 'other key' buffer. How would I define the correct key?

about the defines at top of your sketch ..... convert 0x02,  0x10, 0x20 and 0x47 to binary ......  what do you see when you do  that?

source: Stack Exchange

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

sort: votes


text:
How many Amps can a Nano Arduino hold for LED project
I'm really new at this, and here is my doubt. What if I need to light 120x WS2812B (5v)LEDs (link: LEDs) using an Arduino Nano? if it takes 60 mAh each pixel, the total amount needed should be around 7,200 mA.
Could I use the same 5V/ 8A power supply (PowerSupply) for the Nano board and lights? Is that possible?
Thanks in advance, and sorry my ignorance on this area.

Check your units.  Charge (e.g. in mAh a unit of electrical capacity, or how much current can be supplied over a given time).  Current is the rate of charge flow (e.g. in mA).  As written your question does not make sense.

Yes, 120 LEDs * 60 mA = 7200 mA = 7.2A
An Arduino Nano will use 19 mA (Arduino Nano Tech Spec). Of course, if you add a power LED, or other components it will add, but it will likely be less than a few 100 mA. So that totals to max 7.4A.
It's always good to have some headroom which is 0.6A in your case (that's enough).
Actually what's happening is as follows:
- Your 8 mA gives the current the components request
- Your Nano requests 19 mA
- Your LEDs require 7.200 mA.
As long as the voltage is the same (5V for both the LEDs, Nano, and adapter), and the components do not request more than 8 A summed up (with some headroom), the adapter will deliver the current needed. If all components request more than 8 A, than high likely the adapter will break (and possibly the attached components too).

Thanks Michel, I just wanted to make sure that I don't burn the board on my first attempt  ;)

You're welcome .. .you can wait for more answers, if an answer is helpful, upvote it, if the answer answers your question in a satisfactory way, accept the answer.

@juasmilla, why would you think that you would burn the Nano? .... how are you planning to connect the LEDs?

It can supply both, as long as they are supplied separately; the LEDs must not be supplied through the Nano board, but connected directly from the power supply.

Fine, connecting the ground on both I suppose... Thanks for all your inputs! brilliant Arduino World, and of course, its community!!

@Yes connect ground together

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


text:
PID controlled DC Motor Speed
I'm writing a PID program for a simple DC Motor. This motor has an encoder at the bottom which allows me to read motor speed. The goal of the project is to provide a constant speed if there is light friction applied to the motor. Although speed may vary slightly, I can still graph the PWM signal and show the duty cycle increases in response to friction. I've gotten the motor speed and potentiometer to function perfectly, now I'm just stuck on the actual PID part.
The issue I'm having is that whenever I set my SET pin high, the motor completely shuts off. I don't understand why because I'm sending it values in that while loop which should be sufficient to initiate the compensation
Here is my code:
#include "TimerOne.h"
#include <PID_v1.h>

int counter=0;
//Polarity
const int IN1 = 11;
const int IN2 = 10;

volatile float pot=0;
//PWM Signal and Analog from the Potentiometer
const int POT = 0;
const int ENA = 6;

const int SET = 12;

int rotation;

double Setpoint, Input, Output;
double Kp=1, Ki=1, Kd=1;

PID myPID(&Input, &Output, &Setpoint, Kp, Ki, Kd, DIRECT);

void docount()  // counts from the speed sensor
{
  counter++;  // increase +1 the counter value
}

//This takes the docout() counter and calculates how many holes its read to give rotations per second
void timerIsr()
{
  Timer1.detachInterrupt();  //stop the timer
  Serial.print("Motor Speed: ");
  rotation = (counter / 31);  // divide by number of holes in Disc
  Serial.print(rotation,DEC);

  Serial.println(" Rotation per second");
  counter=0;  //  reset counter to zero
  Timer1.attachInterrupt( timerIsr );  //enable the timer
  Serial.print("pot = ");
  Serial.print(pot);

  Serial.print("\n");

}

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

  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
  pinMode(SET, INPUT);
  Timer1.initialize(1000000); // set timer for 1sec
  attachInterrupt(0, docount, FALLING);  // increase counter when speed sensor pin goes High
  Timer1.attachInterrupt( timerIsr ); // enable the timer

  myPID.SetMode(AUTOMATIC);
  myPID.SetSampleTime(10);
}

void loop()
{
  // This bit is how you convert the pot values to manually control the fan
  pot=analogRead(POT)/4.01569;
  analogWrite(ENA, pot);

  // This basically acts as a push button. If the SET pin is HIGH it initiates the PID and whatever
  // the current rotation and pot setting are, they're used to send to the myPID function above to
  // maintain current operating values
  while (digitalRead(SET) == HIGH)
  {

      Setpoint = rotation;
      Input = pot;
      myPID.Compute();
      analogWrite(ENA, Output);
      digitalWrite(10, HIGH);  // set rotation of motor to Clockwise
      digitalWrite(11, LOW);

  }
  digitalWrite(10, HIGH);  // set rotation of motor to Clockwise
  digitalWrite(11, LOW);

  delay (50);
}

You haven't implemented any of the suggestions, that I gave in my answer to your previous question. Did you find them not fitting? Or were something unclear? Then please comment on my answer, so that it can be approved.

Your logic seems garbled. I thought you use the pot (which is constant while SET is HIGH, since you don't read it there) to control the setpoint, but currently you use it for input of the PID, which should instead be the current speed value.

And most likely your while loop runs so fast, that the PWM wave gets restarted again and again, effectively chopping it up to zero, which means no speed


text:
Arduino GSM Implementation
I want to send sms to a number if and only if that number is in the radius of the arduino with GSM module.
I already have GPS into it.
Should i integrate a ultrasonic sensor to get the distance and then send the message??? let me know if there is anyother option.
Thank you in advance.

What kind of radius are we talking about? Line-of-sight ultrasonic sensor radius? But how are you planing to determine the number with ultrasonic sensor?

Can't be done without writing a special app for the phone - and then the sending of the SMS is pointless.


text:
NodeMCU run sensor code while listening for wifi input?
Is it possible to have code running while also listening for local inputs via ip address? I thought it would go in the 'while' portion but I presume that only responses when the ip is loaded.
void loop() {

  WiFiClient client = server.available();
  if (!client) {
    return;
  }
  while (!client.available()) {
    delay(1);
  }
  String query = client.readStringUntil('\r');
  client.flush();

  if (query.indexOf("/open") != -1)  {
    open_fast();
  } else if (query.indexOf("/close") != -1)  {
    close_fast();
  }

  sensor = analogRead(A0);
  sensor = map(sensor, 0, 1023, 0, full);

  Serial.print(sensor);
  Serial.print("  ");
  Serial.println(pos);

  if (sensor > pos) {
    open_slow();
    delay(1000);
  } else if (sensor < pos) {
    close_slow();
    delay(1000);
  }
  delay(100);

}

instead ofif (!client) {     return;   } use if (client) { /* handle client */ }?

@Juraj What does that do?

take a coding course

The problem is that at
while (!client.available()) {
  delay(1);
}
// your wifi code

you wait for a wifi event and in that time you obviously can't read the sensor. Just poll for incoming requests by doing it like
if (client.available()) {
  // your wifi code
}

This way your loop skips the wifi-routine if there is nothing to do and proceeds with reading the sensor.
As mikrocontrollers usually don't run a OS, you don't have multitasking which you have to implement yourself.
Generally you have to avoid using delay loops when you want several tasks being executed "parallely".

The difference between "if" and "while" in this situation, does it negatively effect the wifi or mcu by polling the internet in any different way or are they basically the same?

client.available() just checks if there are any requests in the esp's input buffer, the actual communication has allready taken place at that time and is handled by the esp's hardware. But there is a fundamental difference between if and while: if is only a single test for wifi activity, while delays your loop until wifi activity and is not what you want.


text:
RDM6300 continuous RFID tag read
I have an RDM6300 connected to an Arduino Mega and code that can read the tag just fine:

// Function prototypes
void setup(void);
void loop(void);

// RDM6300 packet details
#define RDM6300_PACKET_SIZE  14
#define RDM6300_PACKET_BEGIN 0x02
#define RDM6300_PACKET_END   0x03

// Globack for reading RFID data
char buff[RDM6300_PACKET_SIZE];
uint32_t tag_id;
uint8_t checksum;

void setup(void) {
  Serial.begin(9600);
  Serial.println("Setting up...");

  // RFID board setup
  Serial1.begin(9600);

  Serial.println("READY. Scanning tags...");
}

void loop(void) {
  while (Serial1.available() > 0) {
    if (Serial1.peek() == RDM6300_PACKET_BEGIN || Serial1.read()) {
      Serial1.readBytes(buff, RDM6300_PACKET_SIZE);
      if (buff[13] != RDM6300_PACKET_END) {
        Serial.println("Bad1");
      }
      else {
        buff[13] = 0;
        checksum = strtol(buff + 11, NULL, 16);
        buff[11] = 0;
        tag_id = strtol(buff + 3, NULL, 16);
        buff[3] = 0;
        checksum ^= strtol(buff + 1, NULL, 16);
        for (uint8_t i = 0; i < 32; i += 8) checksum ^= ((tag_id >> i) & 0xFF);
        if (checksum) {
          Serial.println("Bad2");
        }
        else {
          Serial.println(tag_id);
        }
      }
    }
    else {
      Serial.println("Bad3");
      Serial.println(Serial1.peek(), HEX);
    }
    Serial.println("END");
  }
}

However, the output stops after reading the tag around 28 times sometimes (more, sometimes less...) . If I remove the tag from the "read" area and put it back on it start reading again for a number of times and then stop.
I have an LED connect to the RDM6300 board that is supposed to show when it detects a tag and it does blink while I hold the tag over the antenna but also stops when the Arduino stops receiving data.
As the RDM6300 is supposed to be a continuous RFID reader I was expecting to receive data for the duration I kept the tag over the antenna.
Anyone faced this same thing and found a solution ?
Thanks for any hints.

only guessing here ...... that may be normal behavior for RFID tags ..... maybe repeated reads drain the power from the tag faster than it can be refilled ..... what happens if you introduce a 1 second delay between scans??

@jsotola Unfortunately there is no "read" trigger. The module (https://www.seeedstudio.com/125Khz-RFID-module-UART.html) just starts spitting out data as soon as a tag is within reading distance of the antenna.

Ok, so it seems to be related to the tags. The "standard" keychain and credit-card type cards when used with the RDM360 only emit a single time their ID.
The same tags when used with the RDM3600 module will emit their tags a few times, but at some point the antenna can not provide enough power for the tag to emit again and the flow stops.
Fortunatly the tags I use for this project are very small tags made for birds (https://eccel.co.uk/product/3-3mm-em4102-pit-bird-tag-grey/) and when used with the RDM360 will continuoisly retransmit. I guess they need less power and the antenna is able to provide enough.
If you want to use continuous reading using regular tags, I believe there is still a way... If you "reset" the RDM360 or RDM3600 it forces "re-energize" of the tag and transmission resumes. So one could use a simple transistor to switch on and off the power to the RFID module using an Arduino I/O.

It's OK to accept your own answer as the solution to the problem. I think you get 15 rep for it.


text:
How to use a variable format in `sprintf`
How should I make a variable format sequence for sprintf?.
int i=2,d=9;
String sf;
sprintf(sf,"%%0%d",i);
fprintf(sf,d);

While expecting the output.
09

The compilation fails, with several errors, according the failing change I apply.
Invalid cast from type 'String' to type 'char*'

this may help  ..... https://majenko.co.uk/blog/evils-arduino-strings

Hint: Try char sf[32]; and then correct the rest.

sprintf cannot be used to write data into String objects. More precisely, it is possible to come up with a "hackish" way to write the result directly into a String object, but the latter is definitely not designed for such use.
The target buffer should be an array of char, not a String. Which is what the compiler is telling you.
char buffer[64];
sprintf(buffer, "%%0%d", i);

or better
char buffer[64];
snprintf(buffer, sizeof buffer, "%%0%d", i);

The format string you used in your sprintf will generate %02 result (since i contains 2 at that moment). Why you are expecting 09 is not clear. Why are you expecting the % character to disappear is not clear either, considering that the format string seems to be deliberately designed to include it.
A String object cannot be used as the first parameter of fprintf. It is not clear what that fprintf is doing in your code.

Apparently you are trying to use sprintf to generate another format string at run time (using i as field width), which is later used to output the d variable. In that case that would be something like
char format[16];
snprintf(format, sizeof format, "%%0%dd", i);
fprintf(file, format, d);

That fprintf will indeed output 09.


text:
Arduino keeps looping
I made a program where I give a number(4 bit) as input and four led on the breadboard lights up according to its binary. The problem is the program works all well only for (2-15) but if I give 0 or 1 as input it keeps looping and the serial monitor keeps printing that number. If I remove the "prbline" from the code the program works but the serial monitor only prints the input number if it is 0 or 1. Why is it like this?
#include<stdlib.h>
#include<string.h>
int red1=2;
int red2=3;
int red3=4;
int red4=5;
int num=1; // this is the input number
char number[4];
int len;
char str3[]="000",str2[]="00",str1[]="0",str[]="0000";

void setup() {
  // put your setup code here, to run once:
  pinMode(red1,OUTPUT);
  pinMode(red2,OUTPUT);
  pinMode(red3,OUTPUT);
  pinMode(red4,OUTPUT);
  itoa (num,number,2);
  len=strlen(number);
  Serial.begin(9600);
  Serial.println(num);
  Serial.println(number);
  Serial.println(len);
  Serial.println(str);

  if(len==1){
    strcat(str3,number);
    strcpy(str,str3);
    }
  else if(len==2){
    strcat(str2,number);
    strcpy(str,str2);
    }
  else if(len==3){
    strcat(str1,number);
    strcpy(str,str1);
    }
  else {
    strcpy(str,number);
    }
  Serial.println(str); //prbline

}

void loop() {
  // put your main code here, to run repeatedly:
  if(str[0]=='1'){
    digitalWrite(red1,HIGH);
    }
  if(str[1]=='1'){
    digitalWrite(red2,HIGH);
    }
  if(str[2]=='1'){
    digitalWrite(red3,HIGH);
    }
  if(str[3]=='1'){
    digitalWrite(red4,HIGH);
    }

}

How are you providing the input?

I change the value of the 'num' variable from the IDE and upload

So many mistakes in such a short code:

number is too short for more than 3 bit numbers (8 and higher)
strcat is modifying first string, so all strings str1, str2, str3 are too short too
if you want to use them more than once, it'l be adding string to them over and over.....

Basically, if you can see output from the setup over and over, it means crash and start from the reset vector.
But, the main question is why don't you use bit manipulation on num directly:
  digitalWrite(red1, (num & 0b1000) != 0 );
  digitalWrite(red2, (num & 0b0100) != 0 );
  digitalWrite(red3, (num & 0b0010) != 0 );
  digitalWrite(red4, (num & 0b0001) != 0 );

Or with using bit positions:
  digitalWrite(red1, (num & (1 << 3)) != 0 );
  digitalWrite(red2, (num & (1 << 2)) != 0 );
  digitalWrite(red3, (num & (1 << 1)) != 0 );
  digitalWrite(red4, (num & (1 << 0)) != 0 );

Bit positions little bit more readable by using macro _BV (which is translated to 1 << ..)
  digitalWrite(red1, (num & _BV(3)) != 0 );
  digitalWrite(red2, (num & _BV(2)) != 0 );
  digitalWrite(red3, (num & _BV(1)) != 0 );
  digitalWrite(red4, (num & _BV(0)) != 0 );

or more interesting macro wrapper bit_is_set to be more readable:
  digitalWrite(red1, bit_is_set(num,3));
  digitalWrite(red2, bit_is_set(num,2));
  digitalWrite(red3, bit_is_set(num,1));
  digitalWrite(red4, bit_is_set(num,0));

And, as a bonus, it can be even done in a loop:
byte reds[] = { 5, 4, 3, 2 }; // to preserve the same order as in the question
byte num    = 1;

void loop() {
  byte tmp = num;
  for (byte pin : reds) {
    digitalWrite(pin, tmp & 1);
    tmp >>= 1; // bit shift by one to the right (= division by 2)
  }
}

Thank you very much for the answer it really helped me.

To add to KIIV's concise response, the line
Serial.println(str); //prbline

can be easiest created without itoa and leading zero helper strings by
int num = 9; // Test input 0 .. 9 ( or even 15 = 0x0F )
void setup() {
 char str[] = "0000";
 byte tmp = num & 0x0F; // limit to valid values
 for (byte i=3; tmp != 0; i--, tmp >>= 1)
   if (tmp & 0x01) str[i] = '1';
Serial.begin(9600);
Serial.print(num);
Serial.print(" = ");
Serial.println(str);
}

You are overwriting memory.
 if(len==1){
    strcat(str3,number);
    strcpy(str,str3);
    }

There is room for 3 characters in str3, however you are using strcat to add more characters.
I don't understand your technique, however this might help make it work:
char str3[6]="000",str2[6]="00",str1[6]="0",str[6]="0000";

Thank you very much for the answer it really helped me.


text:
Connection of a DS18B20 on a Arduino pro mini
I'm actually trying to connect a DS18B20 sensor to a homemade board build with a ATmega328P processor running with a power of 3.3V and at 8 Mhz.
In order to get the address I wired the board as the following schematic on the pin 5 of my board.

To power the sensor and the pull up resistor I use the VDD output of my board which provides 3.3V.
For the code part I uploaded this:
// This sketch looks for 1-wire devices and
// prints their addresses (serial number) to
// the UART, in a format that is useful in Arduino sketches
// Tutorial:
// http://www.hacktronics.com/Tutorials/arduino-1-wire-address-finder.html

#include <OneWire.h>

OneWire  ds(5);  // Connect your 1-wire device to pin 5

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

void discoverOneWireDevices(void) {
  byte i;
  byte present = 0;
  byte data[12];
  byte addr[8];

  Serial.print("Looking for 1-Wire devices...\n\r");
  while(ds.search(addr)) {
    Serial.print("\n\rFound \'1-Wire\' device with address:\n\r");
    for( i = 0; i < 8; i++) {
      Serial.print("0x");
      if (addr[i] < 16) {
        Serial.print('0');
      }
      Serial.print(addr[i], HEX);
      if (i < 7) {
        Serial.print(", ");
      }
    }
    if ( OneWire::crc8( addr, 7) != addr[7]) {
        Serial.print("CRC is not valid!\n");
        return;
    }
  }
  Serial.print("\n\r\n\rThat's it.\r\n");
  ds.reset_search();
  return;
}

void loop(void) {
  // nothing to see here
}

When I make it run on an Arduino Uno card I can get the address of the sensor but when I make it run on my card I only obtain this:

Looking for 1-Wire devices...

That's it.
Anyone got a idea why it's working on an Arduino Uno but not on my card?

On schematic two pins are connected, in question description and code, there's only one pin.

Is that a mosfet? Is it used to shortcut the data to 3.3v? why?

Sorry @domen  i had put the wrong diagram in my post, i edited my post

You're saying it's same chip (and similar surrounding hardware) and same software? Is there a schematic for your own hardware, because you've probably made some mistake there. Include the details of all differences to working setup.

@domen i added in the post a hardware shematic around the chip , we use the PD5 (D5 )

You may have based it on this, but with RX, TX and D5 not connected, your hardware could be quite different :) Is your software the same (vs. working setup)? What are the hardware differences?

Did you try a lower value for the pullup resistor? 2k2 for instance. Check the spec.

I finally made it work, thx @domen.
I looked at the other part of the schematic and found I was using the wrong pin - I have two LDO and the one I was using was deactivated for sensor.
Thanks all for your help.


text:
Modifying normal doorbell to get notification
I'm really not used to Arduino and I would like to know if it would be possible to tweak my doorbell, most specifically the bell itself, to embed a small arduino that would be able to send a notification "somewhere" (well, if it can connect to wifi and send an HTTP request I can handle the rest).
I'm guessing that there will be electricity in the bell itself (to.. ring it I guess) so I could use that to power the Arduino.
My goal is definitelly not to create a "smart" doorbell but to upgrade a tiny bit the one we already have. My biggest problem is that when I am in the office, I can barely hear it and if I turn music on, it becomes impossible.
Before launching myself in this, I'd like to know if it is at all possible. I can (try to) provide more information if needed.
Thanks.
EDIT: I'm guessing that the bell rings when it gets an electric signal when the button at the door is pressed. My goal would be to hook up to that signal to get the arduino to send an HTTP request. Now, my arduino knowledge is very limited and I'd like to see if anyone could give a tiny bit of guidance on how to proceed (which one, which module, ...)
EDIT2: As requested, here is a picture of the bell part:
[![bell][1]][1]
In the center there is a copper coil so I would guess that when someone presses the button, the little hammer (pointy thing going up) hits the 2 metal plates (up and down). I could also see that there is a third cable (purple) hidden behind that is not currently used but I have no clue what it is for or if there is power at all on this thing...
EDIT3: I realized that I have a Friedland D780 on the fuse box (so right next to all the power I can need for an Arduino). It is unclear if I could get the pulse from here though. Anyone?
I can't upload a picture with my phone but I'll add it ASAP...
[1]: https://i.stack.imgur.com/pdgbs.jpg

In order to help some clue as to what your doorbell is would be helpful.
I have a system where I modified a standard doorbell's powered push button to send a signal via an ESP01 and WiFi to MQTT running on a Raspberry Pi but the permutations and methods are many.

I'm going to try and get more informations and photos

I added a photo in the question as requested.

Most doorbells use AC with a voltage of 8-24 Volt. This voltage is created by a transformer. Where I live this transformer is located in the fuseboard closet. This voltage goes to the bell, but is interrupted by the bell-button, until it's pressed. So to power your device you'd have to rectify the AC to DC, and then regulate the voltage to 5Volt of 3.3Volt. The problem is that you only get power while the button is pressed, so you'd need a way to store enough energy to make your HTTP request.

If you have a multimeter, I'd measure the voltage between the purple wire and the white/blue wires.

After checkin, there is indeed something in the fusebox closet. I'll try to get my hands on a multimeter and do more checks. I'll also look deeper in the fusebox to see what is attached there and if I could potentially modify that.

do you have constant power available to an MCU by the bell? if so, then it's trivial to use an optocoupler to pull a pin low when voltage comes on the coil.

Sorry for the late reply. It occured to me that I was maybe looking at it from the wrong angle. I looked at the fuse box and saw a Friedland D780. Could I get the pulse from there? I'll add a photo of it in the question

Many (most?) household doorbell systems in the US are powered by a simple transformer that converts 120V AC household electric supply to a lower voltage AC. Often 16V AC or 24V AC.
The coil and hammer form a device called a solenoid. When the coil is energized, the hammer (often also called a plunger) is forced in one direction, either up (against gravity) or against a return spring, striking one of the plates. When power is removed, gravity or the return spring pull the plunger back to the rest position, striking the other plate, forming the familiar ding-dong sound.
Power is applied or removed extremely simply -- by the momentary, normally-open pushbutton at your door. When you press the button, the solenoid is energized, and when you release it, the device returns to the normal state.
With regard to powering your Arduino, it is important to understand the difference between AC and DC power. The Arduino requires DC (direct-current) of either a regulated 5V DC into the 5V pin, or unregulated 7-12V DC into the VIN pin, or the regulated 5V DC from a USB device.
I don't know your level of electricity understanding, but there exists quite a bit of information on the difference between AC and DC power. Suffice it to say, you would need some additional circuit to rectify and filter and regulate the 16-24V AC into something between 5V and 12V DC.
Then, there is the issue of the loss of a good power tap while the button is pressed. If you measure the voltage across the contacts of the pushbutton while it is not pressed, you will likely find the full 16V AC or 24V AC, but if you measure those contacts while the button is pressed, you will read 0V AC. This means that tapping off of the pushbutton wires is not a good way to power a device that needs to remain on while reacting to the button press. Whether or not you could tap power off of the solenoid terminals is dependent on the voltage drop across the coil, and still you have the issue to convert the AC to DC at the proper voltage.
If this doorbell is near the ceiling, you will likely find the transformer mounted in the attic space above the ceiling near the doorbell (if there is attic space -- depending on your specific setup).  If there is a power outlet in this attic space, you could plug in a good quality AC-DC 5V adapter there to power the Arduino in the attic. The Arduino will need to remain electrically isolated from the doorbell circuit. To detect the pushbutton press, you could use a current transformer measuring the current flow through either of the 16V AC wires coming off of the transformer (measure with one of the the analog inputs of the Arduino), or with an Opto-isolator, with the transmitter connected to the doorbell circuit in a way that delivers a small current (10mA or so normally) to the transmitter side of the opto-isolator, and read the receiver side with a digital input pin on the Arduino.
Unfortunately, interfacing with a doorbell that uses AC power will require some good planning and evaluation of your doorbell system and how much additional circuitry you are willing to apply.
If you aren't careful, working near the transformer can be very dangerous to your life. Working with 16-24V AC will not be as dangerous to your life, but can easily damage the Arduino beyond repair in the flash of an eye. Take great care.

Much as I like Arduinos, it might be easier to just run a wire from your current doorbell to your office and add a 2nd doorbell, or a piezo buzzer that will run on AC. As others have said doorbells in the US are usually powered by AC, and that power is only available while the doorbell is actually ringing. You would need a constant source of power in order to drive your Arduino long enough to connect to a network and send a signal.
You might be able to build a circuit that rectified the AC power to DC and charged a capacitor, then used that capacitor to drive a DC power supply to the Arduino. The capacitor might hold a charge long enough for the Arduino to make a network connection and send a signal, but you'd need a fair amount of electronics knowledge to make that work.

Some of the piezo buzzers I've seen will run with a wide range of voltages, from 6 to 18. You could put a bridge rectifier on the AC in from the doorbell, then a simple voltage divider to drop the voltage from 24V to 12. Alternately you could use a 2:1 transformer to step down the 24VAC to 12VAC, then a bridge rectifier, and then the piezo buzzer.

If I could offer a different approach -- to maintain isolation between the doorbell AC and an Arduino, you could have the separately powered Arduino 'listen' for the sound of the gong. A cheap mic feeding an analog input does the trick. Mount it in the same housing to isolate it from household and other noises, or maybe tune it to respond to a narrow range of frequencies.
There are other non-contact, non-wired possibilities too -- sense the motion of the solenoid, or its electrical field, etc.


text:
How to stop and repeat a melody using a button?
How can we make our melody stop when we press the button the first time and repeat the melody when we press the button the second time?
// Noterna defineras

#define NOTE_B0  31
#define NOTE_C1  33
#define NOTE_CS1 35
#define NOTE_D1  37
#define NOTE_DS1 39
#define NOTE_E1  41
#define NOTE_F1  44
#define NOTE_FS1 46
#define NOTE_G1  49
#define NOTE_GS1 52
#define NOTE_A1  55
#define NOTE_AS1 58
#define NOTE_B1  62
#define NOTE_C2  65
#define NOTE_CS2 69
#define NOTE_D2  73
#define NOTE_DS2 78
#define NOTE_E2  82
#define NOTE_F2  87
#define NOTE_FS2 93
#define NOTE_G2  98
#define NOTE_GS2 104
#define NOTE_A2  110
#define NOTE_AS2 117
#define NOTE_B2  123
#define NOTE_C3  131
#define NOTE_CS3 139
#define NOTE_D3  147
#define NOTE_DS3 156
#define NOTE_E3  165
#define NOTE_F3  175
#define NOTE_FS3 185
#define NOTE_G3  196
#define NOTE_GS3 208
#define NOTE_A3  220
#define NOTE_AS3 233
#define NOTE_B3  247
#define NOTE_C4  262
#define NOTE_CS4 277
#define NOTE_D4  294
#define NOTE_DS4 311
#define NOTE_E4  330
#define NOTE_F4  349
#define NOTE_FS4 370
#define NOTE_G4  392
#define NOTE_GS4 415
#define NOTE_A4  440
#define NOTE_AS4 466
#define NOTE_B4  494
#define NOTE_C5  523
#define NOTE_CS5 554
#define NOTE_D5  587
#define NOTE_DS5 622
#define NOTE_E5  659
#define NOTE_F5  698
#define NOTE_FS5 740
#define NOTE_G5  784
#define NOTE_GS5 831
#define NOTE_A5  880
#define NOTE_AS5 932
#define NOTE_B5  988
#define NOTE_C6  1047
#define NOTE_CS6 1109
#define NOTE_D6  1175
#define NOTE_DS6 1245
#define NOTE_E6  1319
#define NOTE_F6  1397
#define NOTE_FS6 1480
#define NOTE_G6  1568
#define NOTE_GS6 1661
#define NOTE_A6  1760
#define NOTE_AS6 1865
#define NOTE_B6  1976
#define NOTE_C7  2093
#define NOTE_CS7 2217
#define NOTE_D7  2349
#define NOTE_DS7 2489
#define NOTE_E7  2637
#define NOTE_F7  2794
#define NOTE_FS7 2960
#define NOTE_G7  3136
#define NOTE_GS7 3322
#define NOTE_A7  3520
#define NOTE_AS7 3729
#define NOTE_B7  3951
#define NOTE_C8  4186
#define NOTE_CS8 4435
#define NOTE_D8  4699
#define NOTE_DS8 4978

#define melodyPin 3
//här är noterna som är i melodin
int melody[] = {
  NOTE_E7, NOTE_E7, 0, NOTE_E7,
  0, NOTE_C7, NOTE_E7, 0,
  NOTE_G7, 0, 0,  0,
  NOTE_G6, 0, 0, 0,

  NOTE_C7, 0, 0, NOTE_G6,
  0, 0, NOTE_E6, 0,
  0, NOTE_A6, 0, NOTE_B6,
  0, NOTE_AS6, NOTE_A6, 0,

  NOTE_G6, NOTE_E7, NOTE_G7,
  NOTE_A7, 0, NOTE_F7, NOTE_G7,
  0, NOTE_E7, 0, NOTE_C7,
  NOTE_D7, NOTE_B6, 0, 0,

  NOTE_C7, 0, 0, NOTE_G6,
  0, 0, NOTE_E6, 0,
  0, NOTE_A6, 0, NOTE_B6,
  0, NOTE_AS6, NOTE_A6, 0,

  NOTE_G6, NOTE_E7, NOTE_G7,
  NOTE_A7, 0, NOTE_F7, NOTE_G7,
  0, NOTE_E7, 0, NOTE_C7,
  NOTE_D7, NOTE_B6, 0, 0
};
//tempo mario(hastigheten på tonerna)
int tempo[] = {
  12, 12, 12, 12,
  12, 12, 12, 12,
  12, 12, 12, 12,
  12, 12, 12, 12,

  12, 12, 12, 12,
  12, 12, 12, 12,
  12, 12, 12, 12,
  12, 12, 12, 12,

  9, 9, 9,
  12, 12, 12, 12,
  12, 12, 12, 12,
  12, 12, 12, 12,

  12, 12, 12, 12,
  12, 12, 12, 12,
  12, 12, 12, 12,
  12, 12, 12, 12,

  9, 9, 9,
  12, 12, 12, 12,
  12, 12, 12, 12,
  12, 12, 12, 12,
};

// här bestämmer jag vilken pin sakerna ska sitta på
const int ledPin = 13;
const int buttonPin = 4;
const int buzzerPin = 3;
int musikSpelar = 0;
int buttonState = 0;
int musik = 1;
int notlangd = 0;

void setup(void)
{
  pinMode(buzzerPin, OUTPUT);//buzzer
  pinMode(buttonPin, INPUT); // knappen
  pinMode(ledPin, OUTPUT);// lampa på arduinon

}
void loop()
{

  buttonState = digitalRead(buttonPin);

  if(digitalRead(buttonPin)==0){
    delay(10);
  }
  if(digitalRead(buttonPin)==1){
    sing(musik); //Här spelar jag musiken
    musikSpelar = 1;
  }
  if(digitalRead(buttonPin)==0){
    delay(10);
  }
   if(musikSpelar == 1){
    //buzzer(melodyPin, 0, notlangd);
    musikSpelar = 0;
  }
}

void sing(int musik) {
  // upprepning av noterna i melodi:

    Serial.println(" 'Mario Theme'");
    int size = sizeof(melody) / sizeof(int);
    for (int Noten = 0; Noten < size; Noten++) {

      // för att räkna ut längden på noterna, tar man en sekund och dividerar på nottypen

      //vilket resuletar i att fjärde noten = 1000 / 4, åttonde noten = 1000/8, etc.

      notlangd = 1000 / tempo[Noten];

      buzzer(melodyPin, melody[Noten], notlangd);

      // för att hålla isär noterna, sätter jag ett minimum på tiden mellan dom.
      // notens längd + 30% ( va de som fungerade bäst:)
      int pausMellanTon = notlangd * 1.30;
      delay(pausMellanTon);

      // sluta spela tonerna:
      //buzzer(melodyPin, 0, notlangd);
    }

}

void buzzer(int targetPin, long frekvens, long length) {
  digitalWrite(13, HIGH);
  long delayValue = 1000000 / frekvens / 2;

  // räknar ut pausen mellan varje byte
  //// 1 sek i microsekunder, delat på frekvensen , sedan delat på hälften

  long numCycles = frekvens * length / 1000;

  // Beräkna antalet cykler för korrekt timing
  //// multiplisera frekvensen ,vilket egentligen är kretslopp per sekund, med antalet sekunder till
  //// det totala antalet "kretslopp"

  for (long i = 0; i < numCycles; i++) { // för den uträknade tiden...

    digitalWrite(targetPin, HIGH); // buzzern är på high för att den ska låta

    delayMicroseconds(delayValue); // vänta på den uträknade pausen

    digitalWrite(targetPin, LOW); // ha buzzern på pin low...

    delayMicroseconds(delayValue); // wait again or the calculated delay value
  }
  digitalWrite(13, LOW);

}

You need to explain your code, what it does, and the section you need help with. (Having comments in Swedish doesn't help most of your readers.)

https://www.arduino.cc/en/Tutorial/InputPullupSerial


text:
Unable to interface using Softserial with ESP8266 and Arduino uno
I am trying to use a ESP8266 in an Arduino project, but I'm unable to get the basic Software serial interface working with it.
I have the ESP connected to a secondary 3.3v power supply. When connecting the RX and TX pins to the Uno's RX and TX, and uploading bare minimum code, I am able to interface with the module. Doing this I can connect to networks, send and receive packets, etc.
However, when connecting the ESP to any other pins and trying to implement a software serial interface, I am unable to get any response from the module. When sending it data I see the on board blue LED flash, so I think its receiving the data? I've found tons of example codes and Youtube videos that do what I'm trying to do. But following their steps I'm still not able to get any response.
I've tried using voltage divider circuits for the ESP's RX pin so its not getting 5v, but that hasn't seemed to change anything either. Any troubleshooting advice would be greatly appreciated.
One of the basic codes I've tried to get this to work:
#include <SoftwareSerial.h>

SoftwareSerial wifi(8,9);

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

  Serial.println("started!");

}

void loop(){
  if(Serial.available() > 0){
    byte b = Serial.read();
    Serial.write(b);
    wifi.write(b);
  }

  if(wifi.available() > 0){
    byte b = Serial.read();
    Serial.write(b);
  }
}

and with SoftwareSerial you wire TX to RX? and set the SoftwareSerial and the AT firmware to 9600 baud

Correct. And I've tried several different baud rates. The primary one I've been using is 115200 because that is what was working when directly interfacing with the ESP.

set the default baud rate of the AT firmware to 9600 baud and use that in Serial Monitor and with Software Serial

I'm going to get an FTDI to interface with it more reliably. I bought a lot of 4 and bricked one trying to change the baud rate through AT commands. I'm going to try to flash a new firmware on the bricked one and see where that takes me.


text:
error: invalid use of non-static member function attachInterrupt(0,count,RISING);
XRPM_COUNTERS.h:15:5: error: expected unqualified-id before string constant

     ISR(PCINT0_vect) {

     ^

In file included from C:\Documents and Settings\SAM\Desktop\automation_1_A_NEW_AAA\automation_1_A_NEW_AAA.ino:10:0:

XRPM_COUNTERS.h:72:1: error: expected ';' after class definition

 }

 ^

sketch\XRPM_COUNTERS.h: In function 'void XRPMLoop()':

XRPM_COUNTERS.h:77:19: error: 't' was not declared in this scope

   if ((millis() - t) > 300) rpm = 0;

                   ^

XRPM_COUNTERS.h:77:29: error: 'rpm' was not declared in this scope

   if ((millis() - t) > 300) rpm = 0;

                             ^

XRPM_COUNTERS.h:79:17: error: 'ot' was not declared in this scope

   else if (t != ot) {

                 ^

XRPM_COUNTERS.h:81:5: error: 'rpm' was not declared in this scope

     rpm = 60000.0 / (float)(t - ot);

     ^

XRPM_COUNTERS.h:87:13: error: 'rpm' was not declared in this scope

   lcd.print(rpm);

             ^

XRPM_COUNTERS.h:93:14: error: 'printVu' was not declared in this scope

   printVu(rpm);

              ^

sketch\XRPM_COUNTERS.h: At global scope:

XRPM_COUNTERS.h:97:1: error: expected declaration before '}' token

 };

 ^

exit status 1
expected unqualified-id before string constant

My source code
class XRPM_COUNTERS {

  private:
#include <Wire.h>  // Comes with Arduino IDE
#define interrupt_pin2 A8 //Define Analog Pin (analog pins are 16-21)

    volatile unsigned long t = 0;

    volatile unsigned long ot = 0;

    ISR(PCINT0_vect) {

      if (PINB & 1) {

        ot = t;

        t = millis();

      }

    }

    //actualizar o visor (aqui calibrado para um maximo de 3000 rpm, basta mudar o valor)

#define max_rpm 3000

    void printVu(int r) {

      int i = map(r, 0, max_rpm, 0, 20);

      for (int n = 0; n < 20; n++) {

        lcd.print((char)(n < i ? 255 : ' '));

      }

    }

  public:

    void XRPMSetup() {
      lcd.begin(16, 2);  // initialize the lcd for 20 chars 4 lines, turn on backlight

      lcd.print("RPM with PCINT");

      MCUCR = (1 << ISC01) | (1 << ISC00);

      PCICR |= (1 << PCIE0);

      PCMSK0 |= (1 << PCINT0);

      pinMode(interrupt_pin2, INPUT); //Make pin an input

      digitalWrite(interrupt_pin2, HIGH); //Enable pullup resistor on Analog Pin

      interrupts();

    }

    unsigned int rpm = 0;

}
void XRPMLoop() {

  //lcd.setCursor(0,3);lcd.print(millis()-t);lcd.print("     ");

  if ((millis() - t) > 300) rpm = 0;

  else if (t != ot) {

    rpm = 60000.0 / (float)(t - ot);

  }

  lcd.setCursor(0, 1);

  lcd.print(rpm);

  lcd.print(" rpms    ");

  lcd.setCursor(0, 2);

  printVu(rpm);

}

};
XRPM_COUNTERS XRPM;

Format your question so that people can see where error messages end and code begins.

Possible duplicate of expected unqualified-id before string constant

You placed an #include directive inside a class definition. Don't place #include directives inside class definitions. (Unless you are including a file specifically designed for that purpose.)
#include directives for regular header files should normally reside somewhere at the top of your file, separately from any other declarations.


text:
Coin Recognition from Parallel Coin acceptor to Arduino
I have one project to do where I have one big problem and I need your help. At this stage, it is not a problem for me to write Arduino program for a money receiver who has an impulse output. But the coin receivers that have a parallel output lines which is described in the manuals in detail how it comes to information in the cables of the coin drop, but I can not hit on a decision on how to program Arduino to know coin type, I hope you any of you have a similar experience and will be able indicating which way to raise in order to get to work this project. Coin model is:

EMP 800 v6
Link to the manual

Any your suggestions may be the my life saver...
Thank you in advance guys...

The biggest problem I see is programming the coin-collector. I think you can make it learn coins with only the dip-switches, but other options seem to only be programmable by PC. The outputs of the coin-collector are simple open collector outputs. So connect the ground to the ground of the Arduino, and the open-collector outputs to the Arduino inputs, and add/enable a pull-up resistor. When a coin is accepted, the input pin will read a short LOW pulse.

Nice Suggestion.   I  will try this for next week and I will inform you what will happen

@Gerben Programming coins on Coin Acceptor is not problem for me I m working in Service Center where my main work is programming Coin and Bill Acceptors and I have all programmers that I need including this EMP's programmer and PC Software too... But problem is output for this channels(1,2,3,4,5,6) I think is different then normal Pulse Output. Pulse gives output by getting Low in 50 - 100 MS one time and that means its 1 impulse but this parallel output I think is difference then IMPULSE ;(

From my reading the datasheet, I gathered that you get a Pulse output on the channel that corresponds to the coin that's being recognized. Fer example, if channel 3 is for a 10cent coin, then you get a LOW pulse on channels 3's output pin.


text:
Built-In Digital Map for Robot Driving
So, I'm creating this project for school. It's a simple robot with Arduino MEGA 2560 and basically, I create a digital map, feed it into the Arduino program and then the robot can drive. However, I've run into some problems while trying to implement my idea. Parsing errors mostly. And I want to know if there is another and different approach.
So, basically at the moment, this is how my digital map works:
Using C# and Visual Studio IDE I've created a program with which I can create the map. Basically, I create connections(lines/roads) and the connection has a starting and end point, a median point and a label(what it is). So, each connection info token is something like this:
"Connection[x1: 0, y1: 0|x2: 13, y2: 0|xm: 6.5, ym: 0|label: Nothing]"

"Connection[x1: 13, y1: 0|x2: 13, y2: 28|xm: 13, ym: 14|label: library]"
Now, I have figured out a way to import this information into Arduino, and I've stored the information into a class object I created. Now, the difficulty I'm experiencing is how am I going to drive the robot from one point to another, store the robot's position and go to any point in the map when asked to.
Edit:
As for the implementation and storage of the map, it's like this:
So, I have a class Vertex. It basically the equivalent of a point and store (x, y) values.

class Vertex {
  public:
    int x;
    int y;

    Vertex(int _x, int _y) {
       x = _x;
       y = _y;
    }
};

Then there's the connection class. It stores the starting vertex, the end vertex, the median vertex and the label(string). It's like this:
class Connection {
  Vertex v1();
  Vertex v2();
  Vertex median();
  String label;

  public:
    Connection(Vertex _v1, Vertex _v2, Vertex _median, String _label) {
        v1() =  Vertex(_v1.x, _v1.y);
        v2() =  Vertex(_v2.x, _v2.y);
        median() = Vertex(_median.x, _median.y);
        String label = _label;
  }
};

And, finally, there's the map class where the user passes in the info tokens produced by my map creating application made in Visual Studio and it works like this:
#include "Connection.h"

class Map {
  public:
    Map(string infoTokens[]) {
      //I import the info tokens here.
    }

    void drawMap(MCUFRIEND_kbv tft, String ) {
      //This is a totally different function, it is just for drawing the map
        on top of the TFT screen that I have on my robot.
    }

    void driveTo(Vertex rP, String destinationLabel) {
      //This is where I drive my robot when the user requests to go to a
        destination and provides the label.
    }
};

As for the importing of the info tokens(the map information) I just do some String Manipulation on, for example, this
"Connection[x1: 0, y1: 0|x2: 13, y2: 0|xm: 6.5, ym: 0|label: Nothing]"
and get back all the info in the required data types. As for the importing it doesn't really change anything because I have tested my function(not present here) a lot of times and it works brilliantly. My question is how to use that information to hopefully drive the robot.

Do you want to command the robo "go to position 6, 3" or "got to library" (last one is using the label instead of the physical location)?

And do you want the shortest connection to the target through your street net?

I want it to command using 'go to position 6,3' as it would be more useful. And yeah implementing the shortest distance possible would be a great idea.

Can you please show the implementation of your class object, so that we can see, how the data is stored?

Added the information you requested. Hopefully, it is what you need and can give me a solution. Thanks!

You were able to create a custom data structure from your string, but it seems, that the connections, that are stored in the Map class, are not connected. So the map does not really represent the structure of the "street" net. I would propose a different approach:
Instead of defining connections you can define the nodes of your net (where 2 or more streets meet). For each node you save the position (x, y) (or an instance of your vertex class), a label (like "library") and an array of pointers to other node objects. In code this may look like this (I left the methods out):
class Node {
    Vertex pos;
    char label[25];
    Node *connections[6];
}

Excursion: If you don't know, what pointers are in C/C++, here a short introduction. You should definitely read more about it on the web.
A pointer variable contains the address of another variable in the RAM. You can change this address and let the pointer point to another variable. A variable is marked as pointer with a * at the declaration. You can get the address of a variable (to set the pointer to this variable) through the & operator: pointer = &variable . If you dereference a pointer (by writing a * before the pointer name), you can work with the value, that the pointer points to. Each pointer variable has a type. It is the type of the object, that it points to. The pointer declaration int *var let's var point to int variables. If the type is a class or struct and you want to access members of the target (where it points to), you can use the shortened version pointer->member.

You define each node and add pointers to other nodes to represent connections. To traverse through the map, you need a start node. You save the address of the current node in a pointer. Then you can use it to access the connections of the current node. To actually go to the next node, you would set your pointer to the value saved in one of the connections elements, because that are pointers to the connected nodes.
The robot can then be moved along the straight lines between 2 nodes. When you want to also have non-straight, you can also do that by defining a middle point. You just to define the geometrical form, that the line should take.
The Map class can contain an array of Nodes. You can loop through all nodes in the array, if you need to, or you can traverse through the net by using the pointers.

The actual algorithm to find the path with the smallest travel distance is a big out of scope here. Doing that efficiently can be a complex task. You can research these algorithms on the web. The easiest way is to test all different paths in your program (without actually moving the robot), save the needed distance for each path and then choose the path based on that. You would need to write a termination condition, so that no connected will be taken twice on the same path (which would mean some kind of loop). Also keep in mind, that this will need more and more computation time, as your net grows. If it stays small and you don't need very fast computation, it might stay sufficient. If your implementation is recursive, you also have to consider, that each recursion takes up memory on the stack. You don't want to get out of memory.
Speaking of memory: In your implementation you use String for the label and you might want to use dynamic memory allocation for your map. That is not a good idea, because it can make swiss cheese out of your heap memory (heap fragmentation). It is better to define a fixed array, that can hold the maximal number of elements (as I have done with the connection of a node). The not needed elements can be set to something meaningless (for the connections you can use the null pointer and for unused nodes simply only null pointer connections).

Oh, thank you so much. Exactly what I needed. I was stuck with trying to implement the idea based solely on coordinates and ended with nothing. This was exactly the solution I was looking for. Thank you!


text:
Is there a simple (permissive license) Leonardo driver for a USB-to-USART bridge to substitute an FTDI chip?
I'm making an ESP32 development board and I'm thinking about putting an Arduino Leonardo chip between the USB port and the ESP32's USART pins to act as a USB/USART converter instead of the FTDI chip so that I can program the ESP32 through a USB serial port like any other Arduino board.
Is there a library/sketch licensed under a permissive license (MIT, BSD, Apache, etc.) which can make the Leonardo chip act as a HID Serial Port device which has a device name I want for easy identification in Device Manager and which requires no special driver installation in Windows and Linux once plugged into the computer?
Thank you for your time.

you should do a better research before asking. "Leonardo chip"? "HID Serial port"? why do you wan't to use a 32u4 as USB-to-TTL-Serial? only Uno and Mega use an Atmel MCU for USB. most boards have FTDI or CH340 USB chips

@Juraj I use a small PIC32MX chip as a USB interface on my boards. I like the flexibility that creating your own interface gives you. For example, activating DTR on my system automatically creates a reset pulse, instead of just holding the line low.

The reason I'm using 32U4 is because I'd also like to use it as a virtual HID CD drive with a virtual CD providing an exe application for the end user to be able to upload firmware, communicate with the existing firmware, etc.. And most importantly, it's programmable as I want and all the code I add upon it is mine.

Why not write your own?
First off, you'll want to create your own custom board definition. To do that, find the boards.txt file in the AVR core of your installation. Then find the block of entries that starts leonardo. and copy the whole block. Change the leonardo to a name of your choosing.
Then change the .name entry to give your board a new name in the IDE.
Finally look for the (renamed) entries:
leonardo.build.vid=0x2341
leonardo.build.pid=0x8036
leonardo.build.usb_product="Arduino Leonardo"

Of course the leonardo will be whatever you changed them to.  You can now give your board a new VID and PID to uniquely identify them - and also change the usb_product to name your board.
You can also add a myboard.build.usb_manufacturer="..." entry to change the manufacturer from the default of Arduino.
Now you have a board definition that identifies your board as what you want it to be.  So now just write a sketch that passes through the serial between USB and UART, and also handles the DTR and RTS signals to be able to enter flash mode on the ESP32 (hint: use Serial.dtr() and Serial.rts() to check the status of those signals).

That's quite a comprehensive response. Thank you! However, I still don't understand where's the HID Serial Port driver library (under a permissive license) for me to include in my C++ project and which functions/classes I need to use to talk to the USB side of things. I understand the Serial library, but that's for the USART between the Leonardo and the ESP32. I need the virtual USART part. Could you please append that to your answer?

It's already there. It's in the Arduino core. There is no library needed.

Oh, so there's Serial and Serial1? Is that correct?

Yes. Serial is the USB, and Serial1 is the TX/RX pins.


text:
Help with Arduino Micro Keypress Algorithm
Greeting, first time Arduino user here.
So I am using the Arduino Micro as an HID keyboard device. It accepts arbitrary input from a Node-JavaScript program I am running (so I have full freedom in in the data transferred to the micro).
The goal is for the data transmitted to the micro to include information about a keypress: whether it was pressed or released and which key it is. The serial connections are all fine and dandy - I just have questions regarding the key pressing logic.
As far as the JavaScript program goes, a key down is detected based on the keyCode, not the character code so when tapping “a”, character code  97, the Arduino micro is receiving “A”, character code 65 since the JavaScript detected keyCode is 65. So that all sounds like problems with JavaScript (which it is), but remember that I have freedom in portraying the information sent to the micro.
That being said, instead of detecting by keyCodes and character codes in JavaScript, I could just transmit the letter e.g. “a” with some identifier for press/release such as “+a” for release and “-a” for press. My problem here is how would I handle modifier keys using the Keyboard library.
Should I handle character keys and modifiers keys separately i.e. Keyboard.write for characters and Keyboard.press/release for modifiers or are there cases where it would make sense to press and hold “a” (which would also be different than pressing and holding “A”)?
Below is my original code using keyCodes and “u/d” identifiers to denote up or down (which I am thinking now that “u/d” could be easily confused as a letter if I decide to transmit characters as characters:
/*
  Receives from the hardware serial, sends to software serial.
  Receives from software serial, sends to hardware serial.

  The circuit:
   RX is digital pin 10 (connect to TX of other device)
   TX is digital pin 11 (connect to RX of other device)

  Not all pins on the Leonardo and Micro support change interrupts,
  so only the following can be used for RX:
  8, 9, 10, 11, 14 (MISO), 15 (SCK), 16 (MOSI).
*/

#include <SoftwareSerial.h>
#include <Keyboard.h>

SoftwareSerial rpiSerial(10, 11); // RX, TX

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(115200);
  // Set the data rate for the SoftwareSerial port
  rpiSerial.begin(115200);
  // initialize control over the keyboard:
  Keyboard.begin();
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.println("Keyboard Serial Connection Established");
}

String keyCode = "";
char state;

void loop() {
  while (rpiSerial.available() > 0) {
    // "Type" via keyCodes (recommended for modifiers)
    // https://www.arduino.cc/en/Reference/KeyboardWrite not behaving as expected

    int data = rpiSerial.read();
    if (isDigit(data)) {
      keyCode += (char)data;
    }

    if (isAlpha(data)) {
      state = (char)data;
    }

    if (data == '\n') {
      Serial.print(state);
      Serial.println(keyCode.toInt());

      if (state == 'd') {
        Keyboard.press(keyCode.toInt());
      }

      if (state == 'u') {
        Keyboard.release(keyCode.toInt());
      }

      keyCode = "";
      char state;
    }
  }
}

I have also noticed that the data from the serial connection parsed by the micro is sometimes incorrect i.e. a keyCode will be misidentified. For instance, by repeatedly pressing “a” through my JavaScript program, the JavaScript program will consistently identify keyCode 65 yet Arduino will identify the received data as keyCode 65 most of the time and then randomly keyCode 64. This happens with other keys as well and the keyCode doesn’t always happen to be just one less nor does it always occur after “n” presses.

SoftwareSerial is not reliable at 115200. use 9600 baud

Good to know! I will try that @Juraj

ASCII code for 'A' is 65 and for 'a' it is 97. http://www.asciitable.com/ the key on keyboard is 'A', not 'a'.

So how would you recommend identifying with the micro that the key has been pressed/released?

what do you want to do in Arduino sketch while the key is pressed?

@Juraj I guess nothing aside from leaving the key pressed until it is released.

What do you mean?

sorry. I didn't know the press/release functions work for any key

Maybe there are some idiosyncrasies

Modifier keys are treated no different to normal keys.
The Arduino Keyboard library contains code to map different keys from the internal list of macros to specific keypresses:

If the key value is >= 138 it's a non-printing special key (subtract 138)
If the key value is >= 128 it is a modifier key (1 << (k - 128))
Otherwise look the code up in a mapping table.

That means you can use:
Keyboard.press(KEY_LEFT_SHIFT);

or
Keyboard.release(KEY_RIGHT_GUI);

The full list of modifier keys is:
#define KEY_LEFT_CTRL   0x80
#define KEY_LEFT_SHIFT    0x81
#define KEY_LEFT_ALT    0x82
#define KEY_LEFT_GUI    0x83
#define KEY_RIGHT_CTRL    0x84
#define KEY_RIGHT_SHIFT   0x85
#define KEY_RIGHT_ALT   0x86
#define KEY_RIGHT_GUI   0x87

So to do a capital A you can use:
Keyboard.press(KEY_LEFT_SHIFT);
Keyboard.press('a');
Keyboard.release('a');
Keyboard.release(KEY_LEFT_SHIFT);

There is also a shortcut, and that is:
Keyboard.press('A');
Keyboard.release('A');

The character 'A' is the same in the lookup table as character 'a' except the high bit of the result is set, which triggers a "Press or release the shift key" addition in the mapping code.
A USB keyboard report consists of 8 bytes:

Up to 8 modifier keys (bitmap)
One reserved byte
6 bytes to indicate pressed keys

This means that you can have up to 6 keys pressed at once, plus modifier keys. Never any more than that. So you don't need to handle any more than that in your code.
The current list of pressed keys is maintained by the keyboard and is sent in every report. There's no concept as such of "pressed" or "released" - only the list of what is currently pressed. If a key is released it's just removed from that list of pressed keys.
So what you need is some way of transferring that data in such a way that the Arduino can interpret it properly.
Since the data is not high throughput you can afford to be quite wasteful in your protocol.  I would suggest using a fairly verbose ASCII based protocol.

All the protocol data is using ASCII characters between 32 and 127 inclusive
This frees up control characters (<32) for controlling the protocol.

The simplest thing is to use a single control character (such as \n) to act as a line ending to break your data up into packets.  Each packet can then contain a list of instructions.
For example, you might choose to have a protocol that looks like:
P,129\n
P,97\n
R,97\n
R,129\n

By treating each line as a complete entity you know that you want to Press key 129 (#define KEY_LEFT_SHIFT    0x81), press key 97 ('a'), release 97, then release 129.
There's no confusion, since commands are all a single upper-case character, and keys are all a decimal number.
For your application, though, a "raw" access interface would be of more use, since you don't really want the Arduino interpreting things for you. However, the API doesn't provide that kind of thing.  So you just have to make the best of what you have and work around it.


text:
For Arduino Uno it is possible to use the digital pins with PWM to read analog data, is this also possible with the Wemos D1 Mini?
I want to read out data from a load cell, for this I seem to need 2 analog input pins, the Wemos doesn't have this. In the Arduino I was also able to use the digital pint with PWM, there are also Wemos pins who have that. Is it possible to use them to read the data from the load cell?

You need to clarify what are you talking about. How did you manage to use digital pins in Arduino Uno to read analog data? And what does PWM have to do with it?

PWM is quasi-analog output, and they have no symmetric analog read function.
The ESP8266 that is the heart of the Wemos D1 Mini has only 1 analog input.
If you need to read 2 analog signals, you can use an analog switch/multiplexer to read one value, and then the other value in quick succession. Or you can purchase an external ADC with multiple inputs -- these often communicate with a host by SPI or I2C connection, which the Wemos supports.

There is one way you could measure analogue voltages using a PWM output: Use it as a DAC to build your own Successive Approximation ADC:

The PWM is filtered through a low-pass filter to create an analogue voltage
That is compared to an incoming voltage using a comparator
The output of the comparator is recorded for different reference voltages using a "divide and conquer" method.

You can read more about how Successive Approximation works here.
However, doing that would be overly complex and needlessly expensive. It is far better to just add an ADC chip using I2C or SPI. It's cheaper, easier, and the results will be far superior.
But as a learning exercise to discover how ADCs work, it could be kind of fun.

You can use a capacitor and resistor to build a simple circuit to turn a voltage into a time duration, then precisely measure the timing to get a voltage. This isn't as fast as a direct read, but it can be more precise in some cases, and the sampling might be fast enough for your needs. The cost is great compared with external or home-brew ADCs.  I once used this method to build an ohmmeter with an ESP-01, which had a much greater range than a naive voltage divider would have provided.
You feed your voltage through a resistor into a capacitor, and have a digital input pin watching the resistor-cap voltage. You'll need to be generous with the timing because you want the cap to fully drain, and you can't tell from the MCU when that's completed, but a few preliminary DMM measurements will give you that info.
To measure voltage, you switch the GPIO from OUTPUT/low to to INPUT-PULLUP and wait for it to go HIGH. By measuring the time it takes before the pin goes high, you can calculate the voltage expected to fill the cap to the trigger threshold in that amount of time. You will need to do some manual measurements to calibrate it up-front, as different pins have different pull-up values and slightly different schmitt trigger voltage thresholds. Once setup, it can be repeatable to about +/- 5%, maybe more with slower sampling.
ascii schematic:
(vSensor) --- [R1] --- (GPIO) --- [C1]  --- GND


text:
How do I feed NRF24L01 from Arduino Pro Mini?

I wanted to control speed of my four coreless DC motors using Arduino Nano. Then I realised my 3.7V 380mAh 25C and 720mAh (110mAh on picture is just to hold my battery's place) 25C LiPo batteries won't meet the voltage requirement of a Nano. Then I came up with the idea of using Pro Mini instead of Nano; however I couldn't find a 3.3V pin on Pro Mini to feed NRF24. On Nano, I was using a 3.3V pin and 10uF capacitors between Vin and Gnd legs of NRF24.
So my question is: can I feed NRF24 directly from Vcc pin? Or as an alternative what would happen if I fed NRF24 directly from battery and reduce 3.7V to 3.3V via another TIP122 transistor?
Note: I am using 4 of TIP122 transistors whose gate legs are connected to Pro Mini's 5, 6, 9 and 10 pwm pins (I forgot to add base-resistors). Do you also think it is a reliable way of controlling the motors' speed?

can I feed NRF24 directly from Vcc pin?

NO: the pro mini is either 5V or not strong enough to power the RF24.
EDIT: the 3V3 pro mini "could" power the RF24 via VCC, if you use the cap and if it's not the PA&LNA model (or in full power mode). Best practise is to use an external regulator.

if I fed NRF24 directly from battery and reduce 3.7V to 3.3V via
  another TIP122 transistor?

NO: lipos are 4.2V when fully charged, and they can be used until 3V (I mean 3V sag voltage, when the load is powered, not when disconnected): External 3V3 regulators is the way to go.

Do you also think it is a reliable way of controlling the motors'
  speed?

These are PWM output, so yes, why not? Also, add flyback/freewheeling diodes (and -maybe- 100nF polyester caps should help) between the motors terminals.

Please consider that since the OP said "switch from nano to pro mini" he will be using the arduino board powered from a 3-4V source, rather than 5V. This means that connecting to the Vcc pin is ok, provided that the voltage is not greater than 3.6V (and as you explained LiPos go even higher than 4V). So if the pro mini is powered by a linerar/switching regulator to 3.3V, then Vcc can be used

@frarugi87: the pro mini only has 150mA MAX on VCC, as i said it's not a matter of voltage but current instead (assuming a 3V3 pro mini is used). The capacitor helps but stable performance can't be guaranteed with the VCC supply, especially with other devices connected to the pro mini. https://forum.mysensors.org/topic/3961/nrf24l01-pa-lna-power-consumption/23

your comment made me think that probably I misunderstood the OP intentions. For me, the best way to power the pro mini is to directly connect the Vcc to the battery input, bypassing the onboard regulator in the pro mini. But probably yes, the OP wanted to connect the battery to the RAW pin, and so the reply is "it depends". As long as a standard NRF24L01+ is used the current generated is ok, but if a high power board (NRF24L01+PA-LN) is used then the regulator is not enough

Connecting the Pro Mini straight to the power bus alongside motors can cause noise-related issues and sudden current draw due to motors being turned on can cause the MCU to reset. Some voltage stabilization is required, in addition to that, the nRF24L01+ is suspectible to noise, I can't imagine it working in such a setup without at least one mF of capacitance (half electrolytic and half ceramic to get rid of HF as well) attached to it.


text:
WebSocket message with Arduino MKR 1010 using WiFiNINA and ArduinoHttpClient libraries
I am trying to send a WebSocket message to a server. The example for the ArduinoHttpClient library uses WiFi101 but that will not work for the MKR 1010. So I am trying to use WifiNINA instead. The WiFi part works fine but is seems the WebSocket cannot "begin".
#include <SPI.h>
#include <WiFiNINA.h>
#include <ArduinoHttpClient.h> /*Need to implement*/
//https://github.com/arduino-libraries/ArduinoHttpClient/blob/master/examples/SimpleWebSocket/SimpleWebSocket.ino
//https://www.arduino.cc/en/Tutorial/WiFiNINAConnectWithWPA

char ssid[] = "SSID_NAME";        // your network SSID (name)
char pass[] = "WPA2_Password";    // your network password (use for WPA, or use as key for WEP)
int status = WL_IDLE_STATUS;     // the Wifi radio's status
char serverAddress[] = "192.168.0.195";  // server address
int port = 3652;

WiFiClient wifi;

WebSocketClient client = WebSocketClient(wifi, serverAddress, port);

void setup() {
  //Initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // check for the WiFi module:
  if (WiFi.status() == WL_NO_MODULE) {
    Serial.println("Communication with WiFi module failed!");
    // don't continue
    while (true);
  }

  String fv = WiFi.firmwareVersion();
  if (fv < "1.0.0") {
    Serial.println("Please upgrade the firmware");
  }

  // attempt to connect to Wifi network:
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network:
    status = WiFi.begin(ssid, pass);

    // wait 10 seconds for connection:
    delay(10000);
  }

  // you're connected now, so print out the data:
  Serial.print("You're connected to the network");
  printCurrentNet();
  printWifiData();

}

void loop() {
  // check the network connection once every 10 seconds:
  delay(10000);
  //printCurrentNet();

    Serial.println("starting WebSocket client");
    client.begin();
    Serial.print("Is client connected? -> ");
    Serial.println(client.connected());

      client.beginMessage(TYPE_TEXT);
      client.print("Fire alarm from arduino mkr1010 - sensor1 ");
      client.endMessage();

    while (client.connected()) {
      Serial.print("Sending fire alarm ");
      // send fire alarm
      client.beginMessage(TYPE_TEXT);
      client.print("Fire alarm from arduino mkr1010 - sensor1 ");
      client.endMessage();
    }
    /*
      // check if a message is available to be received
      int messageSize = client.parseMessage();

      if (messageSize > 0) {
        Serial.println("Received a message:");
        Serial.println(client.readString());
      }*/

}

void printWifiData() {
  // print your board's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);
  Serial.println(ip);
}

void printCurrentNet() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.println(rssi);

  // print the encryption type:
  byte encryption = WiFi.encryptionType();
  Serial.print("Encryption Type:");
  Serial.println(encryption, HEX);
  Serial.println();
}

Could it be that there are compatibility issues between the ArduinoHttpClient library and the Arduino MKR1010? I am thinking of getting an ESP32 instead since there seem to be more WebSocket libraries built around it.

doesn't firewall on server block the port?

Good point @Juraj, will have to look into it, there is a firewall

I needed to use port 80.
I got a hint from wikipedia:

The communications are done over TCP port number 80 (or 443 in the case of TLS-encrypted connections), which is of benefit for those environments which block non-web Internet connections using a firewall.

https://en.wikipedia.org/wiki/WebSocket
Switched to port 80 and it works!


text:
NodeMCU (ESP8266) board controlled over shared hosting database
I have a NodeMCU (ESP8266) board that I want to control over the internet. I am trying to find a solution where I don't have to set up any configurations on my router like port forwarding. I came up with the following solution:

I have a website where the user changes the device status (with status I mean for example GPIO5 pin value HIGH or LOW) which is then saved to a database on a shared hosting server. The NodeMCU sends periodically (for example every 5 seconds) a HTTP GET request to the database. According to the value that is received from the database the NodeMCU board changes the pin value to HIGH or LOW. If NodeMCU changes it's status (for example a pin value from HIGH to LOW) the new device status is sent to the database with a HTTP POST request. The device also sends a HTTP POST request periodically (for example every 60 seconds) so the user can monitor the device status on the website.
There are a few problems with this configuration:

There is no real-time connection between NodeMCU and the user (there
is always a delay in the device response)
The device sends thousand of queries every day that are a load to
the shared hosting server. For example if the GET request is sent
every 5 seconds, that gives 17280 queries per day for one device.

So my question is how practical is this configuration on shared hosting or any kind of hosting, what are the alternatives or improvements to this configuration and how to establish a connection with the NodeMCU so that the device sends a GET request to the database only when the device status is changed in the database by the user.

a HTTP request can wait until the server has something to send as a response

@Juraj please check out my question at stackoverflow https://stackoverflow.com/questions/55932766/postpone-http-get-response-until-the-user-changes-the-value-in-the-database

you can check if the client is still connected and if not, send the request again. but I don't know how to handle the php side

just use websockets; a 2-way always-connected low-overhead protocol supported by webserver platforms and ESPs. You could also use server-sent events, which almost any php box can support, and for which you can semi-easily mod the existing ESP libs to handle.

@dandavis can I use websockets without the need to configure my router (for example setting port forwarding)

websockets works without adjusting any router settings.

@dandavis I tried to use websockets but I had some difficulties on finding an example (how to install a websocket server on a shared hosting server) on the internet. Do you know where I can find an example where the websocket server is on a shared hosting server and the websocket client is an ESP8266

you probably can't do it on a shared server, you would have to use SSE, a light modification of normal HTTP.

Use MQTT.
You need:

The PubSubClient.h library
An MQTT server

For MQTT there are some free ones around on the internet (ask Google). Or if you have a Linux server available for use (e.g., a cheap VPS server from one of many many providers online) then you can run your own with mosquitto.
MQTT works kind of how you describe, but it's not making constant GET requests - it opens a single connection to the MQTT server and realtime requests are sent down it to the client, and back from the client to the server.
Near realtime communication.


text:
HC-05 connecting to Arduino
I have been looking through StackExchange, and searching on the web and cannot find an answer to my issue.
Setup:
Arduino Nano 168
HC-05 VERSION:3.0-20170601
I am trying to connect my Android phone to my Nano to control an output. I have found tons of varying examples, but they all basically boil down to MIT App Inventor to create app to connect via BT and send data to the Nano to control.
After many attempts with no results, I attempted the following:

#include <SoftwareSerial.h>

int light=8;
int Received=0;
int light_state =0;

SoftwareSerial BTSerial(10, 11); // RX | TX

void setup(){

  Serial.begin(38400);
  pinMode(light,OUTPUT);
  BTSerial.begin(38400);

}

void loop(){
  // Keep reading from HC-05 and send to Arduino Serial Monitor
  if (BTSerial.available()) {
    Serial.write(BTSerial.read());
 }

 if(BTSerial.available()>0) {
    Received = BTSerial.read();
 }

if (light_state == 0 && Received == '1') {
    digitalWrite(light,HIGH);
    light_state=1;
    Received=0;
  }
if (light_state ==1 && Received == '1') {
    digitalWrite(light,LOW);
    light_state=0;
    Received=0;
  }
}

So, when I run the MIT app on my phone to connect to the HC-05 the status LED on the HC-05 changes.  Before I connect, the status LED flashes fast.  After I connect, it flashes slow.
I have the serial monitor open on my laptop monitoring the Nano.  The HC-05 connects via pins 10 & 11.  When the phone connects to the HC-05, the data printed on the serial monitor is garbage.
⸮x⸮x⸮⸮x⸮x⸮x⸮⸮xxxxxx⸮x⸮⸮xx⸮⸮xxx⸮⸮
That is what I get.
The app is set to transmit a "1" via BT to the Nano.  When I press the button to send the 1, no data comes across.  But every time I pick the HC-05 and tell the app to connect to the unit, I get that same string of data above.
Thank you in advance for your help.

Seems, that you have a mismatching baud rate. Is the HC-05 really set to 38400 baud? You can try other baudrates to test

I forgot to mention, if I can access the HC-05 and run AT commands to read settings from the HC-05.

@chrisl I checked the baud rate on the HC-05 via the AT commands, but I will double check it tonight.
On the serial monitor, I checked every baud rate, but that was just between the Nano and the laptop.

@chrisl, I checked the settings.  I used AT+UART? and it returned 9600, 0, 0.  I have reset it to 34800, 1, 0.  I looked up the default settings for the Arduino Nano, and it said default is an 8bit word, 1 stop bit, and 0 parity bits.  So I made sure to match this setup.  I will test again shortly.

After getting the rate and bits correct, I do get data through the port.
However, all I get is:  +DISC:SUCCESS

where do you get this?

@chrisl, I got the units from ebay.  However, I have found out that my hardware and Nano code is correct (I setup a software serial port and used a BT terminal program on my phone to send data from the phone to the HC-05 on the software port on the nano, then the nano dumps the data to the hardware serial port to my serial monitor on my laptop).  My issue lies in my App Inventor code somewhere.  That is where I am working on now.

You should add the correct answer and close this question.And then ask another question regarding your app.

This issue has been resolved.  There was an issue with the parity and stop bits.
When setting up for arduino comms, remember, baud rate, 1 stop bit, 0 parity bits.


text:
Output pin low used to complete 12V LED circuit?
I have a project that (in part) will drive 3 LEDs where the LED
anodes are at 12V.  The thought is to drive each LED by connecting
each cathode to a 650 ohm resistor, and connect that to an Arduino DIO pin which, when needed, is set to output LOW.  Arduino VIN = same 12V with
common ground.  Am I going to have an Arduino problem of any sort?

Why would you want to do that?  Do you want to switch the LED on/off by changing the digital HIGH/LOW state of the Arduino pin?  If so, no, that will not work.  Depending on the power consumption of the LEDs you could (i) low power, drive directly from the Arduino like in the Blink example, (ii) high power, drive via the same code but with a transistor in between the IO pin and LED.

That doesn't work. When you set the pin to output LOW, then leds will be on (like you want). But if you set the pin to output HIGH, the voltage is 5V, so there is still 7V (12V - 5V) across the leds, and the leds will light up dimly. If you set the pin to input, the voltage at the pin will become around 12V, which exceeds the allowed voltage. The clamping diodes inside the MCU will clamp the voltage to around 5V, so the leds will still be on, dimly, and the internal clamping diodes will die from overheating, potentially destroying the the entire MCU.

The detailed Gerben explanation is the WHY my approach will not work.  Thanx.

No, what you propose will not work. And it risks damaging your Arduino.
Normally you would include a single transistor which the Arduino uses to control the power through the LEDs. This removes the 12V from the Arduino and turns the output into an actual switch.
The problem is that the Arduino's GPIO isn't just a single transistor.  It is (amomgst other things):

Two complimentary transistors (that's the C in CMOS) for HIGH and LOW switches
ESD Diodes
Input buffer

By just adding the one transistor like this:

simulate this circuit – Schematic created using CircuitLab
the 12V is kept well away from the Arduino. Setting the output HIGH will turn on the transistor, allowing the current to flow to ground. Setting it LOW with turn it off, blocking the flow of current and switching the LEDs off.
Further: the Arduino's GPIO has a maximum sustained current of 25mA. Ideally you don't want to even come anywhere near this. By adding the transistor it acts as a buffer and allows you to deal with much higher currents - and hence more, and brighter, LEDs.
Incidentally, R1 in that schematic is there solely to keep the transistor off when the Arduino is not actively driving the output - e.g., when it's either unpowered or is running the bootloader - or you happen to have the GPIO in INPUT mode (as it defaults to).

Thank you.  I am aware of the transistor approach, altho I had not considered the addition of R1 and using a mosfet.  Each Arduino output will be driving only one LED.  My original post was motivated by a desire to minimize the component count needed to drive each LED...and to have a better understanding of Arduino I/O limitations.


text:
Arduino Mega - Enabling CTC mode disables timer
I'm trying to use timer3 on an Arduino Mega 2560 in CTC mode. However, enabling CTC disables the code entirely.
Here is the function I call in setup() to setup the times.
void SetupInterrerupt() {
  cli(); // Disable interrupts

  // Setup timer
  TCCR3A = 0;     // set entire TCCR3A register to 0
  TCCR3B = 0;     // same for TCCR3B

  // Setup compare match register
  OCR3B =  CMP_FAST; // CMP_FAST = 40

  // turn on CTC mode:
  TCCR3B |= (1 << WGM32); // Commenting out this line makes the code work
  // Set CS10 and CS12 bits for 1024 prescaler:
  TCCR3B |= (1 << CS30) | (1 << CS32);
  // enable timer compare interrupt:
  TIMSK3 |= (1 << OCIE3B);

  sei(); // Enable interrupts

  Serial.println("Timers enabled");
}

And the interrupt vector.
// Timer 3 Interrupt
ISR(TIMER3_COMPB_vect){//timer1 interrupt 1Hz toggles pin 13 (LED)
  // do stuff...
}

As is, the interrupt doesn't execute at all. As noted in the code, commenting out "TCCR3B |= (1 << WGM32);" actually executes the interrupt, except the frequency is more like 1Hz instead of 720.
I'm using the arduino-lmic library, as well as some other data structure libraries. I don't think they use any timers, but since lmic is designed for Uno's, I figured that using timers 3 and up would be fine.
I'm a little rusty on my timers unfortunately. Is anyone able to spot my mistake?
Thanks.

I think your problem is that you are using the wrong "TOP" counter value register.
OCR3B =  CMP_FAST; // CMP_FAST = 40

should be:
OCR3A =  CMP_FAST; // CMP_FAST = 40

I am not too familiar with the workings of the AVR times, but according to the datasheet:

In Clear Timer on Compare or CTC mode (WGM22:0 = 2), the OCR2A Register is used to manipulate the counter resolution. In CTC mode the counter is cleared to zero when the counter value (TCNT2) matches the OCR2A. The OCR2A defines the top value for the counter, hence also its resolution.

(Note: it only mentions the register for timer 2, but the same holds true for all the timers in the same class, including timer 3).
Since OCR3A is zero it never triggers a match.  And since there is only one counter (TCNT3) which gets reset to 0 on a match, there can only be one register to compare to, and that is the "A" register. The "B" register appears to be redundant in CTC mode.
You may also need to switch to the COMPA vector (I am not sure on this one TBH)

Thanks for the response! Unfortunately, that didn't seem to work. Switching from OCR3B to OCR3A doesn't change the behavior. Switching to the COMPA vector causes the Arduino to reboot continuously (I suspect whenever the interrupt occurs).
Enabling TCCR3B |= (1 << WGM32); simply disables the timer again.
I think I've also tried using timers 0-2, to no avail.

Maybe you should switch to using a library to manage it for you instead. I'm sure there's some variation on the TimerOne library for Timer 3.

Besides changing OCR3B to OCR3A, you also need to change OCIE3B to OCIE3A, and TIMER3_COMPB_vect to TIMER3_COMPA_vect.


text:
SR505 PIR sensor Time Delay Using Ticker Library NodeMCU
I am trying to make the value of PIR sensor value HIGH for certain time using code. SR505 have a default time delay of 8 seconds. But I want to increase it to 20 seconds.
I am thinking of increasing it using TICKER library. I have tried and tested a basic code and seems to be working fine. But I want to implement it with Ticker which will keep the value HIGH for 20 seconds as soon as the timer goes above 20 seconds and PIR is not detecting the motion then it will go set again the timer to 0.
Here is how my code looks like:
#include <Ticker.h>

#define SIGNAL_PIN D2

Ticker flipper;

void setup()
{
  Serial.begin(9600);
  pinMode(SIGNAL_PIN, INPUT);
  digitalWrite (SIGNAL_PIN, LOW);

}

void flip(){
  Serial.println("From callback");
  digitalWrite (SIGNAL_PIN, HIGH);
}

void loop() {
  if(digitalRead(SIGNAL_PIN)==HIGH) {
    Serial.println("Movement detected.");
    flipper.attach(1, flip);
  } else {
    Serial.println("Did not detect movement.");
    flipper.detach();
  }
  delay(1000);
}

Thank you!

Why do you feel the need to use the Ticker library? There is absolutely no need. All you need is a millis() timestamp.

Ok but I never used millis() before. How that work I will just check. If you have any example based on the same scenarios that will be amazing.

I'm writing one for you as we speak.

You really don't need the Ticker library. Just maintain a timestamp of the last time the PIR was seen to be HIGH:
void loop() {
    static uint32_t lastSeenHigh = millis();
    static bool pirState = false;

    // If it's active then record that fact along with the time
    if (digitalRead(SIGNAL_PIN) == HIGH) {
        lastSeenHigh = millis();
        pirState = true;
    } else {
        // otherwise, if it's been 12 seconds since last seen
        // active, record that it's inactive.
        // 20 seconds, minus the 8 second active time, times 1000 is
        // 12000 milliseconds to extend the time by
        if ((millis() - lastSeenHigh) > 12000) {
            pirState = false;
        }
    }

    if (pirState == true) {
        // Do whatever you want in here when the PIR is active
    }
}

With that (untested) code:

Any time the PIR is active the current time is recorded and the state is set true
When the PIR is LOW and at least 12 seconds have passed since the last activation, set the state to false.

Thank you so much, its amazing its working great! No library needed.


text:
ESP8266 print DNS address (obtained via DHCP)
I've set up an ESP8266 (Wemos D1 Mini) to get IP-information via DHCP.
Everything works fine and I can print the information :
Serial.print(WiFi.macAddress());
Serial.print(WiFI.localIP());
Serial.print(WiFi.subnetMask());
Serial.print(WiFi.gateway.IP());
But how do I print the DNS-address ??
I cant find a function for this ???
/Kind regards : Gurra

https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/station-class.html#dnsip

Serial.println(WiFi.dnsIP());

If you have more than one DNS server you can specify the index:
Serial.println(WiFi.dnsIP(1));

Thanks Majenko, i've Googled this question and found answers to ip, netmask, mac & gateway but not DNS, so you saved me hours of extra work by this....So I am very grateful !!

You're welcome. You can find all the functions in the ESP8266WiFiSTA.h header file.


text:
Arduino stopped working: avrdude: ser_open(): can't set com-state
I'm playing with my first Arduino device (Arduino Leonardo). It worked fine but at some point it failed. I'm getting this error:

avrdude: ser_open(): can't set com-state for "\.\COM6"
An error occurred while uploading the sketch

The error came out of nowhere because I didn't change the port or cable or anything. Everything seems to be in order: the port, the driver, the IDE, the cable. And everything worked just an hour ago.
1) I've tried to change the port
2) I've reinstalled IDE
3) I've tried different cable
What else can I do?
And another thing: after manual reset of Arduino (with button) device disappears.

The thing to remember with the Leonardo and other ATMega32U4 based boards is that there is no actual serial connection.
What there is, is a USB connection which is controlled by the sketch (and independently by the bootloader) to provide a "CDC/ACM" connection over USB.  This emulates a serial connection, but it's not a real serial connection.
This actually has a huge number of benefits, because you can be other things besides a serial port, such as a keyboard or a mouse. However, it comes at a cost:  the serial port is at the mercy of the sketch that's running at the time.
If your sketch crashes for any reason then the serial port can no longer be used. That's bad. It can cripple your Arduino. Since it's the sketch that is providing the driving force for the CDC/ACM serial emulation, if that sketch dies, so does the control of the USB and thus the CDC/ACM.
So while the port may be created initially by the sketch, if it then subsequently crashes the port is still there, but unresponsive.  Or the port can vanish completely.
So how do you fix it?  Well, there's a couple of strategies:

Some people have had success by pressing the RESET button twice in quick succession. This depends on the version of the bootloader in use though, and it's not something I have ever tried.
Pressing RESET at just the right moment to get the bootloader to run just before avrdude runs and catch it at the right time to accept a new sketch, or
Using a hardware programmer (e.g., USBASP) or another Arduino to wipe the chip and reinstall the bootloader

My preferred method is 3, since it is certain to always work - however it requires either a hardware programmer or another Arduino. However you can pick up a USBASP on eBay / AliExpress / Amazon etc for next to nothing, and when you're working with AVR chips they're always good to have to get you out of tight spots like this.

thanks a lot. That make total sense.