text:
Sparkfun Pro Micro (5v) as ISP error
I'm trying to use Sparkfun Pro Micro (5v 16MHz) as ISP to program Attiny chips (OS:Windows10Pro). I followed instructions. Installed proper driver and added Sparkfun boards to ArduinoIDE:

Using Arduino IDE uploaded ArduinoISP sketch on it. As you can see there are two options available to choose for programmer:

Arduino as ISP
Arduino Leonardo/Pro Micro as ISP

Which unfortunately both of them give the same error:
Sketch uses 28 bytes (2%) of program storage space. Maximum is 1024 bytes.
Global variables use 0 bytes (0%) of dynamic memory, leaving 64 bytes for local variables. Maximum is 64 bytes.
C:\Users\K1\AppData\Local\Arduino15\packages\MicroCore\tools\avrdude\7.1-arduino.1/bin/avrdude -CC:\Users\K1\AppData\Local\Arduino15\packages\MicroCore\hardware\avr\2.3.0/avrdude.conf -v -pattiny13a -cstk500v1 -PCOM16 -b19200 -Uhfuse:w:0xff:m -Ulfuse:w:0b00111010:m -Uflash:w:C:\Users\K1\AppData\Local\Temp\arduino_build_207900/sketch_aug28a.ino.hex:i

avrdude: Version 7.2
Copyright the AVRDUDE authors;
see https://github.com/avrdudes/avrdude/blob/main/AUTHORS

System wide configuration file is C:\Users\K1\AppData\Local\Arduino15\packages\MicroCore\hardware\avr\2.3.0\avrdude.conf

Using Port                    : COM16
Using Programmer              : stk500v1
Overriding Baud Rate          : 19200
avrdude stk500_recv() error: programmer is not responding
avrdude stk500_getsync() warning: attempt 1 of 10: not in sync: resp=0x00
avrdude stk500_recv() error: programmer is not responding
avrdude stk500_getsync() warning: attempt 2 of 10: not in sync: resp=0x00
...

avrdude done.  Thank you.
the selected serial port
 does not exist or your board is not connected

I tried avrdude in command line with these parameters and got the same results:
avrdude -p attiny13a -P COM16 -c avrisp -b 19200 -U flash:w:r.hex -v

I also found out that issue most probably has nothing to do with:

Target chip that I'm using: because changing it has no effect
Wiring: because even when there is no chip connected to SPI pins of ProMicro I get the same error
USB cable is good: I can upload sketches successfully to Pro Micro but cannot use it as ISP and replaced cable to rule that probably out.

This is while in this video the guy does what I want easily and has no issues whatsoever:
https://www.youtube.com/watch?v=7Rz9A9VbDx4
Any ideas appreciated.

GOTCHA...
After two days of search and speculation finally found the solution:
Short answer:
In avrdude command instead of -c avrisp use -c arduino:
avrdude -p attiny13a -P COM16 -c arduino -b 19200 -U flash:w:r.hex -v

Long answer:
My target chip was ATtiny13a, so I had to use MicroCore v2.3.0 which is the only core supporting ATtiny13 for Arduino. Contrary to other cores, in this core's programmers.txt list, each entry should have a upload.protocol line:
arduinoasispatmega32u4.upload.protocol=

otherwise it will give this error:
avrdude programmer_not_found() error: cannot find programmer id {upload.protocol}

I have added this line before to make that error go away but apparently with wrong parameter of stk500v1 that I have imitated from fabric entries! Converting this parameter to arduino solved the problem. This is what that entry should look like for ATtiny13 of MicroCore v2.3.0 (\packages\MicroCore\hardware\avr\2.3.0\programmers.txt):
arduinoasispatmega32u4.name=Arduino Leo/Micro as ISP
arduinoasispatmega32u4.communication=serial
arduinoasispatmega32u4.protocol=arduino
arduinoasispatmega32u4.upload.protocol=arduino
arduinoasispatmega32u4.speed=19200
arduinoasispatmega32u4.program.protocol=arduino
arduinoasispatmega32u4.program.speed=19200
arduinoasispatmega32u4.program.tool=avrdude
arduinoasispatmega32u4.program.extra_params=-P{serial.port} -b{program.speed}

For other cores, like ATTinyCore v1.5.2 (\packages\ATTinyCore\hardware\avr\1.5.2\programmers.txt) no such line is needed hence this entry works fine:
arduinoasispatmega32u4.name=Arduino Leo/Micro as ISP
arduinoasispatmega32u4.communication=serial
arduinoasispatmega32u4.protocol=arduino
arduinoasispatmega32u4.speed=19200
arduinoasispatmega32u4.program.protocol=arduino
arduinoasispatmega32u4.program.speed=19200
arduinoasispatmega32u4.program.tool=avrdude
arduinoasispatmega32u4.program.extra_params=-P{serial.port} -b{program.speed}

Also you should update avrdude in the Arduino core manually:
Download latest release from HERE, and replace them IDE's related files. If you can not find them take a look at HERE. If avrdude is not updated you might get an error like this:
Error during upload using programmer
The uploader process failed

The uploader process failed
The uploader returned an error
avrdude: Version 6.3-20201216
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch
         System wide configuration file is "C:\Users\K1\AppData\Local\arduino15\packages\MicroCore\hardware\avr\2.3.0/avrdude.conf"
avrdude: error at C:\Users\K1\AppData\Local\arduino15\packages\MicroCore\hardware\avr\2.3.0/avrdude.conf:421: syntax error
avrdude: error reading system wide configuration file "C:\Users\K1\AppData\Local\arduino15\packages\MicroCore\hardware\avr\2.3.0/avrdude.conf"

Third Solusion:
Use this App with this configuration:


text:
WaveHC Library Trouble
I posted this on the main Arduino forum, but no one has responded in 24 hours.
I'm trying to use the WaveHC library from Adafruit with a custom PCB. I am having trouble getting the SPI com to work for some reason, I modified the ArduinoPins.h, SS_PIN, from pin 10 to 8.
Using the Arduino SD library, I can see all the files no problem.
In the WaveHC library, all of the examples freeze after card.init(), I traced it to the spiSend(uint8_t b) in SdReader.cpp. It seems to get stuck in while(!(SPSR & (1 << SPIF)). This looks like the SPDR register (the SPI data register) is never loaded properly.
Does anyone know what is going on?
Adafruit library : https://github.com/adafruit/WaveHC
Edit :
This is the output from the SDReadTest example (Arduino SD Library)
Initializing SD card...Wiring is correct and a card is present.

Card type: SD2

Volume type is FAT32

Volume size (bytes): 1973350400
Volume size (Kbytes): 1927100
Volume size (Mbytes): 1881

Files found on the card (name, date and size in bytes):
SYSTEM~1/     2016-11-07 14:11:06
  INDEXE~1      2016-11-07 14:11:06 76
0.WAV         2016-11-07 11:44:14 22124
1.WAV         2016-11-07 11:44:14 18604
2.WAV         2016-11-07 11:44:14 19244
3.WAV         2016-11-07 11:44:14 19884
4.WAV         2016-11-07 11:44:14 21164
5.WAV         2016-11-07 11:44:14 23084
6.WAV         2016-11-07 11:44:14 21484
7.WAV         2016-11-07 11:44:14 29484
8.WAV         2016-11-07 11:44:14 20844
9.WAV         2016-11-07 11:44:14 25004
P.WAV         2016-11-07 11:44:14 21804

Notes :

I am using an Atmega328P @ 8MHz with the pro mini bootloader (this may be the issue)
SPI_DEFAULT_HALF_SPEED is set to true
SPI_INIT_SLOW is set to 1

Please post both code and circuit schematic.

I have tried all the examples in their repository https://github.com/adafruit/WaveHC. A schematic is unnecessary, I have verified my connections by testing my board with the arduino SD library.

Please edit your question to include a link to your Arduino forum post. Try setting the pinMode of SS pin of your microcontroller(10 on ATmega328P, 53 on ATmega2560) to OUTPUT in your setup() function. Even though you can use any pin to control the SS pin of the SD card, you need to sure the microcontroller's SS pin doesn't go low while using SPI, otherwise it goes into slave mode. Other useful information would be which microcontroller you're using and whether you've tried using the WaveHC library with SS on pin 10.

The arduino post is copy and paste...and still no one has responded. The pinMode for the SS pin is in the init method in SdReader.cpp, also I already tried adding in another pinMode in the setup. I'm using the Atmega328P 8Mhz. I can't try to use pin 10 because it is a smd custom PCB.

Have you tried the suggestions in the WaveHC readme?

Yes, I have tried all the suggestions in the readme

Just noticed that if the SS_PIN is left as 10 (as default, but not connected to anything in my case), I immediately get an error code, when I set it to 9 (not connected to anything either), it gets stuck in the while(!(SPSR & (1 << SPIF)) just like when it is set to 8 (which is the correct SS_PIN)

It seems that something is happening in the library that only allow SS to be 10, but I can't find where that is.. EDIT: Just thought that maybe there is a timing thing that depends on a 16Mhz clock

Just ran my board at 16MHz (@3.3V, don't yell at me, I know it's unstable) and it does the same thing, so I'm kind of ruling out the clock frequency being the issue.

Alrighty, found an SD breakout with a buffer and tested it with an Arduino Uno, and it works with pin 10 but not with pin 8 (whereas the official SD library works with both pins). So it looks like there is something in the library preventing the SS from being changed....

So the problem was that I did not read this comment carefully
/** SPI slave select pin. Warning: SS may be redefined as another pin
but the hardware SS_PIN must be set to output mode before any calls to
WaveHC functions. The SS_PIN can then be used as a general output pin */

"SS_PIN must be set to output mode before any calls to
WaveHC functions"
I read this and thought that meant whatever pin was being used as the SS pin needed to be an output, but it meant literally that pin 10 (the hardware SS pin) had to be set as an output regardless of whether it was being used or not.
So the solution is to add
pinMode(10, OUTPUT);

to anywhere in the code
Edit : also thanks @per1234 for pointing out the correct answer, I just didn't read your comment properly.

Glad to hear you found the solution! Please update your post on the Arduino forum with a link to this page so that people there will know you no longer need assistance. This will also help anyone with the same problem who finds your post there to be led to the answer.

source: Stack Exchange

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

sort: votes


text:
How do I display serial monitor on LCD keypad shield?
I want to be able to display what I am seeing on the serial monitor onto the LCD keypad shield I have connected to my Arduino UNO. Can someone possibly write the the code ontop of this for me?
I'm very new to coding so I apologies if it's hard for anyone to understand what i'm asking for.
int ledPin = 13; // LED is attached to digital pin 13
int x = 0; // variable to be updated by the interrupt

//variables to keep track of the timing of recent interrupts
unsigned long button_time = 0;
unsigned long last_button_time = 0;

void setup() {
  //enable interrupt 0 which uses pin 2
  //jump to the increment function on falling edge
  attachInterrupt(0, increment, FALLING);
  Serial.begin(9600);  //turn on serial communication
}

void loop() {
  digitalWrite(ledPin, LOW);
  delay(500); //pretend to be doing something useful
  Serial.println(x, DEC); //print x to serial monitor
}

// Interrupt service routine for interrupt 0
void increment() {
  button_time = millis();
  //check to see if increment() was called in the last 250 milliseconds
  if (button_time - last_button_time > 250)
  {
    x++;
    digitalWrite(ledPin, HIGH);
    last_button_time = button_time;
  }
}

I think it's much better if you figure this yourself, since it is a very basic question. You should just substitute (or add to) the Serial.println function with a writing to the LCD. You can use the LiquidCrystal library (click to go on the arduino reference page to see the functions and the examples). If you have problems following the examples, post a more specific question and we'll try to help..

I have attempted it but have failed :(

It keeps giving me the number 3 on the lcd

Never  mind I have done it!!! Thank you so much for the help and links :)

And now you learnt something new ;) good work, anyway :)

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


