text:
One shift delay in receiving the response messages when using two nRF24L01 to communicate with each other
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:
#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

Probably you are waiting too long between sending the message and listening for data, so you're only getting the data on the next radio transmission.  See my answer to your other nRF24 question.  It looks like you can use ACK payload to send and receive data in the same radio transaction.  Please remember to upvote or accept the answer if correct.

From the code it looks like the slave keeps repeatedly sending the serial data. Shouldn’t it only sent it once?

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

you should accept your own answer.


text:
ISP with 115200 baud
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?

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

"programmers.txt" was the key! However I really had to change the one in "/hardware/arduino/avr/". Probably it's because I am  using Windows 10, or probably because I am still on Arduino 1.6.7. Anyway, it works now. Thank you so much!

They changed the way the board manager works in 1.8.x, in the new versions, other boards (cores) you install are in the ~/.arduino15/packages folder, including the standard AVR core. However, the old (1.6.x) hardware folder that you're using right now was not deleted, that's why I specifically added it. It's not a problem in 1.6.x, only newer versions.

source: Stack Exchange

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

sort: votes


text:
How to store an RFID tag number in a string
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=";

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.

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

do not use String
char url[64];
sprintf(url, "GET /ethernet/data.php?rfid_uid=%02x%02x%02x%02x", rfid[0], rfid[1], rfid[2], rfid[3]);

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


text:
Digital output from one nano to digital input of another.
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..

Do you only need unidirectional (A -> B) or bidirectional comm. (A <-> B)? Also, with common ground it's always at least two wires (GND + Signal). Or you use a differential signaling (signalPLUS, signalMINUS), like RS-485  which allows for longer cables due to higher noise immunity. How long is the cable?

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.

Thanks guys... Its just A>B so that's great. I will dig out a resistor


text:
TimerOne Library - Response time
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);
  }
}

please post all the code

That's going to be a lot but alright

then post minimal code that demonstrates the problem.

Yes, that's what I did

@jsotola got any idea as to why it wouldn't work?

narrow down the area that is causing the problem by reducing the transmitBit() code to only digitalWrite() and some supporting code that alternates the bit value between 1 and 0

I've had it work before with a different timer but I can't use that anymore

Is there a question here?

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.


text:
Is there any library for use Arduino Uno with esp8266-01 module?
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

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

No thanks! I was just looking for a tutorial for AT and arduino, I already have something from Expresif but programming the ESP8266 is not what I want to do right now and I don't have the tools required for the job.

You don't need one. You have an Arduino and a NodeMCU, both of them can be used as a USB programmer for the ESP-01. But you're free to do it the hard way, of course.

4 AT commands are harder than wiring and programming esp8266 with arduino? I'm just returning json

If it were easy, would you come to this site to ask for help? All I'm saying is that it is much easier to use the mature and well-written Arduino ESP8266 Core libraries for network communication, and that it's pretty wastful to use both an Arduino and an ESP8266 if you just want to read a temperature sensor. The most basic temperature logger could be written in ~20 lines, it would work great and have good error handling. From my own experience, I know that it is much more cumbersome to do the same thing using AT commands.

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.

The sensor that I'm using LM35 needs at least 4V, besides I will need to program the esp8266 and I don't have tools for that, and I bought for provide wifi to arduino. I have a nodemcu too btw

If you have the tools to program the Arduino UNO then you also have the tools to program the ESP8266.

You didn't google hard enaugh.
There are plenty of examples serving your environment.
This instructables 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.

That is not what I need check my description again.


text:
How do you convert PCM to PWM?
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?

http://playground.arduino.cc/Code/PCMAudio

An Arduino is not an audio player. It won't have enough processing power and/or memry for running an SD card, refreshing an OLED display and playing audio. Use specialized hardware and a decent DAC for audio playback.

Or go the cheap route and use an LC filter. This video has good info on both DACs (R2R-style) and PWM+Filter "DACs": https://www.youtube.com/watch?v=Y2OPnrgb0pY What's your speaker system? You might need another OpAmp or audio amplifier.

