body: I have `int arr[50][2];` and I need to send it through Serial. But I don't know how to do it. is it possible?

title: How to send int[][] as a byte array through Serial

Answers: 1

body:
In the comment you write that the receiving end is an Arduino too. Then you can send the data in binary form.

To send the array:

    Serial.write((byte*) arr, sizeof(arr));

 - `(byte*)` is cast of the memory location of arr to a byte array
 - `sizeof` returns the size of the array in bytes

To receive the binary data you must know the size. Here we read 100 16-bit integers:

    Serial.readBytes((byte*) arr, 100 * sizeof(short));

Function [readBytes][1] is one of the 'timed' functions of Stream. It waits for the next byte (until timeout).

If one Arduino is 8-bit and the second is 32-bit, then use the type `short` instead of int, because the size of type int is different, but [the type short is 16 bit long on all Arduinos][2].

  [1]: https://www.arduino.cc/reference/en/language/functions/communication/stream/streamreadbytes/
  [2]: https://www.arduino.cc/reference/en/language/variables/data-types/short/


body:
I want to use an MFRC522 module as explained in this [video][1].

But is it possible to get around with Arduino and use a TTL to USB converter to connect RC522 directly to my PC running Ubuntu?

Using the RC222's UART interface, should I rewrite Arduino libraries from scratch for PC or is there a way to easily port the libraries?

  [1]: https://www.youtube.com/watch?v=So83sH6-jwM

title: How to run Arduino code on Linux?

Answers: 1

body:
Arduino libraries rely on the Arduino API to operate (usually). Things like the Serial object are expected to be defined.

Linux doesn't have any of that stuff, so you would have to implement it all yourself.

There is the "Wiring Pi" project for (obviously) the Raspberry Pi that implements the majority of the Arudino API, but whether that could be made to run on Linux on a PC is anyone's guess.

It may be simpler to just examine the existing library (and datasheet) and implement it yourself in your chosen language.


body:
If I have a single 100Hz AC signal biased by two 1 M-ohm resistors (as per schematic below), and then output to an Arduino UNO analog input pin, with the UNO sampling at around 1 kHz using delays, would there be any issues with the ADC result?

[![Biasing circuit][1]][1]

(*Source of schematic: http://tinyurl.com/ycprqsdx*)

From the Atmega328P's spec sheet (the UNO's microprocessor) it recommends an output impedance of 10 k-ohms or less, as shown below.
If I used the pair of 1 M-ohm resistors as a biasing circuit and then deliberately slow down the sampling with delays (i.e.: in loop, do analogRead, then delay, then do analogRead, etc.), would it still be okay?

[![Excerpt from Atmega328P spec sheet][2]][2]

  [1]: https://i.stack.imgur.com/XQBEb.png
  [2]: https://i.stack.imgur.com/0GaAF.png

title: If I use a biasing circuit for a signal going into an analog input pin, will it affect the ADC operation?

Answers: 2

body:
It will give bad results. You're not slowing down the sampling, you're taking samples at a longer interval - a very different thing.

The Arduino uses a *Successive Approximation* ADC. That uses a clock to control the output of a DAC and compare that voltage with the incoming voltage stored in the S&H capacitor.

In order for the S&H capacitor to get charged to the correct level it has to be connected to the GPIO pin long enough. Since there is only one ADC and 6 analog input pins, it goes through a MUX first.

The delay that needs increasing is the delay between the pin being connected to the capacitor and the capacitor being connected to the ADC.  This is called the *acquisition time*.

The `analogRead()` function does these basic operations in sequence:

1. Connect the SHC to the GPIO pin through the mux.
2. Wait
3. Disconnect the SHC from the GPIO and connect it to the ADC
4. Clock each bit from the comparator to the result registers.

Putting a delay between each analogRead would just delay the connecting of the SHC to the GPIO pin, not increase the time it's connected to the GPIO pin.

You would have to manipulate the ADC registers to do your own sample timing.  Or, just reduce your output impedance.

body: Adding capacitance to the input will help compensate for the high impedance but it also forms a low pass filter. For a 16 MHz Arduino the ADC clock is set to 16 MHz/128 = 125 KHz. Each conversion in AVR takes 13 ADC clocks so 125 KHz /13 = 9615 Hz. That is the maximum possible sampling rate, but the actual sampling rate in your application depends on the interval between successive conversions calls.


body:
i am using nRF24L01 to connect between 3 of them ( 1 is master and the others are slaves) and i am using nRF24 library , my problem is that when the master receive something from the other slaves and do not know from which channel the infromation come so is there is a way to know from which channel

//master channel code:
  const byte addresses[][6] = {"00001", "00002","00003"};
  radio.openWritingPipe(addresses[1]); // mastr
  radio.openReadingPipe(2, addresses[0]); // carwl
  radio.openReadingPipe(2, addresses[2]); // carwl2

//slave 1 channel code :
  const byte addresses[][6] = {"00001", "00002","00003"};
  radio.openWritingPipe(addresses[0]); // carw1
  radio.openReadingPipe(2, addresses[1]); // mastr

//slave 2 channel code:
  const byte addresses[][6] = {"00001", "00002","00003"};
  radio.openWritingPipe(addresses[0]); // 00003
  radio.openReadingPipe(2, addresses[2]); // 00002

library i use: https://github.com/nRF24/RF24

title: how to know the channel i receive information from when i use nRF24L01 to connect between 3 of them

Answers: 2

body:
The nRF24 is highly versatile and can be programmed for a number of different network topologies.  It appears you want either

 1. One-to-many network - where the master node sends data to the slave nodes
 2. Many-to-one network - where the master receives data from many slaves.

Both networks are achieved with the same radio channel (`RF_CH`) on all nodes.

For a one-to-many network you need to have a different RX address for each slave node.  Set the master TX address to the RX address of the corresponding slave  that you want to receive the data.  Done.

For a many-to-one network you are limited to 6 slave nodes.  On the master radio you will need to set the addresses of data pipes 0-5 to the slave TX addresses.  The master will be listening for data on all pipes and signal an interrupt whenever data is received on any of them.

To achieve bi-directional communication with a (practically) unlimited number of slave nodes, your best bet is to use the in-built ACK PAYLOAD feature of nRF24.  In addition to configuring a one-to-many network, you need to enable ACK payload on each radio node.  The procedure to follow is given in the nRF24L01 data sheet.  I can't recommend strongly enough how important that is to read and learn from.  You will be able to send a message from the master to one slave, and get data back from that node in the same radio transmission, auto-retransmit etc included in the bargain.  This way you also know which node the data are coming from - without needed to encode the identity of the slave node in the message.  It's incredible what these little radios will let you achieve!

body:
You can pass the`RF24.available` function a pointer to a variable. The available function will write the pipe-number of the message to that variable.

