message:
Encoder coupled with motor shaft.Encoder is giving larger redings than expected

I am a rookie and i dont have much experience on arduino. please help me.
I intend to build a robot that will drive on a straight path even on nonuniform surfaces like the ones we see in agricultural fields(It is just a prototype, so i want to run it on normal offroad surfaces).The robot has 4 motors, one for each wheel. I plan to use encoder feedback method to drive straight.
Right now, I have coupled a slotted disc to the shaft of a dc motor and i am trying to get the counts from the encoder and display the count after a certain interval(5 seconds) on serial monitor. The count that i get is way off the mark. The disc is having 30 slots. With just 2 to 3 rotations I am getting a count of around 180.

I am using arduino R3.
Encoder output:- Pin2 (external interrupt)
motor Pins :- 8,9
I am attaching the code below.

    const int motorPin1  = 8;  // Pin 14 of L293
    const int motorPin2  = 9;  // Pin 10 of L293
    const int encoder_pin = 2;
    volatile unsigned int count = 0;
     int time1 = 0;
     int time2 = 0;
    void setup() {
      // put your setup code here, to run once:
      pinMode(motorPin1, OUTPUT);
        pinMode(motorPin2, OUTPUT);
        pinMode(encoder_pin,INPUT);
        digitalWrite(encoder_pin,HIGH);
        attachInterrupt(0,encoder,RISING);
        Serial.begin(9600);
         digitalWrite(motorPin1,HIGH);
        digitalWrite(motorPin2,LOW);
        time1 = millis();
    }

    void loop() {
      // put your main code here, to run repeatedly:
        time2 = millis();
        if(abs((time2 - time1) > 5000))
        {
        digitalWrite(motorPin1,LOW);
        digitalWrite(motorPin2,LOW);
        Serial.println(count);
        }
    }

     void encoder()
     {
      count++;

     }

the end of code

The disc that i have mounted on the shaft doesn't rotate in vertical plane exactly. But i do get the blinks on the encoder when i rotate the shaft with my hand.Can that misalignment be the reason.

body:
I guess this is a kind of debouncing problem, caused by noise on the interrupt pin. The behaviour might also get worsened by the disalignment you mentioned. You could verify this by manually rotating the shaft, even though you "get the blinks" I doubt they are accurate in count.

If that is the case there are two things you could do:

 - add a capacity or a RC filter to the interrupt pin to smoothen out voltage peaks if there are some. This will decrease the chance that the interrupt gets triggered accidentially (and will **not** solve the problem), but as a low pass it also limits the maximum count rate you are able to detect.
 - implement debouncing in software. This is usually done by ignoring the input signal for a specific amount of time ("deadtime") after an interrupt has occured. As you are expecting a periodic signal and debouncing behaviour might be different at different speed it could be a good idea to capture the time span between two "blinks" and make the deadtime dependend on this calculated speed.

Something else: the way you check for the timestamp is little incorrect. You should instead do something like this:

    void setup() {
      unsigned long starttime=millis();
    }

    void loop() {
      if (millis()-starttime > 5000) {
        starttime=millis();
        // put code here to run every 5000 ms
      }
    }


sender: user

sender: assistant

body:
Usually a rotary encoder has at least 2 sensors.

Incremental rotary encoders usually only have 2 sensors. Absolute or positional encoders have more, and let you figure out the absolute orientation of your sensor by reading a bit pattern.

To read an incremental encoder you write your code to only pay attention to alternating changes in the sensors. That gives you automatic debouncing of the contacts. I suggest you search for Arduino code for decoding rotary encoders.


message:
VirtualWire `vw_get_message`: docs and examples on the PJRC site

I'm looking at he following page, that describes functions from VirtualWire library and provides some examples.

https://www.pjrc.com/teensy/td_libs_VirtualWire.html

Some basic questions I have after reading it:

1. The description of `vw_get_message` function states.

 > Read the last received message. This should be called only when a message is known to be received with any of the 3 functions above.

 "3 functions above" refers to `vw_have_message`, `vw_wait_rx` and `vw_wait_rx_max` functions.

 However, in the example on that very same page `vw_get_message` function is called from receiver's `loop()` without making any attempts to call any of those 3 functions first.

 Why? Is it legal to use `vw_get_message` by itself? And how does it work in this case, i.e. what is the semantics of the return value?

 The function is explicitly described as non-blocking, apparently implying that if this usage is legal, there's no way to tell "corrupted message" situation from "no message" situation.

2. Does the library preserve the granularity/separation of messages? I.e if the TX side sends 1-byte messages, does it guarantee that each call to `vw_get_message` on RX side will return 1-byte messages? It seems to be implied by the description of the protocol, but I'd like to ask just in case.

3. If the answer to the second question is "yes", then does this API preserve zero-length messages? Or are they discarded immediately?

body:
1. The example with only `vw_get_message` is the common usage of the VirtualWire library. It returns `true` if something was received and the checksum was okay.

2. Yes, each message is seperated from the other messages. Each message gets extra bits (intro bits) and extra bytes (checksum and length).

3. I don't know, I have never tested that. Looking at the source code, there is no problem with zero length messages.