text:
Using IR Sensor to sense movement?
I was wondering if I could use a IR sensor with my Arduino to detect if someone is present in front of it.
Like, the emitter should emit continuously and if the receiver drop connection it should do something.
Will this work fine? or the emitter wide angle and a human body in front of it wont drop the signal?

This will work fine. The easiest way to do this is using IR Sensor Module.

This will give you a digital output of whether there is someone in front of sensor or not. Use can use it as an Edge Trigger to detect Humans passing by.
You can buy one. They are both cheap and easily available.
Or you can create your own.

This works quite fine !
The "hardest" part is isolating the IR beam and especially the receiver with anti-reflective paint or paper (ie : a small hole in a cardboard)
You can make this by two (at least) ways :

[IRled]         [human]          [IRreceiver]
[IRled and receiver pointing the same way]       [human]        [mirror]

The second way is what you find in auto-flushing toilet rooms. But if the human is wearing quite reflective clothes, this will fool the receiver.
This is great for long-range detection, but if you need a smaller range, go for the 1/.


text:
ESP8266 sending GET Request and getting 408 Timeout error
I am using esp8266 to send a GET Request but I am getting 408 Timeout error.
Here is a screenshot of my output.

I only count 60 characters, but you tell it your going to send 69.

@Gerben:  I am getting error when I trying to use "AT+CIPSEND=60"

Are you sending actual "carriage return" and "new line" characters or just a \r\n string? Show us your code.

I assume you're doing all this from the serial monitor. You can't use escape sequences like \r in the serial monitor entry box. Everything you enter is evaluated as a string of separate ASCII characters; \r is just a backslash character followed by lowercase r. To send a HTTP request, you make the serial monitor send the \r\n for you.

First set the serial monitor to BOTH NL & CR permanently; it will serve you well for commands and HTTP requests as it appends \r\n to everything you send.
Count the number of bytes in the your HTTP request, including the carriage return and newline characters. I count 61 characters in your request.
Use this count in AT+CIPSEND
Type the first line of your request, and stop right before the first \r\n, and click Send. Because of your setting, the monitor will now send what you typed with \r\n suffixed to it.
Type and send each line of the request, just like you sent the first line, until you've sent the last line.
Since there is an additional \r\n after the last line, you click Send again, without typing anything. And since the module requires \r to indicate the end of the data packet, you click Send one last time.

Hopefully, this should give you the right results.


text:
Detection of DS18B20, arduino Mega
I just bought a DS18B20 temperature sensor. I can't detect the device when i run this code :
#include <OneWire.h>
#include <DallasTemperature.h>

// Data wire is plugged into pin 10 on the Arduino
#define ONE_WIRE_BUS 10

// Setup a oneWire instance to communicate with any OneWire devices
// (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);

void setup(void)
{
  // start serial port
  Serial.begin(9600);
  Serial.println("Dallas Temperature IC Control Library Demo");

  // Start up the library
  sensors.begin();
 }

 void loop(void)
{
  // call sensors.requestTemperatures() to issue a global temperature
 // request to all devices on the bus
  Serial.print(" Requesting temperatures...");
  sensors.requestTemperatures(); // Send the command to get temperatures
  Serial.println("DONE");

  Serial.print("Temperature for Device 1 is: ");
  Serial.print(sensors.getTempCByIndex(0)); // Why "byIndex"?
    // You can have more than one IC on the same bus.
    // 0 refers to the first IC on the wire

}

Here are my connections:

and output on Serial Terminal is:

      "Temperature for Device 1 is: -127.00 Requesting temperatures...DONE"

I also tried to detect the address of my device but with no success.
I am using an arduino Mega 2560, i have read in some forms that maybe it has something to do with Clock speed or something like that.

I appreciate your help.
I mainly followed this tutorial : http://www.hobbytronics.co.uk/ds18b20-arduino

In the Tutorial, which you are following, it says,

So we will use the 2 wire method. Simply connect both the GND and VDD
  pins to 0V (yes both)

and it shows:

but I think you are missing this step, because i can't see any connection like that here:

I still have the same result :/ I only get the -127 (I apologize for the mistake there was just that i was trying several tutorials and happened to leave that connection)

I attached VDD to GND and set it up so the 4K7 resistor was connecting the 5V to the data line - at first it didn't work, then I swapped it around as if the VDD and data lines from the sensor were switched - which it turned out they were.
Might be the case with your one.


text:
Emulate Joystick
I am trying to automate a existing system that uses Joystick as its input to move the Motors in x&y directions. I actually want to emulate arduino to exactly do what the joystick is doing by just emulating the joystick through arduino. Joystick has 4 wires
1- 5Volt
2- Ground
3- x-axis
4- Y-axis
Actually i want arduino to map in such a way that it's only two digital pins are used to connect with joystick cable 3 & 4 and process inputs exactly in such a way that system thinks that as it is the input from the joystick. I just don't want to mess with the electronics of the existing system. That's why just trying to hack into joystick.
UPDATE: i have checked the Joystick for simple voltage and Resistance Measurements.
It seems like it is 1KOhm Pot.

what is your question? ... it is unclear what you are trying to do

what does this mean? ... emulating the joystick through arduino

I actually emulate arduino ... it is possible that you are using the wrong word emulate

For reading a joystick you need 2 analog inputs. You cannot get the same info from 2 digital input pins. Not possible. Is that what you wanted to ask?

I am trying to say that, i want arduino to act as the joystick and output exactly same signals as the joystick does. Actually i am trying to automate a system which takes input from the joystick and subsequently rotates the motors in that direction.

Then you need to provide the link to the joystick that you want to emulate. Is the joystick just the potentiometers for the axes or is there some additional electronics?

Actually i am trying to automate a system which takes input from the joystick and subsequently rotates the motors in that direction ... is that somehow relevant to the question?

i want arduino to act as the joystick and output exactly same signals as the joystick does ... why didn't you say this at the begining?

Maybe "DS3502 I2C Digital 10K Potentiometer" will work. I am interested to hear if it really works as a joystick pot replacement because I have never used it.

Thank you, i am already going to use digital Pot. As per my knowledge, does digital Pot also Acts as a DAC. correct me of i am wrong please.

But i will be using two channel digital pot that is MAX5392

Based on your wiring information, this looks like an analog joystick. You specified using two digital output pins to emulate the joystick to the target device.
The way to do this is to use PWM and a simple resistor-capacitor filter to convert the digital output to an analog 0-5v signal.
Here is some information about PWM:

Arduino and PWM The Arduino IDE has a built in function
“analogWrite()” which can be used to generate a PWM signal. The
frequency of this generated signal for most pins will be about 490Hz
and we can give the value from 0-255 using this function.
analogWrite(0) means a signal of 0% duty cycle.
analogWrite(127) means a signal of 50% duty cycle.
analogWrite(255) means a signal of 100% duty cycle.
On Arduino Uno, the PWM pins are 3, 5, 6, 9, 10 and 11. The frequency
of PWM signal on pins 5 and 6 will be about 980Hz and on other pins
will be 490Hz. The PWM pins are labeled with ~ sign.

Here is a tutorial on converting the PWM signal to an analog voltage level:

The RC filter is a simple circuit element used to convert a pulsed
signal to a flatter signal. The key concept is that the capacitor
shunts the varying voltage to ground, producing a DC voltage.

Thank you for such comprehensive reply. Will look into it.

Any help Guys, please? I am Still stuck at the same point that how can i emulate Arduino as a joystick.

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


text:
HOW convert momentary button to touch sensor TTP223?
I am trying to convert
this project https://maker.pro/arduino/projects/simple-fm-radio-receiver-with-arduino-uno-and-rda5807m
to  3 touch sensors TTP223.
But so far  my new code don't work.
Please can you have a look at these changes?
Update:
The code goes in loop and the serial monitor show:
push 3
push 4
push 2
push 3
push 4
push 2
and so on
I can also see in the oled, the 3 menu options change cyclically.
TTP223 sensor linked to pin 4 stay always with his red light on.
If I touch the sensor connected to pin 3,  menu does not change (Manual tune,  Volume, Auto tune).
(I have checked Touch sensors if they work alone).
|
|
//TTP223
#define Pin_DOWN 4   //  destra
#define Pin_UP 2     // sinistra
#define Pin_SET 3    // menù
#define FIX_BAND 1

int menu;
#define MAXmenu  3
int menux;
#define MAXmenux  3

