do two arduinos that are linked to a common 9v rail and ground still need a common negative connection for a serial tx rx connection? so that there a 2 wires rather than 3 to connect between the two for purposes of serial communication.  And the same question for 3 arduino megas on a common rail and using serial connections?

All voltages are ground referenced, hence the ground is the only (supply) connection required. Remote modules can be self-powered and signals will still be discriminated as long as ground is connected.


Arduino due erase button and power switching Last days I have been investigatin schematics of arduino due board. The purpose of proper understanding of schematics in crucial for me, beacuse I indend to build myself my own board with some minor modifications.

I would really want to learn something from it and not just blindly copy stuff that are already done. In schematics there are two things that I do not understand. First is the working principle of erase button (see: erase button). I have my own idea how does it work, but would like to clarify the working principle from someone that know exactly what is the purpose of all the elements that are connected to erase button. Also, why is ERASE_CMD  line connected to Atmega processor?
 Second thing is switching of power supply between external power and both usbs (see: usb switch). Again, would someone please just brifly describe working principle? Here I really do not undertand why is there op amp added?

Thank you in advance.

Erase button:

USB switch:

PLEASE NOTE: Both pictures are taken from original arduino webpage: https://store.arduino.cc/due  (see: documentation -> schematics)

The asker posted the same question and received an answer here
There is discussion regarding the purpose of the Erase switch here


Use website to communicate with Arduino WirelessProtoShield I have a small office with wireless network, is it possible to make a wireless doorbell?
Practical example:
Arduino is connected to the main wireless network and has a static ip,
i have a website that connects through arduino using ftp to activate the "open door" function.
note: "open door" activates a motor to press the button, or i will hack the current doorbell to connect wires :D

Arduino wifi web server: http://arduino.cc/en/Tutorial/WiFiWebServer just modify the webserver to show a "open" button and to receive a post request and open the door.


I need help setting up my Arduino Uno with the port I'm using a Windows computer, and if I recall correctly I installed the IDE using the installer, so I probably don't need to manually install the drivers. However, I can't figure out how to set up the serial port with the Arduino. For me under Tools, there's no "Serial Port" option but instead "Serial Monitor" and "Serial Plotter."

When I tried to upload my file, it failed. When I clicked Serial Plotter, it gave this error message:

Arduino: 1.8.4 (Windows 8.1), Board: "Arduino/Genuino Uno"

Sketch uses 940 bytes (2%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for
local variables. Maximum is 2048 bytes.
avrdude: ser_open(): can't open device "\\.\COM1":
The system cannot find the file specified.

Problem uploading to board.
See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.
Board at COM1 is not available

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

How am I supposed to resolve this?

I figured it out by following the tutorial by Adafruit. I had to install it manually in order for it to work.


L293D driver DC motors need help to start rotating I set up this circuit which uses L293D motor driver IC to control two DC motors.

+6V input is connected to unregulated power supply. It's current rating is 500 mA.
There is a connection between Arduino's ground line and power supplies ground line. There is a parallel 0.1 uF capacitor connected between motor terminal pins.
There is a wheel at the end of the motors but they don't have a gearbox. The wheels are suspended so that they can rotate freely.
The source code of the software is as follows.
#include <Arduino.h>

unsigned int firstMotorPositive = 8;
unsigned int firstMotorNegative = 7;
unsigned int enableFirstMotor = 9;
unsigned int secondMotorPositive = 5;
unsigned int secondMotorNegative = 4;
unsigned int enableSecondMotor = 3;

void setup()
{
    pinMode(firstMotorPositive, OUTPUT);
    /*  I've changed this part as shown by @timemage  */
    //pinMode(secondMotorPositive, OUTPUT); // <------
    pinMode(firstMotorNegative, OUTPUT);
    pinMode(enableFirstMotor, OUTPUT);
    pinMode(secondMotorPositive, OUTPUT);
    pinMode(secondMotorNegative, OUTPUT);
    pinMode(enableSecondMotor, OUTPUT);

    // All motors are off
    digitalWrite(firstMotorPositive, LOW);
    digitalWrite(firstMotorNegative, LOW);
    digitalWrite(secondMotorPositive, LOW);
    digitalWrite(secondMotorNegative, LOW);
}

void turnOnMotors()
{
    // Set motors to maximum speed
    // For PWM maximum possible values are 0 to 255
    analogWrite(enableFirstMotor, 255);
    analogWrite(enableSecondMotor, 255);

    // Turn on motor A & B
    digitalWrite(firstMotorPositive, HIGH);
    digitalWrite(firstMotorNegative, LOW);
    digitalWrite(secondMotorPositive, HIGH);
    digitalWrite(secondMotorNegative, LOW);
    delay(2000);

    // Turn off motors
    digitalWrite(firstMotorPositive, LOW);
    digitalWrite(firstMotorNegative, LOW);
    digitalWrite(secondMotorPositive, LOW);
    digitalWrite(secondMotorNegative, LOW);

    analogWrite(enableFirstMotor, 0);
    analogWrite(enableSecondMotor, 0);

}

void speedControl()
{
    digitalWrite(firstMotorPositive, HIGH);
    digitalWrite(firstMotorNegative, LOW);
    digitalWrite(secondMotorPositive, HIGH);
    digitalWrite(secondMotorNegative, LOW);

    analogWrite(enableFirstMotor, 63);
    analogWrite(enableSecondMotor, 63);

    delay(3000);

    analogWrite(enableFirstMotor, 127);
    analogWrite(enableSecondMotor, 127);
    delay(3000);

    analogWrite(enableFirstMotor, 191);
    analogWrite(enableSecondMotor, 191);
    delay(3000);
/*
    analogWrite(enableFirstMotor, 255);
    analogWrite(enableSecondMotor, 255);
    delay(3000);
*/

    // All motors are off
    digitalWrite(firstMotorPositive, LOW);
    digitalWrite(firstMotorNegative, LOW);
    digitalWrite(secondMotorPositive, LOW);
    digitalWrite(secondMotorNegative, LOW);
    analogWrite(enableFirstMotor, 0);
    analogWrite(enableSecondMotor, 0);
}

void loop()
{

    /*
      turnOnMotors();
      delay(1000);
    */

    speedControl();
    delay(1000);
}

The problem is they need help to start rotating. They will only start rotating if I physically twist the shaft with my fingers first.
As far as I know the motors used in this circuit are two 6 volt DC motors.
When I measure the maximum voltage between motor terminals I read about 0.5 volts. If I twist the shaft I read about 4.5 volts.

The L2978D is a terrible motor driver (I really wish people wouldn't use it!). It is "bipolar" which means that both the high and low side switches of the H-bridge are Bipolar Junction Transistors. This means that you get about 1.4V voltage drop in total between the inputs and outputs.
To counter that you must provide at least 1.4V more than your motors need for them to operate properly.


Arduino OBD library and software serial library Can I use Arduino OBD library with "custom" software serial or it needs to be used with hardware UART only? For example if I have D5 and D6 pin as RX and TX in my code hooked on OBD board, how do I initialize OBD library from there?

This is the OBD library that I'm referring to.

And I'm using this Allpro OBD board.

Update
Actually I would be satisfied with a answer how to know when entire response from the board is received, because this way is way too messy:

void getResponse(void){
 while(obdSerial.available()){
   Serial.write(obdSerial.read());
  }
}

Here I don't know when the message is received. And if I try to use example from Sparkfun obd-ii-uart-hookup-guide (different board doe) I ended up in infinite-loop since the board never return \r, if I send ELM command to use \n as terminator, and if I disable ELM to echo the command so that I use just one getResponse call I get some readings, but not all the time, I ended up in infinite-loop again.

That library is hard-coded to use the single Hardware Serial device on the Arduino Uno or the second Hardware Serial1 device on other boards.

#ifndef OBDUART
#if defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168P__)
#define OBDUART Serial
#else
#define OBDUART Serial1
#endif
#endif

You can edit the library's header file OBD.h to define your own serial port though:

#include <SoftwareSerial.h>
extern SoftwareSerial mySerialPort;
#define OBDUART mySerialPort

And then in your sketch create the mySerialPort SoftwareSerial object.


Boolean variable with if statement I am trying to use boolean variables with two if statements. The second if condition never evaluates to be true. May be it's a problem with how I have defined my boolean variables. Do you see the mistake?

Here is the code:

int x = 0;
boolean state1 = (x <= 10);
boolean state2 = (x > 10);

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

void loop() {

  x++;

  if (state1) {
    Serial.println("x <= 10");
  } else if (state2) {
    Serial.println(" x > 10");
  }

}

I asked this question to be moved to Stackoverflow as it is not Arduino related.

However to answer your question, you assign the booleans before you start the program, so they are never re-evaluated and always keep their initial value, based on when x = 0.

What you should do is, reevaluate them within the loop:

int x = 0;
boolean state1;
boolean state2;

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

void loop() {
  x++;
  state1 = (x <= 10);
  state2 = (x > 10);
  if (state1) {
    Serial.println("x <= 10");
  } else if (state2) {
    Serial.println(" x > 10");
  }
}

Also, because if state1 is true, state2 will always be false and vice versa, so you don't need to have two booleans. This will give:

int x = 0;
boolean state;

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

void loop() {
  x++;
  state = (x <= 10);
  if (state) {
    Serial.println("x <= 10");
  } else {
    Serial.println(" x > 10");
  }
}

Beyond that, you don't need to define the boolean globally, because you only need it inside the loop and is not need to be 'stored' from one loop to another. So you get

int x = 0;

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

void loop() {
  x++;
  boolean state = (x <= 10);
  if (state) {
    Serial.println("x <= 10");
  } else {
    Serial.println(" x > 10");
  }
}

Of course you can also directly check for x <= 10 instead of storing it in a boolean, but I assume you need the boolean elsewhere further within the loop function later.


Linking one circuit to two Arduinos I don't actually have to achieve this, it's more of an attempt to see what the best way to do this is. I'm sure the answer also differs depending on what circuitry you're trying to connect.

In this case, I plan on an Arduino (probably a Pro Mini or similar) that will control some RGB LEDs (via the WS2811 chip). If I wanted to add a second Arduino that would drive the LEDs if the first one failed (obviously very unlikely), I was wondering how I would do it. The WS2811 chip takes 5V, GND and data in.

My best attempt at a solution is using 3 relays which are SPDT. Connect the LEDs to the main Arduino via the normally open, which is controlled by that particular Arduino, and connect the LEDs to the backup Arduino via the normally closed, which is held open by the main Arduino. In the event of a failure, the main Arduino would lose connection to the LEDs while the backup would make a connection.

This probably isn't a very safe way of doing it (especially if the relay failed for example). Is there a way to do this?

The two Arduinos will be powered from two separate laptops.

You first need to make a communication between both Arduinos and then you can control RGB led from any Arduino.

For the connection between both the Arduinos, you can make a serial port interface for doing this, you just need softwareserial.h library. Then you just need to connect the RGB LED to one Arduino. Then when you send a command from another Arduino to that one, the Arduino (Connected to RGB LED) can operate the LED according to the command.


Arduino Leonardo RX TX mystery I'm at the tail end of a project using a Leonardo, a HC-06 bluetooth module and a few cell phone vibration motors.  Everything is working fine except the serial communication between the Leonardo and the HC-06.  I've done some tests to rule out common mistakes

TX is connected to RX, and vice versa.
Using a multimeter I checked for continuity with the RX TX, no problem there
I can upload the script
I uploaded the exact same script to an Uno, using the same HC-06.  I was able to connect to the HC-06 with my phone and execute the script.  So I know it's not the script and I know it's not the HC-06.
The Leonardo is working properly because I can upload the script and execute it using the Arduino Serial Monitor.

The only clue I have is that I can upload the script with the RX/TX connected and that's not supposed to work.  However, I checked the connections and there is continuity.  So I'm stumped.  The only thing I can think of is that I damaged the RX/TX while I was soldering, but I'm hoping it's not that.  Is there a way to test for that.  Any suggestions?

/*
 * created by Rui Santos, http://randomnerdtutorials.com
 * Bluetooth App - Turn On and Off LED
*/

#include <SoftwareSerial.h>
SoftwareSerial mySerial(1, 0); // RX, TX

int led = 3;
int state;

void setup() {
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
}

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

  if (state == '1') {
      digitalWrite(led, HIGH);}   // turn the LED on (HIGH is the voltage level)

  else if (state == '2') {
      digitalWrite(led, LOW);}    // turn the LED off by making the voltage LOW

  delay(100);               // wait for 100ms

  //For debugging purpose
  //Serial.println(state);
}

An Arduino Leonardo has native USB support. Which means that it has separate serial interfaces to the PC and to the hardware pins.

Serial is only used for the communication with the PC and is unrelated to the hardware serial pins 0 and 1. Those are exposed trough Serial1.

So, if you are using the exact same Uno sketch, that uses the hardware serial pins, it can't work on a Leonardo, because data is just sent-to/read-from the PC and not to the connected Bluetooth module connected on pins 0 an 1.


AVR-GCC can't call function located on fixed address I wrote the following code:

#include <avr/io.h>

__attribute__((noinline, section(".app_start"))) void app_start() //app_start section starts at 0xFA0
{
    //register_packet_dispatch(packet_received);
    PORTB = 0xFF;
}

__attribute__ ((noinline)) void call_app()
{
    asm ("call 0xFA0\nret");
    //app_start();
}

int main()
{
    DDRB = 0xFF;
    //call_app();
    app_start();
    while(1){}
}

What I compiled with:

avr-gcc -Wl,--section-start=.reg_dispatch=0xdac -Wl,--section-start=.app_start=0xFA0 -mmcu=atmega328p -Os -o ubb.o ub_bootloader.cpp -DF_CPU=16000000

Which tries to simulate a host application that tries to call a relocated client application, begins from the 4000 address (0xFA0). If it would work, it's light up the LED wired to the arduino's 13. pin. But why app_start won't be called?

I've also inspected the output assemlby:

avr-objcopy -j .text -j .data -O ihex ubb.o ubb.hex

00000fa0 <_Z9app_startv>:
 fa0:   8f ef           ldi r24, 0xFF   ; 255
 fa2:   85 b9           out 0x05, r24   ; 5
 fa4:   08 95           ret

00000080 <main>:
  80:   8f ef           ldi r24, 0xFF   ; 255
  82:   84 b9           out 0x04, r24   ; 4
  84:   0e 94 d0 07     call    0xfa0   ; 0xfa0 <_Z9app_startv>
  88:   ff cf           rjmp    .-2         ; 0x88 <main+0x8>

Everything seems correct, why it isn't working at all?
Of course, if i remove the "noinline" attribute, it works. But that's a mirage, the compiler inlines the content of the function, but when I build this into an application, the code after the 0xFA0 address will be rewritten by the host application.

I've tried this code with arduino and it worked (i taught, of course, i can't add the "-Wl,--section-start=.app_start=0xFA0" flag to the compilation process so the function not gonna be moved to other section)
So i set the arudino IDE to show every command from the compilation to the end of the upload process.