An [example can be found in the documentation](http://tmrh20.github.io/RF24/classRF24.html#ace7dd139fabc16b77cb8325faa07620f)


body:
When I send "a" from the Serial Monitor of the slave, on the master slave window it will show "car1_place_2_go = a" then it should show on the slave Serial Monitor "a" but it doesn't show up in the slave serial window until I send another new characters. So there is a 1 delay shift in the messages showed on the slave Serial Monitor.

Master:

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

    #include <SPI.h>
    #include <SoftwareSerial.h>
    #include <nRF24L01.h>
    #include <RF24.h>

    RF24 radio(7, 8); // CE, CSN
    const byte addresses[][6] = {"00001", "00002"};

    char car1_place_2_go;
    char car2_place_2_go;
    char temp_place = 0 ;

    void setup()
    {
      Serial.begin(9600);
      radio.begin();
      radio.openWritingPipe(addresses[1]); // mastr
      radio.openReadingPipe(1, addresses[0]); // carwl

      radio.setPALevel(RF24_PA_MIN);
    }

    void loop()
    {
      delay(5);
      radio.startListening();

      if (radio.available())
      {
        radio.read(&car1_place_2_go, sizeof(car1_place_2_go));
        Serial.print("car1_place_2_go = ");
        Serial.println(car1_place_2_go);

        delay(5);
        radio.stopListening();

        radio.write(&car1_place_2_go, sizeof(car1_place_2_go));
      }
    }

Slave:

    #include <SPI.h>
    #include <SoftwareSerial.h>
    #include <nRF24L01.h>
    #include <RF24.h>

    RF24 radio(7, 8); // CE, CSN
    const byte addresses[][6] = {"00001", "00002"};

    char car1_place_2_go;
    char car2_place_2_go;

    void setup() {
      Serial.begin(9600);
      radio.begin();
      radio.openWritingPipe(addresses[0]); // 00003
      radio.openReadingPipe(1, addresses[1]); // 00002

      radio.setPALevel(RF24_PA_MIN);
    }

    void loop()
    {
      if (Serial.available() > 0)
      {
        car2_place_2_go = Serial.read();

        delay(5);
        radio.stopListening();

        radio.write(&car2_place_2_go, sizeof(car2_place_2_go));

        radio.startListening();

        if ( radio.available())
        {
          char text[32] = "";
          radio.read(&text, sizeof(text));
          Serial.println(text);
        }
      }
    }

Library I use: https://github.com/nRF24/RF24

title: One shift delay in receiving the response messages when using two nRF24L01 to communicate with each other

Answers: 1

body:
i found the problem is that the receiver in the slave doesn't see what send to it until the next loop and that mean it need a delay so it can see what transmit to it so i add this while loop in the slave so the slave doesn't exit the "void loop" function until it get the message from the master

slave

     radio.startListening();

        while(! radio.available())
        {

        }
        if ( radio.available())
        {
            char text[32] = "";
            radio.read(&text, sizeof(text));
            Serial.println(text);
         }


body:
I have a serial ISP programmer of protocol type "stk500v1" which expects 115200 baud data rate. I have used it successfully with Atmel Studio by calling avrdude manually (custom tool) in the past. This just involves the avrdude option

> -b 115200

But recently I wanted to do use the Arduino software instead of Atmel Studio for a quick mockup. But everytime I try to "Upload with Programmer", the avrdude commandline includes the option

> -b 19200

and so the programming fails.

I can make it work by changing the hard wired serial rate in the programmer from 115200 to 19200, but then of course the programming is dead slow, which I don't want.

I have also looked for a baudrate entry for stk500v1 in "avrdude.conf", but didn't find any. How can I change the baud rate for "Upload with programmer" in the Arduino software?

title: ISP with 115200 baud

Answers: 1

body:
You have to edit the `programmers.txt` file. (The one in `~/.arduino15/packages/arduino/hardware/avr/1.6.21/`, _not_ the one in `arduino-1.8.x/hardware/arduino/avr/`)

    avrisp.name=AVR ISP
    avrisp.communication=serial
    avrisp.protocol=stk500v1
    avrisp.program.protocol=stk500v1
    avrisp.program.speed=115200
    avrisp.program.tool=avrdude
    avrisp.program.extra_params=-P{serial.port} -b{program.speed}

Add a `avrisp.program.speed` option, and pass this option as one of the `extra_params` to the command line call of avrdude.
It is then used on [line 112](https://github.com/arduino/ArduinoCore-avr/blob/b7c607663fecc232e598f2c0acf419ceb0b7078c/platform.txt#L112) of `platform.txt`:

    tools.avrdude.program.pattern="{cmd.path}" "-C{config.path}" {program.verbose} {program.verify} -p{build.mcu} -c{protocol} {program.extra_params} "-Uflash:w:{build.path}/{build.project_name}.hex:i"

You could of course also make a copy of that avrisp entry, and add your own programmer, just give it a different name.


body:
I want to send RFID tag number to PHP page. So far I have sent a fixed string to php and it worked, now I am not getting data in string when i scan rfid tag. I want to store every RFID tag number in a string when it is scanned, so that I can send it to php page.

    if (rfid.isCard()) {

        String rfid_uid = "";
        if (rfid.readCardSerial()) {
            String rfid_uid = "";
            for (int i = 0; i < 4; i++) {
                Serial.print(rfid.serNum[i], HEX);
                rfid_uid = rfid.serNum[i];
            }

            Serial.println();
        }
        //delay(7000);
        Serial.print("User ID \n");
        Serial.println(rfid_uid);
        make_request(rfid_uid);
    }

This is the path to php page

             String method = "GET /ethernet/data.php?rfid_uid=";

title: How to store an RFID tag number in a string

Answers: 2

body:
    String rfid_uid = "";
    if (rfid.readCardSerial()) {
        String rfid_uid = "";
        for (int i = 0; i < 4; i++) {
            Serial.print(rfid.serNum[i], HEX);
            rfid_uid = rfid.serNum[i];
        }

        Serial.println();
    }

This code has multiple problems:

* the variable `rfid_uid` is defined twice, they are overshadowing each other. The inner part only assigns a value to the `rfid_uid` delcared in the inside of the `if` statement, the outer `rfid_uid` will remain empty
* As you can see with `Serial.print(rfid.serNum[i], HEX);`, the element `rfid.serNum[i]` is an integer, which is printed as hex. (e.g. 123 = `7B`), in `rfid_uid = rfid.serNum[i];` you however assign the direct numerical value, without converting it to hex

You can try the following, if you want the serial number as a 4 byte hex string:

    String rfid_uid = "";
    if (rfid.readCardSerial()) {
        for (int i = 0; i < 4; i++) {
            String uid_part = String(rfid.serNum[i], HEX);
            Serial.print(uid_part);
            rfid_uid += uid_part;
        }

        Serial.println();
    }
    //rest as before

This should construct a `String` object from the integer in `HEX` format and append (using the `+=` operator it to the `rfid_uid` string). Thus, after 4 iterations, the `String` value is built up and can be used in the request.

body:
[do not use String][1]

    char url[64];
    sprintf(url, "GET /ethernet/data.php?rfid_uid=xxxx", rfid[0], rfid[1], rfid[2], rfid[3]);

  [1]: https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/


body:
Can I connect the digital out of one arduino to a digital input of another? To detect a high/low state...
One powered in one room on USB. The other in another room separate psu (connecting the grounds).
I know I can use tx/rx serial. But if the other way would work, less programming and 1 wire less..

title: Digital output from one nano to digital input of another.

Answers: 1

body:
Yes, you can. As you noted, you do need to connect the grounds of both Arduinos.

For some extra protection you could put a resistor between the output and the input. For example a 1kOhm. That way, if you accidentally set both pins as outputs, or plug the wire in the incorrect pin, you won’t get a dead-short.


body:
I'm trying to write a library for (rather slow) communication with visible light and have recently tried to include the TimerOne library as a timer.
I want to send bits at 2kHz, so with a period of 500µs. I'm initializing the `Timer1` with 500(µs) like this and then attach an interrupt to it to call my transmit function:

    Timer1.initialize(500);
    Timer1.attachInterrupt(transmitBit);

However, when I try to measure the period with a logic analyzer, it tells me that there is actually a period of 2,000µs. Could this be due to some overhead created by the library? Where else could the problem be?

If you need any other information just let me know and I'll try to provide it.

Thanks in advance for your feedback.

**EDIT:** I've just tried adding the period as a parameter to the `attachInterrupt` like so:

    Timer1.attachInterrupt(transmitBit, 500);

And now I'm measuring a period of 30µs for whatever reason? Can anyone explain me what's going on?

**EDIT:** This is the rest of my (relevant) code:

    Transmitter::Transmitter()
    {
      [...]
      Timer1.initialize(500);
    }

    Transmitter* Transmitter::_instance;

    void Transmitter::start() {
      _instance = this;
      Timer1.attachInterrupt(_transmitBit, 500);
      _active = true;
    }

    static void Transmitter::_transmitBit() {
      _instance->transmitBit();
    }

    void Transmitter::transmitBit() {
      if(_active) {
        //Preperation
        if(!_manHalf) { //only change the state when the manchester bit is completely transmitted.
          if(_busy) {
            //Serial.println("Transmitting!");
            /** if there is currently a transmission running
              * read the next bit from the frame
              */
            _state = *(_frame + _pos);
            if(_pos >= _frameSize) {
              _busy = false;
              _state = 0;
              _pos = 0;
            }
            _pos++;
          } else { //else transmit the idle pattern
            _state = 0;
          }
        }
        //Transmission
        if (!_manHalf) {
          digitalWrite(_pin, !_state);
        } else {
          digitalWrite(_pin, _state);
        }
        _manHalf = !_manHalf;
      } else {
        digitalWrite(_pin, HIGH);
      }
    }

title: TimerOne Library - Response time

Answers: 1

body:
Before using libraries, try to see whether you can manipulate the timer registers directly to achieve what you want.  You may find it is easier!

In the following example I assume you are using an ATmega328 chip.  The code may be slightly different for other microcontrollers.  In that case you can read the data sheets for both microcontrollers and work out what you need to change.

I also assume the data you want to transmit is stored in a byte array.  Initialize the data how you prefer.

e.g: ` byte my_data[10] = {0,0,0,0,0,0,0,0,0,0};`

Next, you want to initialize timer1 in the main loop

    TCCR1A=0;
    TCCR1B=0;

To send data at 2000 bits per second, the following settings can be used

    ICR1=124; // Timer counter resets to 0 after reaching 124
    OCR1A=125;
    OCR1B=125; // other counter match registers must be higher than ICR1
    TCCR1A=B00000010; // waveform generation mode 14, fast PWM, ICR1=top
    TCCR1B=B00011011; // clock scaler 64, 1 count = 4 us.  125*4 us = 500 us
    TIFR1 |= (_BV(ICF1) | _BV(OCF1A) | _BV(OCF1B)); // Clear match flags

This will set the timer1 match register bit `ICF1` every 500 us.  There are several ways of using the timer to send the data.  My preference would be to poll the match flag.  The timing precision is about as good as you can get - a couple of clock cycles:

    loop_until_bit_is_set(TIFR1,ICF1); // wait until TCNT1=ICR1
    TIFR1 |= (_BV(ICF1) | _BV(OCF1A) | _BV(OCF1B)); // clear match flags
    // switch digital output high or low depending on data bit to be sent

One way is to run a state machine loop like this:

    unsigned int state;

    void setup(){
    state=0;
    }

    void loop(){
    switch (state){
    case 0: // idle or receiving data to be sent
    TCCR1A=0;
    TCCR1B=0;
    // insert other code here
    // conditional function, when message data received, set state=1;
    break;

    case 1: // setup timer
    ICR1=124; // Timer counter resets to 0 after reaching 124
    OCR1A=125;
    OCR1B=125; // other counter match registers must be higher than ICR1
    TCCR1A=B00000010; // waveform generation mode 14, fast PWM, ICR1=top
    TCCR1B=B00011011; // clock scaler 64, 1 count = 4 us.  125*4 us = 500 us
    TIFR1 |= (_BV(ICF1) | _BV(OCF1A) | _BV(OCF1B)); // Clear match flags
    state=2;
    break;

    case 2:
    loop_until_bit_is_set(TIFR1,ICF1); // wait until TCNT1==ICR1
    TIFR1 |= (_BV(ICF1) | _BV(OCF1A) | _BV(OCF1B)); // clear match flags
    // switch digital output high or low depending on data bit to be sent

    // add conditional function so that when you are finished sending data, reset to state=0;
    break;

    }
    }

As always, please upvote if you find this helpful.


body:
I have a Arduino Uno and the esp8266 module,(NOT THE SHIELD).

I was looking for some library that I could use to connect to Wifi and set a webserver, but I can't find anything. I just found for Arduino Wifi Shield which uses SPI.

It is possible to use arduino lets say to read a LM35 and then send that data to the ESP8266 module and serve it in a page as webserver?

I know that I can use AT commands with ESP8266 to connect to wifi and to create a server, but I cannot find any function to set the data to be served.

https://www.espressif.com/sites/default/files/documentation/4a-esp8266_at_instruction_set_en.pdf

title: Is there any library for use Arduino Uno with esp8266-01 module?

Answers: 3

body: Why involve the UNO at all.  The ESP88266 could be programmed with the Arduino IDE to read the sensor and deal with the internet all by itself.  It doesn't need the UNO to do what you want.

body:
You didn't google hard enaugh.

There are plenty of examples serving your environment.

This [instructables](http://www.instructables.com/id/Simple-Webserver-Using-Arduino-UNOMega-and-ESP8266/) is just one of it.

> The main aim of this instructable is to show how you can create a simple web server using Arduino and Wi-Fi module which displays the sensor data in the webpage.

body:
For a webserver, program the ESP8266 directly. This allows you to make use of the internal SPI flash memory to store your webpages. You can't do this with AT commands.

The Arduino UNO does not have enough processing power and/or memory for advanced internet stuff. If you want a webserver over AT commands, the Arduino has to do all the hard work, the ESP8266 is just a dumb slave that establishes a TCP connection.
The ESP8266 is much faster, and has many times more memory, so it makes sense to let it do all the heavy lifting.

Take a look at this guide:
[ESP8266 temperature logger][1]

You can copy pretty much all code, but instead of measuring the temperature from an actual sensor, read it from the `Serial` input.

Then just connect the Arduino to the ESP8266 over Serial (or SPI or I²C or SoftwareSerial, whatever you prefer), and have it send the temperature to the ESP8266, for example every second.

To program the ESP8266, you can use the USB-to-Serial adapter of one of your Arduinos.

***

In this case, where you just want to read a single LM35, you could even use only the ESP8266. It is true that the LM35 requires at least 4V, but this is not a problem, since most ESP8266 dev boards also provide a 5V supply. The analog input range of 0-1.0V would allow for a temperature up to 100°C.

  [1]: https://tttapa.github.io/ESP8266/Chap16 - Data Logging.html


body: I'm a beginner and I've been developing my own library for a wave player. so far I have the SD card installed and OLED and rotary encoder all connected. I've successfully read the wave chunk and it's data(16bit and 44.1KHz). My question is that the data in wave file is PCM and I wish to play is using 16bit PWM and so how do I convert PCM to PWM?

title: How do you convert PCM to PWM?

Answers: 2

body:
There is no such thing as a PCM file. PCM is completely erroneously used to describe an uncompressed digital audio file. What it actually means is "A file which contains data that can be fed directly to a PCM device without any form of intermediate conversion".

What you have in a "PCM" WAV file is just raw sample data. After your header (usually 44 bytes) you just have 16-bit values representing your sample points, with the two channels interleaved one after the other.

Since PCM is a linear audio representation, the sample data it expects is a simple linear representation of the audio (unlike µLaw or A-law) and with no compression (such as MP3 or FLAC). And that is the exact same data that PWM expects since it too is a simple linear output.

However, none of that matters, because the Arduino simply isn't powerful enough to play your file. Maybe a smaller one (8kHz, mono, 8-bit) would be playable, but not yours. The numbers just don't add up.

There is a [PCMAudio](http://playground.arduino.cc/Code/PCMAudio) example available, but it only works from audio embedded within your program.

There is also a [TMRpcm](https://github.com/TMRh20/TMRpcm) library available which plays from SD card, but is limited to 8-bit mono, though it can supposedly do up to 32kHz sample rate (though I wouldn't want to try doing anything else at all at that rate).

You would be better off using a system more geared towards audio - something with an I2S CODEC chip attached would be the best solution.

body:
You should use an MCU with PWM generators to do that.

The problem with PWM is that the max resolution is quite low (10-bit) so you are effectively limited to 8-bit PCM.

 - Use a DSP editor like Audacity to export a 16KHz unsigned 8-bit WAV.
 - Import the WAV file as an array of unsigned char.
 - Set your PWM freq to the resonant freq of your speaker (eg. 31250Hz)
 - Set your PWM timer to fire at 16KHz and set the PWM duty cycle to the next array value.

I use 16KHz sample rate because:
 - Reduced memory footprint
 - Fewer timer interrupts
 - PWM's limited resolution does not seem to benefit from anything above 16KHz
 - I use piezo speakers directly wired to PWM pins in H-bridge.
 - A separate amp module might benefit from higher sample rates.


body:
HC-05 Bluetooth RX requires 3.3 v (TX has a regulator built in)
I understand my uno and nano are 5v
Ive connected a 3.3v Zennor in series with a led and resistor and with multimeter established the black stripe goes ground to achieve 3v
But which is considered ground between hc-05 RX or the arduino TX that it connects to..
Is this an acceptable way to drop the voltage?
If not I've ordered some small voltage regulators.
But I still have the same question, which way round.
The regulator has connections v1...gnd...vo
Thanks Paul
(Edit to this post)
Ive read a bit more and if correct I now think the Hc-05 rx connects direct with the arduino tx and the Zennor connect anode to the link and stripe side to ground...
Still unsure..

title: HC-05 3.3 voltage regulation

Answers: 0


body:
i am new to ESp and yesterday i received my **ESP8266MOD**, i don't have FTDi connector with me right now(it's on the way).

**Is it possible to flash ESP with Arduino UNO?**

Regards,
Ben

title: Is it possible to program/flash ESP8266MOD(07) With Arduino UNO

Answers: 2

body:
I think it is possible. You can use the Arduino Uno 's Rx and Tx lines, but maybe you will need to have a voltage divider resistor arrangement to step down the 5V UART lines from the Uno to the 3.3V needed by the ESP, otherwise you risk damaging the ESP.

The basic approach to flash a ESP is described by several web sources and instructables, such this one [Getting started with the ESP8266 ESP-12](http://www.instructables.com/id/Getting-Started-with-the-ESP8266-ESP-12/) (there is also one section how to flash with an Arduino Uno).

body:
Yes you can.

Take a look at [this detailed guide](https://tttapa.github.io/Pages/Arduino/ESP8266/Flashing/Flashing-With-an-Arduino.html).

The most important thing to keep in mind is that you have to connect from the ATmega16U2's perspective, so you have to swap RX and TX:
[![enter image description here][1]][1]

You'll probably want some buttons to facilitate the flashing process:
[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/Rj6FV.png
  [2]: https://i.stack.imgur.com/mtLtN.png


body:
I appreciate the help of this forum very much and it`s my first time to ask you experts befor driving crazy...

ArduinoUno and SDcard-BreakOutboard and DistanceSensor HC-SR04 are not working well together. The problem - as far as I found out - is in this statement:

    if (!sd.begin(sdChipSelect) || !file.open("DATALOG.TXT", O_CREAT | O_WRITE | O_APPEND)) {
    // Replace this with something for your app.
    Serial.println(F("SD problem"));
    //while(1);
    }

When it is erased the distance sensor works perfectly, if it is in place it shows 0 cm (and that for days! ;-) ). I read something that SdFat ist doing something with Pin10 but also putting it on OUTPUT - HIGH or LOW didn't do the trick. Any ideas?

Kind regards

Rob

The "minimal" code:

    /*
    SD card datalogger

    This example shows how to log data
    to an SD card using the SdFat library.

    The circuit:
    * analog sensors on analog ins 0, 1, and 2
    * SD card attached to SPI bus as follows:
    ** MOSI - pin 11
    ** MISO - pin 12
    ** CLK - pin 13
    ** CS - pin 7 (for MKRZero SD: SDCARD_SS_PIN)
    */
    #include <SdFat.h>
    const uint8_t sdChipSelect = 7;
    // SD file system.
    SdFat sd;
    // Log file.
    SdFile file;

    // Hook up HC-SR04 with Trig to Arduino Pin 9, Echo to Arduino pin 10
    // Maximum Distance is 400 cm
    unsigned long echo = 10;
    int ultraSoundSignal = 9; // Ultrasound signal pin
    unsigned long ultrasoundValue = 0;

    void setup() {
    // Serial Port
    Serial.begin(9600);
    // Pin 9 = TriggerPin
    pinMode(ultraSoundSignal,OUTPUT);

    // Initialize the SD and create or open the data file for append.
    if (!sd.begin(sdChipSelect) || !file.open("DATALOG.TXT", O_CREAT | O_WRITE | O_APPEND)) {
    // Replace this with somthing for your app.
    Serial.println(F("SD problem"));
    //while(1);
    }
    Serial.println("card initialized.");
    delay(1000);
    }

    void loop() {
    Serial.println("Beginn");
    // Distanzmessung mit HC-SR04
    int x = 0;
    x = ping();
    Serial.print(x); Serial.println(" cm");
    delay(1000); //delay 1/4 seconds.
    }

    unsigned long ping()
    {
      pinMode(ultraSoundSignal, OUTPUT); // Switch signalpin to output
      digitalWrite(ultraSoundSignal, LOW); // Send low pulse
      delayMicroseconds(2); // Wait for 2 microseconds
      digitalWrite(ultraSoundSignal, HIGH); // Send high pulse
      delayMicroseconds(5); // Wait for 5 microseconds
      digitalWrite(ultraSoundSignal, LOW); // Holdoff
      pinMode(ultraSoundSignal, INPUT); // Switch signalpin to input
      digitalWrite(ultraSoundSignal, HIGH); // Turn on pullup resistor
      // please note that pulseIn has a 1sec timeout, which may
      // not be desirable. Depending on your sensor specs, you
      // can likely bound the time like this -- marcmerlin
      // echo = pulseIn(ultraSoundSignal, HIGH, 38000)
      echo = pulseIn(ultraSoundSignal, HIGH,38000); //Listen for echo
      ultrasoundValue = (echo / 58.138);// * .39; //convert to CM then to         inches
      return ultrasoundValue;
    }

title: SdFat initialization blocks HC-SR04

Answers: 1

body:
Pin 10 is the SS pin for SPI. Since you are using SPI for the SD card pin 10 *must* be an output (for SPI to operate in master mode). Ideally you will use that pin as the SS (or CS, whatever you want to call it) for the SD card.

You can't use it as the echo input of an ultrasound range finder and use SPI.


body:
I am new to arduino and am confused about how I would go about doing this: I want to attach a device to a small ball, that will move through the air at speed. The purpose of this device would be to determine the speed of this object as it moves through the air. My ball will always move in the same path because it will be shot out of a tennis ball shooter. My initial intuition would be to use an accelerometer to determine the acceleration at quarter second intervals and then multiply those values by a quarter of a second to obtain the change in speed and then add it to the sum of all the previous change in speed values (starting at 0).

Would this work? Is my reasoning correct? Are there any better solutions?

Thank You!

title: Measuring the speed of an object moving fast through air

Answers: 1

body:
You are proposing calculating velocity based on sampled acceleration.  Essentially taking the integral of the acceleration.  This is the first step in a process call [dead reckoning][1]. This is discussed in [this arduino.stackexchange.com answer][2].  In that answer there is a [link to a web page which implements dead reckoning using an Arduino][3]. You will find this equation on that web page:

    velocity(i) = velocity(i-1) + acceleration (i)

  [1]: https://en.wikipedia.org/wiki/Dead_reckoning
  [2]: https://arduino.stackexchange.com/questions/25529/detecting-distance-moved-by-accelerometer/25547#25547
  [3]: http://bluelemonlabs.blogspot.com/2013/07/blog-post.html


body:
I recently saw [this video][1] where the creator controlled a DMX light via the Arduino. There he used the pins 3 and 4 for the data on the Arduino Duemilanove. As DMX library he used DmxSimple.

Based on my research DMX is RS-485 and for this there's a driver chip required.

So I have three questions about this:

1. Why do all sources I found say that there's a driver chip required when it seems to work without?

2. I got a Arduino Leonardo compatible device (Devduino). Is it possible to control DMX like stated above on this platform?

  [1]: https://www.youtube.com/watch?v=3Q4hLA7YM7c

title: DMX on the Arduino without additional driver chip

Answers: 3

body:
The physical layer of a DMX interface is based on [differential signaling][1] over an [RS485 link][2].  This is exactly what is said [here on the DMX Arduino.cc][3] page.

A differential signal (like RS485 or USB) can travel greater distances than signals which reference ground (like RS232, I2C or SPI).  This is because noise, which affect both sides of a differential signal, can be canceled out at the far end when one of the signals is inverted then added to the other by the differential receiver.

Connecting one side of a differential receiver to ground and driving the other side with logic level voltage is not recommended.  Even if it worked and did not cause harm to the transmitting processor nor the differential receiver the signal will likely be susceptible to undesirable noise.

RS485 is a ubiquitous standard and likely several easily sourced designs exist for the Arduino.

  [1]: https://en.wikipedia.org/wiki/Differential_signaling
  [2]: https://en.wikipedia.org/wiki/RS-485
  [3]: http://playground.arduino.cc/Learning/DMX

body:
It might be possible, actually. A differential signal **can** be produced via a standard Arduino, though there's still the 5V logic level to be concerned about. I am guessing that his lamp was capable of a 5V-swing signal (10V, all told), but this is not a guarantee, especially if the standard does not normally support this. In that sort of case, you trust that the manufacturer made the device sufficiently hardened/overengineered so that the higher voltages do not cause damage.

From watching the linked video, the signal wires are **both** attached to *GPIO pins* of the Arduino board. If one is pulled HIGH (5v) and the other LOW (Gnd), you produce a signal. The other differential signal is provided by swapping which pins are LOW and HIGH.

EDIT: That's a Duemilanove, NOT an Uno, so the outputs might be different. (Still, one of the newer 3v3 boards would probably be safer, if you are testing this). Further, if the wires are long enough, there might even be something of a voltage drop that makes it safe(er).

The end result then uses bit-banging to emulate a transceiver using this jury-rigged differential transmitter.

body:
RS485 or RS422 and consequently DMX use differential drivers at 5 volts.  This means that both lines are 0 to 5V nominally, with a (usually, depending on the cable used) 120 ohm resistor as a terminator on both ends.  A 3.3V signal might work, but barely.

perhaps sending the signal on one line and just 0V on the other might work sort-of, but I've never tried or even heard of that.

My guess would be that in this case they are using a bit-banged serial port modified to also control the other pin, but inverted.  Perhaps something could be done with a standard serial port on one pin, setting up an interrupt on that pin changing level, and using the ISR to check the level on the 'serial pin and invert it and set the other pin.  I think that would probably incur too much of a delay between the two pins, but perhaps not.  Strictly speaking, the delay between the two pins changing if it was bit-banged is probably out of spec for RS422/485, but might work anyway unless the baud rate was higher.

If you are going to use DMX, spend the $0.30 and buy a driver chip or a bit more and get a DMX shield.  I've seen DMX get screwed up by a whole lot less than the differential line being a bit out of sync.


body:
I'm having some issues dealing with strings in a small Arduino app.
I wonder why **this code works**:

    mqtt.setServer("192.168.1.42", port);

and this code doesn't:

    IPAddress ip = MDNS.queryHost(...);
    mqtt.setServer(ip.toString().c_str(), port);

Even when `strcmp` returns 0 when I compare both:

    strcmp(ip.toString().c_str(), "192.168.1.42"); // output = 0 => equality

I've also tried other alternatives, such as creating a `char` array, with no luck:

    String ipstr = ip.toString();
    char ipchar[ipstr.length() + 1];
    ipstr.toCharArray(ipchar, ipstr.length() + 1);

    mqtt.setServer(ipchar, port);

All alternatives compile, but the mqtt connection is never established later on. I must be missing something obvious because it works when I hardcode the "192.168.1.42" string.

title: char array comparison

Answers: 1

body:
`PubSubClient::setServer(const char * domain, uint16_t port)` just saves the pointer, it doesn't copy the string (probably because it expects a static string literal).
([Source][1])
In your case, when `ip` goes out of scope, the pointer is no longer valid, so it won't work.

Just use the `PubSubClient::setServer(IPAddress ip, uint16_t port)` function instead.
([Source][2])

Always read the [API documentation][3], most libraries have one, even though it can be hard to find. The ReadMe and GitHub Wiki pages are a good place to start.
If that's insufficient (not uncommon for open source projects), read the [header files][4], which list all functions of the library.
If you still have doubts about what a function does, refer to the actual [implementation files][5].

  [1]: https://github.com/knolleary/pubsubclient/blob/f029640ee6365c58ebfe66ebf6bf1733d322f2ec/src/PubSubClient.cpp#L566
  [2]: https://github.com/knolleary/pubsubclient/blob/f029640ee6365c58ebfe66ebf6bf1733d322f2ec/src/PubSubClient.h#L118
  [3]: https://pubsubclient.knolleary.net/api.html#setserver
  [4]: https://github.com/knolleary/pubsubclient/blob/f029640ee6365c58ebfe66ebf6bf1733d322f2ec/src/PubSubClient.h
  [5]: https://github.com/knolleary/pubsubclient/blob/f029640ee6365c58ebfe66ebf6bf1733d322f2ec/src/PubSubClient.cpp


body:
I have used Nick Gammon's (MAX7219) and (bitBangedSPI) libraries to drive SPI 7-segment 8 digit led modules successfully from the Arduino Uno.  I would like to extend the number of Slave Select (CS) choices by using the MCP23S17 chip.  The Mcp23s17 libraries to use might be https://github.com/dreamcat4/Mcp23s17 or https://github.com/MajenkoLibraries/MCP23S17.  I have found the stackExchange entry https://arduino.stackexchange.com/questions/16348/how-do-you-use-spi-on-an-arduino to be helpful and this entry to be helpful http://www.ermicro.com/blog/?p=1050, but all the examples just turn on LED lights, not digits of 7-segment led modules.

I realize I might have to modify the MAX7219 and bitBangedSPI libraries where the digitalWrite command is used.  However, I'm not sure how to modify or drive these 7-segement modules using the MCP23S17 chip.

A skeleton script to display PI selected on pin 6 on the Uno and address 0x0 of the MCP23S17 is shown below.  I would like to choose which pinout to utilize as well but am not sure how this would be coded.
[![enter image description here][1]][1]

    #include <SPI.h>
    #include <bitBangedSPI.h>
    #include <MAX7219.h>
    // Mcp23s17 library available from https://github.com/dreamcat4/Mcp23s17
    #include <Mcp23s17.h>

    // Wire up the SPI Interface common lines:
    // #define SPI_MOSI             7 //arduino   <->   SPI Master Out Slave In   -> SI  (Pin 13 on MCP23S17 DIP)
    // #define SPI_MISO   not used 12 //arduino   <->   SPI Master In Slave Out   -> SO  (Pin 14 on MCP23S17 DIP)
    // #define SPI_CLOCK            8 //arduino   <->   SPI Slave Clock Input     -> SCK (Pin 12 on MCP23S17 DIP)

    // Then choose any other free pin as the Slave Select (pin 10 if the default but doesn't have to be)
    #define MCP23S17_SLAVE_SELECT_PIN  6 //arduino   <->   SPI Slave Select           -> CS  (Pin 11 on MCP23S17 DIP)
    // MULTIPLE DEVICES
    // Up to 8 MCP23S17 devices can share the same SPI bus and slave select pins.
    // Assign each chip a unique 3-bit device address (by setting the A2,A1,A0 pins)
    // Then below, device address is optional 2nd parameter to the constructor fn...
    // MCP23S17 Mcp23s17_0 = MCP23S17(MCP23S17_SLAVE_SELECT_PIN,0x0);
    // ...
    // MCP23S17 Mcp23s17_7 = MCP23S17(MCP23S17_SLAVE_SELECT_PIN,0x7);

    // SINGLE DEVICE
    // Instantiate a single Mcp23s17 object
    MCP23S17 Mcp23s17_0 = MCP23S17(MCP23S17_SLAVE_SELECT_PIN,0x0);
    const byte chips = 1;
    static char outputBuffer[20]; // outputBuffer[] likely 2x the size it needs to be.

     // 1 chip, bit banged SPI on pins 6, 7, 8

    MAX7219 display(chips, 6, 7, 8);  // Chips / LOAD / DIN / CLK
    void setup()
    {
     // Set all pins to be outputs (by default they are all inputs)
     Mcp23s17_0.pinMode(OUTPUT);

     display.begin();
     display.setIntensity(1);
     float pi = PI;
     dtostrf(pi, 7, 7, outputBuffer);
     display.sendString(outputBuffer);

    }  // end of setup

    void loop() { }

An example of the 8-digit 7-segment display.  They are available on Amazon, Ebay, AliExpress etc. This one has 0.33 inch digits; other modules are 0.56 inch digits.

[![enter image description here][2]][2]
[![enter image description here][3]][3]

  [1]: https://i.stack.imgur.com/vzqGZ.jpg
  [2]: https://i.stack.imgur.com/hO8nC.jpg
  [3]: https://i.stack.imgur.com/4zU8L.jpg

title: How to drive SPI MAX7219 7-segment led module using MCP23S17 extender

Answers: 3

body:
I'm not 100% on what you want to do but I have used both the chips you seem to want to do it with.

The MAX7219 can control 8 7Segment displays.
I don't remember it being an SPI device, you just set the pattern you want in the registers and off it goes.  (It could be that is used such a high level abstraction that I didn't realise it was SPI)

The IOX chip you are referring to is quite similar in behaviour, you setup the registers and away it goes.

On the surface it appears you can do what you want, but I suspect you will hit timing issues unless you want very static displays (maybe < 1FPS).  The time it takes you to establish the correct settings on the IOX chips will be the limiting factor.

You might want to look at the I2C version of the IOX which will require just 2 pins to connect to up to 7 ICs.

Alternatively use a network of microprocessors to each drive the maximum number of MAX7219s that they can, such as Nanos, ESP8266-12/NodeMCU, etc.

body:
The MAX7219 chip is designed to be daisy chained -- connect Dout to the Din of the next MAX7219 (see the No-op Register section in the [data sheet][1]). I'm not sure if there is a limit to the number that can be daisy chained.

In fact Nick Gammon's library appears to support this.  The "chips" parameter is the number of daisy chained MAX7219s.

The MAX7219 is does not use SPI. As I understand it the SPI/bitBangedSPI libraries are used as a convenient way to send the data bits with a synchronized clock.

  [1]: https://www.sparkfun.com/datasheets/Components/General/COM-09622-MAX7219-MAX7221.pdf

body: Just daisy chain the MAX7219s as already mentioned. I use SPI directly with the chip all time, it works great with the default modes - 4 MHz clock, Mode 0, MSBFIRST.  Many libraries use software SPI to talk to it, which I think is just a waste of the SPI hardware in the '328P family of chips.


body:
Each LDR is connected to one LED because I am doing a parking lot model. I have tried but with no luck. Help!

        int ledPin = 11;
    int sensorInput = A0;

    boolean ledIsOn = false;

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

    void loop() {
      int lightLevel = analogRead(A0);

      if (ledIsOn) {
        if (lightLevel > 600) {
          ledIsOn = false;
        }
      } else {
        if (lightLevel < 400) {
          ledIsOn = true;
        }
      }

      digitalWrite(ledPin, ledIsOn);

      Serial.println(lightLevel);
    }

*this is the code for one LED to one LDR Sensor but I cannot make the 6 led to 6 ldr

and I did this code for 6 LDR

    #define pin_size 6
    const int pin[pin_size] = { A0, A1, A2, A3, A4, A5};

    void setup() {

      Serial.begin(9600);

    }

    void loop() {
      for (int i = 0 ; i < pin_size; i++) {
        Serial.print(analogRead(pin[i]));
        Serial.print(" - ");
        Serial.print(i);
        Serial.print("  |  ");

      }
      Serial.print("\n");
      delay(1000);

    }

title: I want a code for 6 LDR/LED pair

Answers: 1

body:
You need to convert all the regular variables to arrays. The loop through each index and run the the same as before for each index.

    const int pin_size 6
    int ledPins[] = {3, 4, 5, 6, 7, 8};
    int sensorPins[] = {A0, A1, A2, A3, A4, A5};
    boolean ledIsOn[] = {false, false, false, false, false, false};

    void setup() {
      for (int i = 0 ; i < pin_size; i++) {
        pinMode(ledPins[i], OUTPUT);
      }
      Serial.begin(9600);
    }

    void loop() {
      for (int i = 0 ; i < pin_size; i++) {
        int lightLevel = analogRead(sensorPins[i]);

        if (ledIsOn[i]) {
          if (lightLevel > 600) {
            ledIsOn[i] = false;
          }
        } else {
          if (lightLevel < 400) {
            ledIsOn[i] = true;
          }
        }

        digitalWrite(ledPins[i], ledIsOn[i]);

        Serial.println(lightLevel);
      }
    }


body:
I am trying to correctly power a Lilypad Arduino that is attached with an HC-05, Lilypad temp sensor, and Amped pulse sensor. So far I have found that powering by plugging the Lilypad into my laptop and using three coin cells in parallel will allow for the Pulse sensor and Temp sensor to function properly. When I attach the HC-05, the readings become extremely incorrect. To remedy this, I attached the HC-05 to a 9v battery.

As I'm sure you can tell, I am novice to say the least. How can I properly power these components without damaging them. Thank you.

Update : I failed to tweak the program to reflect voltage change when disconnected from laptop. Temperature data much better and BPM is correct. Only issue that remains is the question of how to safely power all components through Lilypad. Thanks again.

title: Correctly Powering Lilypad Arduino

Answers: 0


body:
To get this out of the way first: I have already looked at ["Timer2 does not work as it should"](https://arduino.stackexchange.com/questions/830/timer2-does-not-work-as-it-should) and ["Timer2 “Clear OC2B on Compare Match” not working as expected in CTC mode"](https://arduino.stackexchange.com/questions/30507/timer2-clear-oc2b-on-compare-match-not-working-as-expected-in-ctc-mode) but have not found the answers there very useful.

Now on to my problem:

I'm trying to use the Timer2 in CTC mode to have an interrupt every 500us. For this, I have the following code:

    #include "TimerTwo.h"

    TimerTwo Timer2;

    ISR(TIMER2_COMPA_vect) { //ISR on Compare Match A
      Timer2.isrCallback();
    }

    void TimerTwo::initialize() {
      cli();
      TCCR2A = 0;// set entire TCCR2A register to 0
      TCCR2B = 0;// same for TCCR2B
      TCNT2  = 0;//initialize counter value to 0

      // set compare match register for 2khz increments
      OCR2A = 124;// = (16*10^6) / (2000*64) - 1 (must be <256)

      // turn on CTC mode
      TCCR2A |= _BV(WGM21);

      // Set CS22 bit for 64 prescaler
      TCCR2B |=  _BV(CS22);

      // enable timer compare interrupt
      TIMSK2 |= _BV(OCIE2A);
      sei();
    }

    void TimerTwo::attachInterrupt(void (*isr)()) {
      TIMSK2 |= _BV(OCIE2A);
      isrCallback = isr;
    }

    void TimerTwo::detachInterrupt() {
      TIMSK2 &= ~_BV(OCIE2A);
      isrCallback = nullptr;
    }

and

    #ifndef TIMERTWO_H
    #define TIMERTWO_H

    #include <Arduino.h>

    class TimerTwo
    {
      public: //methods
        void initialize();
        void attachInterrupt(void (*isr)());
        void detachInterrupt();
        void (*isrCallback)();
    };

    extern TimerTwo Timer2;

    #endif

It was inspired by the TimerOne library.

However, when I measure the period at the output pin (which I have attached inside some other code) I only get a period of 1ms. Even if I set `ORC2A` to 63, this fact doesn't change.

I have the constructor of this called inside my `setup()` so the registers should not be overwritten by the wiring.c.

I have also looked at the [datasheet of the ATmega328p](http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf#G1.1920802) and checked that all registers are set correctly.

Thanks in advance for your help. If you need any further information, let me know.

title: Timer2 Compare Interrupt not working as expected

Answers: 1

body:
So you're right that CTC is acting weird. I've noticed this few years ago too on different board, but I've always suspected asychronous mode (I've added 32k RTC Xtal on Arduino Mega).

However Fast PWM mode with `OCR2A` as a `TOP` value seems to be working:

    class TimerTwo
    {
      public: //methods
        void initialize();
        void attachInterrupt(void (*isr)());
        void detachInterrupt();
        void (*isrCallback)() = nullptr;
    };

    TimerTwo Timer2;

    ISR(TIMER2_COMPA_vect) { //ISR on Compare Match A
      Timer2.isrCallback();
    }

    void TimerTwo::initialize() {
      cli();

      OCR2A = 124;                        // = (16*10^6) / (2000*64) - 1 (must be <256)
      TCCR2A = _BV(WGM21) | _BV(WGM20);   // turn on fast PWM mode with top in OCR2A
      TCCR2B = _BV(WGM22) | _BV(CS22);    // Set CS22 bit for 64 prescaler
      TCNT2  = 0;                         // initialize counter value to 0

      sei();
    }

    void TimerTwo::attachInterrupt(void (*isr)()) {
      isrCallback = isr;
      TIMSK2 |= _BV(OCIE2A);
    }

    void TimerTwo::detachInterrupt() {
      TIMSK2 &= ~_BV(OCIE2A);
      isrCallback = nullptr;
    }

    volatile uint32_t counter = 0;
    void isrHandler() {
      ++counter;
    }

    void setup() {
      Serial.begin(115200);
      Timer2.initialize();
      Timer2.attachInterrupt(&isrHandler);
    }

    void loop() {
        static uint32_t counter_old = 0;
        Serial.println(counter - counter_old);
        counter_old = counter;
        delay(500);
    }

EDIT: Ok, so after some digging on [this issue][1] I've found that setting CTC mode might cause OCR2A corruption (I guess?) . It seems to be working if you reorder the settings to:

      TCCR2B = 0;          // stop the timer and reset WGM22
      TCCR2A = _BV(WGM21); // turn on CTC mode with top in OCR2A
      OCR2A  = 124;        // = (16*10^6) / (2000*64) - 1 (must be <256)
      TCNT2  = 0;          //initialize counter value to 0
      TCCR2B = _BV(CS22);  // Set CS22 bit for 64 prescaler (for starting the timer)

  [1]: https://www.avrfreaks.net/forum/issue-timer2-ctc-mode-arduino-uno-board


body:
I need help with this code:

<!-- language:lang-cpp -->

    /**
    *  Modbus master example 1:
    *  The purpose of this example is to query an array of data
    *  from an external Modbus slave device.
    *  The link media can be USB or RS232.
    *
    *  Recommended Modbus slave:
    *  diagslave http://www.modbusdriver.com/diagslave.html
    *
    *  In a Linux box, run
    *  "./diagslave /dev/ttyUSB0 -b 19200 -d 8 -s 1 -p none -m rtu -a 1"
    * This is:
    * serial port /dev/ttyUSB0 at 19200 baud 8N1
    * RTU mode and address @1
    */

    #include <ModbusRtu.h>

    // data array for modbus network sharing
    uint16_t au16data[16];
    uint8_t u8state;

    /**
    *  Modbus object declaration
    *  u8id : node id = 0 for master, = 1..247 for slave
    *  u8serno : serial port (use 0 for Serial)
    *  u8txenpin : 0 for RS-232 and USB-FTDI
    *               or any pin number > 1 for RS-485
    */
    Modbus master(0,0,2); // this is master and RS-232 or USB-FTDI, PIN 9 PARA INDICAR QUE TRASMITO

    /**
    * This is an structe which contains a query to an slave device
    */
    modbus_t telegram;

    unsigned long u32wait;

    void setup() {
     master.begin( 9600 ); // baud-rate at 19200
     master.setTimeOut( 2000 ); // if there is no answer in 2000 ms, roll over
     u32wait = millis() + 1000;
     u8state = 0;
    }

    void loop() {
     switch( u8state ) {
     case 0:
       if (millis() > u32wait) u8state++; // wait state
       break;
     case 1:
       telegram.u8id = 1; // slave address
       telegram.u8fct = 5; // function code (this one is registers read)
       telegram.u16RegAdd = 0; // start address in slave
       telegram.u16CoilsNo = 2; // number of elements (coils or registers) to read
       //telegram.au16reg = au16data; // pointer to a memory array in the Arduino

       // PARA EL VARIADOR OMRON MX1: MODBUS RTU 01 05 00 00 FF 00 -> START
       // 01 -> SLAVE (VFD OMRON)
       // 05 -> WRITE COIL
       //  00 00 -> ADDRESS COIL
       // FF 00 -> VALUES TO WRITE IN COIL FOR RUN

       telegram.au16reg[0] = 0;
       telegram.au16reg[1] = 0;
       telegram.au16reg[2] = 0;
       telegram.au16reg[3] = 0;
       telegram.au16reg[4] = 0;
       telegram.au16reg[5] = 0;
       telegram.au16reg[6] = 0;
       telegram.au16reg[7] = 0;

       telegram.au16reg[8] = 1;
       telegram.au16reg[9] = 1;
       telegram.au16reg[10] = 1;
       telegram.au16reg[11] = 1;
       telegram.au16reg[12] = 1;
       telegram.au16reg[13] = 1;
       telegram.au16reg[14] = 1;
       telegram.au16reg[15] = 1;

       master.query( telegram ); // send query (only once)
       delay(3500);

       telegram.u8id = 1; // slave address
       telegram.u8fct = 6; // function code (this one is registers read)
       telegram.u16RegAdd = 1; // start address in slave
       telegram.u16CoilsNo = 4; // number of elements (coils or registers) to read
       //telegram.au16reg = au16data; // pointer to a memory array in the Arduino
       //telegram.au16reg = 0000000111110100;

       // PARA EL VARIADOR OMRON MX1: MODBUS RTU 01 06 00 01 01 F4 -> CHANGE FQ
       // 01 -> SLAVE (VFD OMRON)
       // 06 -> WRITE IN REGISTE
       // 00 01 -> REGISTER ADDRESS
       // 01 F4 -> VALUE TO WRITE IN THE REGISTER TO CHANGE THE MOTOR FREQUENCY

       telegram.au16reg[0] = 0;
       telegram.au16reg[1] = 0;
       telegram.au16reg[2] = 0;
       telegram.au16reg[3] = 0;
       telegram.au16reg[4] = 0;
       telegram.au16reg[5] = 0;
       telegram.au16reg[6] = 0;
       telegram.au16reg[7] = 1;

       telegram.au16reg[8] = 1;
       telegram.au16reg[9] = 1;
       telegram.au16reg[10] = 1;
       telegram.au16reg[11] = 1;
       telegram.au16reg[12] = 0;
       telegram.au16reg[13] = 1;
       telegram.au16reg[14] = 0;
       telegram.au16reg[15] = 0;

       master.query( telegram ); // send query (only once)
       delay(3500);
       telegram.u8id = 1; // slave address
       telegram.u8fct = 5; // function code (this one is registers read)
       telegram.u16RegAdd = 1; // start address in slave
       telegram.u16CoilsNo = 2; // number of elements (coils or registers) to read
       //telegram.au16reg = au16data; // pointer to a memory array in the Arduino

       // PARA EL VARIADOR OMRON MX1: MODBUS RTU 01 05 00 00 00 00 -> STOP
       // 01 -> ESCLAVO (VARIADOR OMRON)
       // 05 -> ESCRIBIR EN UNA BOBINA
       // 00 00 -> DIRECCION DE LA BOBINA
       // 00 00 -> VALOR A ESCRIBIR EN LA BOBINA PARA STOP

       telegram.au16reg[0] = 0;
       telegram.au16reg[1] = 0;
       telegram.au16reg[2] = 0;
       telegram.au16reg[3] = 0;
       telegram.au16reg[4] = 0;
       telegram.au16reg[5] = 0;
       telegram.au16reg[6] = 0;
       telegram.au16reg[7] = 0;
       telegram.au16reg[8] = 0;
       telegram.au16reg[9] = 0;
       telegram.au16reg[10] = 0;
       telegram.au16reg[11] = 0;
       telegram.au16reg[12] = 0;
       telegram.au16reg[13] = 0;
       telegram.au16reg[14] = 0;
       telegram.au16reg[15] = 0;
       master.query( telegram ); // send query (only once)
       delay(3500);
       u8state++;
       break;
     case 2:
       master.poll(); // check incoming messages
       if (master.getState() == COM_IDLE) {
         u8state = 0;
         u32wait = millis() + 100;
       }
       break;
     }
    }

I've managed to send RUN command to VFD but i can't (so far) send the change frequency command "01 06 00 01 01 F4" + CRC check.

When I connect logic analyzer with modbus rtu decoder, it shows "Device ID:'1' Function Write single coil ('5') Addr: '0' value: '65280' Chksum: '14988'.

The problem is that it pass only 1 telegram (array of packets) for command "RUN" but no the two others. Any help will be appreciated.

This is the link for VFD Omron MX: https://industrial.omron.us/en/media/I570-E2-02B_3G3MX2_UsersManual_tcm849-112721.pdf

TIA

title: Arduino Modbus RTU VFD control

Answers: 1

body:
You should update the comments and remove unused settings like the count fields for request with one value (function 5 and 6).

au16reg are the data to be send. ignore the binary format from the example.

To send a value of the coil or register set the value to telegram.au16reg[0].

For the Modbus message protocol see for example [the Wikipedia article][1].

  [1]: https://en.wikipedia.org/wiki/Modbus#Supported_function_codes


body:
Currently trying to get a teensy 3.5 to spam a series of notes in a loop over USB and hardware serial, which I am pretty sure it can do.

I have a MIDI circuit set up as per the specifications here:
https://www.pjrc.com/teensy/td_libs_MIDI.html
And currently have it booping a looping grouping of notes through massive embedded in ableton over a 5 PIN DIN circuit feeding into a generic MIDI 5 Pin DIN -> USB converter.

     #include <MIDI.h>

    #define HWSerial Serial1
    MIDI_CREATE_INSTANCE(HardwareSerial, Serial1, MIDI);
    const int channel = 1;

    void setup() {

      HWSerial.begin(9600);
      MIDI.begin();
    }

    void loop() {
      int note;
      for (note=10; note <= 127; note++) {
        MIDI.sendNoteOn(note, 100, channel);
        delay(200);
        MIDI.sendNoteOff(note, 100, channel);
      }
      delay(2000);
    }

I am lead to believe that when working with the USB serial output on the teensy you simply refer to the port as 'Serial' and for the others it's 'Serial1', 'Serial2', and so on.

I have tried using serial in place of the arguments within MIDI_CREATE_INSTANCE
and also tried using MIDI_CREATE_DEFAULT_INSTANCE which should do this setup on the default serial port, which I assume is USB? (This worked fine on my arduino mega setup where I was using the 16u2 chip as a serial -> USB midi converter as per this method: https://github.com/ddiakopoulos/hiduino)

I'm just a little stumped as I have managed to get the code to compile using default instance and it appears as a midi device in windows device manager and also in ableton when I set USB Type: Serial + MIDI from arduinos tools dropdown box but does not output any notes :(

Can anyone help me get this working?

I'm currently toying with:

        #include <MIDI.h>

    const int channel = 1;

    void setup()
    {

    }

    void loop()
    {
      int note;
      for (note=20; note <= 63; note++) // Range was changed from 10:127 to save eardrums.
      {
        usbMIDI.sendNoteOn(note, 100, channel);
        delay(200);
        usbMIDI.sendNoteOff(note, 100, channel);
      }
      delay(2000);
    }

but get

        C:\Users\Jamie\AppData\Local\Temp\arduino_build_144363/..\arduino_cache_283435\core\core_teensy_avr_teensy35_usb_serialmidi,speed_120,opt_o2std,keys_en-us_4939f5412a75a8560acb0f9e98268f02.a(pins_teensy.c.o): In function `_init_Teensyduino_internal_':

    C:\Program Files (x86)\Arduino\hardware\teensy\avr\cores\teensy3/pins_teensy.c:582: undefined reference to `analog_init'

    collect2.exe: error: ld returned 1 exit status

    Error compiling for board Teensy 3.5.

and if I try inluding 'usbMIDI' I get

    F:\GigaTech\MMMM_Beta_Code\debug\TeensyUSBMIDILoopTest\TeensyUSBMIDILoopTest.ino:1:21: fatal error: usbMIDI.h: No such file or directory

    compilation terminated.

    Error compiling for board Teensy 3.5.

although midiUSB is definitely installed :S

----------------------------------------------------------------------------
------------------------------C O N T I N U E D ----------------------------
----------------------------------------------------------------------------

Ok so I now have a working sketch for both USB and Hardware MIDI comms but I can't seem to get them to work simultaneously.
My code for the hardware is as shown above, and the USB method is below:

     #include <MIDI.h>

    MIDI_CREATE_INSTANCE(HardwareSerial, Serial1, MIDI);
    const int channel = 1;

    void setup() {
      MIDI.begin();
    }

    void loop() {
      int note;
      for (note=10; note <= 127; note++)
      {
        usbMIDI.sendNoteOn(note, 100, channel);
        delay(200);
        usbMIDI.sendNoteOff(note, 100, channel);
      }
      delay(2000);
    }

I sort of assumed it would be possible to do something like this:

     #include <MIDI.h>

    #define HWSerial Serial1
    MIDI_CREATE_INSTANCE(HardwareSerial, Serial, MIDI); // 5 Pin DIN Out
    const int channel = 1;

    void setup()
    {
      HWSerial.begin(9600);
      MIDI.begin();
    }

    void loop() {
      int note;
      for (note=20; note <= 63; note++) // Range was changed from 10:127 to save eardrums.
      {
        usbMIDI.sendNoteOn(note, 100, channel);
        MIDI.sendNoteOn(note, 100, channel);
        delay(200);
        usbMIDI.sendNoteOff(note, 100, channel);
        MIDI.sendNoteOff(note, 100, channel);
      }
      delay(2000);
    }

But It doesn't seem to work.
The code compiles and uploads just fine, however, ableton only sees MIDI messages coming over the teensy usb port and not through my MIDI receiver.
I wondered if this is because the two are both being routed to my PC via a usb port but this shouldn't be a problem surely.
I have also tried assigning the USB and hardware MIDI sends to different channels but to no avail.

I would love to get these both working simultaneously.

title: Using Teensy 3.5 (Arduino) to produce USB and Hardware MIDI messages simultaneously. Help?

Answers: 2

body:
Just use [usbMidi][1].

    #include <MIDI.h>

    MIDI_CREATE_INSTANCE(HardwareSerial, Serial1, MIDI);
    const int channel = 1;

    void setup() {
      MIDI.begin();
    }

    void loop() {
      int note;
      for (note=10; note <= 127; note++) {
        MIDI.sendNoteOn(note, 100, channel);
        usbMIDI.sendNoteOn(note, 100, channel);
        delay(200);
        MIDI.sendNoteOff(note, 100, channel);
        usbMIDI.sendNoteOff(note, 100, channel);
      }
      delay(2000);
    }

  [1]: https://www.pjrc.com/teensy/td_midi.html

body:
So I managed to get both working sumultaneously!

It seems that no declaration of a MIDI instance is necessary for teensy MIDI over USB, and I had a small error in my code, Said function declaration should read 'Serial1' not 'Serial'.

Working code is below! :)

    #include <MIDI.h>

    #define HWSerial Serial1
    MIDI_CREATE_INSTANCE(HardwareSerial, Serial1, MIDI); // 5 Pin DIN Out
    const int HWChannel = 2;
    const int USBChannel = 1;

    void setup()
    {
      HWSerial.begin(9600);
      MIDI.begin();
    }

    void loop() {
      int note;
      for (note=20; note <= 63; note++) // Range was changed from 10:127 to save eardrums.
      {
        usbMIDI.sendNoteOn(note, 100, USBChannel);
        MIDI.sendNoteOn(note, 100, HWChannel);
        delay(200);
        usbMIDI.sendNoteOff(note, 100, USBChannel);
        MIDI.sendNoteOff(note, 100, HWChannel);
      }
      delay(2000);
    }


body:
I am making a device which will have a button to measure the input and another button to reset and the inputs are variable analog values(0 to 5v) and output is a ratio of two analog input voltages. It also has a selection keys(two buttons) for four selections(like gain eg. if key1 == LOW key 2 == LOW then J = 1 and likewise)
but the problem is when i am multiplying j with it the output shows zero if I multiply numbers like 1,2,3etc without using j then the ratio value gets multiplied.

here is the code

        void setup() // put your setup code here, to run once:
        {
          Serial.begin(9600);
          pinMode( K1, INPUT );
          pinMode( K2, INPUT );
          pinMode( MeasureButton, INPUT );
          pinMode( ResetButton, INPUT );
          dsp.begin(20, 4);
          current = millis();
        }

        void loop()
        {

          while(current < wait)
          {
          Serial.println("INITIALIZING");
          delay(1000);
          current = millis();
          }
          Serial.println("                   ");
          delay(1000);
          Serial.println(" READY TO MEASURE ");
          delay(2000);
          while (digitalRead(MeasureButton) == LOW)
          {
            if(K1 == LOW && K2 == LOW)
            {J = 1; // SOMETHING VALUE
            showMessage1();
            i = 0;
            delay(1000);
            }if(K1 == LOW && K2 == HIGH)
            J= 2; // SOMETHING VALUE
            showMessage1();
            i = 0;
            delay(1000);
            if(K1 == HIGH && K2 == LOW )
            J= 3; // SOMETHING VALUE
            showMessage1();
            i = 0;
            delay(1000);
            if(K1 == HIGH && K2 == HIGH )
            J= 4; // SOMETHING VALUE
            showMessage1();
            i = 0;
            delay(1000);

          }
          while (digitalRead(ResetButton) == HIGH)
          {
          dsp.setCursor(1,0);
          dsp.print("                   ");
          Serial.println("                   ");
          delay(1000);
          dsp.setCursor(1,0);
          dsp.print("RESETED");
          Serial.println("RESETED");
          delay(1000);
          }
    while (digitalRead(ResetButton) == LOW)
          {
          dsp.setCursor(1,0);
          dsp.print("                   ");
          Serial.println("                   ");
          delay(1000);
          dsp.setCursor(1,0);
          dsp.print("PRESS MEASURE");
          Serial.println("PRESS MEASURE");
          delay(1000);
          }
        }

        void showMessage1()
        {
           while(i<5)
            {
            A = analogRead(A0);
            B = analogRead(A1);
            C = analogRead(A2);
            D = analogRead(A3);
            N = analogRead(A4);
            W1 = (A/N)*J;        // J is another variable whose value is dependent on K selection values
            W2 = (B/N)*J;        // J is another variable whose value is dependent on K selection values
            W3 = (C/N)*J;        // J is another variable whose value is dependent on K selection values
            W4 = (D/A)*J;        // J is another variable whose value is dependent on K selection values

            sumW1 = sumW1 + W1;
            sumW2 = sumW2 + W2;
            sumW3 = sumW3 + W3;
            sumW4 = sumW4 + W4;
            i++;
          }
            Serial.print("W1-");
            Serial.print(sumW1);
            Serial.print("W2-");
            Serial.println(sumW2);
            Serial.print("W3-");
            Serial.print(sumW2);
            Serial.print("W4-");
            Serial.println(sumW4);
            sumW1 = 0;
            sumW2 = 0;
            sumW3 = 0;
            sumW4 = 0;
        }

title: Digital selection for gain control not working instead showing 0

Answers: 1

body:
      pinMode( K1, INPUT );

with

        if(K1 == LOW && K2 == LOW)

makes no sense. `K1` is a pin number. `LOW` is a macro for `0` (`HIGH` for `1`). You are comparing a static pin number against a static number.

If `K1` is not equal to 0, the inner part of that if statement can never be reached.

What you meant to do was "if the voltage at the pin K1 is low". For that you need to read out the current value of the pin and check it.

For that you must replace your `if(K1 == LOW)` type statements to `if( digitalRead(K1) == LOW)`.

I'd also like to mention that you must have a pull-up on your buttons for this "LOW"/"HIGH" logic to work. Either externally, or use `INPUT_PULLUP` instead of `INPUT` in `pinMode`.


body:
I am new into arduino and stuff. So i was playing around with the pull up resistor. It worked fine but the problem rised when I used a delay to turn the led on for few seconds before it gets back to low state it stopped working when I pressed the switch multiple times it may work sometimes but maximum time it is not working

***here is the code***

    const int buttonPin = 4;
    const int ledPin =  12;
    int buttonState = 0;

    void setup() {
          pinMode(ledPin, OUTPUT);
          pinMode(buttonPin, INPUT_PULLUP);
    }

    void loop() {
            buttonState = digitalRead(buttonPin);
          if (buttonState == LOW)
      {
        digitalWrite(ledPin, HIGH);
        delay(5000);
      } else
      {
        digitalWrite(ledPin, LOW);
        delay(5000);
      }
    }

title: Why the LED freezes? when I am adding a delay?

Answers: 1

body:
Your Arduino does nothing during the delay(5000). So pressing the button during the 5000 mSec that the led is off won't do anything. Or you must be very lucky to press the button in the very small time between one loop and the next.

I learned a lot about timing and delays with this tutorial: [Blink Without Delay][1]

  [1]: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay


body:
I ordered some cheap servos from Amazon before I noticed that there seemed to be two different kinds (digital & analog).

Mine are Tower Pro SG90 Analog ([http://www.towerpro.com.tw/product/sg90-analog/][1])

I was trying to get mine to work with an extremely simple sample code (below) using the Arduino Servo library (using digital pin 3) and I was experiencing the jitters.

I read over the solutions at : [https://electronics.stackexchange.com/questions/77502/is-there-a-way-to-stop-servos-from-shaking][2]

While reading that I learned that there is also a *digital* flavor of the servo:
[http://www.towerpro.com.tw/product/sg90-7/][3]

I'm wondering if that is part of the problem I'm seeing with the servo jittering.  I haven't seen this addressed elsewhere.

**My questions are:**

 1. Are those servos even different? Maybe that is just a marketing
    thing??
 2. Do I need to switch to using an analog pin for the servo data
        connection?
 3. Is it even possible to use the Arduino Servo library for this
    purpose or do I need to use some *manual* code (like analogWrite()) **and** move the servo to an analog pin?
 4. Or, should it work completely fine and the jittering is just some
    unrelated problem?

Here's the simple code I'm using:

    #include <Servo.h>
    Servo myservo;  // create servo object to control a servo
    // twelve servo objects can be created on most boards

    int pos = 0;    // variable to store the servo position

    void setup() {
      myservo.attach(3);  // attaches the servo on pin 3 to the servo object
    }

    void loop() {
      for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
        // in steps of 1 degree
        myservo.write(pos);              // tell servo to go to position in variable 'pos'
        delay(15);                       // waits 15ms for the servo to reach the position
      }
      for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
        myservo.write(pos);              // tell servo to go to position in variable 'pos'
        delay(15);                       // waits 15ms for the servo to reach the position
      }
    }

  [1]: http://www.towerpro.com.tw/product/sg90-analog/
  [2]: https://electronics.stackexchange.com/questions/77502/is-there-a-way-to-stop-servos-from-shaking
  [3]: http://www.towerpro.com.tw/product/sg90-7/

title: Will analog servo work with Arduino servo library?

Answers: 2

body:
Jitter can be caused by a lack of power, in which case it will be an irregular pattern that leaves the servo in the wrong place or it can be caused by the increment commands not being sent to the servo smoothly enough.

Have you got enough power for the servo? Where is the power coming from, does this output match the datasheet?

This analog servo requires PWM, so is pin 3 of you board PWM capable?

How fast does you servo rotate?  At the moment you are saying 1degree every 15ms, I suspect that is too slow and that's why the arm is coming to a stop and then rotating again which is making it jitter.

body:
There's a [discussion here][1] about the difference. The short answer is they both are commanded by a PWM signal but differ in the internal control circuitry that responds to it.

  [1]: https://www.rcgroups.com/forums/showthread.php?498802-Help-on-digial-servos&highlight=digital servo


body:
    //Error message Arduino: 1.8.5 (Windows 10), Placa:"Arduino/Genuino Uno"

    Tone.cpp.o (symbol from plugin): In function `timer0_pin_port':

    (.text+0x0): multiple definition of `__vector_7'

    libraries\IRremote\IRremote.cpp.o (symbol from plugin):(.text+0x0): first defined here

    collect2.exe: error: ld returned 1 exit status

    exit status 1
    Erro ao compilar para a placa Arduino/Genuino Uno.

    Este relatório teria mais informação com a
    opção «Mostrar mensagens detalhadas durante a
    compilação» seleccionada nas Preferências.
    //

Code

    #include <IRremote.h>      //must copy IRremote library to arduino libraries
    #include <Servo.h>
    #define plus 0xFD10EF   //clockwise rotation button
    #define minus 0xFD50AF  //counter clockwise rotation button

    int RECV_PIN = 2;       //IR receiver pin
    Servo servo;
    int val;                //rotation angle
    bool cwRotation, ccwRotation;  //the states of rotation

    IRrecv irrecv(RECV_PIN);

    decode_results results;

    const int pinoledlar=10;
    int portaled4 = 12;
    int portaled3 = 8;
    int portaled2 = 11;
    #define pinopir 3
    int acionamento;
    const int sirene=7;
    int portaLDR = A5; //Porta analógica utilizada pelo LDR

    void setup()
    {
      Serial.begin(9600);
      irrecv.enableIRIn(); // Start the receiver
      servo.attach(9);     //servo pin
      pinMode(pinoledlar,OUTPUT);
      pinMode(portaled2, OUTPUT);
      pinMode(portaled3, OUTPUT);
      pinMode(portaled4, OUTPUT);
      pinMode(pinopir,INPUT);
      pinMode(sirene,OUTPUT);
    }

    void loop()
    {
        acionamento=digitalRead(pinopir);
        if (irrecv.decode(&results))
        {
        Serial.println(results.value, HEX);
        irrecv.resume(); // Receive the next value

        if (results.value == plus)
        {
          cwRotation = !cwRotation;      //toggle the rotation value
          ccwRotation = false;         //no rotation in this direction
        }

        if (results.value == minus)
        {
          ccwRotation = !ccwRotation;   //toggle the rotation value
          cwRotation = false;            //no rotation in this direction
        }
        }
        if (cwRotation && (val != 175))
        {
        val++;                         //for colockwise button
        }
        if (ccwRotation && (val != 0))
        {
        val--;                         //for counter colockwise button
        }
        servo.write(val);
        delay(20);          //General speed

        if (acionamento==HIGH)//se detetar movimento
        {
        digitalWrite(pinoledlar,LOW);
        tone(sirene,440,1000);
        delay(1500);
        }
        else// senão detetar movimento
        {
        digitalWrite(pinoledlar,HIGH);
        noTone(sirene);
        delay(1500);

        int estado = analogRead(portaLDR);  //Lê o valor fornecido pelo LDR

        // Caso o valor lido na porta analógica seja maior do que
        // 800, acende o LED
        // Ajuste o valor abaixo de acordo com o seu circuito
        if (estado > 900)
        {
        digitalWrite(portaled2, HIGH);
        digitalWrite(portaled3, HIGH);
        digitalWrite(portaled4, HIGH);
        }
        else  //Caso contrário, apaga o led
        {
        digitalWrite(portaled2, LOW);
        digitalWrite(portaled3, LOW);
        digitalWrite(portaled4, LOW);
        }
    }
    }

title: What's wrong with this code?

Answers: 1

body: You have a very common problem that is documented all over. You have two libraries, Servo and IRremote, that are both trying to use the same hardware timer. Do a little Google searching for possible fixes. You will need to either find a different Servo library or a different IRremote library.


body:
im using 4 channel relay to switch the motor pump.  but when the arduino output is high and i check first with led. the led behavior were high too but when i attached to the relay input IN1,  the relay were low.  its like reversed action(the arduino is high, but relay was low then when arduino output is low,  suddenly the relay was high.  i try to edit the code hoping if i set arduino output is low then relay will be high but its still the same,  its reversed.  arduino output is low but the relay become high.  is there any way to make the relay to become high when the digital output is high?

however.. i didnt have the the actual circuit act but im using the digital pin as the output and some switches.  the project im work on is the automatic aquarium pump and water change which is the pump will automatically refill the water actuated by the float switch and will automatically drain the water and refill the new water in certain time.

im using pin 13 as the output.. and the pin 1 as the input which is a switch
as in picture im using a led as a output. but as soon i change to the relay, it become what i just said at the above
[![enter image description here][1]][1]
[![enter image description here][2]][2]
[![enter image description here][3]][3]
[![enter image description here][4]][4]

  [1]: https://i.stack.imgur.com/y2CDQ.jpg
  [2]: https://i.stack.imgur.com/gH2Ky.jpg
  [3]: https://i.stack.imgur.com/IZEPA.jpg
  [4]: https://i.stack.imgur.com/7Yoi3.jpg

title: Using a channel relay

Answers: 1

body:
First of all, you'll soon blow up that LED. (Or the Arduino if you're really unlucky.) You need a current limiting resistor.

Secondly, most relays have two switch contacts: normally closed (N.C.) and normally open (N.O.). If you want your device to be off, unless the Arduino turns on the relay, use the N.O. connection. If you want your device to be on, unless the Arduino turns on the relay, use the N.C. connection.
It looks like you need N.O.

N.b: 'closed' means on (i.e. the switch is closed and current is allowed to flow).

Finally, you seem to be using an external pull-up resistor for you switch, which is completely unnecessary: the Arduino has an internal pull-up resistor on every digital pin that you can enable using `pinMode(pin, INPUT_PULLUP)`.

**Edit**: you didn't connect the relay to the button pin instead of the LED pin, did you?


body:
I'm trying to issue a connection via HM-10 from arduino (rather than my phone).
However, I'm unable to start a connection from arduino using both AT+CON and AT+CONNL. When I try AT+CON I get `OK+CONNA` and when I use AT+CONNL I get `OK+CONNE`. Here's my code:

    #include <SoftwareSerial.h>
    SoftwareSerial bluetooth(8,9);

    void setup() {
      Serial.begin(115200);
      Serial.setTimeout(50);
      bluetooth.begin(115200); //open BLE connection
      bluetooth.setTimeout(50); //set timeout
      bluetooth.write("AT+ROLE1");
      //bluetooth.write("AT+ROLE0");
      delay(50);
      bluetooth.write("AT+NOTI1");
      delay(50);
      bluetooth.write("AT+CONC40BCB403020");
      delay(50);
      //bluetooth.write("AT+CONNL");
    }

    void loop() {
        while (bluetooth.available() > 0) {
          String response = bluetooth.readString();
          Serial.println(response);
        }
    }

The response that I get is:

    OK+Set:1
    OK+Set:1
    OK+CONNA

title: HM-10 Central mode starting a connection

Answers: 1

body: By now you've surely moved past this, but: I found that I had to try connecting multiple times in order to get a connection to complete.  Also, your timeout might need to be longer?


body:
I am trying to make a device which has two push buttons and one analog input. At first the serial monitor will show INITIALIZING, then it will show ready to begin if the measured pin is pressed. Then only it will start to measure if again pressed, then it will show ****************************** and if the reset pin is pressed, it will show reset. If again pressed then ------------------------
but the problem is, it is showing

*************
----------
(analog value) at the same time.

This is my code.

    int sensor = A0;
    int A = 0;
    int resetPin = 3;
    int measurePin = 2;
    int resetstatus = 0;
    int measurestatus = 0;
    boolean flag1 = true;
    boolean flag2 = true;
    long current = 0;

    void setup() {
     Serial.begin (9600);
     pinMode (sensor, INPUT);
     pinMode (resetPin, INPUT_PULLUP);
     pinMode (measurePin, INPUT_PULLUP);
     current = millis ();
    }

    void loop() {
     while (current < 3000) {
      Serial.println ("INITIALIZING");
      current = millis ();
      delay (200);
     }
     Serial.println ("Ready to begin");
     delay (200);
     resetstatus = digitalRead (resetPin);
     measurestatus = digitalRead (measurePin);
     if (resetstatus == LOW) {
      flag1 = !flag1;
      delay (50);
     }
     if (flag1 == HIGH) {
      delay (50);
      reset ();
     }
     if (flag1 == LOW) {
      Serial.println ("------------------------------------");
     }
     delay (100);
     if (measurestatus == LOW) {
      flag2 = !flag2;
      delay (50);
     }
     if (flag2 == HIGH) {
      delay (50);
      measure ();
     }
     if (flag2 == LOW) {
      Serial.println ("***********************************");
      digitalWrite (13, LOW);
     }
     delay (100);
    }

    void measure() {
     A = analogRead (sensor);
     Serial.println (A);
     digitalWrite (13, HIGH);
    }

    void reset() {
     Serial.println ("reset");
    }

title: How to show one thing in the serial monitor?

Answers: 1

body:
You have declare flag1 and flag2 as Boolean values but then you are looking to see if they are HIGH or LOW.  Bools are either true or false.  However because of the quirks of C++ this will probably work, if High and low are 1 and 0, its just bad style.

When you have this bit of code:

    if (flag2 == HIGH)
    {
        delay (50);
        measure ();
    }
    if (flag2 == LOW)
    {
        Serial.println ("***********************************");
        digitalWrite (13, LOW);
    }

You could use an else statement instead, i.e.

    if (flag2 == true) // Corrected to true
    {
        delay (50);
        measure ();
    }
    else
    {
        Serial.println ("***********************************");
        digitalWrite (13, LOW);
    }


body:
I am relatively new to Arduino, and have been doing a project to trigger an LED/alarm when movement is detected to be over a certain threshold value. I am using an Arduino Uno, an LED/buzzer (https://www.adafruit.com/product/2994), an MPU-6050 (https://playground.arduino.cc/Main/MPU-6050), and a 4 channel relay board (http://www.seeedstudio.com/blog/2013/02/28/shield-evolution-flexible-add-ons-for-arduino/relay-shield/ - sorry it's not very descriptive).

The LED/buzzer needs a 12V DC power supply, and I am using a wall wart to supply it. I am wondering how I am supposed to hook everything up - everything online tells me that the LED needs to be connected not only to the relay board, but to a power supply as well. However, my power supply is to the Arduino itself.

Based on the following picture, I would think that I would need to take the ground wire of the LED to the power source itself, then connect the power source to the relay board Common input.

[![This is not my project - I am simply looking at how the power is connected][1]][1]

Here is the circuit without the external power, using a small LED:

[![enter image description here][2]][2]

And here is the current setup (note that the cables were initially shifted over by 1 on the analog input, but I have fixed that since):

[![enter image description here][3]][3]

Is there a way to use the wall wart as the power supply? Do I even need the relay board?

  [1]: https://i.stack.imgur.com/G7Ym3.png
  [2]: https://i.stack.imgur.com/DXHXR.jpg
  [3]: https://i.stack.imgur.com/RvXDY.jpg

title: Arduino Wall Wart and Relay Board Power Supply

Answers: 1

body:
You will need the relay board.  The Arduino output 5V and so you can't use it to directly power the 12V half of the circuit.

If you can split the power from the wall wart so it powers the 12V circuit and the barrel connector on the Arduino then that should work.  If you can, then you will need to ensure that the 0v of the Arduino and the 12v circuit are tied together, otherwise the two halves of the circuit will be using different versions of 0V and you will get interesting results.

If you want to use the setup in your second picture then no you don't need the relay board, but that's only because the whole circuit is 5V.

"How do you split the power?" I hear you say, "do I need any extra hardware?"

That depends, how attached are you to your wall wart's cable?  The way I have done it is to ***UNPLUG*** the wall wart, cut the cable in "half", strip a cm of each wire and plug both ends of it into two empty rows on you bread board.  Then use jumper wires to take an additional feed off to the 12V circuit.

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

**CAUTION** Ensure you get the polarity of the wires the right way around.  You can test this with a volt metre.  I suggest red electrical tape to mark the +ve wire.

**IF YOU ARE NOT CONFIDENT DON'T DO IT!**

  [1]: https://i.stack.imgur.com/bBHCx.jpg


body:
I am trying to pass an image to the display through the GxEPD module. I tested the display and its working fine with an example sketch.

I am using a WEMOS LOLIN32 and a 7,5" B/W Waveshare display.

When I add any other image after converting it to hex values, this happens:

This is the image in GIMP:

[![][1]][2]

And this is what the display shows:

[![][3]][4]

As you can see, the display shows the image glitched a lot. It looks a lot like each "row" of a few pixels is mirrored horizontal. The question here is: Why? All I did was converting the image in GIMP to .xbm, taking the content, stripping whitespace, pasting the Arduino syntax around the code and replacing the example file with this one.

  [1]: https://i.stack.imgur.com/nVQ8Fm.jpg
  [2]: https://i.stack.imgur.com/nVQ8F.jpg
  [3]: https://i.stack.imgur.com/o0XhHm.png
  [4]: https://i.stack.imgur.com/o0XhH.png

title: Waveshare Display on ESP32 has weird graphic glitches

Answers: 0


body:
This bug/stupidity-of-myself/problem is killing me:
I'm have created an RGB strip controller that cycles through the additive-rgb-color spectrum while turning a potentiometer.

I have a pot hooked up to my Arduino Nano v3 (from AZ-Delivery, not official Arduino). Then I have an RGB amplifier hooked up to the Arduino with each phase (R, G, B, V+) and to an external power supply (12V by 2A max).

I shortened my program and removed all the value-to-colour-conversion because that has nothing to do with the problem:

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

    void loop() {
        ColorVal = analogRead(pinPot); //read value of color poti
        ColorByte = map(ColorVal, 0, 1023, 0, 255); //Scales 0-1023 to 0-255

        // potvalue to color conversion
        // ...

        // write via PWM to LED
        analogWrite(pinR, R);
        analogWrite(pinG, G);
        analogWrite(pinB, B);
    }

**My problem:** Theoretically you would expect the system to show white when all variables (R, G and B) are set to 255. However, it behaves the other way around. When all values are set to 255 it's off and vice versa. Another example: When R = 255 and G = 0 and B = 0 Green and Blue are lighting and Red is off.

I thought this has to do with polarity or something but I cannot seem to find it out.

title: RGB LED strip inverted PWM

Answers: 1

body:
The RGB LED strip has a common anode (V+). When you put 12 V on R, G or B, the LEDs have 12 V on both sides, so there is no voltage across it and no current.

And if you put 0 V, they have 12 V across it and light up.

To fix it, just invert the PWM value in your code:

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

    analogWrite(255-pinR, R);
    analogWrite(255-pinG, G);
    analogWrite(255-pinB, B);


body:
I've been working on this small project, not that small for me though, for a while. Because I also had classes and exams I didn't really have time for it. But almost everything was done except that I couldn't figure out the proper way of communicating with the ESP8266-01 and I need your help or guidance or any idea that may help.

**Here is what I am trying to do:**

I have an Arduino Uno, an L298N motor driver, an ESP8266-01 and a small DC motor, all connected properly to my Arduino. Besides that, I also have a gamepad for PC, which I would like to control the DC motor with over the ESP8266-01.

**Here is what I've done so far:**

I've used the [SDL library][1] in C to get the analog stick input from my gamepad and I am able to increase and decrease the speed with my gamepad.

I've also connected the ESP8266-01 to my WiFi and I can change the motor speed from terminal using telnet (via port 80). **But not accurately**.

**What is left** is to find a proper way to communicate with the ESP8266-01 so that it responds to every request and to connect these two together so that my project is done and I can control the DC motor with my gamepad.

I was searching for a proper way to communicate with the ESP8266-01 through the terminal. I've tried using telnet (via port 80) but sometimes for some reason the ESP8266-01 won't respond my request or sometimes I lose the connection and I get a respond like below:

> telnet: Unable to connect to remote host: Connection refused

Below is the code that I am using for my Arduino to control the motor speed and also the direction of it.

    #include <SoftwareSerial.h>
    #define DEBUG true
    SoftwareSerial esp8266(2, 3); //Rx, Tx
    void espsend(String);
    String sendData(String command, const int timeout, boolean debug);

    void setup()
    {
      Serial.begin(9600);    //For Serial monitor
      esp8266.begin(9600);   //ESP Baud rate
      pinMode(13, OUTPUT);
      pinMode(12, OUTPUT);
      pinMode(9, OUTPUT);    //for speed of the DC motor
      analogWrite(9, LOW);
      digitalWrite(12,HIGH); //for direction of the DC motor
      digitalWrite(13, LOW); //for direction of the DC motor

      sendData("AT+RST\r\n", 5000, DEBUG); // reset module
      sendData("AT+CWMODE=1\r\n", 5000, DEBUG); // configure as STA

      sendData("AT+CIPMUX=1\r\n", 3000, DEBUG); // configure for multiple connections
      sendData("AT+CWJAP=\"wifiID\",\"wifiPW\"\r\n", 3000, DEBUG);
      sendData("AT+CIFSR\r\n", 5000, DEBUG); // get ip address
      sendData("AT+CIPSERVER=1,80\r\n", 5000, DEBUG); // turn on server on port 80

    }

    int connectionId;
    void loop()
    {
      int velocity;
      char direction[]="direction=";
      char speed[]="speed=";
      char ipd[]="+IPD,";
      if (esp8266.available())
      {
        if(esp8266.find(ipd)){

        delay(1000);
        connectionId = esp8266.read() - 48;
        esp8266.find(speed);
        if(velocity = esp8266.parseInt()){
          analogWrite(9, velocity);
        }
        if(esp8266.find(direction)){
            delay(300);
            int direction2= esp8266.parseInt();
            if(direction2 == 1){
              digitalWrite(12,HIGH);
              digitalWrite(13,LOW);
        }else{
          digitalWrite(12,LOW);
          digitalWrite(13,HIGH);
        }
    }
      String closeCommand = "AT+CIPCLOSE=";  //close the socket connection
      closeCommand += connectionId; // append connection id
      closeCommand += "\r\n";
      sendData(closeCommand, 2000, DEBUG);
        }
      }
    }

    String sendData(String command, const int timeout, boolean debug)
    {
      String response = "";
      esp8266.print(command);
      long int time = millis();
      while ( (time + timeout) > millis())
      {
        while (esp8266.available())
        {
          char c = esp8266.read(); // read the next character.
          response += c;
        }
      }

      if (debug)
      {
        Serial.print(response); //displays the esp response messages in arduino Serial monitor
      }
      return response;
    }

After uploading this code to my Arduino Uno, from the terminal I connect to the ESP8266-01 through `telnet 192.168.1.40 80`, then I send something like `+IPD,1,speed=40`. This works but not always and sometimes I lose connection.

What is the best way to communicate with the ESP8266-01 in this situation? I've searched on the Internet but I didn't really get anything useful. Using telnet is not always working and I don't know how fast my ESP8266-01 could respond to those requests, as I will be sending them like in miliseconds.

  [1]: https://www.libsdl.org/

title: What is the best way to communicate with ESP8266-01 in LAN?

Answers: 0