body:
I'm studying the structures of libraries currently. I want to learn how good programmers write code, what are the strategies they follow, the art the programmer followed to develop the library. And how important the library should be written in the well arranged form.

But as I'm go back and forth into the library over and over, I really need to understand, the way the programmer followed, and the reasons behind the applied strategy.

The example I'm studying now is the HMC5883L and how the programmer used the Wire library to manage the developing the library. This should be quite easy for experienced programmers, but I'm really studying the concepts, strategies .. etc.

As I'm going over and over I have different questions, so to start this discussion I want to begin with this question about the programmer writing two very similar functions that pretty much do the same thing.

 // Read byte to register
 uint8_t HMC5883L::fastRegister8(uint8_t reg)
 {
  uint8_t value;
  Wire.beginTransmission(HMC5883L_ADDRESS);
  #if ARDUINO >= 100
   Wire.write(reg);
  #else
   Wire.send(reg);
  #endif
  Wire.endTransmission();

  Wire.requestFrom(HMC5883L_ADDRESS, 1);
  #if ARDUINO >= 100
   value = Wire.read();
  #else
   value = Wire.receive();
  #endif
  Wire.endTransmission();

  return value;
 }

 // Read byte from register
 uint8_t HMC5883L::readRegister8(uint8_t reg)
 {
  uint8_t value;
  Wire.beginTransmission(HMC5883L_ADDRESS);
  #if ARDUINO >= 100
   Wire.write(reg);
  #else
   Wire.send(reg);
  #endif
  Wire.endTransmission();

  Wire.beginTransmission(HMC5883L_ADDRESS);
  Wire.requestFrom(HMC5883L_ADDRESS, 1);
  while(!Wire.available()) {};
  #if ARDUINO >= 100
   value = Wire.read();
  #else
   value = Wire.receive();
  #endif
  Wire.endTransmission();

  return value;
 }

Update:
Actually, the programmer used the 1st version only in the `HMC5883L.begin();` function, but why?

    if ((fastRegister8(HMC5883L_REG_IDENT_A) != 0x48)
    || (fastRegister8(HMC5883L_REG_IDENT_B) != 0x34)
    || (fastRegister8(HMC5883L_REG_IDENT_C) != 0x33))
    {
 return false;
    }

Everything else in the library used the 2nd version.
==============================================================================
So, basically the two functions are to read a specified register in the HMC5883L, my questions:

1. what is the difference? I know that there's an extra care has been put into the second function, but why ?
2. Is it so important ?
3. Are there situations that require any version of the functions ?

title: Questions about HMC5883L library

Answers: 2

body:
TBH the second version of the function is trash. The first version is (almost) the right way to do it.  There's stuff in the second version that really shouldn't be there. There is absolutely no reason why the creator of the library created that second function.

* It "waits" for data to be available, when that data will be available the moment `requestFrom()` completes - so is completely redundant
* It makes a spurious `beginTransmission()` call right before the `requestFrom()` call. `beginTransmission()` is only for writing, not for reading. It's pointless there.

However:

* **Both** functions do an `endTransmission()` after the `receiveFrom()`, which makes no sense - the `endTransmission()` goes to balance a `beginTransmission()` only - not a `receiveFrom()`.  `receiveFrom()` is a completely self-contained function that needs no other handling.

This library is probably not a good one to study for learning how to use the Wire library. It contains code that indicates the author themselves didn't have a proper grasp of the workings of the library.

body:
There is no "fast" way to do i2c. If you already use the "fast" functions in your code, then you can make it a inline call to readRegister8.

The function below reads a byte from the HMC5883L.
When the HMC5883L is not connected, the Wire.read() returns -1. That will be converted to a return value of 0xFF.

    // Read byte from register
    uint8_t HMC5883L::readRegister8(uint8_t reg)
    {
        uint8_t value;
        Wire.beginTransmission(HMC5883L_ADDRESS);
        Wire.write(reg);
        Wire.endTransmission();    // add parameter 'false' for repeated start

        Wire.requestFrom(HMC5883L_ADDRESS, 1);
        value = Wire.read();

        return value;
    }


body:
I was working on an Electronic Door Lock/Unlock system using Arduino Uno and RFID Reader/Tags on Ubuntu 18.04.02 lts.

Now the problem is that whenever I punch-in the correct RFID tag to the RFID reader, the Serial Monitor stops working and I notice that the "Port" value under (tools>Port) has also changed or even got un-selected.

Like, before my Port = `/dev/ttyACM0`

then whenever I punch in the correct tag, Port value either becomes None or gets changed to (= `/dev/ttyACM1`)