The problem lies in the usage of avr-objdump, whose i found somewhere and used witouth overview the CLI switches.

I've also made a mistake when i wrote the question. To disassemble the object file, the right command is:

avr-objdump -S --disassemble  ubb.o > ubb.asm

THe command i've used to create hex file:

avr-objcopy -j .text -j .data -O ihex ubb.o ubb.hex

The working one (extracted from arduino):

avr-objcopy -O ihex -R .eeprom ubb.o ubb.hex

-j means keep only the given section(s)

while

-R means, remove only the given section(s)


Seems like I cant control 4 stepper motor at once Im trying to control 4 stepper motors with the AccelStepper library.
Something like this:
AccelStepper FL(1,stepPin,dirPin);
AccelStepper FR(1,stepPin2,dirPin2);
AccelStepper BL(1,stepPin3,dirPin3);
//AccelStepper BR(1,stepPin4,dirPin4);

The problem is, It works just fine if I declare 3 instance of the AccelStepper, but once I uncomment the 4th one there's an error.
Error message: Arduino: 1.8.13 (Windows Store 1.8.42.0) (Windows 10), Board: "ESP32 Dev Module, Disabled, Default, 240MHz (WiFi/BT), QIO, 80MHz, 4MB (32Mb), 921600, None"

In file included from C:\Users\Parit\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1/tools/sdk/include/esp32/xtensa/xtruntime.h:30:0,

                 from C:\Users\Parit\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1/tools/sdk/include/freertos/freertos/portmacro.h:80,

                 from C:\Users\Parit\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1/tools/sdk/include/freertos/freertos/portable.h:94,

                 from C:\Users\Parit\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1/tools/sdk/include/freertos/freertos/FreeRTOS.h:105,

                 from C:\Users\Parit\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1\cores\esp32/Arduino.h:32,

                 from sketch\Test_file.ino.cpp:1:

C:\Users\Parit\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1/tools/sdk/include/esp32/xtensa/config/specreg.h:40:13: error: expected unqualified-id before numeric constant

 #define BR  4

             ^

C:\Users\Parit\Desktop\Test_file\Test_file.ino:31:14: note: in expansion of macro 'BR'

 AccelStepper BR(1,stepPin4,dirPin4);

              ^

Multiple libraries were found for "WiFi.h"

 Used: C:\Users\Parit\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1\libraries\WiFi

 Not used: C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\libraries\WiFi

exit status 1

Error compiling for board ESP32 Dev Module.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

Im not sure if the problem is the ESP 32 or the code. I use the A4988 driver to connect with all 4 stepper motors.

The variable name BR is already used somewhere else.
Use a different variable name
AccelStepper FL(1,stepPin,dirPin);
AccelStepper FR(1,stepPin2,dirPin2);
AccelStepper BL(1,stepPin3,dirPin3);
AccelStepper BackRight(1,stepPin4,dirPin4);


How can Arduino know that the number in a variable is a pin number and not something else? I have a question with the topic variables.

So, a variable is a place where you can store data.

And when you make a variable with datatype int (int ledpin=13;) then you store a value 10 in a variable named ledpin.

BUT how can the Arduino know it's a pin number 13 from Arduino or a random number 13 that we are storing there?

Yes, a variable is just somewhere to store some data.

It's what you do with the variable that is important.

For instance:

int ledpin = 13;
pinMode(ledpin, OUTPUT);
digitalWrite(ledpin, HIGH);

That will set the variable ledpin to 13, then the next line will query the ledpin variable to find out what number it is, then pass that number to the pinMode function to set the mode of the pin to OUTPUT. The line after then does the same thing but passes the number 13 that it read from ledpin to the digitalWrite function to turn the LED on.

However, if you do this:

int ledpin = 13;
pinMode(ledpin, OUTPUT);
ledpin = 10
digitalWrite(ledpin, HIGH);

then it will act just the same at first, but the digitalWrite function will get the number 10 not the number 13 since the value in ledpin has been changed to 10 in the third line.

Remember: an integer is just a number - it's only when you do something with that number that it has any meaning.


My button control working in reverse I built this circuit to learn button control.

But my code (or button) is working in reverse. I want to initialize led flash effect when the button is pressed with this code

buttonState = digitalRead(8);
if (buttonState == HIGH)
  doFlash();

Instead the effect runs continuously and pauses if I push and hold the button. If change the condition as if (buttonState == LOW) code is working as expected. (Effect starts when I push the button.)

This is just the opposite of what I read in tutorials. What is wrong in my circuit or code?

Full code:

 void setup(){
  for(int i=2;i<=6;i++)
  pinMode(i,OUTPUT);
  pinMode(8,INPUT_PULLUP);
 }

 void loop(){
  int buttonState;

  buttonState = digitalRead(8);
  if (buttonState == LOW)
    doFlash();
 }

void doFlash() {
    int i;
    for (i=2;i<=6;i++) {
        digitalWrite(i,HIGH);
        delay(100);
        digitalWrite(i,LOW);
    }
    for (i=6;i>=2;i--) {
        digitalWrite(i,HIGH);
        delay(100);
        digitalWrite(i,LOW);
    }
}

This behavior is expected: INPUT_PULLUP means the pin is pulled up via the internal pull up, i.e. it will read as high if not connected externally.

With your push button you connect it to ground (0 volts), thus bringing it to low level and it will read as low. Therefore, in your code, you need to check for low level (LOW) to check if the button is pressed (as you found out by changing the code).


Do interrupts block other interrupts? If I have an interrupt attached to two pins and the handler of the first is still executing when the second interrupt fires, does it:
a) queue the second interrupt,
b) ignore the second interrupt (missing it altogether), or
c) pause processing of the first interrupt to execute the second?
I am writing code that logs the exact time the interrupt occurs. Quite lightweight, but have three pins and am logging the rise and fall of each, so there is the potential for collisions. If a) then the second interrupt timestamp will be late, b) there is no timestamp for the later interrupt or c) the timing of the first and second interrupts will be ambiguous.
b) is the worst case, the other two are manageable.

It depends on the architecture.
Assuming AVR (8-bit Arduino) then it will queue the second interrupt until the first is finished.
It works by setting a flag in a register at the moment the interrupt occurs. Then between instructions it checks that flag and executes the associated interrupt routine. If an interrupt is in progress at the time the flag still gets set, but it is unable to check the state of that flag until after the current interrupt is over and normal execution occurs, at which point after the next instruction is completed it checks the interrupt flag statuses and runs the second interrupt routine.


How to split a string received via a GSM module (message) I am doing a motorcycle security system. In this system, I will receive a message from GSM in the form {password:operation (like start,stop,alarm):time}.
Example:(9990:start:30)

now i need to split  each term seperately (a=9990,b=start,c=30).help me to solve

Simplest solution is to use sscanf().

  int password;
  char operation;
  int time;
  char* buf = "{14:C:123}";
  int n = sscanf(buf, "{%d:%c:%d}", &password, &operation, &time);
  Serial.print(F("n="));
  Serial.println(n);
  Serial.print(F("password="));
  Serial.println(password);
  Serial.print(F("operation="));
  Serial.println(operation);
  Serial.print(F("time="));
  Serial.println(time);


How to monitor state of 50 Digital Inputs Good day.

I have a specific project need and I spent the past couple of days searching on forum, blogs, etc and I'm still not clear if that's feasible to do with Arduino or not.

I need to monitor the state of ~50 digital inputs and trigger an action when any of the pin changes either from 0 to 1 or from 1 to 0, pretty much the same as pin state interrupt works, only difference is that I need to "listen" to ~50 pins, instead of just a couple. I must be able to identify what pin triggered the action and what was the change (0->1 or 1->0).

My initial idea is to use a MEGA 2560 and have a group of 50 "if" statements on the main loop comparing the previous state or each pin (stored in individual variables) with the current one and triggering the corresponding action if something changed.