The VirtualWire library is outdated, although it is still used with Arduino boards with little memory (Arduino Uno, Nano, Leonardo, Pro Mini, and so on).
The RadioHead library ([www.airspayce.com/mikem/arduino/RadioHead][1]) has included the VirtualWire protocol with the RH_ASK mode. The examples for the RH_ASK mode shows that the usage is almost the same. The RadioHead library should be used when there is more memory (Arduino MKR, Zero, Due, and so on).

  [1]: https://www.airspayce.com/mikem/arduino/RadioHead/


message:
About UART one transmitter multiple receivers

I have vector nav vn100 IMU that sends data serially rs232...I want to drive 4 servo motors using atmega32 upon roll angel from vector nav vn100..atmega32 can only drive 2 servos using hardware fast pwm mode 14...so I should to use two atmega32...so I should receive the vn100 message to the two atmega32...my question is ..does UART rs323 support one transmitter multiple receivers?

body:
If you do not need the control lines, and the communication is only one
way, then yes, you can connect the TX (transmit) of the IMU to the RX
(receive) of both microcontrollers. On the other hand, connecting one RX
to multiple TX is likely to burn something.

Note however that the ATmega MCUs do not support RS-232 communication.
If you want to go this way, you will then have to attach an RS-232
transceiver to each MCU. If the distances are short (say, a few
centimeters), I would recommend using “serial TTL” instead.


message:
Is there any limitation with Arduino Nano serial communication distance?

I am trying to build Project which communicate multiple Arduino Nanos. I wanted to understand if Arudino Nano is capable of doing that, while doing research I came across post where it says communication with nano can be done up to 2-3 meter, where as my goal is up to 30 meter.

Project - I am trying intercom system, I have 4 Ring button at main gate, when user press any one of those 4 the Arduino will understand it and send to one of the 4 Arduino sitting at other place. Each Arduino will read that message if its for them they will perform activity if not they will skip it.

My problem is I am in selection mode and want know if Arduino Nano can handle that, communication is not that complex. It will be just sending 2/3 value max during communication. As I saw post of distance limitation, I just want get inputs from community. If you have any similar examples of serial communication between multiple Arduino Nano please let me know, I found several but it might save my time if I find something more similar.

body:
For that sort of difference you are better using RS-485 instead of UART.  UART is really only designed for short-distance communication.

Converting UART to RS-232 will give an improvement, but switching to RS-485 instead will give you the ability to create a multi-drop bus for connecting more than two Arduinos together over a long distance.

* UART uses 5V logic level signalling (on the normal Arduinos - 3.3V on most 32-bit boards). It has a "weak drive" and is highly susceptible to induced noise over longer distances.
* RS-232 uses ±10V "Non Return to Zero" signalling. This gives far greater immunity to noise and a stronger drive for greater distances.
* RS-485 (and the associated peer-to-peer RS-422) use *differential* signalling. This gives the greatest immunity to noise over the longest distances.

In summary:

* RS-232 can be used if you only want to connect two devices together in a low noise environment.
* RS-422 can be used to connect two devices together in a high noise (industrial) environment.
* RS-485 can be used to connect lots of devices together in a high noise environment.

For more information on how they work there are some good Wikipedia pages:

* [RS-232](https://en.wikipedia.org/wiki/RS-232)
* [RS-422](https://en.wikipedia.org/wiki/RS-422)
* [RS-485](https://en.wikipedia.org/wiki/RS-485)

For interfacing any of these to an Arduino you will need extra hardware ("Driver Chips"). For example:

* RS-232: [MAX232](https://www.maximintegrated.com/en/products/interface/transceivers/MAX232.html)
* RS-422: [MAX1184](https://www.maximintegrated.com/en/products/interface/transceivers/MAX1484.html)
* RS-485: [MAX485](https://www.maximintegrated.com/en/products/interface/transceivers/MAX485.html)

----

There is also "CAN", which is a more modern replacement for RS-485 and is used in many industrial and automotive environments. As this is a newer technology than RS-485 there are fewer resources available and "initial cost to entry" can be higher.


body:
Roughly speaking, for a given protocol and medium (cable) the data rate and the distance are inversely related, that is, a connection with half the data rate can work across twice the distance. You will eventually hit the hard limit when the total capacitance of the cable will become too much for the driver.

RS-232 standard provides this table of maximum cable lengths for standard shielded cables:

    Data rate (bps) Distance (m)
    2400            60
    4800            30
    9600            15
    19200           7.6
    38400           3.7
    56000           2.6

So, 30 meters can be easily achieved even with RS-232, if you don't mind the 4800 bps baudrate. Even longer distances (or higher baudrates) can be achieved by running RS-232 over a twisted pair, e.g. a UTP 5 cable: these cables have lower capacitance and can run at 9600 bps over 100 m or more.

There are other protocols suitable for long-distance communication. There are Arduino shields for CAN, RS-485 and even Ethernet.


body: Hi please have a look at Nick Gammon's website as he does an Arduino libary for RS485 using cheap driver modules. In particular the non blocking example may well fit your needs.  The library also works for ESP8266 and ESP32 modules under the Arduino IDE.


message:
Can't connect to my ESP32 board via serial

I'm completely new to electronics work.

Today I've received the ESP32 board that I ordered. (It's a WROOM-32.) I followed the instructions [here](https://startingelectronics.org/articles/ESP32-WROOM-testing/). I connected the board to my computer via USB and I successfully installed the CP210x drivers and got a new serial port COM3, but when I tried to connect to the board with that serial port, I got nothing. I'm on Windows 7.

I tried with Tera Term, and it just shows an empty screen.

I tried `type COM3` in the shell, but got an empty string.

I tried doing `esptool.exe --chip esp32 -p com3 erase_flash`, but I get "Failed to connect to ESP32: Timed out waiting for packet header".

I tried playing with the two buttons on the WROOM32 board, but that didn't help.

Any idea what I'm doing wrong? I'm a complete newbie so it's likely that I'm forgetting something basic.

body:
The issue is that the Serial port on the ESP32-WROOM setup is not like like on the Arduino. It seems that the initialisation will 'miss' the USB enumeration after reboot.

To fix this add a delay in your setup() function of 10 to 15-seconds before initialising the serial.

For example:

    void setup() {
      delay(10000);
      Serial.begin(115200);

      Serial.println("Setting up Access Point...");
      .
      .
      .


message:
Working with Wire core library

I'm studying the Wire library code driver `utility/twi.h` to learn how twi buffering and ISR management work.

What I did actually, is that I copied the header/source files from the Arduino path `F:\Program Files\Arduino\hardware\arduino\avr\libraries\Wire\src\utility` and put them in the Arduino custom libraries and changed the `.c` to `.cpp` and it worked.

I actually ran through different i2c libraries for avr and this code library is one of the best IMHO.

My test code is to initialize the HMC5883L, and read back those configuration setting from the first SFRs of the HMC5883L.

I'm using Serial.prints inside/outside the ISR to debug my coding. It is working pretty much OK. I'm not sure if this could cause some problems.

But, because I don't have a complete understanding of how twi works, I'm trying to understand things now as displaying the content that is going in the ISR.

I think the initialize is working ok, but the read procedure may not as it should be.

Here's my code, for application code in the Arduino IDE, and the code in the library.

Arduino IDE code:

    #include "twi.h"
    ////////////////////////////////////////////////////////////////////////////
    // HMC5883L
    #define HMC5883L                    0x1E
    #define CONFIG_REG_A                0x00  //Read/Write
    #define CONFIG_REG_B                0x01  //Read/Write
    #define MODE_REGISTER               0x02  //Read/Write
    #define DATA_OUTPUT_X_MSB_REGISTER  0x03  //Read
    #define DATA_OUTPUT_X_LSB_REGISTER  0x04  //Read
    #define DATA_OUTPUT_Z_MSB_REGISTER  0x05  //Read
    #define DATA_OUTPUT_Z_LSB_REGISTER  0x06  //Read
    #define DATA_OUTPUT_Y_MSB_REGISTER  0x07  //Read
    #define DATA_OUTPUT_Y_LSB_REGISTER  0x08  //Read
    #define STATUS_REGISTER             0x09  //Read
    #define IDENTIFICATION_REGISTER_A   0x10  //Read
    #define IDENTIFICATION_REGISTER_B   0x11  //Read
    #define IDENTIFICATION_REGISTER_C   0x12  //Read
    #define DECLINATION_ANGLE 3.46

    void hmc5883l_init(void);
    void init_read(void);
    void hmc5883l_print_serial(void);

    void setup() {
      Serial.begin(9600);
      twi_init();
      hmc5883l_init();
      init_read();
    }

    void loop() {
      hmc5883l_print_serial();
    }

    void hmc5883l_init(void){
      uint8_t err,HMC5883L_ini[] = {CONFIG_REG_A,0x78,0x20,0x00};//
        err = twi_writeTo(HMC5883L,HMC5883L_ini,4,1,1);
        if(err != 0){Serial.print("error of init is");Serial.println(err);}
        Serial.println();
    }

    void init_read(void){
        uint8_t err,len,dat[3];
        err = twi_writeTo(HMC5883L,0x00,1,0,1);
        if(err != 0){Serial.print("error of init is");Serial.println(err);}
        Serial.println();

        len = twi_readFrom(HMC5883L,dat,3,1);
        Serial.print("length of read op:              ");
        Serial.println(len);
        Serial.println();

        Serial.print("config settings:                ");
        Serial.print(dat[0],HEX);Serial.print("\t");
        Serial.print(dat[1],HEX);Serial.print("\t");
        Serial.println(dat[2],HEX);
    }

    void hmc5883l_print_serial(void){
      int16_t x,z,y;
      uint8_t data[6],len,err, dst_reg[] = {0x03};
      float heading,heading_in_degrees,declination_angle_YANBU;

      err = twi_writeTo(HMC5883L,dst_reg,1,0,1);
      if(err != 0){Serial.print("error of init is");Serial.println(err);}
      Serial.println();

      len = twi_readFrom(HMC5883L,data,6,1);
      Serial.print("len is: ");Serial.println(len);
      x = data[0] << 8 | data[1];
      z = data[2] << 8 | data[3];
      y = data[4] << 8 | data[5];

      heading = atan2(y,x);
      declination_angle_YANBU = ((3.0 + (52.0 / 60.0)) / (180 / M_PI));  // in yanbu city it's
      heading += declination_angle_YANBU;

      if (heading < 0){heading += 2 * PI;}
      if (heading > 2 * PI){heading -= 2 * PI;}

      heading_in_degrees = heading * 180 / M_PI;
      Serial.println(heading_in_degrees);

      //Serial.print("x-axis\t");Serial.print("z-axis\t");Serial.println("y-axis");
      Serial.print(x);Serial.print("\t");
      Serial.print(z);Serial.print("\t");
      Serial.println(y);
    }

And this is the core library:

In this part, I've put Serial.prints inside the ISR cases to display what's going from the start of the tx/rx buffers. Also, I've cut the slave half of the code because it's not necessary in this problem, as I'm only dealing with HMC5883L as a slave and I'm the master.

 #include <math.h>
 #include <stdlib.h>
 #include <inttypes.h>
 #include <avr/io.h>
 #include <avr/interrupt.h>
 #include <compat/twi.h>
 #include "Arduino.h" // for digitalWrite

 #ifndef cbi
 #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
 #endif

 #ifndef sbi
 #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
 #endif

 #include "pins_arduino.h"
 #include "twi.h"

 static volatile uint8_t twi_state;
 static volatile uint8_t twi_slarw;
 static volatile uint8_t twi_sendStop;   // should the transaction end with a stop
 static volatile uint8_t twi_inRepStart;   // in the middle of a repeated start

 static void (*twi_onSlaveTransmit)(void);
 static void (*twi_onSlaveReceive)(uint8_t*, int);

 static uint8_t twi_masterBuffer[TWI_BUFFER_LENGTH];
 static volatile uint8_t twi_masterBufferIndex;
 static volatile uint8_t twi_masterBufferLength;

 static uint8_t twi_txBuffer[TWI_BUFFER_LENGTH];
 static volatile uint8_t twi_txBufferIndex;
 static volatile uint8_t twi_txBufferLength;

 static uint8_t twi_rxBuffer[TWI_BUFFER_LENGTH];
 static volatile uint8_t twi_rxBufferIndex;

 static volatile uint8_t twi_error;

 void twi_init(void)
 {
   // initialize state
   twi_state = TWI_READY;
   twi_sendStop = true;  // default value
   twi_inRepStart = false;

   // activate internal pullups for twi.
   digitalWrite(SDA, 1);
   digitalWrite(SCL, 1);

   // initialize twi prescaler and bit rate
   cbi(TWSR, TWPS0);
   cbi(TWSR, TWPS1);
   TWBR = ((F_CPU / TWI_FREQ) - 16) / 2;

   // enable twi module, acks, and twi interrupt
   TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA);
 }

 void twi_disable(void)
 {
   // disable twi module, acks, and twi interrupt
   TWCR &= ~(_BV(TWEN) | _BV(TWIE) | _BV(TWEA));

   // deactivate internal pullups for twi.
   digitalWrite(SDA, 0);
   digitalWrite(SCL, 0);
 }

 uint8_t twi_readFrom(uint8_t address, uint8_t* data, uint8_t length, uint8_t sendStop)
 {
   uint8_t i;

   // ensure data will fit into buffer
   if(TWI_BUFFER_LENGTH < length){
  return 0;
   }

   // wait until twi is ready, become master receiver
   while(TWI_READY != twi_state){
  continue;
   }
   twi_state = TWI_MRX;
   twi_sendStop = sendStop;
   // reset error state (0xFF.. no error occured)
   twi_error = 0xFF;

   // initialize buffer iteration vars
   twi_masterBufferIndex = 0;
   twi_masterBufferLength = length-1;  // This is not intuitive, read on...

   twi_slarw = TW_READ;
   twi_slarw |= address << 1;

   if (true == twi_inRepStart) {
  twi_inRepStart = false;   // remember, we're dealing with an ASYNC ISR
  do {
    TWDR = twi_slarw;
  } while(TWCR & _BV(TWWC));
  TWCR = _BV(TWINT) | _BV(TWEA) | _BV(TWEN) | _BV(TWIE); // enable INTs, but not START
   }
   else
  // send start condition
  TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA) | _BV(TWINT) | _BV(TWSTA);

   // wait for read operation to complete
   while(TWI_MRX == twi_state){
  continue;
   }

   if (twi_masterBufferIndex < length)
  length = twi_masterBufferIndex;

   // copy twi buffer to data
   for(i = 0; i < length; ++i){
  data[i] = twi_masterBuffer[i];
   }

   return length;
 }

 uint8_t twi_writeTo(uint8_t address, uint8_t* data, uint8_t length, uint8_t wait, uint8_t sendStop)
 {
   uint8_t i;

   // ensure data will fit into buffer
   if(TWI_BUFFER_LENGTH < length){
  return 1;
   }

   // wait until twi is ready, become master transmitter
   while(TWI_READY != twi_state){
  continue;
   }
   twi_state = TWI_MTX;
   twi_sendStop = sendStop;
   // reset error state (0xFF.. no error occured)
   twi_error = 0xFF;

   // initialize buffer iteration vars
   twi_masterBufferIndex = 0;
   twi_masterBufferLength = length;

   // copy data to twi buffer
   for(i = 0; i < length; ++i){
  twi_masterBuffer[i] = data[i];
   }

   // build sla+w, slave device address + w bit
   twi_slarw = TW_WRITE;
   twi_slarw |= address << 1;

   // if we're in a repeated start, then we've already sent the START
   // in the ISR. Don't do it again.
   //
   if (true == twi_inRepStart) {
  // if we're in the repeated start state, then we've already sent the start,
  // (@@@ we hope), and the TWI statemachine is just waiting for the address byte.
  // We need to remove ourselves from the repeated start state before we enable interrupts,
  // since the ISR is ASYNC, and we could get confused if we hit the ISR before cleaning
  // up. Also, don't enable the START interrupt. There may be one pending from the
  // repeated start that we sent outselves, and that would really confuse things.
  twi_inRepStart = false;   // remember, we're dealing with an ASYNC ISR
  do {
    TWDR = twi_slarw;
  } while(TWCR & _BV(TWWC));
  TWCR = _BV(TWINT) | _BV(TWEA) | _BV(TWEN) | _BV(TWIE); // enable INTs, but not START
   }
   else
  // send start condition
  TWCR = _BV(TWINT) | _BV(TWEA) | _BV(TWEN) | _BV(TWIE) | _BV(TWSTA); // enable INTs

   // wait for write operation to complete
   while(wait && (TWI_MTX == twi_state)){
  continue;
   }

   if (twi_error == 0xFF)
  return 0; // success
   else if (twi_error == TW_MT_SLA_NACK)
  return 2; // error: address send, nack received
   else if (twi_error == TW_MT_DATA_NACK)
  return 3; // error: data send, nack received
   else
  return 4; // other twi error
 }

 void twi_reply(uint8_t ack)
 {
   if(ack){
  TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWINT) | _BV(TWEA);
   }else{
    TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWINT);
   }
 }

 void twi_stop(void)
 {
   // send stop condition
   TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA) | _BV(TWINT) | _BV(TWSTO);

   while(TWCR & _BV(TWSTO)){
  continue;
   }

   // update twi state
   twi_state = TWI_READY;
 }

 /*
  * Function twi_releaseBus
  * Desc     releases bus control
  * Input    none
  * Output   none
  */
 void twi_releaseBus(void)
 {
   // release bus
   TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA) | _BV(TWINT);

   // update twi state
   twi_state = TWI_READY;
 }

 ISR(TWI_vect)
 {
   switch(TW_STATUS){
  // All Master
  case TW_START:     // sent start condition
  case TW_REP_START: // sent repeated start condition
    // copy device address and r/w bit to output register and ack
    TWDR = twi_slarw;
    Serial.print("mt add sent is:                 0x");
    Serial.println(twi_slarw, HEX);
    twi_reply(1);
    break;

  // Master Transmitter
  case TW_MT_SLA_ACK:  // slave receiver acked address
  case TW_MT_DATA_ACK: // slave receiver acked data
    // if there is data to send, send it, otherwise stop
    if(twi_masterBufferIndex < twi_masterBufferLength){
   // copy data to output register and ack
   Serial.print("mt byte transmitted no:         ");
   Serial.println(twi_masterBufferIndex);
   Serial.print("content of tx byte:             0x");
   Serial.println(twi_masterBuffer[twi_masterBufferIndex], HEX);
   TWDR = twi_masterBuffer[twi_masterBufferIndex++];
   twi_reply(1);
    }else{
  if (twi_sendStop){
   Serial.println("mt stop");
   twi_stop();
  }

  else {
    Serial.println("mt repst");
    twi_inRepStart = true; // we're gonna send the START
    TWCR = _BV(TWINT) | _BV(TWSTA)| _BV(TWEN) ;
    twi_state = TWI_READY;
  }
    }
    break;
  case TW_MT_SLA_NACK:  // address sent, nack received
  Serial.println("mt add sent nack");
    twi_error = TW_MT_SLA_NACK;
    twi_stop();
    break;
  case TW_MT_DATA_NACK: // data sent, nack received
    twi_error = TW_MT_DATA_NACK;
    twi_stop();
    break;
  case TW_MT_ARB_LOST: // lost bus arbitration
    twi_error = TW_MT_ARB_LOST;
    twi_releaseBus();
    break;

  // Master Receiver
  case TW_MR_DATA_ACK: // data received, ack sent
    // put byte into buffer
   Serial.print("mr byte received no:            ");
   Serial.println(twi_masterBufferIndex);
   Serial.print("content of rx byte:             0x");
   Serial.println(twi_masterBuffer[twi_masterBufferIndex], HEX);
    twi_masterBuffer[twi_masterBufferIndex++] = TWDR;
  case TW_MR_SLA_ACK:  // address sent, ack received
    // ack if more bytes are expected, otherwise nack
    if(twi_masterBufferIndex < twi_masterBufferLength){
   twi_reply(1);
    }else{
   twi_reply(0);
    }
    break;
  case TW_MR_DATA_NACK: // data received, nack sent
    // put final byte into buffer
   Serial.print("mr last received byte:          ");
   Serial.println(twi_masterBufferIndex);
   Serial.print("content of last rx byte:        0x");
   Serial.println(twi_masterBuffer[twi_masterBufferIndex], HEX);
    twi_masterBuffer[twi_masterBufferIndex++] = TWDR;
  if (twi_sendStop)
     twi_stop();
  else {
    twi_inRepStart = true;
    TWCR = _BV(TWINT) | _BV(TWSTA)| _BV(TWEN) ;
    twi_state = TWI_READY;
  }
  break;
  case TW_MR_SLA_NACK:
    twi_stop();
    break;
    }

**The problem now is:**

I get these readings on the Arduino serial monitor.
Note: I've wrote my notes on each section.

    // initialization
    // I think this process is done just fine, the exact bytes are sent
    // but each time I open the serial monitor I get like garbage at the first
    // of the window, like this flipped question mark I get it most the time
    // Is there something like flush function to clear things?
 ⸮mt add sent is:                 0x3C
 mt byte transmitted no:         0
 content of tx byte:             0x0
 mt byte transmitted no:         1
 content of tx byte:             0x78
 mt byte transmitted no:         2
 content of tx byte:             0x20
 mt byte transmitted no:         3
 content of tx byte:             0x0
 mt stop

    // writing target register which is 0x00, but I get 0xA3 ??!
 m
 mt byte transmitted no:         0
 content of tx byte:             0xA3
 mt stop

    // Here requesting the 6 bytes data, I send read of HMC5883L which is 0x3D
    // but 1st byte should be 0x78 then 2nd should be 0x20, 3rd 0x00
    // but the result is different ! it's like they are shifted somehow

    // At the end I'm trying to read back the passed array to the function, but
    // I get 0s!!
 mt add sent is:                 0x3D
 mr byte received no:            0
 content of rx byte:             0xA3
 mr byte received no:            1
 content of rx byte:             0x78
 mr last received byte:          2
 content of last rx byte:        0x20
 length of read op:              3

 config settings:                0 0 0

body:
The second parameter to `twi_writeTo` should be a pointer to a buffer. You have now

    twi_writeTo(HMC5883L,0x00,1,0,1);

which sends a byte read at address 0x00.
change it to

    uint8_t b = 0x00;
    twi_writeTo(HMC5883L,&b,1,0,1);

(C arrays are a pointer to first item)


message:
Passing variables for a PID in an interrupt

I'm needing to pass variables from my timerIsr() function to my loop() function. I have little experience with the Arduino language, I'm mostly familiar with Python so this has been quite difficult for me.

Essentially I'm creating a PID controller to maintain RPM of a fan motor if friction is applied to it. I'm implementing the PID control in the loop() function but I need the rotation variable information from my timerIsr() function. I've tried to return the variable info but it doesn't match up to the actual fan speed. I think it has something to do with difference delay/timer times operating at different instances but I'm unsure.

Here's what I have so far
```
#include "TimerOne.h"
#include <PID_v1.h>

int counter=0;

const int IN1 = 11;
const int IN2 = 10;
volatile float pot=0;
const int POT = 0;
const int ENA = 6;

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

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

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

void timerIsr()
{
  Timer1.detachInterrupt();  //stop the timer
  Serial.print("Motor Speed: ");
  int rotation = (counter / 30);  // 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");

  //return rotation;
}

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

  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);

  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);
}

void loop()
{
  //Input = timerIsr();
  pot=analogRead(POT)/4.01569;
  //Setpoint = sp;

  //Serial.print(Input);

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

  delay (250);
}
```
As you can see I've commented some stuff out that's related to the PID library. Right now I'm just trying to pass the rotation variable to the loop() function.

Is it possible to update global variables at different times so any function can access them?

body:
Short answer: Yes, it is possible to update global variables from interrupt routines, but it comes also with problems.

Long answer:

First you have to understand, how interrupts work. You are using a timer interrupt and an external (pin) interrupt. The compiled program lies in the flash of the chip. At the start there are some special addresses for the different interrupts. If the hardware then registers a condition for an interrupt, it will stop the execution of the main code (the code, that was executed, when the interrupt condition occured), saving the current state and jumping to the corresponding address, where it get's send to the ISR (interrupt service routine), that you defined (in your case the function `docount()`). After the execution of this program the microcontroller will return to the execution of the main code (by restoring the previously saved state and jumping there). An ISR can only have a return type of `void` (no return value), because when it returns, there is no special code to receive and use this value. The interrupt may occur at different times every time.

Instead it is common to write global variables in the ISR. For this you have to consider some points:

1. Global variables, that may be changed during an ISR, has to be declared (additionally to the type) as `volatile`. This means, that the compiler cannot optimize this variable (for example to a local variable) and has to consider, that it may change anytime, so that he cannot use a cached value.
2. The usage of the variable in the main code has to be atomic or secured against changing of the variable. If you use a variable in a calculation, it may take many cycles for it (especially if you have a big datatype or some expensive calculations as with `float`). If the interrupt occures in this time, the value might be changed in the middle of calculation, making the result a bunch of garbage. If the calculation only takes 1 statement cycle, is cannot be interrupted and is called atomic. Since this is rarely possible, you can enclose the corresponding code into securing code. For the Arduino platform, you can use the `noInterrupts()` and `interrupts()` functions, to turn off all interrupts, do the calculation and turning the interrupts on again. Be sure do turn the interrupts off only for a short time, so that you don't miss interrupts. Often this is only used to copy the variables value into a local variable (local working copy), which then can safely used for calculations, while the global variable may still change.

Besides that, you also have to think about, what code you write into an ISR. An ISR cannot be interrupted by another interrupt. So functions, that depend on interrupts to work, will not behave like intended. The `delay()` function for example will simply block all code execution, since the return of the `millis()` function will not change (it depends on the timer0 interrupt). In your Timer1 ISR, you use `Serial.print()`. This function can be used, but only until the `Serial` libraries buffer is filled. The actual communication will take place, after the ISR returns, because it also depends on interrupts. When you try to send more, than fits in the buffer (64 bytes), you will loose data. Currently you should be below that, but you should have this in mind, when coding.

---

I don't think, that you really need a timer interrupt for calculating and outputting the data every second. Here I would use a non-blocking coding style in the `loop()` function, like you can see in the `BlinkWithoutDelay` example, that comes with the Arduino IDE. This is better than using `delay()`, which is just busy waiting. You save a timestamp with the `millis()` function and check the time difference. That saves Timer1 for other purposes and also refactors your main code for being extendable and non-blocking, if you want to add more functions.

---

As I read from [this example][1] from the PID library, you need to call `myPID.Compute()` once in a while to do the PID calculations with the new values. Since these only change every second, you should call this function directly after the calculation of `Input`.

---

All in all you need something like this (I didn't include all the code, just the important part, so that you should be able to understand the principle):

    unsigned long timestamp;
    #define INTERVAL 1000

    void loop(){
        if(millis() - timestamp >= INTERVAL){
            timestamp += INTERVAL;
            noInterrupts();
            int counter_copy = counter;
            interrupts();
            // Do the calculations with counter_copy and same the result to `Input`
            // You can put the code from your timerisr here (without the Timer1 code)
            myPID.Compute();
        }
    }

Your `pot` code then should also be enclosed in such an if statement, to prevent, that the PWM get's restarted again and again very fast. If a reaction time of 1s is ok for you, you can put this code in the if statement above. If you want faster reaction times, you can add a second if statement like this to the `loop()` function (including it's own global timestamp variable and interval value).

The `digitalWrite()` calls for the direction can be put into the setup, since they don't ever change in your code.

  [1]: https://github.com/br3ttb/Arduino-PID-Library/blob/master/examples/PID_Basic/PID_Basic.ino


message:
Is new.cpp programmed improperly? Arduino 1.8.9

I'm having trouble with my code and I'm not sure if it's a memory allocation issue. So I look at the new, delete to see if it throws errors, and finding the source code I find outrageously simple codes. So simple, I think it can't be right.

```
#include <stdlib.h>

void *operator new(size_t size) {
  return malloc(size);
}

void *operator new[](size_t size) {
  return malloc(size);
}

void operator delete(void * ptr) {
  free(ptr);
}

void operator delete[](void * ptr) {
  free(ptr);
}
```

Does this mean if I call `customClass *ptr = new customClass[10];` it allocates only 10 bytes instead of `sizeof(customClass)*10`?

body:
http://www.cplusplus.com/reference/new/operator new[]/:

> in C++, new[] is an operator with a very specific behavior: An
> expression with the new operator on an array type, first calls
> function operator new (i.e., this function) with the size of its array
> type specifier as first argument (plus any array overhead storage to
> keep track of the size, if any), and if this is successful, it then
> automatically initializes or constructs every object in the array (if
> needed). Finally, the expression evaluates as a pointer to the
> appropriate type pointing to the first element of the array.


message:
is PIN To PIN matching mcu against Atmega328P-AU available?

I want to upgrade my product which is based on Atmega328p-AU, having the problem of programming memory. I don't want to change the PCB of the product. Is PIN To PIN matching MCU against Atmega328P-AU available?

body:
The only other AVR chip with more program memory in the 32/TQFP form factor is the [ATMEGA4808][1] at 48 kB.

Unfortunately, the pinout is not the same compared to the ATMEGA328P-AU:

[ATMEGAx8P family datasheet][2]

[ATMEGAx08 family datasheet][3]

  [1]: https://www.microchip.com/wwwproducts/en/ATMEGA4808
  [2]: http://ww1.microchip.com/downloads/en/DeviceDoc/ATmega48A-PA-88A-PA-168A-PA-328-P-DS-DS40002061A.pdf
  [3]: http://ww1.microchip.com/downloads/en/DeviceDoc/32-pin-Data-Sheet-megaAVR-0-series-DS40002017B.pdf


message:
Arduino - "expected primary-expression before '.' token" Error

#include "Ultrasonic.h"
    #include <Wire.h>
    #include <LiquidCrystal_I2C.h>

    // Set the LCD address to 0x27 for a 16 chars and 2 line display
    LiquidCrystal_I2C lcd(0x27, 16, 2);

    void setup() {
      // put your setup code here, to run once:
      lcd.begin();
      Serial.begin(9600);
    }
    Ultrasonic ultrasonic(11, 12); //Ultrasonic ultrasonic(Trig,Echo);
    void loop()
    {
      int a = (Ultrasonic.Ranging(CM));
      if (a >= 15 && a < 20)
      { Serial.println("guvenli");
        lcd.print("guvenli");
        delay(500);
        lcd.clear();
        tone(3, 2000, 100);
        delay(500);
        noTone(3);
      }
      if (a >= 10 && a < 15) {
        Serial.println("guvenli dikkat");
        lcd.print("guvenli dikkat");
        delay(500);
        lcd.clear();
        tone(3, 2000, 50);
        delay(250);
        noTone(3);
      }
      if (a < 5)
      {
        Serial.println("vurdun");
        lcd.print("vurdun");
        delay(500);
        lcd.clear();**uıhhf
        tone(3, 2000, 50);
        delay(50);
        noTone(3);
      }
    }

In this code i'm getting an error like this:

       C:\Users\*\AppData\Local\Temp\arduino_modified_sketch_113625\sketch_apr29a.ino: In function 'void loop()':

    sketch_apr29a:19:22: error: expected primary-expression before '.' token

       int a = (Ultrasonic.Ranging(CM));

                          ^

    exit status 1
    expected primary-expression before '.' token

body:
`Ultrasonic` is a class name. Why are you trying to use it before a `. ` in an expression?

Judging by the declaration, you need `ultrasonic`. That is your object name. `ultrasonic`, not `Ultrasonic`.


message:
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:

<!-- language: lang-c++ -->

    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);
    }