Also, after every 2nd or 3rd upload, I get the error message as `/dev/ttyACM0: Permission Denied`

My code is as follows:

    #include <Servo.h>
    #include <SPI.h>
    #include <MFRC522.h>

    #define SS_PIN 10
    #define RST_PIN 9
    #define ledPin1 A0
    #define ledPin2 A1
    #define Buzz A2
    Servo servo;
    int pos = 0;
    MFRC522 rc522(SS_PIN, RST_PIN);

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
      SPI.begin();
      rc522.PCD_Init();     // Initialize card reader
      pinMode(A0, OUTPUT);
      pinMode(A1, OUTPUT);
      pinMode(A2, OUTPUT);
      servo.attach(3);
      servo.write(0);
      Serial.println("Scan the Card:");
    }

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

      // check if any card is present and also scan only one card if multiple are present
      if(!rc522.PICC_IsNewCardPresent() || !rc522.PICC_ReadCardSerial())  return;

      // check if the type of the card is what we need and not any other card.
      MFRC522::PICC_Type type = rc522.PICC_GetType(rc522.uid.sak);
      if(type!= MFRC522::PICC_TYPE_MIFARE_MINI &&
         type!= MFRC522::PICC_TYPE_MIFARE_1K &&
         type!= MFRC522::PICC_TYPE_MIFARE_4K) return;
      String strID = "";
      for(byte i=0; i<4; i++) strID += (rc522.uid.uidByte[i] < 0x10 ? "0" : "") + String(rc522.uid.uidByte[i], HEX) + (i != 3 ? ":" : "");

      // put ID in capitals
      strID.toUpperCase();
      Serial.print("Card: ");
      Serial.println(strID);

      // Do the verification
      if(strID.indexOf("92:AA:CD:73") >=0){
        Serial.println("Access Granted");
        digitalWrite(A0, HIGH);
        tone(Buzz, 3000, 500);
        for (pos = 0; pos <= 60; pos += 1) {  // goes from 0 degrees to 60 degrees
        // in steps of 1 degree
        servo.write(pos);                // tell servo to go to position in variable 'pos'
        delay(10);                       // waits 10ms for the servo to reach the position
      }
      delay(500);
      for (pos = 60; pos >= 0; pos -= 1) {  // goes from 60 degrees to 0 degrees
        servo.write(pos);                   // tell servo to go to position in variable 'pos'
        delay(10);                          // waits 10ms for the servo to reach the position
      }
        digitalWrite(A0, LOW);
        delay(500);
      }
      else{
        Serial.println("Access Denied");
        digitalWrite(A1, HIGH);
        tone(Buzz, 300, 200);
        delay(250);
        tone(Buzz, 300, 200);
        delay(250);
        tone(Buzz, 300, 200);
        digitalWrite(A1, LOW);
        delay(400);
      }
    }

Please Help!

Thanks in Advance.

title: Arduino Port randomly changes whenever I punch correct RFID tag

Answers: 0


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

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

Answers: 2

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

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.


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

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

Answers: 1

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/


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

title: About UART one transmitter multiple receivers

Answers: 1

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.


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

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

Answers: 3

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.


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

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

Answers: 1

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


body: On my ESP32 project I've run out of pins and have incorporated using a MCP23017 port expander.  I need to run multiple slow serial connections (9600 baud) thru the port expander.  Are there any software serial libraries available that would work over a port expander?

title: Software serial and port expanders

Answers: 0


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

title: Working with Wire core library

Answers: 1

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)


body:
Consider my loop() in Arduino be:

    void loop(){
      for(int i = 0; i<100; i++){
       Value[i] = analogRead(A0);
       delayMicroseconds(62);
      }
       //delay(2) //when I use this line esp8266 works properly
       Udp.beginPacket(IP, Port);
       Udp.write(Value, 100);
       Udp.endPacket();
    }

after analogRead() UDP can't send packets and crash occur after a moment. But when I use `delay(2)` line in the above code it works properly. I want to record samples of microphone with `16000` sample rate and I use `62` microseconds for this. Thus in my application it is not possible for delay 2 milliseconds. How can I fix this without delay?

title: Why UDP does not work after analogRead() on esp8266-12N module?

Answers: 0


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

title: Passing variables for a PID in an interrupt

Answers: 1

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


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

title: Is new.cpp programmed improperly? Arduino 1.8.9

Answers: 1

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.


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

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

Answers: 1

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


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

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

Answers: 1

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


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

title: Counting the number of pulses in a second

Answers: 3

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.