I'd like to hear from the experts here what would be a more elegant or smarter/faster way to accomplishing this.

I'm eager to receive your feedback.

Thank you.

I had a project that used 16 rotary encoders and I used the MUX Shield which uses 74HC4067 analog multiplexers. They port to A0 - A3 on the shield which is fine as you can set these pins to Digital Inputs else you can get teh breakout version and connect to any input pins.
I also used a Due since ALL pins can be interrupt enabled.
Reading was a bit of a pain but worked like this...
The method is.. Continually address each input in turn in the loop or an interrupt is not detected, when an interrupt fires, address each input in turn again to find out which pin changed state.
Hope that helps.


How to send data in response to HTTP get request from ESP8266? I'm trying to control some RGB LEDs with ESP8266. I have built an HTML page to set the color and send the RGB color code to the ESP using HTTP get request. Everything works as expected. I just want to send an HTTP get request to the ESP and ask what the current color is. But after a couple of hours of searching and trying I don't know how to send data in response to get request, I just can send HTTP ok code. I'm using jquery to send get command as below

$.get("http://192.168.4.1/rgb(120,50,60)", function(data,status){
    //I don't know how to send data fram ESP get it here.
});

this is the corresponding ESP response code written in Arduini IDE

WiFiClient client = server.available();
   if (client) {
  String req = client.readStringUntil('\r');
  client.print("HTTP/1.1 200 OK\r\n");
  client.print("Access-Control-Allow-Origin: *");
.
.
.

This is the HTTP header, How do I send some data(text)?

@Gerben answered my question in a comment all credit goes to him. I retype it here maybe it helps someone in the future.

I had to send two new line after setting up the header

//header
client.print("\r\n\r\n");
clinet.print("Hello, I'm comming from ESP!!");

And in jQuery I get it like this:

$.get("http://192.168.4.1/rgb(120,50,60)", function(data,status){
    var receivedData=data;  //=Hello, I'm comming from ESP!!
});

It is simple but it may help some newbie like me.


Playing music with an Arduino Good evening!

I am quite new with Arduino but not in programming. Still, I have already done some programs with few leds.

I was just wandering how to create a circuit and a program that would play the "happy birthday" song with the following materials:

I have a breadbord and some wires.

Else, do you have some links where I could start learning how to play music with it?

Thanks to Mikael Patel for suggesting that link (your Google-Fu must be strong!).

I am pasting the code below so that this answer survives any possible future deletion of the read-only part of the Arduino Forum.

//ONG LIT YIT 2013-07-20
//This following code plays happy birthday melody on Arduino
//Put Piezo Buzzer on GDN and 9 (Positive and negative are reversible)
//this project requires a Piezo Buzzer and

// an Arduino board and
//jumper wires to connect Buzzer's (+) to ~9 and (-) to GND (any GND)

const int speakerPin = 9;
const int LENGTH = 28; // the number of notes
const char notes[LENGTH + 1] = "GGAGcB GGAGdc GGxecBA yyecdc";
const int beats[LENGTH] = { 2, 2, 8, 8, 8, 16, 1, 2, 2, 8, 8, 8, 16, 1, 2, 2, 8, 8, 8, 8, 16, 1, 2, 2, 8, 8, 8, 16 };
const int tempo = 150;

void playTone(int tone, int duration)
  {
  for (long i = 0; i < duration * 1000L; i += tone * 2)
    {
    digitalWrite(speakerPin, HIGH);
    delayMicroseconds(tone);
    digitalWrite(speakerPin, LOW);
    delayMicroseconds(tone);
    }
  } // end of playTone

void playNote(const char note, const int duration)
  {
  char names[] = {'C', 'D', 'E', 'F', 'G', 'A', 'B',
                  'c', 'd', 'e', 'f', 'g', 'a', 'b',
                  'x', 'y'
                 };
  const int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014,
                  956,  834,  765,  593,  468,  346,  224,
                  655 , 715
                };
  const int SPEE = 5;

  // play the tone corresponding to the note name
  for (int i = 0; i < 17; i++)
    {
    if (names[i] == note) {
      int newduration = duration / SPEE;
      playTone(tones[i], newduration);
    }
  }
} // end of playNote

void setup()
  {
  pinMode(speakerPin, OUTPUT);
  } // end of setup

void loop()
  {
  for (int i = 0; i < LENGTH; i++)
    {
    if (notes[i] == ' ')
      {
      delay(beats[i] * tempo); // rest
      }
    else
    {
      playNote(notes[i], beats[i] * tempo);
    }

    // pause between notes
    delay(tempo);
  }
} // end of loop

I also cleaned up the code a bit.


Weird behavior of variables when replacing for loops with if statement See the picture of serial monitor showing I get a large number, 4 billion, when I multiply two called functions together. It always happens after 53 if I change the amount the if statement counts to. I serial monitored the if statement and it counts to 600 then down then up and repeats good and the sensorValue stays the same.  I get rid of the division in y and I put it all in the for loop and still get a large number. My purpose is to fade pin and adjusts analogWrite at same time. It adjusts but does not fade. Does replacing for loop with if statement or calling to many functions create a bug.

int analogInPin = A0;
int analogOutPin3 = 3;

int sensorValue;

int i = 0;
int a;
int y;

void sens(int &sensorValue){
  sensorValue = (((long)analogRead(analogInPin)*255)/1023);
}

void inOut(int &i){
  if (i > -1){
    i = i + a;
  if (i == 0){
     a = 1;
  }
  if (i == 600){
    a = -1;
  }
  return i;
 }
}

void updateFade(){
  sens(sensorValue);
  inOut(i);
  unsigned long y = ((sensorValue*i)/600);
  Serial.println(sensorValue);
}

void setup() {
  Serial.begin(9600);
  pinMode(analogInPin,INPUT);
  pinMode(3,OUTPUT);
}

void loop() {
  updateFade();
  delay(100);
  analogWrite(3, y);
}

You define i,y,i as global variables so there is no need to hand them over to different functions. They can be accessed and changed in all parts of your program.

define instead of

int y;

change to

long y;

and change

 void inOut(int &i){

to

void inOut(){

and remove

   return i;// Its a global var

change the line

unsigned long y = ((sensorValue*i)/600);

to

y = ((sensorValue*i)/600);

Try to avoid the same names for global and local vars. It might happen that the compiler handles it as a redefinition, which might lead to all sort of trouble in complex programs. (Also for you if you look onto an ill documented code some months later)And get rid of the delay it stops processing (also your subroutines) see Blinkwithoutdelay how to do it properly ArduinoIDE->file->examples->2 Digital->Blinkwithoutdelay


Turning on many (30) leds arduino mega I´m new working with Arduino. Right now I have a project thar requires to turn on 30 LEDs at the same time with an Arduino Mega. The problem is that it would exceed the max current that the chip can tolerate.

It is possible to do this by turning on one LED at the time, very fast?

If it is, any clue on the code to achieve that will be apreciated.

Thank you very much

P.S.: I know there are components to expand the quantity of pins that work like that, but the idea is to avoid using one.

This page explains that the ATmega2560 could drive up to 800mA: Arduino Playground: Arduino Pin Current Limitations
There are limitations for groups of pins, so you have to be careful.
The 800mA is a lot in my opinion. I wonder how hot the chip will become.

What kind of leds do you use ? Normal 20mA leds ? Or is 10mA leds also possible ? 30*20mA = 600mA, but 30*10mA is only 300mA. The 300mA seems a lot safer to me.

With Charlieplexing the leds are not 'on' all the time. However, with the Arduino Mega 2560 you have enough pins, and you could just lower the current through the leds.
Turning them on for a short time (without Charlieplexing) is the same as turning them continuous on with a lower current.

The most common way to drive 30 leds is with a led strip. For example a led strip with neopixels. That led strip has to be powered seperately.

My advice is to lower the current for the leds to 10mA and hope that the ATmega2560 doesn't get too hot.

[ADDED] 300mA is still a lot. Start with 5mA per led for a total of 150mA when they all are on at the same time. Many modern and good quality leds are bright at 5mA.


Being able to run two functions at once So I am doing a project where a bunch of servos are moving from 90 - 120 degrees and slowly speed up over time until they reach their max speed and so stay at that speed.
This is being done by editing the delay under the servo sweep for loop.
However though this works it doesn't work with the next component.

WHat I want to happen next is an MFRC522 RFID reader to always be scanning and at any time it detects a card and verifies it the servos from whatever speed they are now at start to slow down.
The problem is I can't get the two functions to run simultaneously. IF the servo is running its sweep function it must finish before the RFID tag can scan. This makes the whole device look very lagy.
Is there a way I can get the RFID scanner to be reading all the time even when the servo sweep for loop is working?

Here is the code:
Please note that I have put printins everywhere to see how often the RFID is scanning etc just while I test the code out.
I essentially have two functions one called nocardservo and yescardservo each one activating if there is a card there or not.
Any help would be fantastic!!

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

#define RST_PIN     9       //
#define SS_PIN      10      //

MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance

Servo myservo;
int pos = 0;
int y = 15;
int z = y;
void setup() {
  myservo.attach(6);
  myservo.writeMicroseconds(1518);
  Serial.begin(9600);       // Initialize serial communications with the PC
  while (!Serial);      // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
  SPI.begin();          // Init SPI bus
  mfrc522.PCD_Init();       // Init MFRC522
  //ShowReaderDetails();    // Show details of PCD - MFRC522 Card Reader details
  //Serial.println(F("Scan PICC to see UID, type, and data blocks..."));
}

void loop() {
  // Look for new cards
  if ( ! mfrc522.PICC_IsNewCardPresent()) {
nocardservo();
    return;
  }
  delay(20);
  Serial.println("carddetected");
  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial()) {

  }
  Serial.println("correctcard");
  yescardservo();
delay(20);
return;
}

//***If card not detected this function runs**//

void nocardservo() {

  for (pos = 90; 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 >= 90; pos -= 1) // goes from 180 degrees to 0 degrees
  {
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);

  }
}
}

//***If card is detected this function runs**//

void yescardservo() {

  for (pos = 90; 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(50);                       // waits 15ms for the servo to reach the position
  }
  for (pos = 180; pos >= 90; pos -= 1) // goes from 180 degrees to 0 degrees
  {
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(50);

  }

}

What you want to implement is described in Blink Without Delay.  Basically, instead of using the delay function to just wait until your time has elapsed, you use variables to measure how much time has elapsed and only execute your operation when it has.  In the mean time, you can check on other things and do those in the mean time.


PIR motion sensor stuck in a loop I've bought an HC-SR501-compliant PIR motion sensor (like this one) and connected it to a Teensy 3.1. The circuit seems fine, and the LED lights up. However, when nothing is moving in front of it, the sensor keeps reporting HIGH and LOW in suspiciously constant intervals. The monitor reads like this (numbers in milliseconds)

motion detected  4113
motion stopped   7234
motion detected  4114
motion stopped   7274
motion detected  4113
motion stopped   7204
motion detected  4111
motion stopped   7184

When it detects movement, it stays on the triggered position for longer, but even then goes back to predetermined intervals, e.g.

motion detected   4113
motion stopped   17204
motion detected   4111
motion stopped   41754
motion detected   4113

This is the sketch (as found on Adafruit):