body:
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.


body:
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:

<!-- language-all: lang-c++ -->

    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.

[Blink without delay]: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay


body:
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.


message:
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][1]) 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][2]) for the Nano board and lights? Is that possible?

Thanks in advance, and sorry my ignorance on this area.

  [1]: https://es.aliexpress.com/item/1m-4m-5m-WS2812B-Smart-led-pixel-strip-Black-White-PCB-30-60-144-leds-m/2036819167.html?spm=a2g0s.9042311.0.0.274263c0i8fcIU
  [2]: https://www.aliexpress.com/item/5V-LED-Power-Supply-1A-2A-3A-6A-8A-10A-Switching-Adapter-AC110-240V-AC-to/32810906485.html?spm=a219c.10010108.1000001.12.7eb35ccdAeVPQZ

body:
Yes, 120 LEDs * 60 mA = 7200 mA = 7.2A

An Arduino Nano will use 19 mA ([Arduino Nano Tech Spec)][1]. 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).

  [1]: https://store.arduino.cc/arduino-nano


body: 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.


message:
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);

    }

body:
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".


message:
RDM6300 continuous RFID tag read

I have an RDM6300 connected to an Arduino Mega and code that can read the tag just fine:
<!-- language-all: lang-cpp -->

    // 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.

body:
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.