tttapa, I've seen a lot of tutorials online. Maybe if I remove the OLED display it might be able to run it but I'm just curious and I want to get to the end of it even if the output isn't want I desire.

Maximilian Gerhardt, LC filter makes sense after I've generated PWM signal. My whole problem is that I'm not able to do that. I just don't know what the interface between PCM WAVE file and PWM is.

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 example available, but it only works from audio embedded within your program.
There is also a 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.

Thanks for replying early. Well I was thinking if we can use 16bit PWM for audio output at 44KHz timer interrupt. And to compensate for the low memory holding capacity of the Arduino we can use double buffering from an SD card.
OR
Adding an external 16bit DAC IC would reduce the complexity because then maybe I don't have to worry about PWM? (I'm not sure about this part.)

See my answer below. PCM can most certainly be converted to PWM and played on  most MCUs.

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.

Comments have been moved to chat; please do not continue the discussion here. Before posting a comment below this one, please review the purposes of comments. Comments that do not request clarification or suggest improvements usually belong as an answer, on [meta], or in [chat]. Comments continuing discussion may be removed.


text:
HC-05 3.3 voltage regulation
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..

All you need are two resistors. As shown in every single tutorial for using the HC-05 with an Arduino.

Thanks... Where are thease tutorials? . I've watched 12 now on YouTube and they are all connecting them direct. One guy at the start mentioned he was going to use two resistors then proceeded not to use any in his video..

YouTube is worse than instructables for being full of crap. Type "hc-05 Arduino" into Google and look at the pictures.


text:
Is it possible to program/flash ESP8266MOD(07) With Arduino UNO
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

yes you can. all you need is 5 wires. flip rx and tx and put gnd to rst on the uno.

Yes you can.
Take a look at this detailed guide.
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:

You'll probably want some buttons to facilitate the flashing process:

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 (there is also one section how to flash with an Arduino Uno).


text:
SdFat initialization blocks HC-SR04
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;
}

What board are you using?

Arduino Uno ATmega328P-PU (das Original!)

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.