|
|
void setup()
{
  Wire.begin();
  //Serial.begin(9600);
  Serial.begin(57600);

//TTP223
pinMode(Pin_DOWN,INPUT_PULLUP );
pinMode(Pin_UP,INPUT_PULLUP);
pinMode(Pin_SET,INPUT_PULLUP);
boolean SET=digitalRead(Pin_SET);
boolean UP=digitalRead(Pin_UP);
boolean DOWN=digitalRead(Pin_DOWN);

|
|
void loop() {
  int newPos;
  unsigned long now = millis();
 // static unsigned long nextFreqTime = 0;
  static unsigned long nextRadioInfoTime = 0;
  char c;
  /*entradaV = analogRead(entrada);

   #if DEBUG
      Serial.print("sensor = " );  Serial.println(entradaV);delay(50);
   #endif
   */
// Boton menu   d
/* if(entradaV>500 && entradaV<524)
   { */
//TTP223
if(digitalRead(3) == HIGH) {
    delay(150);
    Serial.println("push 3");
    menu++;
    if(menu>MAXmenu)menu=1;
    Visualizar();

    #if DEBUG
      Serial.print("menu = " );  Serial.println(menu);
    #endif
    //while(1020>analogRead(entrada))delay(5);

   }

// Boton derecho
/* if( entradaV<50)
   { */
//TTP223
if(digitalRead(4) == HIGH) {
    Serial.println("push 4");
    menux++;
    if(menux>MAXmenux)menux=MAXmenux;
    #if DEBUG
      Serial.print("menux = " );  Serial.println(menux);
    #endif
    switch(menu)
      {
        case 1:
          frecuencia++;
          if(frecuencia>210)frecuencia=210;
          delay(130);
        break;
        case 2:
           volumen++;
           if(volumen>15)volumen=15;
           // while(1020>analogRead(entrada))delay(5);
        break;
        case 3:
           busqueda(0);
           // while(1020>analogRead(entrada))delay(5);
        break;
        case 4:
           // LcdClear();
            tft.clearDisplay();
           // visualPI();
            delay(3000);
           // LcdClear();
            tft.clearDisplay();
            frecuenciaOld=-1;
        break;
      }
   }

// Boton izquierdo
/* if( entradaV<700 && entradaV>660)
    { */
//TTP223
if(digitalRead(2) == HIGH) {
    Serial.println("push 2");
    menux--;
    if(menux<1)menux=1;
    #if DEBUG
      Serial.print("menux = " );  Serial.println(menux);
    #endif
    switch(menu)
      {
        case 1:
            frecuencia--;
            if(frecuencia<0)frecuencia=0;
            delay(130);
        break;
        case 2:
            volumen--;
            if(volumen<0)volumen=0;
            // while(1020>analogRead(entrada))delay(5);
        break;
        case 3:
            busqueda(1);
            // while(1020>analogRead(entrada))delay(5);
        break;
        case 4:
           // LcdClear();
          tft.clearDisplay();
            //tft.print(frecuencia);
            //visualPTY();
            delay(3000);
           // LcdClear();
            tft.clearDisplay();
            frecuenciaOld=-1;
        break;
      }

   }
|
|

I guess you want to replace the momentary buttons in the project with touch sensors. How exactly doesn't your code work? Please provide a more detailed description. Did you try to read the touch sensors by themselves (without any other code or project part) to make sure that they work correctly?

And as the TTP223 gets configured via its jumpers, have you tried something like this to check their behavior?

I have update the post

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


text:
SIM800L not responding to AT commands
I am using SIM800L module the module. I am new to GSM modules, so I've searched for the basic to use the GSM with the Arduino. this is my code.
#include <SoftwareSerial.h>

SoftwareSerial mySerial(2, 3); // RX, TX

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  mySerial.begin(9600);
}

void loop() {
  if (mySerial.available()) {
    Serial.write(mySerial.read());
  }

  if (Serial.available()) {
    mySerial.write(Serial.read());
  }
}

when I send any AT commands to the GSM I didn't find any respond, so I changed the baud rate of mySrial and try different rates to get any respond, but I didn't get anything.
The wiring of the circuit is:

The 5V of the GSM connected to 5V of a power supply (the maximum current of it is 3A).
The GND of the GSM to the GND of the power supply.
TX of the GSM to pin 2 of the Arduino.
RX of the GSM to pin 3 of the Arduino.
GND to to GND of the Arduino.

The module has two LEDs:

the first one D6 NET blanking every second.
the second one D2 RING blanking every (7, 6, 8 or 9) times of the first one.

What line ending do you have selected in the serial monitor?

Both NL & CR and No line ending

try switching RX and TX pins .... on a modem, TX usually means transmit on modem channel, so it should be connected to the Arduino TX pin ... the SIM800L module may have pins labeled same as a modem

You would have to check the wire connections, remember the wire are connected this way. MCU. SIM800 Tx pin -> Rx pin
Rx pin -> Tx pin
gnd -> gnd if your are using SoftwareSerial library. SoftwareSerial modem(rxdpin, txpin);

In addition to the power supply connecting to the VCC and GND of the module, You need to connect the VDD pin on the module to your Arduino 5V (if you are using a 3.3V MCU, then connect it to 3.3V instead of 5V). This enable the level-shifter on the module for communication.

@hcheung I did it and connect the VDD to 5V of the Arduino but the problem didn't solve.


text:
TVout characters don't line up
I am messing around with the Arduino TVout library and I have created some multi-character tiles (I don't know what else to call them). Just to start out, I created a simple X that spans across 4 characters but when I print them to the screen they align correctly.
How they should align:

How they really align:

Here is the code I have so far:
Main file:
#include "expressions.h"
#include <TVout.h>

TVout win;
unsigned char x = 0, y = 0;

void setup() {
  win.begin(NTSC);
  win.select_font(expr8x8);
}

void loop() {
  win.clear_screen();
  x = 2, y = 5;
  print_char(0, x, y);

  win.delay(1);
}

void print_char(char c, int startx, int starty) {
  int tmpx = startx, tmpy = starty;
  for (char i = c; i < c + 4; i++) {
    win.print_char(tmpx * 8, tmpy * 8, i);
    if (++tmpx == c + 2) {
      tmpy++;
      tmpx = startx;
    }
  }
}

expressions.h
#define EXPRESSIONS8x8_H

#include <avr/pgmspace.h>
extern const unsigned char expr8x8[];

expressions.cpp
#include "expressions.h"

PROGMEM const unsigned char expr8x8[] = {
  8, 8, 0, // width, height, start

  // broken
  0x00, 0x00, 0x30, 0x38, 0x1c, 0x1e, 0x07, 0x03,
  0x00, 0x00, 0x0c, 0x1c, 0x38, 0x70, 0xe0, 0xc0,
  0x03, 0x07, 0x0e, 0x1c, 0x38, 0x38, 0x00, 0x00,
  0xc0, 0xc0, 0x70, 0x38, 0x1c, 0x0c, 0x00, 0x00,

  // happy
  0x00, 0x00, 0x00, 0x00, 0x07, 0x1f, 0x38, 0x70,
  0x00, 0x00, 0x00, 0x00, 0xe0, 0xf8, 0x1c, 0x0e,
  0x60, 0x60, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x06, 0x06, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00
};

Is there something I am doing wrong? How do I fix this bug/issue?

Less lines of code would be to just have 4 prints, one for each character.

I believe your problem is in this line:
if (++tmpx == c + 2) {

Here you are mixing two different things:

c is a character code, i.e. the index of a glyph within the
expr8x8 font
tmpx is the index of a character cell (a 8×8 block of pixels) within
a line of the screen

Comparing those makes little sense. And in fact, the comparison will
always be false, as c is zero, and tmpx starts at 2 and increases
from there.
I guess what you meant was:
if (++tmpx == startx + 2) {


text:
How to rewrite code in millis?
I am currently working on a project that makes a plateua move back and forth using a stepper motor. On this plateau I have attached LEDs that create patterns.
However, the plateau should be moving whilst the pattern is changing. With my current code this is not happening. I know that I have to work with millis, but when I am completely lost on how to do it. Could someone help me?
Here is my code:
#include <AccelStepper.h>

AccelStepper stepper(1, 42, 38);

int i;
int microStep = 46;

int currentAnimation = 0;
int count = 0;
int button = 13;

int state = LOW;
int lastState = LOW;

//bytes for patterns
byte a = B11110000;
byte b = B00010000;
byte c = B01000000;
byte e = B10100000;

//--------------------------------------------------------------------------------------------------------------------------------

void setup()
{
  DDRH = B1111000; // set PORT 6-9 of arduino mega high
  DDRB = B11110000; // set PORT 10-13 high

  stepper.setMaxSpeed(900.0);
  stepper.setAcceleration(400.0);

  pinMode(button, INPUT);
  state = digitalRead(button);

  pinMode(microStep, OUTPUT);
  digitalWrite(microStep, HIGH);
}

//--------------------------------------------------------------------------------------------------------------------------------

void loop()
{
  //This should happen constantly
  stepper.runToNewPosition(2000);
  delay(500);
  stepper.runToNewPosition(0);

  // These are the patterns, that should be played whilst the stepper is running. The patterns chaneg when you push the button
  if ( state == HIGH & lastState == LOW )
  {
    currentAnimation++;
  }

  if (currentAnimation % 3 == 0)
  {
    same();

  }
  if (currentAnimation % 3 == 1)
  {
    left();
  }
  if (currentAnimation % 3 == 2) {
    faster();
  }

  lastState = state;
  state = digitalRead(button);
}

//--------------------------------------------------------------------------------------------------------------------------------
//PATTERNS
void same() {
  for (int k = 0; k < 10; k++) //plays 10 times
  {
    PORTH = a;
    PORTB = a;
    delay(100);
    PORTH = 0;
    PORTB = 0;
    delay(100);
  }
}

void left() {
  for (int z = 0; z < 10; z++)
  {
    PORTH = e;
    PORTB = e;
    delay(100);
    PORTH = ~e;
    PORTB = ~e;
    delay(100);
  }

}

void faster() {
  for (int z = 0; z < 256; z++)
  {
    PORTH = z;
    PORTB = z;
    delay(100);
  }
  PORTH = 0;
  PORTB = 0;
}

The problem is that the animations (or actually the delay in them) will block the other code from running. But could you expand a little on what timing you want to achieve? You'll want to run stepper.runToNewPosition(xxx); every 500ms, and change the pattern each 100ms?

Actually, https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay explains it rather well.

The basic pattern goes like this:
when you start the timer, you essentially store the current millisecond.
After this, in your loop code, among other things you should check if the time has passed by comparing current millisecond with the stored one. If their difference is equal or bigger of the desired delay interval, then the time has passed.
Make sure you use unsigned long variables to store times and check if time has passed with the condition used below (if(millis() - mark >= interval ){...}) so you will not have problem even after millis() rolls over.
If you need more help, do not hesitate to ask.
unsigned long interval=2000; //2000ms
unsigned long mark;
boolean enabled=true;

void setup() {
    Serial.begin(9600);
    Serial.println("starting timer");
    startTimer();

}

void loop() {
    check();
}

void startTimer(){
    mark=millis();
}

void check(){
    if(enabled){
        if(millis() - mark >= interval ){

            enabled=false;
            Serial.println("time elapsed");
        }

    }
}

Hmm, this code will only run once, instead of in 2000ms intervals. I'm not sure if you/he were/was aiming for that.

it only aims to demonstrate the way one would use millis() to measure time.
Apart from that, it is easily modifiable to auto restart ->
just replace line enabled=false; in check() with startTimer();

Ah, that's what the startTimer() function was for, I thought it was pretty silly to set up the mark in a function. You've got my vote, it's a good answer. It's very much like the blink tutorial.

It'd be fairly easy to create a library that allows multiple timers which can be easily started and checked. Which is a nice idea if you're going to have a lot of these projects.

Since microcontrollers typically only have one "core" or "thread" they can only do "one thing at a time".
A microcontroller will step through your code and do everything in order (if you don't call interrupts).
Basically, when you put in a for-loop (or any other type of loop) or a delay, it will only continue with the rest of your code when that is done.
To solve this, and "do two things at a time" (or actually rapidly switch between things) you'll need either interrupts or non-blocking code (or both).
Interrupts
I see you're doing some direct port manipulation, which is really nice. You're writing bytes directly to the control registers of the microcontroller.
You can leverage on that, to set up a timer (check the ATMega328P datasheet). You may make this timer give an interrupt each 100ms, and execute a "frame" of your animation at that point. And the next frame at the next interrupt. So that the time between each frames can be used for other code.
Non-blocking code
Arduino has built-in millis(); which is basically an interrupt that fires every millisecond to keep track of the passed milliseconds. So you can use this instead of fiddling around with the timers (which may very well cause some of the Arduino's functions to fail (like millis() or the servo library).
To write non-blocking code, you'll not use delays, since they effectively throw away "processor time" by doing "nothing-instructions" all the time.
But if we take out the delays, the for-loops will run too fast. And a for-loop also doesn't really work without the delay. Because even if you use millis and wait for half a second, you can't do anything in between.
So we'll have to break up your code (specifically the animations) in chunks of code that can be executed withouth a delay. With only the need to delay in between these chunks.
Frames
Let's split up your animations in "frames". One of your animations same() works by PORTH&PORTB = A for 100msec and low for 100 msec.
void sameAnimation(unsigned char frame){//plays 20 times (1x on, 1x off) instead of 10x on-off.
  if(frame%2==0){//If even
    PORTH = a;
    PORTB = a;
  }else{//if not even.
    PORTH = 0;
    PORTB = 0;
  }
}

So based on the frame of the animation, the port will go high or low.
Now we look at the complete code, we have to change the motor every 500ms and have to change the animation frame every 100ms. And check a button.
We could put these in an interrupt that fires every 100ms, which would get reliable timing and minimum software overhead.
Or use the millis(); (checked against the previous milis) to check if the last update was 100ms ago.
My go at the code is below, but you should be able to figure it out yourself.
void loop()
{
  unsigned char currentFrame = 0;

  //Could be done every round.

  lastState = state;
  state = digitalRead(button);
  if ( state == HIGH & lastState == LOW )
  {
    currentAnimation++;
    PORTH = 0;
    PORTB = 0;
  }

  // These are the patterns, that should be played whilst the stepper is running.

  if(millis() - previousMillis > 500){// Should change every 100ms
    previousMillis = millis();

    if (currentAnimation % 3 == 0)
    {
      sameAnimation(currentFrame++);
    }
    if (currentAnimation % 3 == 1)
    {
      leftAnimation(currentFrame++);
    }
    if (currentAnimation % 3 == 2) {
      fasterAnimation(currentFrame++);
    }

    if(currentFrame % 5){//Should change every 500ms, so every 5 frames.
      if(forward){
        stepper.runToNewPosition(0);
        forward = false;
      }else{
        stepper.runToNewPosition(2000);
        forward = true;
      }
    }
  }
}

//--------------------------------------------------------------------------------------------------------------------------------
//PATTERNS
void sameAnimation(unsigned char frame){//plays 20 times (1x on, 1x off) instead of 10x on-off.
  if(frame%2==0){//If even
    PORTH = a;
    PORTB = a;
  }else{//if not even.
    PORTH = 0;
    PORTB = 0;
  }
}

void leftAnimation(unsigned char frame) {
  if(frame%2==0){//If even
    PORTH = e;
    PORTB = e;
  }else{//if not even.
    PORTH = ~e;
    PORTB = ~e;
  }
}

void fasterAnimation(unsigned char frame){
  PORTH = frame;
  PORTB = frame;
}

The button
Checking the button every round isn't really needed. You can use an interrupt on that pin, so that the code to check it's state and go to the next frame only happens when the button is actually pressed. (interrupt triggered on rising edge?).

You could try something along these lines, I haven't put all of the code in, but just how this could be done for the sweep timer using millis().
unsigned long sweepTime;
unsigned long animationTime;
int stepperPosition;

void setup()
{
    //... other setup code
    sweepTime = millis();       // initialise the variables for the sweep timer, and the animation timer
    animationTime = millis();
    stepperPosition = 2000;     // initialise the next stepper position
}

void loop()
{
    if (millis() - sweepTime > 500) //  check if more than 500 milliseconds have elapsed since last time we ran this.
    {
        stepper.runToNewPosition(stepperPosition);  // change stepper position
        sweepTime = millis();           // reset timer variable
        switch (stepperPosition) {      // need to change the value of the next position to set the stepper to
            case 0 :
                stepperPosition = 2000;
                break;
            case 2000 :
                stepperPosition = 0;
                break;
        }
    }
    //... continuation of loop code
}

Additionally, I don't have my arduino with me, so can't verify the correctness of the code.

You're missing a case label on the second case of your switch. I would've used a if-else statement anyway.
And the time variables should be unsigned long rather than long.

@Paul. Thanks for feedback, I have changed and corrected. I tend to use if-else for boolean comparisons - you're probably right in this case, but I personally think the switch allows for additional sweep values in the future.

switch-case statements are extremely useful if you're skipping through states, and when you declare these states in an enum, the compiler even tells you whenever you did not implement one of the states, which is nice. I get your point, but if it's two things, a if-else is smaller and more logical. You could also argue that if-else is better since you can add other conditions to it ;) which isn't quite possible in a switch-case. But I agree that if-statements are often mis-used xD


text:
Why does my lcd screen work fine and then display random characters?
It works as expected for a few seconds and then random letters appear on the second row. The wiring and the programming should be correct. I wired it according to an Arduino Starter Kit Book and coded it myself.

Code:
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int hours=23;
int minutes=0;
String none="00";
unsigned long timer;
void setup() {
lcd.begin(16, 2);
lcd.setCursor(6, 0);
lcd.print("Time:");
lcd.setCursor(6, 1);
lcd.print("23:00");
}

void loop() {
timer=millis();
if(timer%600==0){
   minutes++;
  if(minutes==60){
      minutes=0;
      hours++;
      }
   if(hours==24){
      hours=0;
   }
  lcd.clear();
  lcd.setCursor(6, 0);
  lcd.print("Time:");
  lcd.setCursor(6, 1);
  if(minutes<10){
    if(hours<10){
      lcd.print(String("0")+hours+":"+"0"+minutes);
    }
    else{
      lcd.print(hours+String(":")+"0"+minutes);
    }
  }
  else{
    if(hours<10){
       lcd.print(String("0")+hours+":"+minutes);
    }
    else{
       lcd.print(hours+":"+minutes);
    }

  }
  delay(200);
  }
}

I was able to narrow down the problem. I was testing what happens when it hits 24 hours so I set hours to 23 in the beginning and made the time 600 ms. Once it hits 10 seconds, the characters appear. If the hour is a 2 digit number, the issue happens. I made the hours 9, and the issue disappeared. What can I do?

Where is your decoupling?

There was nothing mentioned about capacitors in the book. I did what was illustrated. I followed the schematic exactly. I will post the schematic.

The problem was that I was adding ":" to the printed string on the lcd without making it a String object. That only occurred if I had double digit hours and minutes.
Incorrect way:
lcd.print(hours+":"+minutes);

Correct way:
lcd.print(hours+String(":")+minutes);

You should avoid using String. There is no need to concatenate your parts like that - just print each bit to the LCD separately. Excessive use of String like that will cause heap fragmentation and could lead you into memory problems further down the line.


text:
Why does servo library conflict with irremote?
I am building an Arduino Mega robot. I am planning to use IRremote.h library for it. I am using multiple libraries in my code and I do not know which timers are taken. I always get errors when compiling because I am using the wrong timer. Here are the libraries I am using:
#include <LiquidCrystal.h>
#include <Wire.h>
#include <RTClib.h>
#include <Servo.h>
#include <IRremote.h>

I get this error message when compiling:
libraries\IRremote\IRremote.cpp.o: In function `__vector_42':

C:\Users\Lyuba\Desktop\Nick\Arduino\libraries\IRremote/IRremote.cpp:339: multiple definition of `__vector_42'

libraries\Servo\avr\Servo.cpp.o:C:\Users\Lyuba\Desktop\Nick\Arduino\libraries\Servo\src\avr/Servo.cpp:95: first defined here

c:/users/lyuba/desktop/nick/arduino/hardware/tools/avr/bin/../lib/gcc/avr/4.8.1/../../../../avr/bin/ld.exe: Disabling relaxation: it will not work with multiple definitions

collect2.exe: error: ld returned 1 exit status

exit status 1
Error compiling for board Arduino/Genuino Mega or Mega 2560.

Here is the code in the library where I can change the timers:
// Arduino Mega
#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
  //#define IR_USE_TIMER1   // tx = pin 11
  //#define IR_USE_TIMER2     // tx = pin 9
 // #define IR_USE_TIMER3   // tx = pin 5
  #define IR_USE_TIMER4   // tx = pin 6
  //#define IR_USE_TIMER5   // tx = pin 46

What can I do to use irremote library? Looking at the error message, the servo library conflicts with irremote. How can I fix this?

@Joe I tried all of them. If I stop using tone() in my code, one of the timer works. But I want to use tone as well.

Usual problem is trying to use the same counter for both. For example arduino pins 6,7,8 are on TC4 and if you try to use IR on pin 6 and servo on 7 or 8, it won't work. You can't use pwms on these pins with servo either (it is possible to do it directly in registers, but in arduino framework it might get bad behavior)


text:
How can I control 4 DC motors with an Arduino?
In a few months, I am planning to construct an Arduino robot with multiple sensors etc. I will use an arduino mega and a 4wd chassis like the one here: Chassis.  The chassis uses 4 DC motors. I was planning to use a motor shield, but I realized that it only fits an Arduino Uno(not Mega) and it controls only 2 DC motors. What can I do to make all 4 DC motors move forward and backward? If I use a motor driver board that controls 2 motors, can I connect the 2 right and 2 left motors in parallel together and the control it through the Arduino?

Use motor drivers that aren't on a shield.

@Majenko would I have to use 2 drivers then?

Each motor needs a driver. If a driver board can drive two motors then you need 2 driver boards for 4 motors. If a driver board can only drive 1 motor then you need 4 driver boards for 4 motors. Find a driver board that is powerful enough for your motors and then do the (very simple) maths.

If it can help, I have some code I'm using exactly for that purpose: https://github.com/igor-stoppa/ChibiOS/tree/car I haven't had much time lately to spend on it, but it does the basic. I'm using 2 of these: http://www.ebay.com/itm/111671736661?_trksid=p2057872.m2749.l2649&ssPageName=STRK%3AMEBIDX%3AIT

In theory, it's true that the 2 wheels on each side could be controlled by the same driver (assuming it can output enough power), however I'm not sure how this would play out when motors are either not sufficiently similar or subject to different load (say one has to overcome a small bump). So I preferred to play it safe and have each wheel controlled independently.

@IgorStoppa Each motor draws 120mA at 6 Volts. I have read about people controlling 2 motors together. I will probably control them individually so that I don't risk anything.

If you want to add a feedback loop to each motor, I found these optical end stop detectors to work quite well: http://www.ebay.com/itm/1-x-Optical-Endstop-End-Stop-Limit-Switch-Solution-for-3D-Printer-or-CNC-NEW-DE-/281983545137?hash=item41a7876f31:g:6UsAAOSwxcRW-UHJ

@IgorStoppa Do you recommend getting the Sparkfun driver or did the one you got from ebay work fine?

@NickSolonko when dealing with motors, you laso have to account for peak current consumption: overcoming the initial inertia will draw much more current than when steadily cruising. In general any change of speed (including steering) will cause a temporary increase.

So far, the driver I linked seems to be ok. I do not have experience with the one from Sparkfun. But I can advice to not buy any based on L298N because of the much higher internal power loss: http://www.ebay.com/itm/Dual-H-Bridge-DC-Stepper-Motor-Drive-Controller-Board-Module-Arduino-L298N-HG-/281551893660?hash=item418dccf49c:g:sm8AAOSwYGFUsJ9I

@IgorStoppa I was looking at buying something based on L298N. Thank you for warning me. Now I will probably get the one you advised. The one I was previously planning to get: http://www.ebay.com/itm/L298N-4-Channels-DC-Motor-Step-motor-Driver-Module-Robot-4WD-Car-for-Arduino-DG-/262482009259?hash=item3d1d259cab:g:srwAAOSw9eVXXnyk

Let us continue this discussion in chat.

6 volt motors expected to be well under an app would probably point to a TB6612FNG.  Some of the newer motor shields use those, as FET devices they are much lower loss.

@ChrisStratton: that's what I linked to.

Yes, you can do this using 2 L293D motor drivers, each motor driver can run 2 motors and it is very easy to use.

You should connect Vcc 1(used to power on the chip) to 5V and Vcc 2 to a power supply that is needed to run your motors, Enable 1,2 and Enable 3,4 are used to enable the 2 sides of the chip and should be connected to 5V. Outputs 1-4 are the outputs to 2 motors and Inputs 1-4 are the inputs from the micro-controller.

But, what if I want to use a separate power supply, such as a 9V battery?  How am I supposed to connect it to the L293D motor driver?  I think, I should connect the positive side of the 9V battery to the VCC 2 pin of the L293D motor driver.  But, where should I connect the negative side of the 9V battery?

You should connect the negative side to the 4 ground pins.

Yes, you can actually do this, but you have to consider the current of the motors and the motor driver. For example, if you have 12V, 2 Amps motors, then you need a 2-channel motor driver that is able to output a little higher that 4 Amps (2*2 Amps) for each channel at 12V. You will need to connect each two motors on the same side in parallel to one channel.


text:
How to get recover numeric data sent by an Arduino in binary
I am a C# dev and these C++ data conversions are killing me.
I have an Arduino sending binary data through LoRaWAN to AzureIOT. I am trying to decode my Temp/Humid/Bat payload that I am pulling out of AzureIOT Hub.
Here is a sample method I am using in C# to parse the byte array. Once I have parsed it, how do I convert those numbers back to their actual values?
Here is the input data on the sensor side:

T=74.48
RH=45.20
BatteryVoltage:3332

Thanks.
Here is how the data was input:
float temperature = readDHTTemperature(); //this method prints T to Serial
float humidity = readDHTHumidity(); //this method prints H to Serial
uint16_t batteryVoltage = readBattery(true);
delay(100);

unsigned char *puc;

puc = (unsigned char *)(&temperature);
appDataSize = 10;
appData[0] = puc[0];
appData[1] = puc[1];
appData[2] = puc[2];
appData[3] = puc[3];

puc = (unsigned char *)(&humidity);
appData[4] = puc[0];
appData[5] = puc[1];
appData[6] = puc[2];
appData[7] = puc[3];

appData[8] = (uint8_t)(batteryVoltage>>8);
appData[9] = (uint8_t)batteryVoltage;

Here is the output:
private static void BytesToString()
{
    var hexStringFromPayLoad = "MzOYQgAAHEINBA==";
    var bytes = Base64Decode(hexStringFromPayLoad);

    Console.WriteLine($"Temp: {bytes[0]}, {bytes[1]}, {bytes[2]}, {bytes[3]}");
    Console.WriteLine($"Humid: {bytes[4]}, {bytes[5]}, {bytes[6]}, {bytes[7]}");
    Console.WriteLine($"Bat: {bytes[8]}, {bytes[9]}");

    /*
    Temp: 51, 51, 152, 66
    Humid: 0, 0, 28, 66
    Bat: 13, 4
    */
}

what is the received payload data, in hex?

https://stackoverflow.com/questions/26310249/converting-4-raw-bytes-into-32-bit-floating-point

@jsotola, sorry, I updated my post iwth the input and the CSV output.  Thank you for your help.

I edited the question to remove the word “decimal”, which you were misusing here.

Arduinos use very standard formats for their internal binary
representations of data:

integers are in two's complement
floats follow the IEEE 754 standard
both are little-endian.

This is the same as your typical x86_64. The implication is that, once
the bytes are in your PC, you do not need to perform any conversion at
all. All you need to do is either alias or copy the bytes to the memory
locations of the variables that are meant to get the values.
Example in plain C:
uint8_t temperature_bytes[] = { 51, 51, 152, 66 };
float temperature;
memcpy(&temperature, temperature_bytes, sizeof temperature);
// now `temperature` holds the value 76.1.

How you would do this in C# is a question that is out of topic in this
site.

Good point.  Thanks for the guidance.  I will move over to overflow.


text:
Frequency problems with DIY arduino and resonator
I made a simple music program using an arduino Uno and the tone() function. It works fine.
I decided to build my own circuit using a barebones AVR and upload that program.
I did not know exactly what frequency was being used by the arduino, so I used a Murata resonator, with a frequency of 8 MHz.
When I put my circuit to the test, the music that I had generated was played an octave lower, and its duration was doubled (taking twice the time to finish played a note).
I figured out that I used the wrong resonator frequency. Indeed, I found out that the Arduino Uno used a 16 MHz resonator.
Since I had half that frequency in my clock, the tone would be lower frequency, and it would take twice the time to finish a note. This made sense.
So I went ahead and rebuilt the circuit with a 16 MHz resonator frequency.
However, now I have the opposite effect!
All the notes are one octave higher compared to my original Arduino Uno design, and the note duration finished in hald the time compared to the original Arduino Uno design...
This suggests that I now have doubled the frequency compared to the original design (and four times the frequency compared to my first custum circuit attempt).
I cannot seem to understand why this is happening, because right now I have the frequency that the original Arduino uses....

If the code runs at twice at the expected speed when clocked at
16 MHz, this can only be because either:

you fixed the program to run correctly when clocked at 8 MHz
you told the IDE that you are using a 8 MHz clock.

The IDE comes with a few configurations that are suitable for an
8 MHz clock. If you select as a board “Arduino Pro or Pro Mini”,
you have something equivalent to an Arduino Uno, except that you can
choose between an 8 MHz clock and a 16 MHz clock (and also
between an ATmega168 and a 328P).

Thanks! That was it!


text:
How to wait outside the loop without delay()?
Is it possible to delay a task inside a function that is called only once (meaning, it's not inside the loop) without using delay()?
This library I'm using, for reading sensor measurements via serial has a delay() in it. I want to get rid of it, but I don't how to do it, because the library's function is not looped.
I guess the simple solution would be to move the library functions inside the loop, so I can do a simple check with millis() and run the delayed part as soon as 250 ms have passed. I would like to improve this library though and do a simple, single call for sensor data that doesn't not hold up the entire program.
This is the function with the delay:
uint16_t COZIR::Request(char* s)
{
  Command(s);
  // empty buffer
  buffer[0] = '\0';
  // read answer; there may be a 100ms delay!
  // TODO: PROPER TIMEOUT CODE.
  delay(250);
  int idx = 0;
  while(CZR_Serial.available())
  {
    buffer[idx++] = CZR_Serial.read();
  }
  buffer[idx] = '\0';
  uint16_t rv = 0;

  switch(buffer[1])
  {
    case 'T' :
            rv = atoi(&buffer[5]);
            if (buffer[4] == 1) rv += 1000;
            break;
    default :
            rv = atoi(&buffer[2]);
            break;
  }
  return rv;
}

I've had a look at the SoftTimer library, but it requires sketches to be written very differently (without a loop). I'm also not sure if I can even pass arguments to delayed tasks with that library.

The first question is: why do you want to eliminate that delay call? Does it harm your program?

Split the function into a startMeasurement and readMeasurement method. Maybe add a measurementReady method for checking if the measurement is done.

The sensor doesn't return data immediately and I use a pulsating LED to indicate certain levels. The delay disrupts the LED's smooth transitions.

You could split Request() into two separate functions: You call sendRequest(), then go do other stuff, then, some time later, you call getResponse(). If you get RESPONSE_NOT_READY, then you know you have to call it later:
#define REQ_WAIT_DELAY     250  // Wait for 250 ms
#define RESPONSE_NOT_READY ((uint16_t) -1)

uint32_t time_request_sent;

void COZIR::sendRequest(char* s)
{
  Command(s);
  time_request_sent = millis();
}

uint16_t COZIR::getResponse()
{
  if (millis() - time_request_sent < REQ_WAIT_DELAY)
      return RESPONSE_NOT_READY;
  buffer[0] = '\0';  // empty buffer
  int idx = 0;
  // From here, same as original COZIR::Request()
}

This assumes that RESPONSE_NOT_READY (0xffff) is not an otherwise valid response. If all 2^16 values of an uint16_t may be valid, then you need another way for the library to signal that the response is not ready. Also, make sure you never compare timestamps, because of the millis() rollover problem. Taking the difference between two timestamps and comparing this with a specified delay (as in the example above) is rollover-safe.
Update: Here is an example of how this could be used:
COZIR cozir(some_serial_connection);

void loop()
{
    static bool waiting_for_a_cozir_response = false;

    if (time_to_get_another_cozir_reading()) {
        if (waiting_for_a_cozir_response) {
            report_something_is_wrong("This COZIR is too slow!");
        }
        else {
            cozir.sendRequest("Hi Cozir! Pliz send me another reading.");
            waiting_for_a_cozir_response = true;
            /* We won't get the response on this iteration. *
             * We will ask next time.                       */
        }
    }
    else if (waiting_for_a_cozir_response) {
        uint16_t response = cozir.getResponse();
        if (response == RESPONSE_NOT_READY) {
            /* Nothing to do now, really. We will just try again *
             * at the next loop() iteration.                     */
        }
        else {
            waiting_for_a_cozir_response = false;
            do_something_with_the_cozir_response(response);
        }
    }
    do_whatever_else_has_to_be_done_in_the_loop();
}

Thanks, but I'm not sure if I completely understand. In the example getResponse() is not called. I could put a call in the loop, but I'd prefer not to.
I tried the code as proposed and it compiles, but now I don't get sensor measurements returned any longer with czr.Celsius();

Yes, you have have to call getResponse() in the loop, see updated answer. Why do you want to avoid it? Here is the deal: You send a request to the Cozir, but it is slow to respond. You have three choices: 1) you just wait: that's the cozir lib approach 2) yo go do your business, but you remember you have to come later see whether the answer is ready: that's the code I gave you 3) you go do your business, and have something interrupt you and tell you it's time to get the response: that's the SoftTimer approach. Now it's time for you to make a choice: which approach do you prefer?

Thanks so much for the clarification, this was exactly what I was wondering about, as I didn't know the options. I will probably go with your second option with the code you provided. That way I don't have to rewrite the sketch completely. For a next project I will probably use SoftTimer though.

You can look at the BlinkWithoutDelay example sketch (under Digital).  Basically you store the current millis as a variable, then have an if statement to check that it has been more than x milliseconds.

I would still have to put that inside the loop.


text:
MISO pin issue in SPI
I have interfaced sd card and ADS1262 (ADC module) with Arduino mega board and sharing the SPI control pin i.e. SCK, MISO and MOSI.
I have found that sd card is not initialized and ADS1262 is giving garbage value.
Now if I remove the MISO pin of sd card then ADS1262 is giving right (although SD card is not initialized.)
Vice-versa, if I remove the MISO pin of ADS1262, sd card is initialized and working perfectly (although ADS1262 is giving garbage value.)
Certainly, there is issue of MISO pin. How can I share MISO pin with both slaves so that both can work properly.
Any comments please.
I am using shifter - TXS0108E.
For SPI interfacing, I have tested two slaves with Mega board and found the below result when MISO is connected with both slaves and MISO pin is removing one by one from slaves.

From Above result, I thing it may be the problem of MISO pin.
I am not getting the idea, how to solve the problem in SPI interfacing in multiple slaves.
Schematic:

Please show us how you've connected everything. Especially the CS pins and the TXS0108E.

It could be the TXS0108 interfering with the SPI bus. MISO must be in a high impedance mode on all inactive devices - the TXS may not be doing that. You need to force it by holding OE LOW when the TFT is not in use. Connect it to the TFT's CS pin through a NOT gate, or use a second IO pin and assert it the opposite of the TFT CS pin.

Also SD cards are notoriously bad at sharing the SPI bus. Try different SD cards.

See How do you use SPI on an Arduino?. From your now-deleted comment: all other devices are expected to have their MISO line in a third state - in other words, input (high impedance). First state is output+high, second state is output+low, third state is input.

Hi Nick, i got the point that all other devices are expected to have their MISO line in a third state but I am not getting the logic that how can I put the inactive device's MISO line in a third state. TFT and SD card both are working on the TXS0108E and the ADS1262 is working directly on 5V. I have still many IO pins to use so it is better to use IO pin to make the MISO pin in third state, if any logic is there.

You probably want to use two SPI busses. If you absolutely need to use one bus, attach a digital out pin to each of the CS pins, one on the 1262 and one on the SD card. When you need to talk to one of the deviced, pull its CS line low to enable it.

I am interfacing ADS1262, SD card and TFT with arduino mega. In that, I am sharing the all three spi lines i.e. miso,mosi and sck. All three slaves has individual cs line. But only, TFT is working fine, ads1262 is giving garbage value and sd card is not initialized, Although, individually, each slave is working fine. I have tested two slaves with arduino mega (instead of all three slaves) and found above given table's result. If I remove the one slave's miso pin, the other slave is working fine and vice versa. So it is the purely spi base problem. but i don't get idea to solve the problem.

You mention in passing that you use a shifter, yet you don't say what you are shifting or where you are shifting it. A full schematic of the whole SPI portion of your project is required.

Some sd card modules which use 5v-3.3v logic level shifters may not have a proper circuit wich is very well explained in this guys blog
http://www.vishnumaiea.in/projects/hardware/interfacing-catalex-micro-sd-card-module
so until you don't make some changes in the sd card module you wont be able to have multiple slaves on your spi bus.


text:
Set PWM by period? And have it variable?
In this other stack QA I'm asking about generating a pulse signal with a period ranging from 63 ms to 6.5 ms. There is a popular PWM library however it doesn't compile and also since 63 ms is 15.8 Hz, that library's integer Hz setting isn't of help.
Is there a definitive process that isn't waving incense bundles in the corners of the room? There is an over abundance of "how tos" on the internet, however, none seemed to get me to a solution.
I've got a Mega and am using TIMER5. It's "just like" TIMER1 in that it is a 16 bit timer.

I stumbled upon a solution via trial and error coupled with watching the results on an o'scope.
The best guidance came from a Stack Exchange QA. Setup isn't particularly special, however the combination of WGM bits here worked and I didn't investigate further. Of the biggest importance are the prescaler divider bits, the least three significant bits of TCCRxB. 001 means no dividing or prescaling of the clock.
It all boiled down to 4 registers and the pinMode() call. Ultimately, seven lines of code:

#define PULSE_PIN 45
void setup() {
    // IMPORTANT: Clear Timer/Counter Control Registers
    TCCR5A = 0;
    TCCR5B = 0;

    // Set Timer/Counter Control Registers
    TCCR5A = B00101001; // Phase and frequency correct PWM change at OCRA
    TCCR5B = B00010010; // least sig bits sets "carrier frequency" by dividing CPU clock
    //  Observation:
    //  TCCR5B = B00010010 and OCR5A = 16667 results in period of 16.70 mSec
    //  meaning OCR5A is period in uSec when TCCR5B = B00010010
    //  TCCR5B = B00010001 : OCR5A = 20000 results in period = 2.5 mSec 399.3Hz

    pinMode(PULSE_PIN, OUTPUT);
}

In the sketch, I watch an analog pin with a potentiometer on it and map its sweep to an effective RPM range of 950 to 9000 RPM. Hence the arbitrary range of periods I want to handle. When loop() sees the ADC change, the below code adjusts the PWM accordingly.
Note that no floating point data types are used. The magic numbers below were chosen by trial and error in a spreadsheet with values rounded to whole numbers.
void setRpm(){
    //  Getting to period in uSec from rpm the long way to keep
    //  the answer in range of the data type:
    unsigned int rpm = map(pot_adc, 0, 1023, RPM_MIN, RPM_MAX);
    unsigned long period = rpm/50;
    period = 24000/period;
    period = period*50;
    //  The trigger lasts 26°, so the PW is 26/360 * period.
    dwell = period/36;
    dwell = dwell*26;
    dwell = dwell/10;

    //  OCR5A is a counter the carrier frequency counts up to,
    //  which sets output period / frequency
    //  meaning OCR5A is period in uSec when TCCR5B = B00010010
    OCR5A = period; //  OCR5A is period in uSec when TCCR5B = B00010010
    //  OCR5B is the width of the pulse. If we used floats,
    //  we could use duty cycle * period.
    OCR5B = dwell;
}

Obviously, this code will have limitations to the range of frequencies it can handle, but the Internet has plenty of means for higher frequency PWM, especially when the desired PWM is fixed and doesn't need varying.
The most helpful way to see the control registers is as binary positions and not to rely upon macros, masks, and bit shifting. This comment block helped greatly:
 // WGM modes:
 // TCCR1A
 // Bit              7      6      5      4      3     2     1     0
 // Bit Name         COM1A1 COM1A0 COM1B1 COM1B0 ----- ----- WGM11 WGM10
 // Initial Value    0      0      0      0      0     0     0     0
 // changed to       1      1      1      1      0     0     0     1

 // TCCR1B
 // Bit            7      6      5       4        3        2        1        0
 // Bit Name       ICNC1  ICES1  -----   WGM13    WGM12    CS12     CS11     CS10
 // Initial Value  0      0      0       0        0        0        0        0
 // changed to     0      0      0       0        1        0        0        1
 // CS12,CS11,CS10 = (0,1,1) = prescaler divide by 64

I like bit-shifting in groups.  E.g. TCCR1A = (0b11 <<COM1A0) | (0b11 <<COM1B0) | (0b01 << WGM10) ; and TCCR1B = (0b11 <<WGM12)| (0b001 <<CS10) -- then the trial-and-error of flipping bits is more clear and self-documenting -- If you want to try the /64 prescaler, it's a 1 bit edit to 0b011


text:
Funduino USB Host Shield problems
I'm currently working on connecting a Funduino version of usb host shield onto an arduino mega board. But the serial output shows "osc did not start", which means the board can't find the shield. However the reset button works, so I estimate insufficient power being supplied.

I'm aware of the bridging solution for the regular arduino module for the 3.3v and 5v (example). But how can this solution be applied to the Funduino model.
Update: I've changed the SPI lines on the shield to the 6 ISCP pins on the Mega, but still no change in results.
I performed a second test using board_qc, which returned:
Circuits At Home 2011
USB Host Shield Quality Control Routine
Reading REVISION register... Die revision invalid. Value returned: 00
Unrecoverable error - test halted!!
0x55 pattern is transmitted via SPI
Press RESET to restart test

Please provide a link to the product page of that shield.

https://www.altronics.com.au/p/z6342-funduino-usb-host-shield/#/

https://fluxworkshop.com/products/ccaa100015-uno-usb-host-shield-keyes-red?variant=32458615783484

And can you please provide a link to the used library (and include either your sketch or point to the example code that you might be using)

https://www.arduino.cc/reference/en/libraries/usb-host-shield-library-2.0/ I used version 1.5 as shield requires.

That shield communicates over SPI. However the SPI pins it uses are the "old" style (10-13) for the Arduino UNO.
The Mega doesn't use those pins, which is why the "new" style 6-pin SPI/ICSP header was added to boards.
You will have to manually jumper the right pins to the SPI pins of the Mega using wires.

Can you provide a pinout, so that I know where to make connections.

You would need to refer to the schematic or manual for the shield (which I don't have). The pinout for the mega is well documented.

I have tried connecting the SPI to the 6 pins in the center, but am still getting the same results.

I have also tried the SPI pins at the bottom of the Mega.

If the shield was designed for the Arduino Uno, then it would have a similar pinout to interface with it. So I used the Uno pinout as reference.

You should look for the actual pinout of the shield. You may have an interrupt signal to cope with, and there's no telling where any other logic signals may be...


text:
The RF 433MHz receiver code is working only when I reset the Arduino
I'm working on RF modules using Arduino but I observed the if statement is only running once and I need to reset the receiver every time to make it work with real-time changes in the transmitter.
I connected the 16X2 LCD display for displaying the data.
If I start the transmitter and started sending data as "1", it's showing "Bye" but when I change the transmitter data to "0", then also it is showing "Bye" only.
I changed a code a little bit but I felt it is the problem with the previous data stored in buf variable.
I'm expecting the LCD should display "Hi" when I changed the transmitting data to "0" from "1" which is not happening only "Bye" is displaying every time.
Here is the Arduino receiver code:
#include <RH_ASK.h>
#include <SPI.h>
#include <LiquidCrystal.h>

const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;

LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
RH_ASK rf_driver;
char message[2];

void setup()
{
    rf_driver.init();
    Serial.begin(9600);
    lcd.begin(16,2);
}

void loop()
{
    uint8_t buf[2];
    uint8_t buflen = sizeof(buf);

    buf[1] = '\0';

    if (!rf_driver.recv(buf, &buflen))
    {
        if (strcmp((char*)buf, "0") == 0) {
            Serial.println("Hi");
            if (strcmp(message[0], (char*)buf[0]) != 0) {
                lcd.print("Hi");
            }

            lcd.display();
        }
        else if (strcmp((char*)buf, "1") == 0) {
            Serial.println("Bye");
            if (strcmp(message[0], (char*)buf[0]) != 0) {
                lcd.print("Bye");
                lcd.display();
            }
        }
    }
    message[0] = (char*)buf[0];
}

Here is the transmitter code:
#include <RH_ASK.h>
#include <SPI.h>
RH_ASK rf_driver;

void setup()
{
    rf_driver.init();
    Serial.begin(9600);
}

void loop()
{
    const char *msg = "1";
    rf_driver.send((uint8_t *)msg, strlen(msg));
    rf_driver.waitPacketSent();
    delay(1000);
}

The Serial monitor output is as follows:

Does the serial monitor output "Hi" if you change the transmitted value to "0"? (You might want to extend your transmitter code a bit for easier debugging.) -- Why do you initialize the LCD each time, is this necessary? -- Please indent your source properly, it is hard to read. I've edited it once, but you have overwritten it, so I repeat the edit.

No, it's not outputting "Hi" when i change the transmitted value to "1". It is continuously showing "bye" only.

Huh? With "1" you want to output "Bye". Why do you expect "Hi"?

sorry,  it's not outputting "Hi" when i change the transmitted value to "0". It is continuously showing "bye" only. Only i click on reset button on Arduino, it is working

What is shown in the serial monitor if you output the received message?

char message[2];  ... if (strcmp(message[0],  You should be getting a warning for this. If not, turn your warning level up in the preferences.

It is just continuously showing "bye" irrespective of the changes in transmitted message

go back to the beginning ... reduce your code ... forget about decoding the received data ... print the received data and the length of the received data ... do you receive what you expect to receive?

I pointed this out in a comment thinking the question would probably get closed when this was understood to be a typo, but I guess it's not a typo.

char message[2]; ... if (strcmp(message[0], You should be getting
a warning for this. If not, turn your warning level up in the
preferences.

If you increase the warning level you should see something that at least hints at some of what I'm saying below.
Cutting your code down to a part relevant to the description of the problem:
char message[2];
// ...
uint8_t buf[2];
// ...
if (strcmp(message[0], (char*)buf[0]) != 0) {

strcmp() expects a pointer to a character for both its first and second arguments. However, message[0] is of type char and buf[2] is of type uint8_t (ultimately an unsigned char). The individual characters being used are being interpreted as pointer values (as in memory addresses) which strcmp() expects to refer to the first characters of strings.  In other words, it's going to some pair of memory addresses between 0 and 255 and trying to interpret whatever it finds at those locations as strings and compare them. The combination of what you're doing being undefined and not having a strong expectation of what to find at these memory addresses, it's not really surprising (to me anyway) how your comparisons are evaluating.
A minimal change that should bring the strcmp closer to making sense is:
if (strcmp(message, (char*)buf) != 0) {

message and buf here will end up evaluating to the actual locations of their strings.
You were already doing half of this line correctly in your other use of buf in if (strcmp((char*)buf, "0") == 0); note no [0] usage there.

In the above I'm addressing this directly and taking it for granted that you have some reason to want to use string that have one (non-null) character in them, that you intended to expand this code to longer messages somehow. Otherwise it makes more sense to just dispense with strings altogether and have rh_driver.recv read directly into a single character type and then use the equality comparison == rather than strcmp().
The sections of code would look more like:
char message; // now individual char
// ...
uint8_t buf;  // now individual char
// ...
if (!rf_driver.recv(&buf, sizeof buf)) { //sizeof buf is 1
    if (buf == '0') { // now simple application of ==
        Serial.println("Hi");
        if (message != buf) {  // now simple application of !=
            lcd.print("Hi");
        }
// ...
message = buf; // no longer using [0] because no longer an array


text:
Flash String Helper object as variable
So I have a Bunch of commonly used char arrays to build commands in my library.
So to preserve memory, I have them put into flash, via PROGMEM ext,
typedef const char PROGMEM ProgChar;
ProgChar AT[] = "AT";
ProgChar AT_RST[] = "RST";

Then in my program I have it all go out to A port via:
*hws << AT << PLUS << CWMODE << EQUAL; //hws can be any Print type,

This is handled by overloading the << operator;
static Print &operator <<(Print &obj, ProgChar* arg) {
  char pbuffbuffer[12]; //create a buffer,
  obj.print(loadProgmemVal(arg,pbuffbuffer)); //Load it, and then pass to obj print method.
  return obj;
}

But this also overloads the << operator for all const char* Which makes me have to do a workaround:
hws->print(1); //HACK

At first, I thought I would overload the operator to handle both a char* and a Prog Char Object, But unfortunately, they are both treated as the same thing at run-time which makes that idea useless.
So after snooping I find the __FlashStringHelper type and macro. Which would allow me to have a sepperate type for these variables, and allow me to overload.
But the problem is, I cant find a good way to Create these:
const __FlashStringHelper MYVAR = F("Some text to be progchared");

Does not compile =/
Now I could probably make some helper method to load them all in, but that is just patching a hack with another hack... Is there any Clean way to do this? So I can use << for all types,
*hws << AT << PLUS << CWMODE << EQUAL << 1 << "\r\n"; //1 and Return break...

Idea: Is the objects in Flash at a lower PTR value then Objects in Ram, and ifso, what is then cutoff?
EG: 0-04f00 = Flash 04f01-fffff = Ram, ext.

Seems like the recommended style is to use the macro FPSTR(). https://arduino-esp8266.readthedocs.io/en/latest/PROGMEM.html static const char xyz[] PROGMEM = "This is a string stored in flash"; Serial.println(FPSTR(xyz));

Is this legal?
typedef const char ProgChar;
ProgChar AT[] = "AT";

I would think that the PROGMEM can't be in the typedef, i.e.:
typedef const char ProgChar;
ProgChar AT[] PROGMEM = "AT";

If you meant "Is typedef const char PROGMEM ProgChar; ProgChar AT[] = "AT";", legal then apparently it is. typedef const char PROGMEM ProgChar; ProgChar AT[] = "AT"; void setup() { Serial.begin(115200); Serial.println((const __FlashStringHelper *)&AT[0]); } void loop() { ; } compiles, runs, and produces the expected output.


text:
Why can't my Arduino IDE recognize serial ports? (Mac El Cap, Ard. UNO)
My Arduino UNO I bought directly from Arduino.cc, so I'm pretty certain it's not a cheap clone. I have a MacBook Pro El Capitan 10.11.5. My Java is 1.8, but I'm pretty sure that doesn't matter. I have never used Arduino before, though I know a good bit of programming and some about computers. Whilst setting up Arduino, the only serial port my computer/Arduino recognizes is /dev/cu.Bluetooth-Incoming-Port. Please comment if there is more information I should provide.
My computer recognizes that I have a USB device as seen here:

Here is a screenshot of the Arduino IDE:

Finally, the commandls /dev/tty.* outputs only /dev/tty.Bluetooth-Incoming-Port. Is it possible no other serial ports exist for me?
Sorry for the barrage of pictures but I thought they'd help.
Things I have tried:

Installing CH34x driver

I'm convinced it's not a driver issue though, as users and Arduino say that OS X does not need drivers installed to run Arduino

Turning off System Integrity with csrutil --disable and also tried csrutil --enable without kext
Installing a FTDI USB Serial Driver
Bought a new USB A/B cable, as many reported the cable was faulty. I am getting a green light on my board

Does anyone know why my computer and/or Arduino does not list more serial ports that work? It's as if I don't have any besides the one Bluetooth port. I've been getting frustrated over this for several hours, so a solution would be much appreciated :)! I've tried all the solutions I've seen on SE thus far, but maybe I'm missing something
Thank you ahead of time!

"ATmega16u2 DFU" indicates a USB interface micro that is in a state to have new firmware downloaded to it (DFU), not one which is ready for operational use as a USB interface to program the Uno's ATmega328p target MCU.  If this persists after power-cycling/re-plugging the board, it is probably faulty and at minimum needs firmware repair - though it might be worth trying on another computer (preferably with a different OS or version) just to be absolutely sure nothing in the host software is forcing it to this mode.
If this is a new board you have not modified in any way, you should probably return it as defective.
If you have modified it, or you want to try to fix things yourself, you would need to follow the instructions for reflashing the 16u2 via USB-DFU.  Beware that this is a non-trivial task that looks like it is going to require installing macports and running some terminal commands, and on older boards some soldering.

Thanks. Kinda comforting that I'm not going crazy. I'll order another one online. I've tried it on Linux, Windows, and Mac and all give the same error!


text:
How can I replace pulseIn with interrupts?
I have an HC-SR04 sensor and I need to get the distance from it. I use this code:
digitalWrite(trig, LOW);
delayMicroseconds(2);
digitalWrite(trig, HIGH);
delayMicroseconds(10);
digitalWrite(trig, LOW);
duration=pulseIn(echo, HIGH, 24000L);
cm=duration/2/29.1;

Pulsein takes too much time and I would like to use interrupts to prevent code from being blocked. From the beginning, I had no idea how to do it. I did not want to ask this question without trying on my own so here is my miserable attempt:
 while(digitalRead(echo)==LOW){
 }
if(digitalRead(echo)==HIGH){
      lowTimer=millis();
}
while(digitalRead(echo)==HIGH){

}

if(digitalRead(echo)==LOW){
   duration=millis()-lowTimer;
}

Obviously, this does not work. I don't know if I am on the right track, but I do know that even if this worked, it would still block my code for a long time. Can someone help me, point me in the right direction? Please don't just write it for me - I want to learn. I would like someone to point me to the right direction till I get it. Thank you!
EDIT:
I tried on of the suggestions:
unsigned long duration;
int cm;
const int echo = 24;
const int trig = 22;
bool doPing=true;

void setup()
{
  pinMode(echo, INPUT);
  pinMode(trig, OUTPUT);
  Serial.begin(9600);
}

void loop()
{
    if(doPing){
        ping();
        doPing=false;
    }
    read_pulse();
    if(duration!=0){
        cm=duration/29.1/2;
        Serial.println("cm: "+cm);
        doPing=true;
    }
    delay(2);
}
void ping(){
  digitalWrite(trig, LOW);
  delayMicroseconds(2);
  digitalWrite(trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(trig, LOW);
}

void read_pulse()
{
    static unsigned long rising_time;  // time of the rising edge
    static int last_state;             // previous pin state
    int state = digitalRead(echo);      // current pin state
    duration = 0; // default return value

    // On rising edge: record current time.
    if (last_state == LOW && state == HIGH) {
        rising_time = micros();
    }

    // On falling edge: report pulse length.
    if (last_state == HIGH && state == LOW) {
        unsigned long falling_time = micros();
        duration = falling_time - rising_time;
    }

    last_state = state;
}

This does not print anything to my serial monitor. Is there something I am missing?

This page explains Arduino interrupts really well:
Interrupts by Nick Gammon also see this: answer on StackOverflow

Start by studying NewPing; https://bitbucket.org/teckel12/arduino-new-ping/downloads.

Note that you can remove both if-statements. Since the while loop before it will only exit, if the condition inside the if-statement is true. Also work on proper indentation. It makes your code a lot easier to read.

First, remove the delay() from your code. The whole purpose of all this is to make the thing non-blocking, and you are completely defeating this with delay(): Not only will you have a terrible resolution of only 2 ms, you may miss the pulse altogether. Second, your pin assignments look dubious: you tagged the question “arduino-uno”, but there are no pins 22 nor 24 on the Uno.

@EdgarBonet I removed the delay and it works! I don't think it makes a difference on which board I tried it. I changed the tag know to arduino mega. Since the speed of sound is 340m/s, if an object is one meter away, it will take 2.9ms for the pulse to arrive. Therefore 2ms delay was indeed a terrible idea.

You do not want the reading of the incoming pulse to block your
program execution. This is the very key requirement: you want a
non-blocking pulse reading. You can write a non-blocking replacement
for pulseIn(), but you will have to use it differently. You cannot
expect a non-blocking pulseIn() to return the pulse length whenever
you call it: instead, it would return that value only when you call it
right after the pulse falling edge. On all other circumstances it will
return a dummy value meaning “the pulse is not finished yet, thus I
cannot give you its length right now, please call me later”.
Below is an example of a function implementing this approach. You have
to call it on every loop iteration: the more often you call it, the
better resolution you will have. This function uses 0 as the dummy value
meaning “no answer available right now”:
/*
 * Non-blocking pulseIn(): returns the pulse length in microseconds
 * when the falling edge is detected. Otherwise returns 0.
 */
unsigned long read_pulse(int pin)
{
    static unsigned long rising_time;  // time of the rising edge
    static int last_state;             // previous pin state
    int state = digitalRead(pin);      // current pin state
    unsigned long pulse_length = 0;    // default return value

    // On rising edge: record current time.
    if (last_state == LOW && state == HIGH) {
        rising_time = micros();
    }

    // On falling edge: report pulse length.
    if (last_state == HIGH && state == LOW) {
        unsigned long falling_time = micros();
        pulse_length = falling_time - rising_time;
    }

    last_state = state;
    return pulse_length;
}

A better approach, but harder to implement for a novice, is to use
interrupts. Chris gave you a pointer to Nick Gammon’s tutorial on
interrupts. This is definitely a good reading. But you will also have to
dig into the data sheet of the ATmega328P microcontroller.
It's a little bit daunting, but a must read if you go into low-level
programming. If you follow this path, I suggest you look at the “input
capture” capability of Timer 1 (chapter 20, section 20.9). This is a
feature of the timer that can have it automatically save a timestamp
whenever some external pin changes state. You then use the input capture
interrupt to alert the program when an edge has been detected, and your
interrupt service routine can read the automatically saved timestamp.
Using this approach, you can have extremely accurate pulse length
measurements, independent on how fast your program goes through its
loop().

Sorry for not checking out your answer in a while. I tried using the function you wrote in my code and the sensor gave back no values. I posted the code above in my question. Can you please take a look at it? Am I calling it at a wrong time?

@Edgar Is there any close example for us to try the input capture ?

@Shahabaz: I have no example at hand, but you can do a search for “input capture Arduino” or “input capture AVR”.

I posted a question and got answer as well. If incase anybody is looking for it https://arduino.stackexchange.com/questions/71434/implementing-plusein-using-interrupt?noredirect=1#comment155354_71434


text:
Should I control each of the four robot wheel separately or wire two from each side together?
I am making a remote controlled Arduino robot. I has 4 DC motors for wheels. I have 2 motor drivers available that control two dc motors each. I was wondering what the downsides are of wiring 2 dc motors together. The DC motors are 6v and the maximum current per channel of my motor driver is 1.2A which should be plenty for the motors. The motor driver that I am using can be found here. Each motor is getting controlled using a PWM signal. The DC motors are controlled separately.

what sort of motor controllers? do they amplify a PWM signal or do they interface over SPI or something else. When you say that each motor controller can control two motors, do you mean that two motors on one controller will always drive the same (as if you Y'd the cables, which would be a good choice, if you want a tank-drive operation) or does each controller control two motors on individual channels?

I added some more info into the question. Each driver controls 2 DC motors individually in both direction and using PWM for speed. @KissMeKimmi

it looks like you have two channels on each controller, so you have some options here. but first I'm going to talk a bit about your motors. If you have a spec sheet for them you can gather most of this info through that, but it doesn't hurt to do some experimentation. A motor will draw max current when it is stalled (is trying to drive but it can't), and you can determine this "stall current" with a multimeter or from the spec sheet. when you're driving the robot, this can occur when you drive up to a wall and try to push through the wall (hint, no robot this size will damage a well built wall) but likely the driver will reach a wall and stop driving (unless she can't see the robot while driving, idk). the lowest current it will draw (aside from zero when it can't...) is it's "free speed" current, this is when it's spinning as fast as it can with no load on it. while you're driving the robot you can expect the current to be between these numbers, if you want to get super fancy (and you want to equip your robot to do this) you could log the instantaneous current every 10ms or however often (this can be useful if you want to diagnose faults, but again its a small robot)... so if you have two motors in parallel (which you want to do because in series one will drive harder than the other), then the current drawn by each will add, so you can double it for two motors.
anyways, here's a few options for the motor configuration:
if two of your motors in parallel draw less than continuous 1.2 amps, you could use a single controller for one robot, controlling left wheels on channel 0 and right on channel 1.
if your motors draw more than that in parallel, you will have to use two channels per side, however you could Y the PWM lines between the motor controller and the arduino
if you are using something like omni wheels and want control over every single wheel, obviously you will want one channel per wheel...