int ledPin   = 13;              // choose the pin for the LED
int inputPin = 1;               // choose the input pin (for PIR sensor)
int pirState = LOW;             // we start, assuming no motion detected
int val      = 0;               // variable for reading the pin status

unsigned long lastTime = millis();

void setup() {
  pinMode(ledPin, OUTPUT);      // declare LED as output
  pinMode(inputPin, INPUT);     // declare sensor as input

  Serial.begin(9600);
}

void loop(){
  unsigned long currentTime = millis();

  val = digitalRead(inputPin);   // read input value
  if (val == HIGH) {             // check if the input is HIGH
    digitalWrite(ledPin, HIGH);  // turn LED ON
    if (pirState == LOW) {

      // we have just turned on
      Serial.print("motion detected ");
      Serial.println(currentTime - lastTime);

      // We only want to print on the output change, not state
      pirState = HIGH;

      // Save time for measurement
      lastTime = currentTime;
    }
  } else {
    digitalWrite(ledPin, LOW); // turn LED OFF
    if (pirState == HIGH){

      // we have just turned off
      Serial.print("motion stopped ");
      Serial.println(currentTime - lastTime);

      // We only want to print on the output change, not state
      pirState = LOW;

      // Save time for measurement
      lastTime = currentTime;
    }
  }
}

Could this be a faulty device? I'm thinking about getting a new one for testing. While I can compensate for the gaps when triggered, I can't think of a way to make sure that it's not actually being triggered by this weird internal interval.

Try powering the PIR motion sensor with a higher voltage.  I get the same problem you're seeing when powering it with the 3.3v output of an Adafruit Huzzah ESP-12, but it works just fine when I power it with the 5v USB power.


How to make two WIR 1186 RF transceivers communicate over serial communication? I want to have two RF transceivers communicate, one as transmitter and one as a receiver, for longer distances. For that I'm using WIR 1186 RF modules with Arduino.

Pin connections are as below:

Arduino :5v,gnd,RX,TX,2,3
WIR1186 :VCC,gnd,Tx,Rx,prg,cts

But Arduino is not serially communicating with the WIR1186 module.

Below is the code:

char ch;
int prog = 2;
int cts = 3;
int stat;
unsigned int output;

void setup() {
  Serial.begin(9600);
  pinMode(prog, OUTPUT);
  digitalWrite(prog, LOW);
  stat = digitalRead(prog);
  Serial.println(stat);
  Serial.write("B=9600\r\n");
  output = Serial.read();
  Serial.println(output);
  digitalWrite(cts, HIGH);
}

void loop() {
  Serial.write('a');
  delay(1000);
}

Here is the datasheet of WIR1186

Please help me out with this.

If you use pin 2 and 3 for serial communication you have to use SoftSerial, because Serial is hardwired to pin 0 and 1.


Replicate a Waveform Exactly with An Arduino Uno So I've got a waveform that's high for 16ms and low for 2ms repeating forever. I need to recreate that and offsets of that waveform time exactly on a different pin. Right now, I've got an interrupt on the rising edge for the 16ms low/high transistion, and delayMicroseconds() that determines the offset and duration of the high and low pulses. Trouble is, I'm not sure the code I have is as fast and accurate as it could be. And the replicated waveform seems to shift through the full period of the original one. I need it to be locked in.Any suggestions?
Here is the code:

 //3 is interrupt for Timing
//4 through 11 are Time dependent receivers
//3-11 Pins 12-19
char incomingByte = 0;

int pins[9] =
{
  3,4,5,6,7,8,9,10,11
};

void timing()
{
  //Serial.println("This is a 0ms Event");
 // if(Serial.available() > 0)
 // {
    incomingByte = Serial.read();
    Serial.print("I received");
    Serial.println(incomingByte);

     pinMode(10, OUTPUT);
     digitalWrite(10, HIGH);
     delayMicroseconds(16000);
      digitalWrite(10, LOW);
      delayMicroseconds(2000);
      digitalWrite(10, HIGH);
 }
//}

void setup() {
  // put your setup code here, to run once:

for(int i=0;i<8;i++)
{
  pinMode(pins[i], INPUT);
}
pinMode(3,INPUT);
attachInterrupt(1,timing,RISING);

//Begins Serial
Serial.begin(115200);
}

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

Here's the waveform I'm trying to duplicate:

If you're looking to speed your code up I would recommend not using digitalWrite or Serial. When using digitalWrite it can take quite a few unneeded clock cycles to turn the pin on or off, as a replacement I would suggest looking into using port manipulation.

Example of turning a pin on or off with a preprocessor macro using port manipulation

#define DIGITAL_WRITE_10_HIGH() PORTB = PORTB | B00000100     // Town ON only pin 10
#define DIGITAL_WRITE_10_LOW() PORTB = PORTB & ~B00000100     // Turn OFF only pin 10

Using port manipulation in your code:

#define DIGITAL_WRITE_10_HIGH() PORTB = PORTB | B00000100     // Town ON only pin 10
#define DIGITAL_WRITE_10_LOW() PORTB = PORTB & ~B00000100     // Turn OFF only pin 10

void timing()
{
    //incomingByte = Serial.read(); // If needed uncomment, but it's slow
    //Serial.println(incomingByte); // If needed uncomment, but it's slow

     // Set pinMode in setup()
     DIGITAL_WRITE_10_HIGH();
     delayMicroseconds(16000);
     DIGITAL_WRITE_10_LOW();
     delayMicroseconds(2000);
     DIGITAL_WRITE_10_HIGH();
 }


How to make universal remote controller? I am trying to make simple TV remote using Arduino.

I got this link from Google for making a remote.

Code uploaded perfectly on my device. But all it does is blink a the LED on pin 13.

I hope I have got right code. I have tested it on my TV at home. Is that the correct way of testing it?

IR receiver I have is TSOP-15

P.S. I am completely new to Arduino

The below shown is my Arduino board(induino r3)

As you've stated in your question, the TSOP-15 is a receiver. That means it detects infrared signals rather than sending them out.

To make a remote control with that code, you need a simple infrared light emitting diode.

It's also important to note that you need to know what signals to send. Different TVs will have different IR codes, depending on the manufacturer. That information can be detected using your receiver module along with your TV's proper remote control.


Is there a sensor to measure a distance between 2 point as in range [0-2 meter]? I'm looking for a way of detecting if 2 pieces of hardware are within 2 meters of eachother or not. The idea is to build a prototype to lock computers automatically. I just need a recommendation on the sensor if it exists. Geofencing, bluetooth etc are not reliable enough.

You can use a lot of different methods with advantages/disadvantages:

Use an IR LED/receiver and calculate the distance of travelling of the lights. Disadvantage: you need a very precise timing mechanism (light is fast), also take latency into account for non-light parts, and hardware needs to be in visible range and pointing to each other with LEDs)
Use an ultrasonic sensor like SR-HC04. Disadvantage: devices must point to each other in a small precise angle.
Using an RF method and sending/receiving e.g. via nRF24L01+ 2.4 GHz trasnceivers, to check the difference in time between sending and receiving when very close or a few meters apart. However, there might be aspects that might distort the result (other receivers/transmitters, what kind of material is in between, nRF antenna placement/direction etc). Using lowest speed (most reliable), highest power.


How compile an Arduino program for a desktop PC I have an arduino program that only does serial communications with a little bit of math, and I am writing another one to communicate with it on a second arduino.  For testing purposes I was hoping I could run the serial only program on my desktop.  I know it is possible to run on a raspberry pi but I have never done that.  Can I do something similar on windows?  If not, can anybody recommend the easiest way to do this with a regular C++ program that would require very little editing? Here is a copy of my code if it's helpful.  It basically increments a variable up and down between 0 and 100.

int pos = 60;
bool flag=0;
int dly=50;
int vel=0;

const int buttonPin =  12;      // the number of the LED pin

// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status

void setup() {
  pinMode(buttonPin, INPUT_PULLUP);

Serial.begin(115200);
}

void loop() {
    dly=50;
    buttonState = digitalRead(buttonPin);
    if (buttonState==0)dly=12;
    Serial.print(vel); //speed
    Serial.print(",");
    Serial.println(pos); //position
    delay(dly);
    if (pos==30)flag=1;
    if (flag==1) pos+=1;
    if (pos==100)flag=0;
    if (flag==0) pos-=1;
    vel=1000/dly;
    if (flag==0) vel*=-1;

}

If you want to run the Arduino sketch on your desktop, you just have to
implement the Arduino core library for your PC.

It may not be as bad as it sounds. If your program makes only minimal
use of the Arduino core, you may implement only the parts you really
need. For example, this partial implementation is enough to run your
program:

#include <cstdint>
#include <iostream>
#include <unistd.h>  // for usleep()

using std::cout;
using std::endl;

#define INPUT_PULLUP 2

void pinMode(uint8_t, uint8_t) {}

uint8_t digitalRead(uint8_t) { return 0; }

void delay(int t) { usleep(t * 1000UL); }

struct {
    void begin(int) {}
    template<typename T> void print(T x) { cout << x; }
    template<typename T> void println(T x) { cout << x << endl; }
} Serial;

int main()
{
    void setup();
    void loop();
    setup();
    for (;;) loop();
}

I tested this on Linux, by simply appending your program right below
this. If you are using Windows, you will have to replace the usleep()
function with the appropriate Windows call (and <unistd.h> with the
appropriate header). The serial stream goes to the standard output. You
may redirect it to the USB serial port if you wish (trivial to do in
Linux, I assume it should be doable on Windows). You may also want to
replace digitalRead() with something that simulates a more realistic
user interaction.

Keep in mind that the sizes of the basic data types can be different on
the Arduino and on the PC. On an AVR-based Arduinos, int and pointers
are 16 bits while long is 32 bits. This is an “IP16” data model. An
ARM-based Arduino would typically be ILP32, whereas a 64-bit PC is LP64,
unless it runs Windows, in which case it's LLP64. This can make a
difference, especially if some of your calculations are prone to
overflow with the smaller data models.

Edit: I recently stumbled upon NCORE, a native core for
Arduino. It may be a good fit for what you are trying to do.
From the page description:

  The native core allows you to compile and run Arduino sketches on the
  PC, generally with no modification. It provides native versions of
  standard Arduino functions, and a command-line interpreter to give
  inputs to your sketch that would normally come from the hardware
  itself.


"'Serial' does not name a type" error I'm getting a "'Serial' does not name a type" error when this program is compiled. I need for the 8 channels of voltage to be displayed. I'm sure it's a simple fix, however I'm still learning Arduino programming. I thank you for your help.

int pin_Out_S0 = 8;
int pin_Out_S1 = 9;
int pin_Out_S2 = 10;
int pin_In_Mux1 = A0;
int Mux1_State[8] = {0};
//float Mux1_State[i] =0;
int RawValue=0;
float Voltage = 0;
void setup() {
  pinMode(pin_Out_S0, OUTPUT);
  pinMode(pin_Out_S1, OUTPUT);
  pinMode(pin_Out_S2, OUTPUT);
  pinMode(pin_In_Mux1, INPUT);
  Serial.begin(9600);
}

void loop() {
 RawValue = analogRead(pin_In_Mux1);
 Voltage = (RawValue * 5.0) / 1024; //scale the ADC
  updateMux1();
  //Serial.println(Mux1_State);
  for(int i = 0; i < 8; i ++) {
    if(i == 7) {
      Serial.println(Mux1_State[i]);
    } else {
      Serial.print(Mux1_State[i]);
      Serial.print(",");
      //vout = (value * 5.0) / 1024.0;
    }
  }
}