Thanks for your quick answer. I tried as you told me and switched SS/CS to pin10 and tried the HC-SR04 on pins 8/9 and 6/7 without success. Now it doesn`t work at all. Not with nor without the line.

WORKED! Sorry I had a mistake in wiring, Perfect. Thanks a lot!


text:
Measuring the speed of an object moving fast through air
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!

some part of the fly path will be without measurable acceleration and deceleration. Mythbusters used a high speed camera

How so? What circumstances would lead to that?

When you get to max speed it will flatten out? What you are proposing is constant integration and is a best-guess scenario. Better is to get the time between two known positions and work it out from there.

But at max speed, I just need to add a 0 change in speed to my speed counter, and that would by default be the max speed right?

The problem is I don't have any two known positions.

How inaccurate should the estimate be? I am fine with a margin of inaccuracy....

It would drift over time. What distances and speeds are you considering?

Less than a meter and a around 2-3 kmph at best.

1m at 3kmph would give you 1.2s to get your samples. The more you take the better. Plus you have to factor in spin (and hence centrafugal & centrapetal force).

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. This is discussed in this arduino.stackexchange.com answer.  In that answer there is a link to a web page which implements dead reckoning using an Arduino. You will find this equation on that web page:
velocity(i) = velocity(i-1) + acceleration (i)

You can probably get off hold if you re-phrase your question to something like: "Measuring the speed of an object using an Arduino".  Then using similar wording in the question.

While this is an interesting project - dead reckoning is usually difficult to get right.  For this reason I would recommend checking out what might be possible using a color video camera and OpenCV.  However, perusing this approach takes you out of the Arduino realm and into (at least) the Raspberry Pi realm.


text:
DMX on the Arduino without additional driver chip
I recently saw this video 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:

Why do all sources I found say that there's a driver chip required when it seems to work without?
I got a Arduino Leonardo compatible device (Devduino). Is it possible to control DMX like stated above on this platform?

The physical layer of a DMX interface is based on differential signaling over an RS485 link.  This is exactly what is said here on the DMX Arduino.cc 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.

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.

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.


text:
char array comparison
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.

What does the mqtt.setServer do? Does it store a pointer reference or does it copy the input string to its own buffers? If you use a constant "192.168.1.42" then that string will be static. WHen you use ip.toString().c_str(), when the ip object is deallocated but .setServer() still has a reference to that char*, it's become invalid. Where is the library you're using?

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)
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)
Always read the API documentation, 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, which list all functions of the library.
If you still have doubts about what a function does, refer to the actual implementation files.


text:
How to drive SPI MAX7219 7-segment led module using MCP23S17 extender
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 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.

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

It isn't really clear to me what you want to do here.  Do you want to just use the pin extender for CS lines?  Then you just need to go into those libraries and rewrite to call whatever function writes a pin high or low on the extender instead of whatever digitalWrite it is calling now.  If you want to try to bitbang a completely separate SPI bus out of the extender then that's going to be a bit harder.  Why are you bit-banging SPI instead of using hardware in the first place?

Answering your second question first -- I have used all the hardware SPI pins for multiple displays which are daisy-chained.  Bit-banging allows me to extend to additional displays but takes up too many pins needed for other devices.  The MCP23S17 seems like the logical choice for extension.  I'm a user of the led control libraries, not a library author.

You can use the three hardware SPI pins to connect to as many displays as you want.  The SPI bus is meant to be used by many things in parallel.

I'm curious how "as many displays as you want" is defined.  I have 18 8-digit display modules to control.  Daisy chaining the cheap 8-digit modules doesn't work well past four and certainly not 18.

it is unclear what 7-segment 8 digit led module you are using? .... is it just an LED array without any drivers/decoders?

I have added an image for clarity.  A max7219 drives the 8 digits.  Each digit has 7 segments of LEDs.

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.

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

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.


text:
I want a code for 6 LDR/LED pair
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);

}

Welcome to Arduino:SE. Please be aware that this is not a free design house or an on-demand online technical encyclopedia. Please revise your question showing your work and findings so far. You might find it helpful to review the site tour and Help Centre and, in particular, [ask].

I have tried ... please show the work that you have done .... do you have a question? ... you have  not asked anything.

When you want to have the same thing happen multiple times with multiple settings or values it can be useful to generalise it by creating a class, then instantiating one object per LED + LDR pair.

can u explain more?

you posted working code for one LDR/LED pair .... please post the code that does not work

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

note: you do not need this statement if (ledIsOn) {  ..... only two lines if (lightLevel > 600)  ledIsOn = false; and if (lightLevel < 400)  ledIsOn = true;

ok can you please help me with the 6 LDR and 6 LED code I cannot seem to be able to do it

use lightLevel_1, ledIsOn_1, lightLevel_2, ledIsOn_2, lightLevel_3, ledIsOn_3, etc.

I cannot seem to be able to do it ... you still have not posted your code that you tried, but that does not work as expected

I edited my post now

I have the code for 6 LDR but I don't know how to make the code with 6 ldr and 6 led

does that code print out the values from the 6 LDRs? ..... do your comparison inside the for loop .... add code that uses lightLevel[i] and ledIsOn[i]

this code is just for 6 LDR and I need to add on it 6 led because my project is to create 6 LDR/LED pair

can you just please help me with the codes

Do you really understand, what the code for 1 LDR/LED pair does exactly? It doesn't seem so. You already created a for loop, that iterates through all the analog inputs. Now create an array with the LEDs pin numbers like you did with the analog pins. Inside the for loop, do what you have done before with 1 LDR/LED pair: Read the analog value into a variable, check if the variable is above 600 or below 400 and use digitalWrite() with the corresponding pin number (from the array) to set the correct value. If you cannot do this, you haven't understood, what the original code does.

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

it seems that you may have done the OP's school assignment.

@jsotola I wasn’t really convinced, and gave it the benefit of the doubt.

you may be correct in your thinking .... i do not mean to put down your choice to answer, i just wonder if the OP learned anything


text:
Correctly Powering Lilypad Arduino
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.

a standard 9V battery is one of the weakest batteries available ... it is 6 AAAA cells in series, which makes the available current is very low

Something tells me that a Lilypad isn't meant to have multiple sensors due to its size and its specifications. I've seen the Lilypad be utilized for appearal like a wrist watch or something.

@KingDuken You are correct, the Lilypad probably isn't designed for this but, in theory, I would expect the only limitation to be power supply.

@jsotola Would it be safe to assume that my issue has to do with current rather than voltage? If so, would you recommend more current into the Arduino or simply powering the components independently from the Arduino? I'm not certain of the limitations of the device.

I'm just not sure that this answer is especially helpful in regards to the question that was asked. Perhaps a more helpful answer might yield a better upvote count?

@simon-marcoux, hey max, this is portal about "how you better solder 2 resistors< 3, 5, 100".. there is another specialized portal about 2 arduinos on even how to connect them.. just take a look. Here an answer is not even right, nor even privillige! Its an opportunity which may be or may be not satisfied.. we are scientists and you could be too if you join so you must understand..

The onboard regulator of the lilpad arduino is able to provide roughly 500 mA of peak current. The temperature sensor and the BPM sensor shouldn't draw a lot of current and since they are Lilypad ready, they can be powered by routing the + and - to their respective pins. The real bummer that you have is probably the HC-05. Finding 5v to power it will be tough.
To power your whole system, I would use a lipo and the lipo connector. However, you will have the 5v problem that I previously mentioned...You will probably need two power source unfortunately.

@SimonMarcoux That makes sense. I only run into issues when I want to use the HC-05 along with the sensors, when powering it separately, I have no issues. Thank you for the insight.

@JHolland for that particular Arduino board (https://www.sparkfun.com/products/12049), the regulator input voltage (MIC5219) can be up to 12 volts. Depending on your board, you might find one with a regulator high enough to split your voltage at the battery level before the regulation occurs. That way, you only need 1 5v ish battery and you would be good to go...or go for a higher voltage with a 5v regulator.


text:
Timer2 Compare Interrupt not working as expected
To get this out of the way first: I have already looked at "Timer2 does not work as it should" and "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 and checked that all registers are set correctly.
Thanks in advance for your help. If you need any further information, let me know.

What's in the isrCallback after the initialize? You should enable timer compare A interrupt in the attachInterrupt method only. And in the attachInterrupt it should be set first, than enabled.

A timer can only run as fast as the ISR that it triggers. If your ISR takes 1ms to run you will get no faster than 1ms - no matter what you set the period to (below 1ms).

It does not take 1ms, as I've already run it at faster speeds already just not with that timer.

@KIIV even after only activating it in the attachIntterupt it still does not work.

Try doubling OCR2A and see in you get a 2ms interval, or not. What Arduino board are you using? E.g. the Pro Mini 3.3V runs at 8Mhz, so half the speed of the 16Mhz your code is assuming.

To go back to my comment about my ISR: Apparently it DOES take about 1ms but that didn't have to do anything with the problem. I don't know how or why the logic analyzer I have showed my once that it could have a period of 30us but since I wasn't able to reproduce this result it was probably a bug or glitch.
The problem described here did not have to with that though since a simple blinky suffered the same problems.

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

Thanks, that really helped.
Another thing I found out, however, is that the code in my ISR takes longer than 1ms apparently. So I'll have to find a solution for that now quickly.


text:
Arduino Modbus RTU VFD control
I need help with this code:
/**
*  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

first you should update the comments and remove unused settings like the count fields for request with one value (function 5 and 6). you do not set the value into au16reg like you have it in PARA EL VARIADOR OMRON MX comments

In this sketch, i don't know how this telegram with the vfd commands made of. For example:telegram.u8id = 0x01; // slave address
telegram.u8fct = 0x06; // function code (this one is registers read)
telegram.u16RegAdd = 0x01; // start address in slave
telegram.u16CoilsNo = 0x04; // number of elements (coils or registers) to read
//telegram.au16reg = au16data; // pointer to a memory array in the Arduino
//telegram.au16reg = 0000000111110100; What those 0's and 1's do?

https://en.wikipedia.org/wiki/Modbus#Supported_function_codes

au16reg are the data to be send. ignore the binary format from the example, send data required by the documentation

After clean those telegram.au16reg you said, i 've managed to pass the second and 3rd packet. How can i pass the appropriate value to the frequency? For example: How can i pass the value 40Hz to it?Any way you saved me a lot of searching time! Thank you!

set the value to telegram.au16reg[0]

How can i change the commands with 3 toggle switches. I wrote this code but it doesn't work. https://pastebin.com/UA0WFgQ7

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.

When i call the last code i gave, it works well and i get the correct message. When i call this code with  "master.query( telegram[0] ); // send query (only once)" call, the program doesn't work. What i've missed? Is it a good way to check button statements and send modbus rtu commands to vfd?

I do not see a problem with sending Modbus request triggered by button, but your code is still a mess. you can't do it if you can't understand and write code.

It looks like that i have a conflict when i call this telegram command then. Although i've test many modbus libraries but none works well. Also i can't achieve good timing with the modbus poll software and i got time error reports. Is it possible to help me with a code snippet to catch the missing point?


text:
Using Teensy 3.5 (Arduino) to produce USB and Hardware MIDI messages simultaneously. Help?
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.

Why are the logs full of mentions of "avr" for a board that does not use any sort of AVR chip???  Is this really bad naming and file locations in a plugin, or is the selected board configuration all mixed up?

Just use usbMidi.
#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);
}

I've been trying to do it this way as that's how I had it working with the arduino mega implementation but I just get this error:
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.

I'm pretty sure there is a proper way to do this, by opening another port with very similiar implementation to the hardware output code, but cant seem to get it right

The code I posted compiles just fine for me (Arduino 1.8.1, Teensyduino 1.41, Teensy 3.5, USB: Serial+MIDI). This is the proper way. Forget everything about MIDI USB on the Mega, it is completely different from the Teensy.

Strange, I tried a literal copy / paste of that code you posted and 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.

Try reinstalling Teensyduino. It looks like something is wrong with your core files.

Ok I will try it in your environment (With fresh installs of everything) and get back to you.

Yes, this has worked beautifully (Got held up by windows updates), I'll test tomorrow using both methods simultaneously, thanks!

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


text:
Digital selection for gain control not working instead showing 0
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;
    }

  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.

you just saved me. :) I will correct that


text:
Why the LED freezes? when I am adding a delay?
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);
  }
}

What does happen, when it doesn't work? Please explain further

the state of the LED doesn't change.

you are not reading the switch during the delay(5000).... you have to hold the button down for up to 5 seconds

Change the second delay to lower value, say 100ms.

one of the things that you have to learn when programming is to identify the area of failure .... your program fails to respond to a pushbutton being pressed, it is not LED freezing

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

Actually the Arduino is doing something, just not what the op thinks.

Yes, it's waiting till the delay is over...

it never waits. You should see what delay actually does.

in the case of this code it does wait... otherwise this is what it does: 'Certain things do go on while the delay() function is controlling the Atmega chip however, because the delay function does not disable interrupts. Serial communication that appears at the RX pin is recorded, PWM (analogWrite) values and pin states are maintained, and interrupts will work as they should.' (From the arduino reference)

You should actually see what it does. Then you will know what I’m talking about.


text:
Will analog servo work with Arduino servo library?
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/)
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
While reading that I learned that there is also a digital flavor of the servo:
http://www.towerpro.com.tw/product/sg90-7/
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:

Are those servos even different? Maybe that is just a marketing
thing??
Do I need to switch to using an analog pin for the servo data
    connection?
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?
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
  }
}

"Analog" servos are the traditional PWM form which example servo code assumes - in fact the term "analog servo" is rarely used in the hobby context as those are the normal type, while "digital" would designate something supposedly premium, either incorporating a microcontroller inside and/or communicating by some more complex scheme.  If you're having a problem, it is something other than the use of a traditional style servo.

If you want to put that as an answer I will set as answer.  The distinction of analog v digital on that tower pro site confused me.  Thanks.

Seems like it would be more useful if you edited this to be about your actual problem.

That's a good point.  I was just thinking of people who have the jitter problem and notice the analog v digital servo and then find this and have an specific answer that it is not the problem.  There's a lot of discussion about the servo jitters out there.  :)

In general, embedded processor like an Arduino have less jitter problems than processors running an entire OS like a Raspberry Pi.  This is because the embedded processor is likely only controlling the servo while the processor running an OS is busy sharing its resources with all the other normally running processes in an OS.

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.

There's a discussion here 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.


text:
What's wrong with this code?
//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);
    }
}
}

IRemote and Servo both want to define the compare interrupt of the same timer. Find a way to shift one library to another hardware timer. (TIMER2_COMPA_vect according to https://arduino.stackexchange.com/a/12389/30175)

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.

Ty for the fast response i will try something before getting into any foward details.

I have solved my problem. I changed the IRremote timer and it works just fine.


text:
Using a channel relay
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

I see. How do I ask a good question about the Arduino?. What relay? What pump? i try to edit the code - what code? Please post your schematic (circuit). Edit your question to include these details and I am sure we will be able to help you.

@NickGammon alright sir, i just edited the post and you can refer to ths detail i given based on your questions

@AsrulAsyraff Could you please kindly post your code.

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?

oh i see... because im just referring to the led on the relay but i didnt connect any load on the relay so im just looking on lights on the led which located at the relay module.  is this means that i should try to connect the load on the relay and see the really output based on NC/NO connection instead just looking on the relay led?

@AsrulAsyraff: You connected the relay to the switch pin, instead of to the LED pin.

i  changed the LED and connect into the relays input


text:
HM-10 Central mode starting a connection
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

Can you let us know what is the response to the commands AT+CON and AT+CONN after 10 seconds?

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?


text:
How to show one thing in the serial monitor?
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");
}

The while statement with millis() is used uncorrectly here. 'current < 3000can only be true within the first 3s after the power up, (and also everytime 'millis()' overflows). If you only want to have it executed one time you should write itsetup(). Also: What do you mean by at the same time`?