body:
I am having a hard time finding documentation on how to properly use USB HID buffers, so the issue may lie there instead of with my code.

To get 0x47, I used this table: https://www.usb.org/sites/default/files/documents/hut1_12v2.pdf

Here's code that is loosely based off of http://mitchtech.net/arduino-usb-hid-keyboard/

        /* Arduino USB Keyboard HID demo
     * Cut/Copy/Paste Keys
     */

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

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

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

    int state = 1;
    int prevState;

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

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

      delay(200);
    }

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

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

Using a keyboard testing application, the green keys (minus mouse) are the buttons that appear to be pressed when the Arduino is using the USB HID firmware:

Upon using Passmark Keyboardtest, it looks like it's pressing Shift, Ctrl, Left alt, and right alt when I press the button.

My assumption is that I am writing to the 'modifier key' buffer instead of the 'other key' buffer. How would I define the correct key?

title: (Arduino Uno reflashed as USB HID) How to send Scroll Lock key?

Answers: 0


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

title: How many Amps can a Nano Arduino hold for LED project

Answers: 2

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.


body:
I'm writing a PID program for a simple DC Motor. This motor has an encoder at the bottom which allows me to read motor speed. The goal of the project is to provide a constant speed if there is light friction applied to the motor. Although speed may vary slightly, I can still graph the PWM signal and show the duty cycle increases in response to friction. I've gotten the motor speed and potentiometer to function perfectly, now I'm just stuck on the actual PID part.

The issue I'm having is that whenever I set my SET pin high, the motor completely shuts off. I don't understand why because I'm sending it values in that while loop which should be sufficient to initiate the compensation

Here is my code:

```
#include "TimerOne.h"
#include <PID_v1.h>

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

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

const int SET = 12;

int rotation;

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

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

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

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

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

  Serial.print("\n");

}

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

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

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

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

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

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

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

  delay (50);
}
```

title: PID controlled DC Motor Speed

Answers: 0


body:
I want to send sms to a number if and only if that number is in the radius of the arduino with GSM module.

I already have GPS into it.

Should i integrate a ultrasonic sensor to get the distance and then send the message??? let me know if there is anyother option.

Thank you in advance.

title: Arduino GSM Implementation

Answers: 0


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

    }

title: NodeMCU run sensor code while listening for wifi input?

Answers: 1

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


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

title: RDM6300 continuous RFID tag read

Answers: 1

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.


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

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

Answers: 1

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


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

    }

title: Arduino keeps looping

Answers: 3

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


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

title: Connection of a DS18B20 on a Arduino pro mini

Answers: 1

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.


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

title: Modifying normal doorbell to get notification

Answers: 3

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.


body:
How can we make our melody stop when we press the button the first time and repeat the melody when we press the button the second time?

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

    // Noterna defineras

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

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

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

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

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

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

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

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

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

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

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

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

    }
    void loop()
    {

      buttonState = digitalRead(buttonPin);

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

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

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

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

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

          notlangd = 1000 / tempo[Noten];

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

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

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

    }

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

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

      long numCycles = frekvens * length / 1000;

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

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

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

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

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

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

    }

title: How to stop and repeat a melody using a button?

Answers: 0


body:
I am trying to use a ESP8266 in an Arduino project, but I'm unable to get the basic Software serial interface working with it.

I have the ESP connected to a secondary 3.3v power supply. When connecting the RX and TX pins to the Uno's RX and TX, and uploading bare minimum code, I am able to interface with the module. Doing this I can connect to networks, send and receive packets, etc.

However, when connecting the ESP to any other pins and trying to implement a software serial interface, I am unable to get any response from the module. When sending it data I see the on board blue LED flash, so I think its receiving the data? I've found tons of example codes and Youtube videos that do what I'm trying to do. But following their steps I'm still not able to get any response.

I've tried using voltage divider circuits for the ESP's RX pin so its not getting 5v, but that hasn't seemed to change anything either. Any troubleshooting advice would be greatly appreciated.

One of the basic codes I've tried to get this to work:

```
#include <SoftwareSerial.h>

SoftwareSerial wifi(8,9);

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

  Serial.println("started!");

}

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

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

title: Unable to interface using Softserial with ESP8266 and Arduino uno

Answers: 0


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

title: error: invalid use of non-static member function attachInterrupt(0,count,RISING);

Answers: 1

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.


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

> EMP 800 v6
[Link to the manual][1]

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

  [1]: https://veq.ru/files/equipment/WH_Munzprufer_EMP_800.pdf

title: Coin Recognition from Parallel Coin acceptor to Arduino

Answers: 0