void updateMux1 () {
  for (int i = 0; i < 8; i++){
    digitalWrite(pin_Out_S0, HIGH && (i & B00000001));
    digitalWrite(pin_Out_S1, HIGH && (i & B00000010));
    digitalWrite(pin_Out_S2, HIGH && (i & B00000100));
    Mux1_State[i] = analogRead(pin_In_Mux1);
  }
}
Serial.print("Raw  Value = " );
Serial.print(RawValue);

Your last two lines are not in any function. This confuses the compiler. You need to move those two statements inside a function.

Because those statements refer to RawValue, I'm guessing you want to put them in loop(), where RawValue is being updated.

Also, remember that the IDE will tell you on which line the error is, which is helpful when debugging compilation errors.


Behaviour of tone() not as expected within while loop I have a smoke detector with a piezo buzzer. I want to operate the arduino in low power mode so that it will last on a 9V battery. I've attached an interrupt, and when the digital output of the MQ-2 sensor goes high, it switches to a monitor function.

In the while loop, I check to see if the analog sensor has reached the threshold value, and I output to serial to see if I am in the conditional. If I use:

digitalWrite(buzzer, HIGH);

then the piezo sounds, however if I use

tone(buzzer, 1000,200);
delay(200);

it does not. I'm confused as to why this would be the case.

Full code as follows:

#include "LowPower.h"

int redLed = 12;
int greenLed = 11;
int buzzer = 10;
int smokeA0 = A5;
// Your threshold value
int sensorThres = 50;
int smokeD0 = 2;

void setup() {
  pinMode(redLed, OUTPUT);
  digitalWrite(redLed, LOW);
  pinMode(greenLed, OUTPUT);
  digitalWrite(greenLed, HIGH);
  pinMode(buzzer, OUTPUT);
  pinMode(smokeA0, INPUT);
  pinMode(smokeD0, INPUT);

}
void switchToMonitor() {
  Serial.begin(9600);
  int digitalSensor = digitalRead(smokeD0);
  if (digitalRead(smokeD0) == HIGH)
  {
    digitalWrite(redLed, HIGH);
    digitalWrite(greenLed, LOW);
  }
  else {
    digitalWrite(redLed, LOW);
    digitalWrite(greenLed, HIGH);
  }
  //This will be updated later to use the analog input
  //Using digital to make debugging easier
  while (digitalSensor == HIGH) {
    int analogSensor = analogRead(smokeA0);
    Serial.print("Pin A0: ");
    Serial.println(analogSensor);
    Serial.print("Pin D0: ");
    Serial.println(digitalSensor);
    // Checks if it has reached the threshold value
    if (analogSensor > sensorThres) {
      digitalWrite(buzzer, HIGH);
      //tone(buzzer, 1000,200);
      Serial.println("here");
      delay(1000);
    }
    else {
//      digitalWrite(redLed, LOW);
//      digitalWrite(greenLed, HIGH);
      noTone(buzzer);
      Serial.println("also here?");
    }
    //delay(100);
    digitalSensor = digitalRead(smokeD0);
  }
  noTone(buzzer);
}

void loop() {
  //delay(100);
  //LowPower.standby();
  attachInterrupt(0, switchToMonitor, CHANGE);
  LowPower.powerDown(SLEEP_FOREVER, ADC_ON, BOD_ON);
  detachInterrupt(0);
}

You can't use delay() or timer based tone() function in interrupt handler. Set a flag in interrupt and run the code  in loop() conditionally based on the flag state. Do not forget to have the flag variable volatile.


Templated class: How to create instance and work with it? I have created a class like this:

#ifndef MyList_h
#define MyList_h

#include "Arduino.h"

template <typename T>
class MyList {
public:
  MyList(void);
  ~MyList(void);

  void addItem(T* item);

  //more stuff

};

#endif

And implementation is like this:

#include "Arduino.h"
#include "MyList.h"

template<typename T> MyList<T>::MyList(void) {
  // constructor implementation here
}

template<typename T> MyList<T>::~MyList(void) {
  // desctructor implementation here
}

template<typename T> void MyList<T>::addItem(T* item) {
  // function implementation here
}

// ...more stuff

In my .ino Sketch I'm doing this (found this solution in a C++ example):

#include "MyList.h"
MyList<word>* list = new MyList<word>(); // global scope
//... more stuff

But when compiling, Arduino IDE complains:

  Test.ino:5: undefined reference to `MyList::MyList()'

I googled a bit and found this alternative way for creating the instance:

ArrayList<word>* list;

Then there's no error, just compiles file. BUT as soon as I want to use this instance (=adding code) like this:

list->addItem(i);

compiler complains again:

  Test.ino:25: undefined reference to `MyList::addItem(unsigned int*)'

What's wrong? Why is this reference undefined?

I tried another way:

ArrayList<word> list; // again global scope