change your pin declarations to #define sensor A0  ect....   there is no reason to have them be variables.  the variable current should be an unsigned long, not just a long.   Also no need to use millis() for your init portion.   In your setup loop you can just do Serial.println("Init"); delay(3000);

Still not sure what your problem is.   Can you post the output

@chrisl i wanted the INITIALIZATION to be showed only for 3secs when the power is turned on

@ChadG i want to observe only analog value when the measured button is pressed and reset to be shown when the reset button is pressed

Then, as Chad and me said, it's better to move this to setup() (as this function is made for one-time initialization) and use a simple delay(). When you are not doing anything during that time (as your sketch already does) this is better to understand

and what is it doing? Please give a little better description of user action and output

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


text:
Arduino Wall Wart and Relay Board Power Supply
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.

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

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

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

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.

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!

Okay that makes sense, thank you. Since I am a newbie, I'm not sure how to split the power between the two. Does that require another piece of hardware, or is it done via the wiring from the Arduino?


text:
Waveshare Display on ESP32 has weird graphic glitches
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:

And this is what the display shows:

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.

looks like a mixup between LSB and MSB encoding

yea, i thought so too, but i dont know how i can effectively solve this - i could include this in my python script im using for formating the code, but i wish there was a simpler fix for that

looks like poor software rescaling to me, are you sure the resolution is correct?

i changed the size of the image to exactly the pixels that were named in the article description - it should definetly be right, i tried making the image a few pixels smaller to see what happen, but that turned the image into an unreadable mess even more.


text:
RGB LED strip inverted PWM
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:
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.

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:
analogWrite(255-pinR, R);
analogWrite(255-pinG, G);
analogWrite(255-pinB, B);

Man, I love you. Thank you so much. The physical explanation makes it even more reasonable.