message:
How to use a variable format in `sprintf`

How should I make a variable format sequence for [sprintf][1]?.

    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*'

  [1]: http://www.nongnu.org/avr-libc/user-manual/group__avr__stdio.html#ga6017094d9fd800fa02600d35399f2a2a

body:
1. `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);

2. The format string you used in your `sprintf` will generate `` 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.
3. 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�", i);
    fprintf(file, format, d);

That `fprintf` will indeed output `09`.


message:
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);
        }

    }

body:
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";


body:
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)
      }
    }


body:
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);
    }


message:
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.
[![wire diagram (edited)][1]][1]

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:

```c
// 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?

[![hardware schematic][2]][2]

  [1]: https://i.stack.imgur.com/BpsaK.jpg
  [2]: https://i.stack.imgur.com/pspQe.png

body:
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.


message:
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![enter image description here](https://i.stack.imgur.com/ry7Wg.jpg)![enter image description here](https://i.stack.imgur.com/NRDsD.jpg)

body:
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.


body:
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.


body:
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.


message:
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;

body:
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.


message:
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.
<!-- language-all: lang-cpp -->

    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.

body:
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).


message:
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.

body:
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).


message:
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:

<!-- language: lang-c -->

    /*
      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.

body:
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 **P**ress 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.


message:
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?

body:
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.


body:
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](https://en.wikipedia.org/wiki/Successive_approximation_ADC).

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.


body:
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```


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

[![My circuit table schematic][1]][1]

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?

  [1]: https://i.stack.imgur.com/jkHS5.png

body:
> 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.


message:
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:

[![enter image description here][1]][1]

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:

 1. There is no real-time connection between NodeMCU and the user (there
    is always a delay in the device response)
 2. 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.

  [1]: https://i.stack.imgur.com/CwUfZ.png

body:
Use MQTT.

You need:

1. The PubSubClient.h library
2. 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.


message:
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:
<!-- language-all: lang-cpp -->

    #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.

body:
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.


message:
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?

body:
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:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/sE7vx.png)

<!-- End schematic -->

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).