But then the compiler also tells me:

  Test.ino:5: undefined reference to MyList<unsigned
  int>::MyList()' /tmp/ccp8qmCz.ltrans0.ltrans.o: In function
  _GLOBAL__sub_D_list':
  /....../Test.ino:5:
  undefined reference to `MyList::~MyList()'

So, how can I create an instance of my class that uses a template?

Environment: Arduino IDE 1.8.3 (I know, I could update...) + Arduino Nano Board.

I think I found the solution:

According to: https://stackoverflow.com/questions/8752837/undefined-reference-to-template-class-constructor

--> Put all implementation in .h file. That's it. No more compler complains, code runs fine.

I think I have to dig deeper into c/c++ development ...


RFM95 LoRa module frequency options I live in India, and unfortunately here the unlicensed band ranges only from 865MHz to 867M Hz. The IBM LoRa code for Arduino (as node) for RFM95 module allow you to choose between 915 Mhz and 868 Mhz only. I initially created a gateway using a Pi3 listening at 865.7 (to conform with Indian rules), but it couldn't receive any payloads from my node running at 868 Mhz. Then, eventually, I tried again with my gateway listening at 868 Mhz, and it worked like a charm. No hiccups.

But, obviously, it seems to be against the rules, and I don't fancy prison. So I want to know if I can get the RFM95 module working somewhere in the range of 865 Mhz to 867 Mhz? And if yes, how can I do it? There certainly doesn't seem to be an option to choose a frequency other than 868 Mhz or 915 Mhz in the IBM Lora code. Here is the link to the code library. https://github.com/matthijskooijman/arduino-lmic

The RF networks of the RFM95 board are ideally configured for the general range of frequencies, but the difference between your 865.7 MHz and the 868 MHz tuning of a European (vs US) version of the board is likely smaller than the error with which the RF networks can be tuned to begin with, so that is unlikely to be a problem unless there is some hard lockout of your desired frequency in the SX1272 chip.  I've even heard claims that some people have managed to at least somehwat use US vs European tuned versions on the opposite bands, which is far more drastic than what you are trying to accomplish.

So assuming there is no hard lockout of your desired frequencies in the hardware, basically what you will need to do is to change the frequency list in the source of the software you are using to operate the module.

Basically you would edit src/lmic/lorabase.h and make a modified version of the EU configuration.  Ideally you'd add that as an additional option and select it, but for an initial test you could just edit the European version to fit your needs.

Do keep in mind the code will probably want to use multiple frequencies - if you have a gateway that receives only on a single frequency, you'll need to modify the code to always use that, after determining if doing so fits with usage-rate rules in your jurisdiction.

It's probably worth doing some online research to see if anyone has already put thoughts into operating LoRa in India - if so, there may already be a modified branch of the LMiC code you can use.


How to pass 'Serial' as an input argument in Arduino function? I have one integer value which I should pass through Serial1, Serial2, Serial3, and Serial4 after performing some algebraic operation on this integer. For this algebraic operation, I made a function and input arguments is an integer and Serial number.
Simple code is given below: (I deleted every extra part of my code to make easy to understand)

String stringG; int d1; int d;

#include<SoftwareSerial.h>
//Software Serial #1: Rx = digital pin 10, Tx = digital pin 11
SoftwareSerial Serial4(10, 11);

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

void loop() {
  // put your main code here, to run repeatedly:
  if (Serial.available() > 0)
  {
     String  XX = Serial.readString();
    int d1 = XX.toInt();
    Serial.println(d1);
    int yy;
    yy = compareFunction (d1, Serial4);
    Serial.println("Now the final values are:");
    Serial.println(d1);
    Serial.println(yy);
  }

}
int compareFunction (int d, String Serialx)
{

  int ZZ = Serialx.readString(); // I will receive some values from motor using serial4
  //to avoid long code I deleted unnecessary parts
  // I will use ZZ and d values and output will be yy
  return yy;
}

As you see in  compareFunction I receive value using Serial (it may be 1,2,3 or 4) So I have to pass Serial as an input argument in this function. If I can't pass Serial then I have to write 4 functions each for Serial1, 2, 3 and 4 which I want to avoid. Is it possible? How can I do it? when I tried with above code it shows error

  exit status 1 could not convert 'Serial4' from 'SoftwareSerial' to
  'String'

The Serial object is the end of a chain of classes, each with a different set of functionality.

Print -> Stream -> HardwareSerial => [Serial]

Since you are reading from it the best class to use is Stream since that is the one that is the one that contains the reading functionality.

You should pass it by reference or as a pointer since you don't want to copy the object.

int compareFunction (int d, Stream &Serialx)
{

  int ZZ = Serialx.readString(); // I will receive some values from motor using serial4
  //to avoid long code I deleted unnecessary parts
  // I will use ZZ and d values and output will be yy
  return yy;
}

By using Stream you can use any object type that also uses Stream in its class inheritance chain - even things like a WiFi socket connection.

This behaviour is called polymorphism and is one of the more powerful features of classes in C++ (and other OO languages).


Load Cell and HX711 only outputting 0's I am using an Arduino Uno and HX711 amplifier to collect data from a load cell. I previously had the load cell calibrated and functioning, but now the load cell will not read any values; only 0's are outputted, even when I apply a small load to the sensor. I have re-soldered and replaced the connecting wires. Are there any suggesting for getting a readout from my sensor?

I have been testing with 2 different load cells: Sparkfun's TAL220 Straight Bar 10kg load cell and an LFS 210-300 from Cooper Instruments (the latter is the one I want to use long term). My load cell is connected like the HX711 Breakout Guide (with an Arduino Uno instead of a RedBoard and a USB connection):

I have been using the HX711 Breakout Guide Calibration sketch to test my load cell:

#include <HX711.h>

#define DOUT 3
#define CLK 2

HX711 scale(DOUT, CLK);

float calibration_factor = 282650; //-7050 worked for my 440lb max scale setup

void setup() {
  Serial.begin(9600);
  Serial.println("HX711 calibration sketch");
  Serial.println("Remove all weight from scale");
  Serial.println("After readings begin, place known weight on scale");
  Serial.println("Press + or a to increase calibration factor");
  Serial.println("Press - or z to decrease calibration factor");

  scale.set_scale();
  scale.tare(); //Reset the scale to 0

  long zero_factor = scale.read_average(); //Get a baseline reading
  Serial.print("Zero factor: "); //This can be used to remove the need to tare the scale. Useful in permanent scale projects.
  Serial.println(zero_factor);
}

void loop() {

  scale.set_scale(calibration_factor); //Adjust to this calibration factor

  Serial.print("Reading: ");
  Serial.print(scale.get_units(), 1);
  Serial.print(" kgs"); //Change this to kg and re-adjust the calibration factor if you follow SI units like a sane person
  Serial.print(" calibration_factor: ");
  Serial.print(calibration_factor);
  Serial.println();

  if(Serial.available())
  {
    char temp = Serial.read();
    if(temp == '+' || temp == 'a')
      calibration_factor += 10;
    else if(temp == '-' || temp == 'z')
      calibration_factor -= 10;
  }
}

I am still new to Arduino and data acquisition in general, so any suggestions would be appreciated!

This line is where you are reading the data and printing it:

Serial.print(scale.get_units(), 1);

The 1 on the end of the line defines how many digits you are displaying from your reading. I have a similar setup to yours and I have it set to 5 which shows up to +/-0.00001kg. (Obviously, the accuracy will be different depending on which load cell you have)


How to run multiple DC motors in different patterns? I am a complete novice in programming and I hope someone could guide me here. I am doing a haptic research project, where 8 DC coin vibrating motors would be fitted on the fingers of subjects (excluding thumbs), and the subject has to respond the number of fingers they feel the vibrations on.
Every trial has to have a different pattern of outputs, say: in first trial, 4 motors are activated-motor 1, motor5, motor8 and motor 3. In a single trial, the motors have to have a common delay of 150 ms and 4 seconds break after next one starts.
My question is, that in 8 motors, there are 255 different activation patterns possible. How do I define all these 255 patterns and randomise their sequence?
I am using the mega board and connecting each motor to a PWM pin and all having a common ground.
Here is a sample code with 3 such combinations (only seven motors are connected here):
#define viboutpin 2
#define viboutpin1 3
#define viboutpin2 4
#define viboutpin3 5
#define viboutpin4 6
#define viboutpin5 7
#define viboutpin6 8

void setup() {
     pinMode(viboutpin,OUTPUT);// define a pin as output
     pinMode(viboutpin1,OUTPUT);
     pinMode(viboutpin2,OUTPUT);
     pinMode(viboutpin3,OUTPUT);
     pinMode(viboutpin4,OUTPUT);// define a pin as output
     pinMode(viboutpin5,OUTPUT);
     pinMode(viboutpin6,OUTPUT);
}

void loop() {
    digitalWrite(viboutpin,HIGH);
    digitalWrite(viboutpin1,HIGH);
    digitalWrite(viboutpin2,HIGH);
    digitalWrite(viboutpin3,HIGH);
    digitalWrite(viboutpin4,HIGH);
    digitalWrite(viboutpin5,HIGH);
    digitalWrite(viboutpin6,HIGH);
    delay(150);
    digitalWrite(viboutpin, LOW);
    digitalWrite(viboutpin1,LOW);
    digitalWrite(viboutpin2,LOW);
    digitalWrite(viboutpin3,LOW);
    digitalWrite(viboutpin4,LOW);
    digitalWrite(viboutpin5,LOW);
    digitalWrite(viboutpin6,LOW);
    delay(2000);

    digitalWrite(viboutpin2,HIGH);
    digitalWrite(viboutpin6,HIGH);
    delay(150);
    digitalWrite(viboutpin2,LOW);
    digitalWrite(viboutpin6,LOW);
    delay(2000);

    digitalWrite(viboutpin4,HIGH);
    delay(150);
    digitalWrite(viboutpin4,LOW);
    delay(2000);
}

Why not generate a psuedo random number from 0 to 255 and use it as a code for which motors are to be activated - bit 0 == viboutputpin0, etc.? Then one function can look at each bit in turn and activate that motor if the bit is set, delay, and stop the motors.
You'll probably want to test your code with a few pre-defined test patterns instead of the random ones, and once you're satisfied that it works, randomly seed the random number generator so your project will generate a different pattern each time. One way to do that is to ask via terminal for the operator to click the 'Send' button (or tap the space bar if you're using a separate terminal emulator that sends key by key). Measure the time from the request to the response in microseconds, discard the 2 or 3 least significant bits of the result and keep the next 8. The micros() function's resolution is 4 usec at 16 MHz, is the reason for discarding those 2 lower bits.


Reset Arduino by connecting vcc and gnd? A follow up question on my previous question, if a memory card reader can be used with three pins (digispark Attiny 85):

Can I read from a memory card with three pins?

Now I came up with another idea.
Since the USB connector or the VCC pin can power an Arduino my guess is that they are in parallel and the actual Arduino is connected to both.
Kind of like this very bad schematic made on my phone: (sorry for that)

Where the blue stuff is the Arduino chip.

If that is true then adding the push button between VCC and GND with a resistor between should remove the power of the Arduino?
In that case I can have my code in setup() and use the pus button to reset the Arduino, and still have four pins to the memory card reader.

Or is this wrong? What kind of resistor value do I need to make sure I don't short the USB connector but still have less resistance than the Arduino chip?

That is wrong. That is very, very wrong. That is one of the worst things you can do to a USB connection short of plugging it into the mains.

Do not even consider doing this.  Short circuits are never a good idea.


Confused between which arduino to use for project? I am planning to build a smarthome working model with arduino. I will also need to connet to wifi(not ethernet). So I was wondering which setup would be the best:-

Arduino Uno + ESP8266
Arduino Yun
Arduino Uno + Wifi Shield
Or any other setup/ board(eg-Raspberry Pi 3B, ESP32 etc).

I would be connecting at least few leds, servos, and some sensors, so it should be able to handle that.

My project will be based on this model

http://www.instructables.com/id/Arduino-controlled-Smart-Home/

It will also have a temperature sensor and a rain sensor.

If you want a project that is wireless adding Wifi to Arduino is pointless when the Wifi boards are more capable than the Arduinos, so I would discount the UNOs straight away.

As I understand the YUN is more of a Pi replacement so (if that's right) I would look at that for the 'master controller'.  The ESP32 Is probably not strong enough to act as the master controller, but it has other feature that might mitigate this including hardware support for encryption algorithms which might be useful for authentication the client devices.  Also they are cheep enough to consider a cluster of them (

Purely for their size I would go with ESP8266, you have an 80/160MHz processor with 512kb of RAM (from memory??), OK it only has 10 Digital and 1 Analog pins, but it you want more fork out another $1.50 on another board.  They are small enough to fit in light switches and cheep enough to hide behind a model door.

If you only want to do your model house then I recommend ESP8266 slaves and a Pi or cluster (pair?) of ESP32 for the master.  If you want to do a real house, I'd recommend the same.


Controlling the Serial Monitor for 10 seconds I am an amateur with Arduino and coding and I am learning in my lab class. My project consists of using a photoresistor to measure the brightness of a white LED. I have the following circuit built.

I am having problems with the code because I need the serial monitor to print every 1/10 of a second for 10 seconds. My professor started talking about the micros() function but never showed an example. I have an idea as to how I can utilize this function to control how long the Serial Monitor prints for but I have been unsuccessful. I know that setting a delay is good enough for reading every 1/10 of a second but how can I make the serial monitor print values for only 10 seconds?

I believe it should be a total of 100 readings.

This is my current code:

unsigned long start, finished, elapsed, total;
int analogInPin = A0;
int LEDreading;           // analog reading
int LEDpin = 9;           // LED on pin 9

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

void loop() {
  analogWrite(LEDpin,255);  // LED brightness
  start = millis();
  LEDreading = analogRead(analogInPin);
  Serial.println(LEDreading);
  delay(100);
  finished = millis();
  elapsed = finished - start;
  total = elapsed*100;

  if (total >= 10000){
    Serial.end();
}

Using micros() is very much like boiling an egg.

When you want your egg to be cooked just right you know that it needs to be in the boiling water for a certain amount of time. There's three ways you can achieve that:

Use an egg timer to alert you when the time has passed,
Sit and stare at the boiling pot counting the seconds as they slowly tick by (booooooring..... ...zzzZZZzzz...)
Remember what time you put the egg in the water and glance at the clock every so often to see how much time has passed.

Using millis() is like option 3. It tells you how many milliseconds have passed since the board was turned on (or since the last millis() rollover at roughly 49 days). So when you put the egg in the water you record the current time. Then you periodically compare the recorded time to the current time (a simple subtraction will suffice) to see if enough time has passed. When it has you remove the egg and chow down.

So to put that more in a coding context - when you start some operation, or want to measure a period of time from a point, you just save the time in a variable:

start = millis();

(start must be uint32_t, aka unsigned long). To find if enough time has passed you just subtract that saved time from the current time and it gives you the elapsed time, which you can compare to your required elapsed time:

if (millis() - start >= 100) {
}

1/10 of a second is 100ms, so if you hit a difference of 100ms (or more) then your time has arrived and you can do something.

If you want it to do it again after that then just set the "start" time to the current time again.

For instance, for your requirements:

void loop() {
    // Record the start time - the static means it
    // only happens once the first time loop() is run and
    // it remembers the value between iterations
    static uint32_t start = millis();

    // Somewhere to store the number of values we
    // have given - again, static so it remembers across
    // iterations of loop()
    static uint8_t count = 0;

    if (count < 100) { // No more than 100 counts
        if (millis() - start >= 100) { // Tick
            start = millis(); // Do it again in 100ms time

            // Add whatever you need for your readings here

            count++; // Add one to the count
        }
    }
}


Continuous Servo not setting speed correctly I have two continuous servos connected to my Uno, and I'm running this code on it:

leftServo.write(91);
rightServo.write(102);
delay(3000);

leftServo.write(112);
rightServo.write(81);
delay(3000);

leftServo.write(91);
rightServo.write(102);
delay(3000);

int i;
while(1) {
  i++;
}

When I run the code, the wheels stop for three seconds (91 and 102 are the zero values for these servos) then they spin for three seconds, then the left servo stops, but the right one only slows down about half way, it doesn't stop, even though the exact same number is used as before.

I can't figure out why this is?

Issue was fixed by adding a delay of 100ms between servo writes, smaller values may work, but I haven't tried yet


Change Arduino Uno clock from 16MHz external to 1MHz internal I've got a project where I need to program an ATmega328P on an Arduino Uno board, then transplant it into a custom PCB - however, this board does not have an oscillator installed, and so I need to run the microcontroller off its internal clock.

My goal here is to be able to code my software with the Arduino IDE, insert a factory-fresh ATmega328P straight from the tube into the socket on the Arduino Uno board, then move the device from the board to the PCB without any changes along the way. What's the best way to go about this?

That will not work. To change the clock source, you'd need to change the fuses. I don't know of any way to do this while the chip is inside the UNO.

Secondly, a factory fresh 328P won't work in an UNO board, because it doesn't have the correct fuses, and doesn't have the bootloader programmed.

I'd suggest placing the 328P chips in a breadboard; connect the ISP pin to the UNO, and use the Arduino-as-ISP to change the fuses, and upload your program.

PS why run at 1Mhz. The internal oscillator runs at 8Mhz. By default the divide-by-8 fuse is set, so it runs at 1Mhz out of the factory, but you can unset this fuse.

PPS use this website http://www.engbedded.com/fusecalc/ to generate the right fuse settings for your project.


Parsing array of an object in a library constructor I am trying to develop an Arduino library that consists out of two classes. I want 'WayPointStack' to store an array of 'WPCommand', but I can't get it to work.

WayPointStack.h

#ifndef WayPointStack_h
#define WayPointStack_h

#include "Arduino.h"
#include "WPCommand.h"

class WayPointStack
{
  public:
    WayPointStack();
    WayPointStack(WPCommand* wp);
    WPCommand GetNextWP();
    WPCommand GetWP(int i);
    void AddWP(int target, int time);
    int SetWPPointer(int i);
    int GetLength();
  private:
    WPCommand* _wp;
    int pointer;
    int length;
};
#endif

WPCommand.h

#ifndef WPCommand_h
#define WPCommand_h

#include "Arduino.h"

class WPCommand
{
  public:
    WPCommand(int target, int time );
    WPCommand();
    int GetTarget();
    int GetTime();
    int LEFT;
    int RIGHT;
    int FORWARD;
    int BACKWARD;
    int STOP;
    int END;
  private:
    int _target;
    int _time;
};

#endif

Parts of WaypointStack.cpp

#include "Arduino.h"
#include "WayPointStack.h"
#include "WPCommand.h"

#define arrSize 100

WayPointStack::WayPointStack()
{
  _wp = new WPCommand[arrSize]; // should be enough, heap blabla
  length = 0;
  pointer = 0;
}

WayPointStack::WayPointStack(WPCommand[] wp)
{
    _wp = new WPCommand[arrSize]; // should be enough, heap blabla
    for (int i = 0; i < sizeof(wp), i++){
        _wp[i] = wp[i];
    }
    length = sizeof(wp);
    pointer = 0;
}

I'm pretty sure I'm doing something wrong with the pointers, but I don't know how to fix it. The first two errors are

WayPointStack.cpp:24:42: error: expected ',' or '...' before 'wp'
WayPointStack::WayPointStack(WPCommand[] wp)

and

WayPointStack.cpp:27:29: error: 'wp' was not declared in this scope
for (int i = 0; i < sizeof(wp), i++){

I obviously have to use a pointer. This is all I know, so far.
Has someone an idea?

This is a C++, not Arduino question and should be asked on Stack Overflow.

In C/C++ the [] must be on variable name, not on type. WPCommand wp[] (it is the same as WPCommand* wp).

sizeof return size in bytes, not element count. send length as parameter

Dynamic memory allocation in MCU is not a good thing. You can have in WayPointStack

WPCommand _wp[arrSize]


Arduino digital output pin controling relay problem I try my code to change the state of a relay on pushing a push button buy checking the state of a digital pin.

My code :

const int led1 = 6;
const int enable1 = 7;
boolean led1_OnOff;
long now;
int minSecsBetweenUpdates = 1; // 1 seconds
long lastSend = -minSecsBetweenUpdates * 1000l;

void setup() {
  led1_OnOff = false;
  pinMode(enable1, INPUT);
  pinMode(led1, OUTPUT);
}

void loop() {
  now = millis();
  if (now > (lastSend + minSecsBetweenUpdates * 1000l))
  {
    if(digitalRead(enable1) == HIGH)
    {
      lastSend = now;
      if(led1_OnOff == true)
      {
        led1_OnOff = false;
        //+digitalWrite(led1, LOW);
      }
      else
      {
        led1_OnOff = true;
        //digitalWrite(led1, HIGH);
      }
    }
  }

  if(led1_OnOff == true)
    digitalWrite(led1, HIGH);
  else
    digitalWrite(led1, LOW);
}

But the code keeps on looping and the relay keep changing it's state as if pin 7 is always high, I'm sure of my schematic but I don't know what's wrong with my code.

for those who want my schematic:

Your problem is that you are basically saying "while the pin is HIGH toggle the relay" rather than "When, and only when, the pin transitions from LOW to HIGH do I toggle the relay".

To do that you must remember what state the pin was in during the last iteration:

const uint8_t led1 = 6;
const uint8_t enable1 = 7;

void setup() {
    pinMode(enable1, INPUT);
    pinMode(led1, OUTPUT);
}

void loop() {
    static bool led1_OnOff = false;
    static bool lastValue = digitalRead(enable1);

    bool currentValue = digitalRead(enable1);

    if (currentValue != lastValue) {
        lastValue = currentValue;
        if (currentValue == HIGH) {
            led1_OnOff = !led1_OnOff;
            digitalWrite(led1, led1_OnOff);
        }
    }
}


Can I implement a LFM method on an Arduino? Can I implement a LFM method for autocorrelation process using an Arduino?
For example if I have a signal input LFM as a real signal and other signal as an imaginer signal.

My question is can I correlate the real signal and imaginer signal using an Arduino?

Since you are talking about Arduino, I suppose you want to do it digitally.

The answer is: it depends.

It depends on:

Desired frequency of the carrier
Desired maximum frequency of the input signal
Desired accuracy (compared to the equivalent done with analog components)

But in general I'd say that it's unlikely it will have sufficient computational power. I'm assuming the question is for the 16MHz 8 bit UNO.
The Cortex M3 on the DUE might stand some chance, being a 32bit core @ 84MHz.

It might be possible to do some trick using a PWM signal and a digital output with a wired AND, but I'll leave to others to comment about its feasibility.


LCD display weird characters Im a newbie. I have a problem with displaying text in LCD (16x2). It shows incorrect message in the lcd. Here is the code and the picture that gives the wrong output : Kindly help Thank you.

#include "SIM900.h"
#include <SoftwareSerial.h>

#include "sms.h"
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

//gsm
SMSGSM sms;

int numdata;
boolean started  = false;
char smsbuffer[160]; //message
String newsms;
char n[20];
unsigned char i;
//lcd
int sensorPin = A0;    // select the input pin for the potentiometer
int sensorValue = 0;  // variable to store the value coming from the sensor
int outputValue = 0;   // value output to the %
int outputValue1 = 0;   // value output to cursor

void setup()
{
  //Serial connection.
  //gsm
    lcd.begin(16, 2);

  Serial.begin(9600);

//  lcd.setCursor(0, 1);
//  lcd.clear();
//  lcd.print("   Wireless Public       via GSM"); //55 chars
//  lcd.setCursor(0, 2);
//  lcd.print("    Notice Board "); //55 chars
   Serial.println("GSM Shield testing.");
  if (gsm.begin(2400)) {
    Serial.println("\nstatus=READY");
    started = true;
  }
  else Serial.println("\nstatus=IDLE");

  //lcd
  // set up the LCD's number of columns and rows:

};

void loop()
{

  // read the value from the sensor:
  sensorValue = analogRead(sensorPin);
  // map it to the range of the analog out:
  outputValue = map(sensorValue, 0, 1023, 0, 100);
  outputValue1 = map(sensorValue, 0, 1023, 0, 200);

  //scroll = lcd.scrollDisplayLeft();
  if (started) {
    //Read if there are messages on SIM card and print them.
    if (gsm.readSMS(smsbuffer, 160, n, 20))
    {
      //lcd
      lcd.clear();
      lcd.setCursor(0, 2);
      lcd.print("SMS Received!");
      delay(2000);
      lcd.clear();
      lcd.setCursor(0,1);
      Serial.println(n);
      Serial.println(smsbuffer);
      lcd.print(smsbuffer);
      delay(1000);
//      lcd.clear();
    }
    delay(1000);
  }
}

The first thing to try is replacing lcd.begin(16, 2) with lcd.begin(20, 4). The image of your LCD looks like a 20 char by 4 line display. Based on your comments, it seems that the SMS part of your code is working because it's outputting the correct characters to the serial monitor. I would focus on the LCD code and connections to your Arduino.


AnalogRead too slow... Faster alternative? For a program that I'm working on, I want to get an accurate reading from a noisy pressure sensor.  So, the idea that I have is to do a thousand AnalogRead commands on the same port very quickly and then average them.  The pressure readings become very precise, however, the program that I am running becomes very slow.  I need my program to be orders of magnitude faster.

I'm sure that there's a faster way to do AnalogRead commands, especially because I am requesting the same port over and over.  Maybe there's a way that I can take lower resolutions of readings and then average those?  I don't know.  Can anyone help me?  I am an amateur Arduino user looking to learn.

I have done a little bit of research on my own and had trouble finding concrete examples.

Ignacio's proposal is surely a good one if you really need higher sample rates, but I would try another approach:
Average your signal before sampling it! This can be done by connecting a simple RC lowpass to your AD input.
With that you get rid off those high frequency noise you don't need, but without wasting CPU time.


Error opening serial port 'COM1'. (Port busy) Im using the arduino Micro pro to read the data out of a temperature sensor (lm35). The program is compiling and NOT uploading, but when I try and open the serial monitor is says: Error opening serial port 'COM1'. (Port busy)

I've got an idea. Your board isn't being recognized. Try unplugging the arduino and see if Com 1 is still there. Sometimes it can recognize mice and other devices as Com 1 or 2 instead of your arduino.

On some of my development machines after everything settled out my devices will show up on Com 4 and 5 when I am working on two at a time.

If this is not the case go into the device manager and see if you can see the board listed.

I would also wonder if you have your sensor hooked to digital pins 0 and 1. These pins are used for your serial line on usb. So if you have anything such as a sensor hooked to them it may be generating data keeping the line busy instead of it being able to negotiate.

I had this happen when setting up hc-05 for the first time. I realized I had to keep the chip off while flashing or I would end up with errors or Com busy.

Please provide your pinout and basic information about the Com ports available on the ide. Also consider that you will need to specify the correct board as it will default to an uno.

Programmer not in sync issues generally occur because the board is recognized but cannot be written to for one reason or another.

the board has something plugged into digital 1 and 0 which are serial i/o pins
the board programmer is busy running your last batch of code
usb error

So

try a different cord
try unplugging potential wiring issues and see if it can be written to without anything on it
try holding down reset on the board until the board when you try to write to it until just after it finishes compiling to clear any potential programing issues

In my experience mega have a tendency to suffer from the last one.


Setting up Huzzah ESP8266 I am trying to set up a Huzzah ESP8266 and can not get it to work. I have scoured the internet for help and to no avail. I have the board loaded with a baud rate of 115200 and am transmitting at  80 MHz. When I try and upload the sketch it successfully uploads and after a second or two it sends me this error.

  Sketch uses 222,209 bytes (21%) of program storage space. Maximum is
  1,044,464 bytes. Global variables use 31,576 bytes (38%) of dynamic
  memory, leaving 50,344 bytes for local variables. Maximum is 81,920
  bytes.

  warning: espcomm_sync failed

  error: espcomm_open failed

  error: espcomm_upload_mem failed

  error: espcomm_upload_mem failed

Here is my code:

 void setup() {
pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
}

// the loop function runs over and over again forever
 void loop() {
digitalWrite(LED_BUILTIN, LOW);   // Turn the LED on (Note that LOW is the    voltage level
                                // but actually the LED is on; this is     because
                                // it is acive low on the ESP-01)
delay(1000);                      // Wait for a second
digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off by making the voltage HIGH
delay(2000);                      // Wait for two seconds (to demonstrate the active low LED)
}

Does anyone know what I'm doing wrong or can anyone help me out.

If you´re working with a development board, they (usually) come with tow buttons: Reset and Flash. If this is the case before start to upload your code you must press the Flash button, this error is common when the Flash button it's not pressed.

If you're working with an ESP8266-01 (this is the "naked" esp8266) you must read this tutorials: GreatScott vid on youtube, and for the connections: a good Hackster.io tutorial.

Hope you can make it run!!!


What's the time out of Wire.begin()? Here's a schematic of my project:

The purpose is to make laptop work as keyboard for desktop PC. Nano uses Serial.read() to get keystrokes from laptop and forwards key press and release data to Leonardo (using I2C) acting as USB-HID keyboard.
Nano's setup looks like:
void setup() {
  Wire.begin();
  Serial.begin(14400);
  Serial.write("Hello");  // https://serialport.io/docs/api-stream#serialpor|
  pinMode(LED_BUILTIN, OUTPUT);
}

Leonardo's setup looks like:
void setup() {
  Keyboard.begin();
  Wire.begin(4);
  Wire.onReceive(cbfunc);
}

I have tested both boards individually, but not the whole setup. Whenever either board connects to USB port it powers up due to +5 volt from USB. Now that I have i2c wires in place, I am confused -
if I connect leonardo & desktop first [and i2c-master (Nano) isn't powered on yet], what will happen at Wire.begin(4)? Will it wait (1s, 5s, forever) until i2c-master comes online?

Generally you should not provide power to any pin of a device, which is powered off. That can cause current flowing through clamping diodes to ground and might destroy the pins hardware or the device (also it can lead to weird situations, where the device is somewhat powered through the IO pin, which might lead to instability).
You can either cut the connection between the devices, if only one of them is powered (this should be possible with some extra components), or you can power both devices from one USB port. For the other port you would cut the V+ (positive supply voltage) line of the USB port/cable (this makes sure, that you don't get a bad current between both computers on the USB power line, if they provide a bit different voltage). Since the ground wire still connects both computers and the Arduinos, the communication will still work correctly.

if I connect leonardo & desktop first [and i2c-master (Nano) isn't powered on yet], what will happen at Wire.begin(4)?

The Wire.begin() line won't get stuck, since it doesn't do much on the lines and it doesn't know, if something is connected on the other end, until some transaction happens on the bus. But it might be, that any transaction from the powered Arduino (the master) might cause a blocked I2C bus (since at some places the library waits for the lines to get high. The connection through the clamping diodes might hold the line at low. I'm not sure about that). Then you would need to reset both Arduinos, to make sure, that the bus is in a healthy state.
The solution from above (powering both Arduinos from one USB port) will also make sure, that both Arduinos start at the same time and thus won't block the bus through the clamping diodes.


Unusual behaviour when moving data to PROGMEM I've got some working code with a definition that looks like this:

const unsigned char DynTextPositions[10][4][4] = {
    ...
};

Which is defined / referenced via a header:

#include <avr/pgmspace.h>
#ifndef DYNTEXTPOS_H
#define DYNTEXTPOS_H

extern const unsigned char DynTextPositions[10][4][4];

#endif

This data is being fed into a rendering function which draws lines based on the given positions. The data is read as follows:

float deltas[4][4];
// ...
deltas[n][k] = float(DynTextPositions[c+1][n][k] - DynTextPositions[c][n][k]) / 32.0;

As-is, this works just fine, as long as I've got my other scenes commented out. When I uncomment them, the combined data size seems to overflow the data segment. This is expected, because there's a fair bit of data, so I'm trying to move the DynTextPositions data into PROGMEM.

I've got PROGMEM working with some bitmaps, but it doesn't seem to work here. An example definition for a working bitmap is as follows:

PROGMEM const unsigned char ArduinoLogo[] = { ... };

However, as soon as I apply the PROGMEM attribute to DynTextPositions the rendering code seems to freak out - the positions appear to be all off-screen and completely wrong.

The only thing I can think of is that, for some reason, the data is either being considered signed rather than unsigned, or is getting corrupted along the way. Either that or the nested array is somehow being treated as a set of pointers.

Any idea why this might be?

Including <avr/pgmspace.h> and using the PROGMEM qualifier macro are only two of the steps required in order to get this to work. Since the data will no longer be available via the data bus you will need to use the various pgm_read_*() macros or *_P*() functions defined in avr/pgmspace.h. These work by using the appropriate assembly code instructions to access data stored in program space, i.e. flash, on the MCU.

Under GCC 4.7 or higher when writing C code, the __flash named address space is available. Variables declared within this namespace do not require any additional steps to access them. Note that the Arduino IDE compiles as C++, and hence does not make this (or any of the others) available.


Can analog pins be defined as either their analog name (A0) or their digital pin number? Can analog pins be defined by their digital pin number, and be used for analog purposes?
For example, instead of defining A0 for a pinout with the Uno, it could be 14?
Where is this documented? Is there a PDF type manual related to this, but not so low level to get into the ATmega chip?

https://www.arduino.cc/en/Hacking/PinMapping2560

For example, instead of defining A0 for a pinout with the Uno, it could be 14?

Yes. In fact A0 is just a placeholder for the number 14.
For all these things you should look in the pins_arduino.h file (Arduino\variants\wifio) for any variant you are interested in. That's where most of these symbols are defined. For example:
#define PIN_A0   (14)
#define PIN_A1   (15)
#define PIN_A2   (16)
#define PIN_A3   (17)
#define PIN_A4   (18)
#define PIN_A5   (19)
#define PIN_A6   (20)
#define PIN_A7   (21)

static const uint8_t A0 = PIN_A0;
static const uint8_t A1 = PIN_A1;
static const uint8_t A2 = PIN_A2;
static const uint8_t A3 = PIN_A3;
static const uint8_t A4 = PIN_A4;
static const uint8_t A5 = PIN_A5;
static const uint8_t A6 = PIN_A6;
static const uint8_t A7 = PIN_A7;

Incidentally, on the Uno you can also just use 0 for A0 with analogRead().


Problems connecting reliably using HC-05 (as bluetooth master) I currently try to connect an Arduino Micro/Leonardo/32u4 to an ELM327 Bluetooth dongle using a HC-05 Bluetooth shield from iTeadStudio. I also have similar problems trying to connect to a bluetooth dongle (with added serial connection) on my PC.

The basic AT-command communication works, but I haven't found out yet why AT+PAIR or AT+LINK are failing and what should be done to avoid this (I've done dozens of Serial Monitor command iterations). Until now I haven't found a command sequence that reliably connects. What I've tried so far (from different documentation and example codes):

Check general AT command set:

AT
> OK

Reset to default values:

AT+ORGL
> OK

Set master mode and check it:

AT+ROLE=1
> OK
AT+ROLE?
> +ROLE:1
> OK

Connect only to the specified bluetooth address:

AT+CMODE=0
> OK

Reset and initialize:

AT+RESET
> OK
AT+INIT
> OK

Configure inquiring mode:

AT+INQM=1,9,48
> OK

Inquire:

AT+INQ
> +INQ:12:34:567890:1F1F,7FFF
> OK
AT+STATE?
> +STATE:INQUIRING

Try to stop inquiring:

AT+INQC
> OK
AT+STATE?
> +STATE:INQUIRING
> OK

Reset and initialize again (otherwise we can't leave the inquiring state):

AT+RESET
> OK
AT+INIT
> OK
AT+STATE?
> +STATE:INITIALIZED
> OK

Try to pair with the found device (my PC asks for the 1234-password and creates a serial port):

AT+PAIR=12,34,567890,20
> OK
AT+STATE?
> +STATE:PAIRED

Try to connect

AT+BIND=12,34,567890
> OK
AT+LINK=12,34,567890
> FAIL
...

Does someone have some hints for finding the right sequence?

I am using a "BIND" between the PAIR and LINK:

AT+PAIR=98D3,31,FC2D54,5
AT+BIND=98D3,31,FC2D54
AT+LINK=98D3,31,FC2D54

That seems to work for me.

See the docs here:

ftp://imall.iteadstudio.com/Modules/IM120723009/DS_IM120723009.pdf


Grounding Arduino UNO with external voltage source I was experimenting with external power supplies and noticed that the only way the Arduino can communicate with an externally powered sensor (through SPI) is when the GND pin under power AND the GND pin under AREF on the UNO is connected to the external ground?
From what I understand, both these pins are connected to the boards mutual ground (i.e. they are already internally connected)?
In the attached image both the orange and yellow wires were required and would not work individually.
I feel that either this shouldn't be the case or I am simply missing something and would appreciate an explanation.
Thanks!

The circuit in the image shows the plan of the Arduino Uno, as you can see the GND pin under AREF and in the GND under the Power pin VCC are connected.
you can double-check this with a tester and figure it out.
so yes, they are internally connected.
now, in your breadboard you have connected GND to VIN, that's the problem, Vin is an input voltage that is regulated to supply 3.3V and 5V.

So remember to share grounds with external voltage supplies (DC-DC), that set the circuit to the same reference.


Using signal strength feature of nRF24L01 module This is a walkie-talkie project and this circuit really worked, voice can be transmitted from one nRF module to another nRF. Additionally, I want to observe how well the signal strength is, by lighting up an LED.

They talked about a test.RPD function here in order to do that. But it is said that we can't use this with nRF24L01, but can use only with nRF24L01P (I don't know what is the difference).

  Test whether a signal (carrier or otherwise) greater than
  or equal to -64dBm is present on the channel. Valid only
  on nRF24L01P (+) hardware. On nRF24L01, use testCarrier().
  Useful to check for interference on the current channel and
  channel hopping strategies.
  @return true if signal => -64dBm, false if not
  */

Can't we use it in nRF24L01 really?

If I cannot use this how can I use the testCarrier function to light up an LED (as Bright, Low and Off) as mentioned in the quote?

If I can use this, what changes in the code should be done? (The member TmrhProjects talked about it a little)

He also hints to this code.

bool rpd = radio.testRPD();

while (radio.available()) {
  signalStrength = rpd + 1;
  radio.read, etc...
}

Should we write the above code in the RF24.h file or should we write it directly into the Arduino's main sketch?

To get the signal strength just send 100 packets with no retries and see how many times the packet arrives.
radio.begin();
radio.setRetries(0,0); // by default nrf tries 15 times. Change to no retries to measure strength

char buffer[32];
int counter = 0;

for(int i=0; i<100; i++)
{
   int status = radio.send(buffer,32); // send 32 bytes of data. It does not matter what it is
   if(status)
       counter++;

   delay(1); // try again in 1 millisecond
}

// if counter > 80 signal strength is great
{

}

// else if counter > 60 signal strength is good
{

}

// etc

radio.setRetries(5,15); change back to its default when done.

For this code to work the receiver must be listening for data. Just listen for data on the receiver there is no need to validate the data.


How to set alarm on DS3231 sensor? I want to know if it is possible to set an alarm in DS3231.
I want to set the alarm every 6 AM in the morning. Is this possible?

Yes it is (see datasheet datasheet) ... the DS3231 has 2 alarms.

There is also a library for the Arduino, see: library.
The alarm(s) can be set (repeatedly) via one of the following functions:

Alarm.alarmRepeat(hours, minutes, seconds, function);
Create an alarm that will call a function every day at a particular time.

Alarm.alarmRepeat(dayofweek, hours, minutes, seconds, function);
Create an alarm that will call a function every week on a specific day at
a particular time.

 "dayofweek" can be dowSunday, dowMonday, dowTuesday, dowWednesday,
 dowThursday, dowFriday, or dowSaturday.

Detailed info and more functions: link


Get 5V output from NodeMCU I have a sensor that requires used of 5V as input to Vcc. But I dont see any 5V output pins on the NodeMCU 1.0(12E). Is there a way I could get 5V output pins?

Its not a duplicate question. I want a 5V output and not provide 5V input to NODEMCU.

The VIN pin outputs 5V approximately (dependent on USB input voltage) from the NodeMCU board.