text:
Arduino Christmas light project with dimmer
I have an existing project using an Arduino Yun that controls Christmas lights with relays to turn them on/off. There are currently 13 separate rows of lights on the (60 foot) tree, each plugged into a wall wart that's controlled by its own relay.
I'm considering adding the ability to dim the lights, so I wanted to figure out the best way to do it. The lights can all be dimmed "in unison" - there's no need for 13 seperately controlled dimmers. But I have to be mindful not to cause any "buzzing" in the audio equipment on stage where the tree is.
I've read about PWN, zero cross, and other terms and saw the zero cross tail from powerswitchtail.com that seem useful in the typical project. I'd like to be able to pull this off with no more than 2 "dimmers" for the whole project, if possible.
Where do I start, and how do I do it?

What voltage lights? What kind of lights? Where are the relays - mains or low voltage side?

Traditional 120v white Christmas lights. The relays are currently powertail switch relays, but as I add more modules in the future (for additional colors) I plan to use sainsmart 8  channel SSR relays (so, low voltage side in both setups).

Do you have the budget to get some DMX dimmers? You could use the Arduino as your DMX controller. For example, something like this 4 channel dimmer.

@dlu I'm powering all my lights from 2 power strips. so if I do as you suggest, with an arduino fix shield, could I plug my 2 power strips (for my 60 foot Christmas tree) into 2 (or 4, at most) outlets on a DMX dimmer? Or does each row need to be on its own outlet on the DMX dimmer?

Basically the DMX dimmer gives you an outlet with a remote control that you can talk to programmatically. I suppose the big question is how much power you need to control. I think the DMX dimmer that I linked to is capable of handling about 5 A (~600 W) per channel (or maybe per outlet, there are two outlets per channel on that one. So depending on how much power you need you could divide up the load amongst the channels. Another approach would be to get one or more X10 dimmers. Looks like they run about $20 US for a 500 W dimmer.

"Traditional 120v white Christmas lights."  does not fully describe the problem.  Presumably you mean a series (and possibly secondarily parallel) string of incandescent bulbs which are presumably dimmable, but your mention of "wallwart" instead implies something else like low-voltage LED which is not AC dimmable but rather requires a PWM source.

@ChrisStratton my apologies for probably not being expert enough to give more specific detail. I don't have on-demand access to the actual lights or tree once it's put away. I assume the lights to be regular Walmart Christmas  lights. My use of the word "wallwart" can be ignored for now given the current use of powertail switch relays. What would be the deciding factor that differentiates DMX dimmers from a PWM implementation, and could that implementation run the risk of interfering with audio equipment in close proximity?

The primary concern shouldn't be audio interference, but utter failure and/or fire.  This is a task which you simply cannot undertake without determining the exact nature of the lights to be controlled.  If they won't unpack samples for you, run away from the project as quickly as you can.

@ChrisStratton again, what determines which implementation I should pursue? How can I tell what I'm dealing with, and what characteristics would determine whether I should go with DMX or PWM?

You need to determine if they are incandescent running directly off the mains supply or if they are LED with some sort of power supply or control module.  With the latter, you must assume that they cannot be dimmed unless you entirely understand and/or replace that power supply.

I can think of a couple of ways to approach this:

Use a DMX dimmer, something like this 4-channel dimmer, or
Use an household X10 dimmer.

DMX is used for stage lighting and there is some information on controlling DMX devices with an Arduino in the Playground where there is also some information on the hardware interface and shields, it looks pretty simple. DMX is a differential RS485 interface.
X10 is used for home automation, the signaling is done over the AC line. There is some information on using X10 and an Arduino library in the Tutorials.
Both seem like viable approaches, if you're working in a theater it is likely that they might already have DMX equipment and it would be as simple as hooking up to the gear in the house. Then you'd only need to add a shield or build the interface hardware.

For the DMX dimmer, since it's meant for stage/DJ use, does that also mean there won't be a hum in the sound system from nearby microphones, speakers, etc? And is there more compact DMX dimmers out there that might fit more nicely into a project box (smaller than, maybe, 6 inches on its biggest side)?

I think that will depend on the dimmer, but yes, I'd expect them to be designed to take interference with other equipment into account. As to size, I don't know off hand. Since they are often close to the load they typically include the outlets and that makes them pretty big – the one I linked to has 8 outlets. But, there are probably DMX chips out there and the triacs they control aren't all that big you might be able to build something pretty small. But in a theatre the equipment might already be there, it might be as simple as hooking up to it with the tree & the Arduino.


text:
Can I set an Arduino pin as input and output?
When I used to program PICs, there was a way to set the pins to input and output, at the same time. Can this be done on the Arduino?
I see the pinmode documentation, but nothing about being an IO port.

Ok, please explain this better. I think you just forgot the "set the pins to Input AND OUTPUT, at the same time". If so, please explain what you mean by "input and output". You want to set the value and then read the same value?

Or do you want to set a group of pins at the same time using a mask? If so, check here: https://www.arduino.cc/en/Reference/PortManipulation

Are you asking if you can do something like creating a memory interface or the control register of a hardware device where you would both read and write data?

No there is no function that lets you set all the pins to either input or output at the same time, but it wouldn't take much to write one.
No, you can't set an Arduino's pin as bidirectional.  If you are running out of pins look at IO expanders or multiple Arduinos.
Hope that helps, if not please feel free to clarify what it is you would like to know and we'll try and help.

I’m not running out of pins, I’m using a piezo electric wafer as a sensor, but after it senses an impact, I'd like it to then mimic the impact (in sound). Sure, I can use 2 peizo electric wafers to do that, but if there were a way to only use, one, I would be very interested. maybe I can toggle the pin mode. I'll look into that.

Surely you want the pin to be an input, and once you get an impact turn it into an output.

@j0h like Nick says you can alter the mode of a pin at runtime (i.e. in the loop function). Would that be enough to achieve what you want?  Of course it will meant there is a period where you won't be able to receive new signals.
Could you use two pins and run the input through a transistor that is normally closed unless the output pin is sending out a signal (to prevent a feed back loop)?

yeah, I looked at how a 3 pin ultra sonic sensor works, using the ping function from USsensor.ino, and realized that the pinmode is being changed. Its a fix. Thanks guys!

source: Stack Exchange

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

sort: votes


text:
Recovering from lost USB connection (Leonardo to Raspberry Pi)
I have several Arduino Leonardos connected to a Raspberry Pi (running Ubuntu) via USB. They appear as /dev/ttyACM0, /dev/ttyACM1, etc.
Occasionally, one will disappear and even pressing the Arduino's reset button won't bring it back. Is there any way to "refresh" or "reinitialize" the ttyACM* devices to make them reappear without having to reboot the Raspberry Pi?

System logs say...?

The USB devices are created dynamically. You might find this question and answer from the SE Raspberry Pi helpful: How to force rescan of USB serial devices?.
You can use the dmesg(8) command on the Pi to see the messages generated by the USB sub-system. Watch the output to see if there are errors associated with the Arduino dropping off the bus. This is what the output will look like (roughly, this is from an Uno connected to a Raspbian system), note the last line which is a disconnect from unplugging the Uno from the Pi. Resetting the Uno did not do anything that the Pi saw. I would guess that that is because the reset button on the Uno doesn't reset the 16U2 (the processor handling the USB port).
[  459.936719] usb 1-1.3: new full-speed USB device number 5 using dwc_otg
[  460.051182] usb 1-1.3: New USB device found, idVendor=2a03, idProduct=0043
[  460.051212] usb 1-1.3: New USB device strings: Mfr=1, Product=2, SerialNumber=220
[  460.051229] usb 1-1.3: Product: Arduino Uno
[  460.051245] usb 1-1.3: Manufacturer: Arduino Srl
[  460.051262] usb 1-1.3: SerialNumber: 75431343334351F061E2
[  460.088018] cdc_acm 1-1.3:1.0: ttyACM0: USB ACM device
[  460.089250] usbcore: registered new interface driver cdc_acm
[  460.089270] cdc_acm: USB Abstract Control Model driver for USB modems and ISDN adapters
[  534.212365] usb 1-1.3: USB disconnect, device number 5

From reading that question and its answers it appears that some versions of the Leonardo may have problems that can cause this behavior.
Another thing that might be worth looking into is the power supply for the Leonardos. If they are being powered by the Pi through the USB interface that might be pushing the capability of the Pi to provide power.

Every device is also found on a symlink, named by its hardware wireing. So this names stay the same after re-appering!
root@raspberrypi:/etc/udev/rules.d# ls -l /dev/serial/by-path/
total 0
lrwxrwxrwx 1 root root 13 May  2 18:11 platform-20980000.usb-usb-0:1.2:1.0 -> ../../ttyACM0
lrwxrwxrwx 1 root root 13 May  2 18:11 platform-20980000.usb-usb-0:1.3.1:1.0-port0 -> ../../ttyUSB0
lrwxrwxrwx 1 root root 13 May  2 18:11 platform-20980000.usb-usb-0:1.3.1:1.0-port1 -> ../../ttyUSB1

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

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


text:
Web Server Options
I want to give my project a simple web GUI to change config options. I know I could get a shield and write some horrible HTML in C but I'm wondering if there is a better way. Is there another IC I could get to help with this? What's the recommended solution for an embedded web server?

The Arduino in combination with a wifi/ethernet module will not give you a lot of options to work with. There are currently no libraries that will give you features like including stylesheets, AJAX or websockets. If your project allows it, due to the number of I/O pins you need etc: replace your Arduino with a ESP8266
If you want to produce something fancy: go with the ESP8266. Getting everything setup and working will be a bit harder than with the Arduino, but it will be worth the effort. You can program it in Lua, but that will only give you access to some basic functions. Just write your program in C like you did on the Arduino. There is a thing called Sming framework which allows you to import Arduino libraries with only changing in few lines of code. The Sming framework also includes a HTTPserver with AJAX, websocket, POST/GET, pre-processing, and style/js-file inclusion features.
The web framework is easier than it is in most webframeworks for the pc! The hard part is installing the toolchain and uploading your first bit of code, but once you've got that done it will be easy to figure out the rest. The Sming framework also contains examples for everything you think of.
If you are planning on buying an ESP8266 I recommend you get a few. The basic ESP-01 cost around $2,40 on ebay, but get a fancier one too with a few extra IO pins. I have also got a development version which can be programmed with a USB cable. It is really usefull for developing your program since you don't have to connect a USB-serial device every time just plug a USB cable. When I think my program is done, I upload it to a more basic and replaceable version of the ESP8266 and fix it in my project.
So a summary: It will be harder to figure everything out, but once you've got everything done it will be worth the effort! Here are a few links:
This will show you the power of a ESP8266:
ESP8266 oscilloscope with websockets video
The Sming framework:
Sming framework github repo

I'm currently using the ESP8266 modules. They are available for little money on eBay and the like and they provide a pretty nice Wifi-Module. You can even (and I would recommend that) be programmed by the Arduino IDE using some clever core that a few people built here: https://github.com/esp8266/Arduino
Using that you got a Wifi-Server built into the delivered Libraries that can provide basic functions. It can also output files from an SD card if available, there is an example for that.
Aside from that the module has a lot of Flash and you might not even need the Arduino if you don't need a lot of I/O, if you need a lot of I/O then you might want to communicate across a serial link. You will need to make sure to lower the voltage for the ESP, either use a 3.3V Arduino or build a level converter between the Arduino and the ESP, like this: http://www.hobbytronics.co.uk/mosfet-voltage-level-converter
It's not as easy as using a Wifi-Shield but it's very cheap to use.

GENERAL IDEA:
I would recommend getting a simple Wi-Fi and/or Ethernet module.
Then simply set up routes to receive and send data to Arduino (assuming arduino_ip to be your Arduino's IP), and GET and POST being HTTP verbs:
Receive data from Arduino:
GET  http://arduino_ip/data
Send data to Arduino:
POST http://arduino_ip/data
Now use any Web development Framework/Language (PHP, Node.js, Python) to receive and send data.
NO ADDITIONAL MODULES SOLUTION:
The above method will allow the arduino and server to communicate if they're on the same network. However, if you can constrain the server to be connected by USB to Arduino, you can use Node.js, Python (even PHP) to directly communicate to Arduino.
ANOTHER SOLUTION:
Add a Raspberry Pi, have it connected to Arduino by USB (Arduino's Serial), and the use Raspberry's Ethernet to bring in networking (Raspberry Pi can host a server itself)

You can buy an ethernet shield of any kind, ENC28J60, wifi module etc etc, and NOT do the html on the chip, just set it up as a server (usually specific the the shield/module you use).
Then you can actually create a local html file on your computer, or even use any webserver on your network or even online. As long as you send the commands to the local address of your arduino.
So if your Arduino ethernet module has the IP-address: 192.168.1.123 then the following form will send a command to the arduino that you can handle in the arduino code:
<form action="http://192.168.1.123/acommand=1">
<input type="submit" value="click to send command">
</form>

So if you create a simple web form to send a command to the arduino you can put this page anywhere, as long as the action is pointing at your arduino IP-address. If you want to go into the whole jquery standard it might be a bit different, unsure how asyncronious submits are handled.
I want to point out that IF you put your simple html page online you dont need to and SHOULDNT open anything in your firewall or router. The code will work as long as the device you are accessing the page from is on the same network as your arduino.

I personally find that one of the simplest solutions to a web server is one of the two following options.

Buy a serial cable, and transmit data using the Serial port on your Arduino. You can transmit data to a PC, and use PHP to read the serial port and display the data you would like.
Buy a Raspberry Pi. You will be doing the same as step 1, however you don't need a serial cable to use serial between Pi and Arduino. However you might need a 3.3V / 5V converter, which depends if the arduino serial port outputs data at 3.3V or 5V.


text:
Not sure if logic analyzer shows an error or perhaps just a 'relay bounce'
I have an Arduino controlling a relay. I was taking a look at the timings using a logic analyzer and at the onset of the relay switching, it quickly switches again.
This seems to be occurring randomly and I thought it could be highlighting a problem with my code but I wondered if it might just be a 'relay bounce' due to the speed of the switch. I've attached an image below. Any feedback is greatly appreciated. Thanks.

It's probably just bounce.

Increase the sample rate and you may get a clearer idea.

you would probably get a better answer in http://electronics.stackexchange.com/ although usually as soon as they see the word "arduino" they usually bump things over here lol. Do you have the relay connected directly to the arduino pin or are you switching through a transistor and if so, on which side are you measuring it. That will give you a much better idea. For all intents and purposes, it does just look like bounce.

Thanks for the replies guys. Madivad: it is connected directly, however it's one of the module boards (https://tinyurl.com/ph5pozj) so there may be a transistor it's going through there. I just thought of using a solid state relay so that may shed some more light on whats going on. Thanks again for your help

If you can, attach the LA to both sides of the relay so that you can watch the signal controlling the relay as well as the relay output. That should make it much easier to tell what is happening.

According to your plot, the pulse length is 50 microseconds. Typical mechanical relay switching time is 10 milliseconds, which is 200 times longer. It's next to impossible that the pulse is due to your software powering the relay back on for a moment, since the relay simply could not react to such a short input pulse.
So yeah, it's just a bounce. You can safely ignore it in most cases, unless you're counting events or doing something similar. In the latter case, there are both hardware and software debouncing techniques, which share the basic idea of a low-pass filter.


text:
Looking for help with WiFi modules
I'm completely new to using modules for the Arduino, so I'm sure some people have more knowledge about this topic than me.
Here's the thing, I want to stream audio over my home wifi, so I'm in need of some rather high-speed modules, I'm aiming for 1-1.5 mbps for some proper compressed audio, including the overhead.
I've looked online for some well known wifi modules, but the only one I've managed to find that is popular is the esp8266, and that thing is definitely not for streaming anything.
Before anyone asks, yes, it is critical for it to work over wifi.
Has anyone done something like this? What gets the best results?

I think the uno will already be a bottleneck here.

The audio issue aside look at the Adafruit Huzzah ESP8266 breakout. It is a really great board, and you can run your Arduino code directly on it, removing the need to fight AT commands and all that.  It is also really cheep, compared to an Arduino and a WiFi shield.  For audio though, i would look at a microcomputer (Raspberry Pi maybe?) instead of a micro controller.

I cant comment so I'm going to post as an answer.  Arduino is most likely not capable of running any sort of audio unless you have an mp3 shield to support it.  As far as the wifi module, I suggest using Ethernet shield as that will run a lot better compared to wifi module.


text:
No new random number generated
I made a teddybaer with buttons, LEDs, and voice output for my son. There are some buttons with pictures of our family with LEDs behind. The adruino is connected to a DfPlayer mini.
After pressing a button (picture) the LED behind gets illuminated and a random track corresponding to the picture will be played.
That´s all no problem and worked good...
But it was a bit boring, being not able to switch a track before it was terminated. So, I outcommented this:
void MP3Player::playTrackNumber(int trackNumber, int volume, boolean waitPlayTerminated)
    {
        player.volume(volume);
        player.play(trackNumber);
        if (waitPlayTerminated)
        {

        //    waitPlayIsTerminated();
        }
    }

Now, it was possible to press another button and a random track corresponding to that button was played.
If I press the same button again, the same track plays every time.
#include "mp3tf16p.h"

long randNumber;
long randNumber2;
long randNumber3;
long randNumber4;
long randNumber5;

MP3Player mp3(2, 3 );

//marina
const int button1 = 4;
//micha
const int button2 = 6;
//mama
const int button3 = 8;
//galina
const int button4 = 10;
//alex
const int button5 = 12;
//marina
const int led1 = 5;
//MICHA
const int led2 = 7;
//mama
const int led3 = 9;
//galina
const int led4 = 11;
//alex
const int led5 = 13;
void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
pinMode(LED_BUILTIN , OUTPUT);

mp3.initialize();

 randomSeed(analogRead(A0) * analogRead(A1));

pinMode (button1,INPUT);
pinMode (button2,INPUT);
pinMode (button3,INPUT);
pinMode (button4,INPUT);
pinMode (button5,INPUT);

pinMode (led1, OUTPUT);
pinMode (led2, OUTPUT);
pinMode (led3, OUTPUT);
pinMode (led4, OUTPUT);
pinMode (led5, OUTPUT);

}

void loop() {
  // put your main code here, to run repeatedly:
int reads = digitalRead(button1);
int reads2 = digitalRead(button2);
int reads3 = digitalRead(button3);
int reads4 = digitalRead(button4);
int reads5 = digitalRead(button5);

 randomSeed(analogRead(A0) * analogRead(A1));

// mp3.playTrackNumber(15, 30);
//marina
if (reads==1)
{

   randomSeed(analogRead(A0) * analogRead(A1));
  randNumber = random(1, 7);

  digitalWrite(led2, LOW);
  digitalWrite(led3, LOW);
  digitalWrite(led4, LOW);
  digitalWrite(led5, LOW);
  digitalWrite(led1, HIGH);

 //  mp3.playTrackNumber(30, 30);

  if (randNumber==1)
  {
  mp3.playTrackNumber(12, 30);
  }

    if (randNumber==2)
  {
  mp3.playTrackNumber(13, 30);
  }
  if (randNumber==3)
  {
  mp3.playTrackNumber(14, 30);
  }

  if (randNumber==4)
  {
  mp3.playTrackNumber(16, 30);
  }
if (randNumber==5)
  {
  mp3.playTrackNumber(17, 30);
  }

if (randNumber==6)
  {
  mp3.playTrackNumber(18, 30);
  }
  digitalWrite(led1, LOW);
}
else {

}

//micha
if (reads2==1)
{

   randomSeed(analogRead(A0) * analogRead(A1));
  randNumber2 = random(1, 7);
   randomSeed(analogRead(A0) * analogRead(A1));

  digitalWrite(led1, LOW);
  digitalWrite(led3, LOW);
  digitalWrite(led4, LOW);
  digitalWrite(led5, LOW);
  digitalWrite(led2, HIGH);

  if (randNumber2==1)
  {
  mp3.playTrackNumber(2, 30);
  }

    if (randNumber2==2)
  {
  mp3.playTrackNumber(3, 30);
  }
  if (randNumber2==3)
  {
  mp3.playTrackNumber(4, 30);
  }

 if (randNumber2==4)
  {
  mp3.playTrackNumber(10, 30);
  }

   if (randNumber2==5)
  {
  mp3.playTrackNumber(11, 30);
  }

   if (randNumber2==6)
  {
  mp3.playTrackNumber(6, 30);
  }

  digitalWrite(led2, LOW);
}
else {

}
//Alexander
if (reads5==1)
{
 // mp3.playTrackNumber(6, 30);
  randomSeed(analogRead(A0) * analogRead(A1));
  randNumber3 = random(1, 10);
  randomSeed(analogRead(A0) * analogRead(A1));
  digitalWrite(led1, LOW);
  digitalWrite(led2, LOW);
  digitalWrite(led3, LOW);
  digitalWrite(led4, LOW);
  digitalWrite(led5, HIGH);

  if (randNumber3==1)
  {
  mp3.playTrackNumber(6, 30);
  }

    if (randNumber3==2)
  {
  mp3.playTrackNumber(5, 30);
  }
  if (randNumber3==3)
  {
  mp3.playTrackNumber(6, 30);
  }

 if (randNumber3==4)
  {
  mp3.playTrackNumber(7, 30);
  }

   if (randNumber3==5)
  {
  mp3.playTrackNumber(8, 30);

}
  if (randNumber3==6)
  {
  mp3.playTrackNumber(9, 30);

}
 if (randNumber3==7)
  {
  mp3.playTrackNumber(15, 30);

}

 if (randNumber3==8)
  {
  mp3.playTrackNumber(20, 30);

}

 if (randNumber3==9)
  {
  mp3.playTrackNumber(21, 30);

}
digitalWrite(led5, LOW);
}
else {

}

//galina
if (reads4==1)
{
   randomSeed(analogRead(A0) * analogRead(A1));
  randNumber4 = random(2, 9);
//  randomSeed(analogRead(A0) * analogRead(A1));
  digitalWrite(led1, LOW);
  digitalWrite(led2, LOW);
  digitalWrite(led3, LOW);
  digitalWrite(led5, LOW);
  digitalWrite(led4, HIGH);
if (randNumber4==2)
  {
  mp3.playTrackNumber(19, 30);

}
if (randNumber4==3)
  {
  mp3.playTrackNumber(24, 30);

}
if (randNumber4==4)
  {
  mp3.playTrackNumber(25, 30);

}
if (randNumber4==5)
  {
  mp3.playTrackNumber(26, 30);

}
if (randNumber4==6)
  {
  mp3.playTrackNumber(27, 30);

}
if (randNumber4==7)
  {
  mp3.playTrackNumber(28, 30);
  }

if (randNumber4==8)
  {
  mp3.playTrackNumber(29, 30);

}
  digitalWrite(led4, LOW);
}
if (reads3==1)
{
    randomSeed(analogRead(A0) * analogRead(A1));
  randNumber5 = random(1, 8);
  randomSeed(analogRead(A0) * analogRead(A1));
  digitalWrite(led1, LOW);
  digitalWrite(led2, LOW);
  digitalWrite(led4, LOW);
  digitalWrite(led5, LOW);
  digitalWrite(led3, HIGH);
    mp3.playTrackNumber(22, 30);
}
else {

}
digitalWrite(led3, LOW);

mp3.serialPrintStatus(MP3_ALL_MESSAGE);

}

Why is it possible in case I press another button while a track is played, that it plays randomly. But if I press the same button again which is already played, the same track will start new as if the program just starts the track new but without generating a new random number?

Where is the rest of the code?

I would put the random seed into setup and not in your main loop. Other than that, maybe there is a bug in the part of the code you haven't shown.

Sorry, I posted all the code, now.

Why do you keep reseeding the random.number generator.  You need that once in setup.

It´s solved, now. You are right, with randomseed in setup only it works perfectly. Would be better to understand an instruction before using it. Thank you!

your code is overly repetitive .... use arrays to define variables ... for example define const int track[] = {6, 5, 6, 7, 8, 9, 15, 20, 21}; then play tracks without the need for if statements, mp3.playTrackNumber(track[random], 30);

you could also define the list of tracks in a 2D array, and then have only one play statement in the whole program mp3.playTrackNumber(track[button][random], 30);

Stop reseeding the random number generator!
You are supposed to seed it once, (in setup). If you reseed it with the same seed, you will get the same number every time.
I would be a bit surprised if the analogRead gave the same result every time, but say A0 returned zero because that pin was grounded then zero times any number will be zero, so you will always seed the random number generator with zero, and the random number you ask for will always be the same.
Also, try to do a bit of arithmetic. Instead of:
 if (randNumber == 1)
    {
      mp3.playTrackNumber(12, 30);
    }

    if (randNumber == 2)
    {
      mp3.playTrackNumber(13, 30);
    }
    if (randNumber == 3)
    {
      mp3.playTrackNumber(14, 30);
    }

    if (randNumber == 4)
    {
      mp3.playTrackNumber(16, 30);
    }
    if (randNumber == 5)
    {
      mp3.playTrackNumber(17, 30);
    }

    if (randNumber == 6)
    {
      mp3.playTrackNumber(18, 30);
    }

How about:
      mp3.playTrackNumber(11 + randNumber, 30);

That's a lot shorter don't you think? Or if that doesn't work for you (I didn't skip track 15 like you did), you can read up on how case statements work.

I didn´t understood how randomseed works and thought I must use it again to get a different number. I put it in setup only and now everything works perfectly! :-)

Thank you very much and thanks for the other hints, too!

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


text:
ESP32-CAM infinite boot loop
I am currently using an ESP32-CAM with an OV5460 camera, and I am interfacing it with my computer using an Arduino nano. I am trying to run a camera web server and using the Arduino example code. I have looked at a couple of YouTube tutorials and so have downloaded all the necessary stuff required to run an ESP32 project on Aurdino and have triple check all connectionss are correct. I am using the AI Thinker camera model. The problem comes in when I download the sketch and run it, I am greeted with some kind of CPU restart boot loop that just loops infinitely
What does this mean? How to fix it?
ets Jun  8 2016 00:22:57
rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0030,len:1288
load:0x40078000,len:13872
load:0x40080400,len:4
ho 8 tail 4 room 4
load:0x40080404,len:3048
entry 0x40080590
E (386) esp_core_dump_flash: No core dump partition found!
E (386) esp_core_dump_flash: No core dump partition found!

E (386) esp_core_dump_flash: No core dump partition found! indicates that the ESP32 is trying to write a core dump but cannot find the partition. This typically occurs when there is a crash or reset. https://forum.arduino.cc/t/esp32-cam-esp-core-dump-flash/1074812

Ensure the correct partition scheme is selected in the Arduino IDE. Go to Tools > Partition Scheme and select "Huge APP (3MB No OTA)" or another suitable scheme.
No "Huge APP partition scheme" (ESP32)


text:
How do I install Firmata so I can access it through the IDE on a computer that doesn't have internet access?
I recently installed arduino 2.3.2 IDE on to a computer without internet access, however, the Firmata library I had been using on the original computer which was the one I transferred the arduino15 folder from did not transfer. The original computer had firmata in its contributed library and the correlating sketches. How will I be able to transfer the firmata library onto the new computer using a thumbdrive?

You mean like copying the folder from your old libraries folder into the one on the new computer? Or downloading it here and then copying it to the new libraries folder?

Either way would work, I was just expecting the sketch examples files with the fermata to transfer over as well.  Where would the default library folder be after install? I am fairly new to Arduino so don't know where all the data and library files go. If I were to download it then move it over is there a specific path/folder I need to put the firmata folder in?

The libraries are placed in the libraries directory, inside your sketchbook location. When you open the Preferences in the Arduino IDE there should be an option, where you can see the current sketchbook location. Inside there you should have the libraries directory, where you can place the libraries.
You can either copy the corresponding directory for the Firmata firmware from your old libraries folder on an USB stick, or you can download it from firmatas Github page (either by cloning with the git command or by downloading as ZIP archive (by clicking the green "code" button at the top right and then clicking "Download ZIP") and placing the (unzipped) directory in your libraries folder.
To move your libraries to a new computer, you can just copy everything in the libraries folder. Examples for these libraries are provided with the library files, so when the library is not there, the examples won't be there.

Thanks for the answer, I'll give it a try.


text:
ESP32 Arduino Bluetooth Serial does not reconnect after disconnecting
The basic ESP32 Arduino Bluetooth Serial example pairs and connects as expected, BUT once I disconnect the Bluetooth terminal it stops responding to new events at all,
once I reset the esp32, it starts working again with the same problem. (it doesn't matter if it keeps being paired or not)
I have tested it with the windows Bluetooth terminal and with the Bluetooth Any terminal. (from the windows store)
I have downloaded the latest esp32-Arduino library from GitHub and I still get the same problem.
I have tested it with several esp32 modules, and they all respond with the same problem.
So it looks like a bug in the library code.
See the simple Arduino example code below:
#include "BluetoothSerial.h"

#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED) #error Bluetooth is not enabled! Please run make menuconfig to and enable it #endif

BluetoothSerial SerialBT;

void setup() { Serial.begin(115200); SerialBT.begin("ESP32test"); //Bluetooth device name Serial.println("The device started, now you can pair it with bluetooth!"); }

void loop() { if (Serial.available()) { SerialBT.write(Serial.read()); } if (SerialBT.available()) { Serial.write(SerialBT.read()); } delay(20); }

Does anyone know of another Bluetooth serial library that does work?
Thank You!

have you looked at the SerialToSerialBTM example code? ... it shows disconnect and reconnect

The SerialToSerialBTM example is for Bluetooth master mode, and not client mode

Nothing wrong with your code, I've the exact same issue as you have. It bothers me whole week long and fortunately, we (along with my colleague) accidentally figured that was caused by Windows 10, weird right? We don't believe it at very beginning either, but after several back-N-forth testing, it just like that. When we upload exact same code from another older computer with Windows 7 OS, it just works no matter how many time we connect/disconnect or even "QUIT" the APP without make it disconnect properly, its been able to be reconnect no problem. But once we use new computer with Windows 10 OS to upload the code, it can only be connected for first time, then stop broadcasting (or advertising).
The arduino official website in IDE download page also has a notice message "IMPORTANT: This app performs with core functionality on Windows 10 S but some limited plugins do not work. We are working with Microsoft on a fix.", hope this information helps.


text:
Control esp32 via keyboard keys
I'm making a project in which I have to control a mini car and get sensor information via bluetooth. I'd like to be able to control the mini car with the computers keyboard (w,a,s,d), but I was not able to find a library that could help with that, like the "keyboard" library does in python for example
Ex.
import keyboard

# when w is pressed, the car goes forward

If (keyboard.is_pressed("w"):

    Forward()

The "keyboard" library in arduino does not seem to work the same way. And I didn't find any other libraries nor tutorials about it online.
How to make it work?

In case someone is trying to do the same, I came up with a way to make it work. In ArduinoIDE, after the setup, the loop checks if the bluetooth serial is available and has received anything, if it receives the right variables for movement, it passes the instruction to the motors connected to the Arduino through an l298n module.
The code is as follows:
// variáveis para conexão bluetooth // variables for bluetooth connection
#include <SoftwareSerial.h>

SoftwareSerial SerialBT(8, 9);
char valorDoBluetooth;

//variáveis para o uso dos motores // variables for the use of motors
// motor 1
const byte in1 = 2;
const byte in2 = 4;
const byte enA = 3;
//motor 2
const byte in3 = 5;
const byte in4 = 7;
const byte enB = 6;

int velocidade = 100; // motor speed (up to 255)

int componentesOut[6] = { in1, in2, enA, in3, in4, enB }; // list created to setup the variables more easily

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

  // loop to set pins to Output
  for (int n = 0; n < 6; n++) {
    pinMode(componentesOut[n], OUTPUT);
  }
}

void loop() {
  // Read data from the Bluetooth module
  if (SerialBT.available()) {
    valorDoBluetooth = SerialBT.read(); // bluetooth Value

    if (valorDoBluetooth == 'F' || valorDoBluetooth == 'T' || valorDoBluetooth == 'D' || valorDoBluetooth == 'E' || valorDoBluetooth == 'P')  // if SerialBt recieved movement value
    {
      movimento(); // movement
    }
  }
}

void movimento() {
  if (valorDoBluetooth == 'F') {
    Serial.println("Frente");  // Forward
    frente();
  } else if (valorDoBluetooth == 'T') {
    Serial.println("Trás");  // Backwards
    tras();
  } else if (valorDoBluetooth == 'D') {
    Serial.println("Direita");  // Right
    direita();
  } else if (valorDoBluetooth == 'E') {
    Serial.println("Esquerda");  // Left
    esquerda();
  } else if (valorDoBluetooth == 'P') {
    Serial.println("Parar");  // Stop
    parar();
  }
  delay(1);
}

void frente() {
  digitalWrite(in1, HIGH);
  digitalWrite(in2, LOW);
  digitalWrite(enA, velocidade);
  digitalWrite(in3, LOW);
  digitalWrite(in4, HIGH);
  digitalWrite(enB, velocidade);
}
void tras() {
  digitalWrite(in1, LOW);
  digitalWrite(in2, HIGH);
  digitalWrite(enA, velocidade);
  digitalWrite(in3, HIGH);
  digitalWrite(in4, LOW);
  digitalWrite(enB, velocidade);
}
void direita() {
  digitalWrite(in1, LOW);
  digitalWrite(in2, HIGH);
  digitalWrite(enA, velocidade);
  digitalWrite(in3, LOW);
  digitalWrite(in4, HIGH);
  digitalWrite(enB, velocidade);
}
void esquerda() {
  digitalWrite(in1, HIGH);
  digitalWrite(in2, LOW);
  digitalWrite(enA, velocidade);
  digitalWrite(in3, HIGH);
  digitalWrite(in4, LOW);
  digitalWrite(enB, velocidade);
}
void parar() {
  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);
  digitalWrite(enA, velocidade);
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);
  digitalWrite(enB, velocidade);
}

To be able to control it via the PC keyboards, I connected the PC to the device through bluetooth, then see which COM it is connected to in bluetooth configurations of control panel, and use this the COM number on a Python code that's able to communicate with the device.
The Python code is as follows:
import serial
import time
import keyboard

# Replace 'COMX' with the actual COM port assigned to the HC-05 module / Esp device on your PC. More info at https://pyserial.readthedocs.io/en/latest/shortintro.html
ser = serial.Serial('COM8', 9600, timeout=1)

flagMovido = True # flag that checks if the motors are finished moving before changing directions

def controle(event):
    global flagMovido

    if event.event_type == keyboard.KEY_DOWN: # if a key is pressed:
        if (event.name == "w" or event.name == "a" or event.name == "s" or event.name == "d") and flagMovido: # if movement keys are pressed and motors are finished moving to any other direction:
            flagMovido = False # motors started moving

            if event.name == "w" and not flagMovido:
                ser.write(b'F')

                print('frente') # Forward

            elif event.name == "a" and not flagMovido:
                ser.write(b'E')

                print('esquerda') # Left

            elif event.name == "s" and not flagMovido:
                ser.write(b'T')

                print('trás') # Backwards

            elif event.name == "d" and not flagMovido:
                ser.write(b'D')

                print('direita') # Right

    elif event.event_type == keyboard.KEY_UP: # if a key is released:
        if (event.name == "w" or event.name == "a" or event.name == "s" or event.name == "d") and not flagMovido: # if movement keys are released and motors are moving to some direction

            flagMovido = True # motors are finished moving

            ser.write(b'P')

            print('parado') # Stop

print('START')

def main():
    while True:
        data = ser.readline().decode().strip()

        keyboard.hook(controle)
        time.sleep(.001)

        if data:
            print(f"Recebido: {data}") # prints data if any received. Used to print the sensor values received.

if __name__ == "__main__":
    main()

obs:

The code runs fine, but may present some problems if you press to many keys at a time, since it was made to handle one direction at a time. But the movement bools will help with that and prevents it from happening to certain extent. Though in specific cases is should be improved.
I ended up using a HC05 module with Arduino, but the code also woks for Esp. But if connecting to an Esp, the ser = serial.Serial('COM8', 9600, timeout=1) line should be changed to the way it connects to the Esp. More info at the link provided.

it is good to see that you were able to figure this out yourself ... the test of all values in loop()  is somewhat redundant, just call movimento() without an if statement

Thanks, and good point. I narrowed down the code to explain the logic here, but in the project I'm making this 'if' statement is actually necessary. That's true nonetheless, as it is, that's just a unnecessary 'if' statement.


text:
WiFi HaLow library
Does anyone know if some Arduino based library is on the way to support new low power WiFi HaLow modules. If there is, I would like to know for which module?
For reference I'm sharing link here

What's a WiFi HaLow module?

I shared link in the question

If anyone will make one Adafruit will, and they haven't yet. The tech is too new for Arduino...


text:
Problem on interfacing 3 flame sensors and servo to Arduino Fire Fighter
I had been trying to make Arduino Fire Fighter Robot but facing several problems in interfacing 3 flame sensors and servo together. When I upload the following code( Which I had posted at the end of my writing) my robot goes backward and detects flame at the front sensor and displays " Flame on Front" on 16x2 LCD display and the 5v  pump pumps out water and the red LED blinks. But I want that my robot will work in the following way- Initially, my robot will be at rest. There are 3 sensors attached at the front part of the robot. And there is a SG90 servo for rotating the water tank( in this tank there is a 5v pump motor and the pump motor will pump out water from this tank). When any one of the three flame sensors  will detect flame then the servo will rotate in that direction and when the front flame sensor detects fire , the servo will be in 90-degree angle and water will be pumped out. LCD will display the status of the flame sensors. But the robot is not working properly. I am not able to interface 3 flame sensors and servo together. My robot is not working according to my expectation as I had said before.
int pos = 0;
boolean fire = false;

#include <LiquidCrystal.h>
int Contrast=20;// for adjusting the brightness of the LCD , 20 is selected for the contrast of LCD
LiquidCrystal lcd(30,31,32,33,34,35);
int buzz= 38; //for led or buzzer
#define Left_S 9 // left sensor
#define Right_S 8     // right sensor
#define Forward_S 23  //forward sensor
#define LM1 52 //for pump motor
#define LM2 53 //for pump motor
#define IN1 5   //for motor
#define IN2 4  // for motor
#define IN3 3      //for motor
#define IN4 22     // for motor
//int flame_pin1 = HIGH ;
int LEDR= 36; // for danger signal
int LEDB=37;// for safe signal

void setup ( )  {
   analogWrite(6,Contrast);
     lcd.begin(16, 2);
      pinMode(Left_S, INPUT);
  pinMode(Left_S, INPUT);
  pinMode(Right_S, INPUT);
     pinMode (Forward_S,OUTPUT);
     pinMode (LEDB,OUTPUT);
 pinMode(LM1, OUTPUT);
 pinMode(LM2, OUTPUT);
  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
  pinMode(IN3, OUTPUT);
  pinMode(IN4, OUTPUT);
  pinMode( buzz,OUTPUT );
  pinMode(LEDR,OUTPUT);
  pinMode(LEDB, OUTPUT);
 // pinMode ( flame_sensor_pinM , INPUT );
  //Serial.begin ( 9600 );
   myservo.attach(25);
  myservo.write(90);
}
 void put_off_fire()
{
    delay (500);

    digitalWrite(IN1, HIGH);
    digitalWrite(IN2, HIGH);
    digitalWrite(IN3, HIGH);
    digitalWrite(IN4, HIGH);

   digitalWrite(LM1, HIGH);
   digitalWrite(LM2, LOW);
   delay(500);

    for (pos = 50; pos <= 130; pos += 1) {
    myservo.write(pos);
    delay(10);
  }
  for (pos = 130; pos >= 50; pos -= 1) {
    myservo.write(pos);
    delay(10);
  }

  digitalWrite(LM1,LOW);
  digitalWrite(LM2,LOW);
  myservo.write(90);

  fire=false;
}

void loop ( ){
   myservo.write(90); //Sweep_Servo();

    if (digitalRead(Left_S) ==1 && digitalRead(Right_S)==1 && digitalRead(Forward_S) ==1) //If Fire not detected all sensors are zero
    {
    //Do not move the robot
    lcd.setCursor(0, 1);
      lcd.print("No flame");
    digitalWrite(IN1, HIGH);
    digitalWrite(IN2, HIGH);
    digitalWrite(IN3, HIGH);
    digitalWrite(IN4, HIGH);
    digitalWrite(LEDR,LOW);
    digitalWrite(LEDB,HIGH);
    digitalWrite(buzz,LOW);
    }

    else if (digitalRead(Left_S) ==0) //If Fire is straight ahead
    {
    //Move the robot forward
    lcd.setCursor(0, 1);
      lcd.print("Flame on Left");
    digitalWrite(IN1, HIGH);
    digitalWrite(IN2, LOW);
    digitalWrite(IN3, HIGH);
    digitalWrite(IN2, LOW);
    digitalWrite(LEDR,HIGH);
    digitalWrite(LEDB,LOW);
    digitalWrite(buzz,HIGH);
    fire = true;

    }
    else if (digitalRead(Forward_S) ==0) //If Fire is straight ahead
    {
    //Move the robot forward
    lcd.setCursor(0, 1);
      lcd.print("Flame on front");
    digitalWrite(IN1, HIGH);
    digitalWrite(IN2, LOW);
    digitalWrite(IN3, HIGH);
    digitalWrite(IN2, LOW);
    digitalWrite(LEDR,HIGH);
    digitalWrite(LEDB,LOW);
    digitalWrite(buzz,HIGH);
    fire = true;

    }

    else if (digitalRead(Right_S) ==0) //If Fire is to the right
    {
    //Move the robot right
    lcd.setCursor(0, 1);
      lcd.print("Flame on Right");
    digitalWrite(IN1, HIGH);
    digitalWrite(IN2, HIGH);
    digitalWrite(IN3, HIGH);
    digitalWrite(IN4, LOW);
    digitalWrite(LEDR,HIGH);
    digitalWrite(LEDB,LOW);
    digitalWrite(buzz,HIGH);
    fire= true;
    }

     delay(300); //Slow down the speed of robot

     while (fire == true)
     {
      put_off_fire();
     }
}

your code is badly indented, so it is difficult to follow the program flow without reformatting

If you format your code correctly, the code becomes less cluttered and the problem becomes more visible.
Also, if you think about the if statements, there is no need to check for no fire for all three sensors at the same time. If none of the three sensors see fire, then the only possibility that is left, is no fire.
Another thing, you have no digitalWrite(IN1, LOW); and no digitalWrite(IN3, LOW); in your code. You could put digitalWrite(IN1, HIGH); and digitalWrite(IN3, HIGH); in setup()
Here is your code rewritten and formatted.
Couple of unnecessary duplications are tagged.
There is no reason to use while (fire == true) because put_off_fire() clears the fire flag
Also, for future programs, while (fire == true) is a redundant form because it is same as while (fire)
Have a really close look at the if statement blocks.
You used copy&paste when writing the code, but you forgot to make changes.
#include <LiquidCrystal.h>

LiquidCrystal lcd(30, 31, 32, 33, 34, 35);

#define Left_S       9                       // left    sensor
#define Right_S      8                       // right   sensor
#define Forward_S   23                       // forward sensor

#define LM1         52                       // for pump motor
#define LM2         53                       // for pump motor

#define IN1          5                       // for motor
#define IN2          4                       // for motor
#define IN3          3                       // for motor
#define IN4         22                       // for motor

//int flame_pin1 = HIGH ;

int LEDR     = 36;                           // for danger signal
int LEDB     = 37;                           // for safe signal
int buzz     = 38;                           // for led or buzzer
int pos      =  0;
int Contrast = 20;                           // for adjusting the brightness of the LCD , 20 is selected for the contrast of LCD

boolean fire = false;

void setup() {

    analogWrite(6, Contrast);

    lcd.begin(16, 2);

    pinMode( Left_S            , INPUT  );
    pinMode( Left_S            , INPUT  );
    pinMode( Right_S           , INPUT  );

    pinMode( Forward_S         , OUTPUT );
    pinMode( LEDB              , OUTPUT );   // xxxxxxxxxxxxx        duplicate

    pinMode( LM1               , OUTPUT );
    pinMode( LM2               , OUTPUT );

    pinMode( IN1               , OUTPUT );
    pinMode( IN2               , OUTPUT );
    pinMode( IN3               , OUTPUT );
    pinMode( IN4               , OUTPUT );

    pinMode( buzz              , OUTPUT );

    pinMode( LEDR              , OUTPUT );
    pinMode( LEDB              , OUTPUT );   // xxxxxxxxxxxxx        duplicate

//  pinMode( flame_sensor_pinM , INPUT  );

//  Serial.begin ( 9600 );

    myservo.attach(25);
    myservo.write(90);
}

void put_off_fire() {

    delay (500);

    digitalWrite(IN1, HIGH);
    digitalWrite(IN2, HIGH);
    digitalWrite(IN3, HIGH);
    digitalWrite(IN4, HIGH);

    digitalWrite(LM1, HIGH);
    digitalWrite(LM2, LOW );
    delay(500);

    for (pos = 50; pos <= 130; pos += 1) {
        myservo.write(pos);
        delay(10);
    }

    for (pos = 130; pos >= 50; pos -= 1) {
        myservo.write(pos);
        delay(10);
    }

    digitalWrite(LM1, LOW);
    digitalWrite(LM2, LOW);

    myservo.write(90);                       // xxxxxxxxxxxxx        duplicate

    fire = false;                            // xxxxxxxxxxxxx        not needed
}

void loop() {

    myservo.write(90);                       // xxxxxxxxxxxxx        duplicate
//  Sweep_Servo();

    lcd.setCursor(0, 1);

    fire = true;                             // preset the state (gets cleared when no fire is detected

    if (digitalRead(Left_S) == 0) {          // If Fire is straight ahead

        lcd.print("Flame on Left");

        digitalWrite(IN1 , HIGH);            // Move the robot forward
        digitalWrite(IN2 , LOW );
        digitalWrite(IN3 , HIGH);
        digitalWrite(IN2 , LOW );
    }

    else if (digitalRead(Forward_S) == 0) {  // If Fire is straight ahead

        lcd.print("Flame on front");

        digitalWrite(IN1 , HIGH);            // Move the robot forward
        digitalWrite(IN2 , LOW );
        digitalWrite(IN3 , HIGH);
        digitalWrite(IN2 , LOW );
    }

    else if (digitalRead(Right_S) == 0) {    // If Fire is to the right

        lcd.print("Flame on Right");

        digitalWrite(IN1 , HIGH);            // Move the robot right
        digitalWrite(IN2 , HIGH);
        digitalWrite(IN3 , HIGH);
        digitalWrite(IN4 , LOW );
    }

    else {                                   // fire was not detected by any of the sensors

        fire = false;

        lcd.print("No flame");

        digitalWrite(IN1 , HIGH);            // Do not move the robot
        digitalWrite(IN2 , HIGH);
        digitalWrite(IN3 , HIGH);
        digitalWrite(IN4 , HIGH);
    }

    delay(300);                              // Slow down the speed of robot

    if (fire) {

        digitalWrite(LEDR, HIGH);            // do fire lights
        digitalWrite(LEDB, LOW);
        digitalWrite(buzz, HIGH);

        put_off_fire();
    }

    else {

        digitalWrite(LEDR, LOW );            // do nofire lights
        digitalWrite(LEDB, HIGH);
        digitalWrite(buzz, LOW );

    }
}

Thanks for your suggestion. But the right motor starts to move when I upload the code to Arduino. And the servo is not also rotating. Suppose, the servo is at 90-degree angle. When the left sensor will detect fire then the servo needs to rotate at the left side. The servo's position remain at 90 degree position. Why?

Will I have to erase myservo.write(90) and fire= false; from Void put off fire()? Beside these two lines you wrote duplicate and not necessary

no, you do not have to delete duplicate lines ... i simply pointed out that you have duplicate code which indicates that you my want to review your code to make sure that you have not overlooked someting else

Thank u so much. But  right motor starts to rotate automatically when I upload the code why? Your suggestion will be highly appreciated.

test your motors ... write a sketch that runs one motor for one second, then reverses it, then the other motor

Ok. I will test my motors.

If I want to add MQ-5 ( for gas leakage detection) sensor in my robot then what's the way of adding it?


text:
Adding SIMCOM SIM 900A to Arduino Fire Fighter Robot for sending alert messages
I had made Arduino Fire Fighter Robot. I want to add SIMCOM SIM 900A GSM module to Arduino. When flame sensor will detect fire then " Fire!!!" message will be sent to mobile phone and when fire is extinguished then " No fire!!" will be sent to mobile phone. So  how can I add the part of SIMCOM SIM 900A GSM in my project?
Here is the code:
 #include <Servo.h>

Servo myservo;

#include <LiquidCrystal.h>

LiquidCrystal lcd(30, 31, 32, 33, 34, 35);

#define Left_S       9                       // left    sensor
#define Right_S      8                       // right   sensor
#define Forward_S   23                       // forward sensor

#define LM1         52                       // for pump motor
#define LM2         53                       // for pump motor

#define IN1          5                       // for motor
#define IN2          4                       // for motor
#define IN3          3                       // for motor
#define IN4         22                       // for motor

int LEDR     = 36;                           // for danger signal
int LEDB     = 37;                           // for safe signal
int buzz     = 38;                           // for led or buzzer
int pos      =  0;
int Contrast = 20;                           // for adjusting the brightness of the LCD , 20 is selected for the contrast of LCD

boolean fire = false;

void setup() {

    analogWrite(6, Contrast);

    lcd.begin(16, 2);

    pinMode( Forward_S         , INPUT  );
    pinMode( Left_S            , INPUT  );
    pinMode( Right_S           , INPUT  );

    pinMode( LM1               , OUTPUT );
    pinMode( LM2               , OUTPUT );

    pinMode( IN1               , OUTPUT );
    pinMode( IN2               , OUTPUT );
    pinMode( IN3               , OUTPUT );
    pinMode( IN4               , OUTPUT );

    pinMode( buzz              , OUTPUT );

    pinMode( LEDR              , OUTPUT );
    pinMode( LEDB              , OUTPUT );   // xxxxxxxxxxxxx        duplicate

    myservo.attach(25);
    myservo.write(90);
}

void put_off_fire() {

    delay (500);

    digitalWrite(IN1, HIGH);
    digitalWrite(IN2, HIGH);
    digitalWrite(IN3, HIGH);
    digitalWrite(IN4, HIGH);

    digitalWrite(LM1, HIGH);
    digitalWrite(LM2, LOW );
    delay(500);

    for (pos = 50; pos <= 130; pos += 1) {
        myservo.write(pos);
        delay(10);
    }

    for (pos = 130; pos >= 50; pos -= 1) {
        myservo.write(pos);
        delay(10);
    }

    digitalWrite(LM1, LOW);
    digitalWrite(LM2, LOW);

    myservo.write(90);                       // xxxxxxxxxxxxx        duplicate

   fire = false;                            // xxxxxxxxxxxxx        not needed
}

void loop() {

    myservo.write(90);                       // xxxxxxxxxxxxx        duplicate
//  Sweep_Servo();

    lcd.setCursor(0, 1);

    fire = true;                             // preset the state (gets cleared when no fire is detected

    if (digitalRead(Left_S) == 0) {          // If Fire is left ahead

        lcd.print("Flame on Left");

        digitalWrite(IN1 , LOW);            // Move the robot left
        digitalWrite(IN2 , HIGH );
        digitalWrite(IN3 , HIGH);
        digitalWrite(IN2 , LOW );
    }

    else if (digitalRead(Forward_S) == 0) {  // If Fire is straight ahead

        lcd.print("Flame on front");
         digitalWrite(IN1 , LOW);            // Move the robot right
        digitalWrite(IN2 , HIGH);
        digitalWrite(IN3 , LOW);
        digitalWrite(IN4 , HIGH);

           }

    else if (digitalRead(Right_S) == 0) {    // If Fire is to the right

        lcd.print("Flame on Right");

        digitalWrite(IN1 , HIGH);            // Move the robot right
        digitalWrite(IN2 , LOW);
        digitalWrite(IN3 , LOW);
        digitalWrite(IN4 , HIGH );
    }

    else {                                   // fire was not detected by any of the sensors

        fire = false;

        lcd.print("No flame");

        digitalWrite(IN1 , HIGH);            // Do not move the robot
        digitalWrite(IN2 , HIGH);
        digitalWrite(IN3 , HIGH);
        digitalWrite(IN4 , HIGH);
    }

    delay(300);                              // Slow down the speed of robot

    if (fire) {

        digitalWrite(LEDR, HIGH);            // do fire lights
        digitalWrite(LEDB, LOW);
        digitalWrite(buzz, HIGH);

        put_off_fire();
      //  delay(100);
    }

    else {

        digitalWrite(LEDR, LOW );            // do nofire lights
        digitalWrite(LEDB, HIGH);
        digitalWrite(buzz, LOW );

    }
}

What is your actual problem in doing so? Have you googled for tutorials about the SIM900 and have you tried some example codes, to learn how it works? There are tons of information about the SIM900 out there

I have tried but I couldn't. I bought SIMCOM SIM 900 module which supports 2G SIM but 2G SIM is no longer available in our country. Then I bought SIMCOM SIM900A but I couldn't connect the GSM module with the above code though I saw many examples. And there are various types of circuit of SIMCOM SIM 900A. Which one should I follow? That's why I am facing difficulty in adding the part of sending alert messages with the above code.

If this is a school project, why not try something where you control all the radio equipment.  Such as LORA?  This may simplify your efforts and code.  If this is a one-off project (you are not sensitive to cost), why not try to use a cell phone as a gate-way to an existing cell phone network.

Thanks for your suggestion. As I had already submitted the concept paper of my project, so there is no scope of changing the concept paper and I have to use SIMCOM SIM 900A module.

As I remember the SIM900A is interfaced via Serial (UART), which means, that no big circuit is involved. Just power supply and RX and TX pins connected. What types of different circuit have you seen? Can you provide links to show, what caused your confusion about the circuit?


text:
Power up Arduino using AC/DC Adapter
Wanna get your advice regarding powering up Arduino Uno using AC/DC Adapter to the barrel jack.
The first adapter I use couldn't work and the shop which I bought it from said the adapter was short circuit-ed.
Out of goodwill, she replace it for free and I tested it out again. The first few tries it worked perfectly fine but stopped working (suspected short-circuited again).
The adapter output is DV9V - 2A.
The circuit consists of 2 ultrasonic sensor and 1 buzzer.
I am quite sure the Arduino circuit does not draw more than 2A of current.
Any idea what's the issue? Thanks!
EDIT -
I've uploaded a photo of the schematic done using Tinkercad. I am using a different breadboard thus the configuration as shown.

As you suspect a short circuit, have you checked for that? Also: Are you sure, that the power supply is broken? Or is it the Arduino? The barrel jack is connected to a voltage regulator, which will go into emergency shutdown, if you draw more current through it, than supported, (for genuine Arduinos).  Cheap clones might get their voltage regulator destroyed. Please show your real circuit, so that we can check for a short circuit

You need to troubleshoot the system. 2 failed power supplies in a row seems suspicious. I would try to rule out a problem with your Arduino or with your circuit. Buy a multi-tester and measure the voltage out of your power supply, and the resistance of your circuit. You might want to add a 2A fuse to your power supply to protect it. (You'd need a male and a female barrel jack connector, a fuse holder, some wire, and a soldering iron.)

Switch-mode based DC adapters virtually have to have short circuit protection and OCP to pass UL certification (otherwise it would fail). Most smps driver chips have that built-in as well, so if it's a recently made adapter, that's probably not the issue.

Hi @chrisl I have uploaded a photo of the schematic. Can you help to take a look? The Arduino works perfectly fine because it is able to power up via USB. I am supplying a 2A into the Arduino which requires only 1A. I read on forum that supplying more current is fine

@DuncanC Hi, I've tested the adapter, it doesn't have any voltage output. So pretty sure the adapter is damaged. I'm trying to find out why the adapter is damaged

@dandavis Hi, yea the adapter should have. It's surprising that the adapter failed on a circuit with merely sensors and buzzer

My guess is that your project has a short circuit somewhere, and you are overloading your power supplies. Check the resistance on the power inputs to your project, and use ohms law to figure out how much current it would draw from the power supply at 9V


text:
Triggering a Sleep Wake-up Event using analog output from a triple axis accelerometer?
I am working on a project that uses a Arduino MKR GSM 1400 and a ADXL335 Accelerometer . I am having trouble setting a interrupt wake up event on one of the GSM's interrupt-capable pin due to the analog nature of the ADXL335's output. The axis outputs typically range between ~1.4V-~2.2V with ~1.65V being the resting voltage level.
I have tried using a NTE987 op-amp to amplify the analog output enough to trigger a CHANGE on the interrupt pin I'm using. This resulted in the analog signal outputted by the ADXL335 boosting to a certain voltage level and not varying at all with any motion.
My current solution, which works very well but is not ideal for power consumption reasons, is using a smaller micro controller with less power draw's ADC to interpret the ADXL335's output and send digital wake-up signals to the GSM when certain thresholds are met. I would like to know if there's a better way to do this, as using an additional microcontroller to wake up the original microcontroller feels like a kludge.

What is the power draw of the opamp? That opamps shouldn't draw that much current.

I'm not familiar with the SAMD21. But some micro controllers have comparitors in them that can trigger an interrupt when the voltage gets above/below a certain value. I'm not sure what you are measuring with the accelerometer, but if the triggering motion isn't a short one, you could have the MCU sleep most of the time, and wake up, say, once a second to do a measurement.

this may help ... https://duckduckgo.com/?q=ultra+low+power+comparator&ia=web

You need to remove that 1.65V offset before amplifying it. The simplest way is to AC couple it with a capacitor.


text:
Using an Arduino as the processor for a computer-mouse-like speed detector
I'm looking at making a pretty cheap and easy odometer, eventually for an electric car or similar vehicle.
My idea is to implement a big computer mouse, and track the speed with that: a computer mouse takes photos of the surface it is on, and finds the difference between sequential images in both the X and Y directions.
What I am wanting to do is to attach a downwards-facing camera; something like this, to the bottom of the vehicle, and use an Arduino Nano to do the image processing to achieve a result similar to a computer mouse.
I was wondering whether anyone knows of an libraries/documentation on anything similar, or if anyone has any pointers on reasons why this would not work, or ways it would work.
Thanks all.

Neat idea! One potential problem that occurs to me is the lens getting dirty. You might also need a light for it to work at night.

Mouse chips are ASICs specifically designed for image processing. Use an encoder instead.

Like @jogco pointed out, you will have very little computational power. With that camera you will have to use a clock at 24MHz to read the data; this means at least a 100MHz uC. So forget the arduinos... Maybe you will manage to do that with higher power uC (for instance ST nucleo boards), but then you'll have to face another problem: resolution. An electric car moving at 7.2 km/h (human speed) travels 2m in 1s. The frame rate is at most 30fps, which means that the car moves 7cm every frame. This means that the camera should be at least at 10cm from the ground to be able to see some common

points between two frames. Since, however, it'll be very difficult to compare them, I think that at most you should allow for half an image of difference. This means that the camera should be at least at 20-25cm from the ground. And if the car is faster than humans, well, just give up. The easiest solution is to use an encoder on a shaft (for instance on the wheels one). I suggest an optical encoder because they are easier to assemble, but dirt can lower their performances, If dirt can be an issue use a magnetic one (or just magnet + reed relay)

@frarugi87 Thanks for that analysis, it definitely puts it in perspective! I can't rationally explain why, but I am trying to avoid shaft encoding. I am wondering about a small array of photoresistors, and simply multiplex them, so I can have a significantly faster read time, and just look for patterns.

@dlu thanks for your input, I hadn't really thought about either of those!

Whooa, wait a minute. This sounds way too complicated, and my guess is that a Nano would be seriously underpowered.
If you really want to do all that work, you probably would need to step up your processing power. I suggest that you do some calculations on that, the number of pixels per second that should be compared.
Also factor in the time it takes to capture the image, the device you suggested is probably not fast enough. My guess is that by the time you can take next picture of the surface, you don't have any part of the image to compare with. According to wikipedia, a modern mouse has a 18 by 18 pixel sensor, and we're not talking a lot of (surface) speed here.
But there's a simpler solution; mount a magnet to one of the wheels (or axle) and a reed switch so that it is actuated as the magnet sweeps by. Then use the Nano (or a Trinket, no need for power here) to count the pulses from the reed switch. Do your math; (circumference of wheel) * (pulses per time unit). Convert to suitable format.
Voila; speed! :-)
This method was used to get accurate speed for deadreckoning, before GPS was really usable on land.. OMG, I'm old.
Possible problems areas - dirt, debouncing the switch, timing of arduino. But these sound simple in comparison.

I totally agreed with this until you wrote that "need RTC" sentence.. An RTC? Why? RTCs are good at keeping time when the device is off, not to measure small time gaps (usually they have a 1s granularity). Crystals' precision is really enough for this project. What really lacks is the computational power to analyse the image in few milliseconds

Sure, then we can straighten out that question mark, and move it: !(need RTC). I was just throwing up possible areas to investigate.

Thanks Jogco, I wasn't totally sure about feasibility. I guess for speed accuracy there is some relationship with the field of view and the speed at which each image is processed. I have been looking for a significantly lower resolution camera, but am unable to find it. I wonder if I would be able to use a small (~10x10?) array of photoresistors and multiplex through them. This would need some form of light source to go with it, too.


text:
How to integrate ESP8266
Just, to make sure how it works:

I will connect the module to Arduino
it will create AP to which I can connect and send commands via HTTP

So I do not need any special equipment on PC side right, I can even connect to the ESP's AP with mobile, right?
Is it possible for the ESP to be WIFI client and connect to regular WIFI SSID (the PC will just communicate over regular network)?
Is it possible to communicate bidirectional somehow?

So I do not need any special equipment on PC side right, I can even connect to the ESP's AP with mobile, right?

If you set the ESP8266 in AP you can connect to it with every wifi capable device.
You can control an ESP8266 with just an Arduino, but you I would not recommend using your Arduino as the power supply. If I remember correctly the mega's VCC pins are rated for 200mA which may or may not be enough for your ESP8266 I'm not sure, but I would recommend using another power supply for the ESP8266.

Is it possible for the ESP to be WIFI client and connect to regular WIFI SSID

Yes that is possible.

Is it possible to communicate bidirectional somehow?

I am not exactly sure what you want, but it is possible to communicate in both directions. Assuming you know the local IP address of your ESP8266, you could for example send an HTTP request to it using any browser to which the ESP8266 can reply with anything.
Your ESP8266 can also send data to your computer, but it would require some program on your computer listening for incoming connections. Also possible, but more difficult.
At last I would like to tell you that driving an ESP8266 with an Arduino is like driving a Ferrari with the engine from a tuk tuk. It will move, but you will never use all of it's features. I don't know which version of the ESP8266 you have, but there are versions out there that can be programmed via USB just as your Arduino and you can just use the Arduino IDE and all of it's features like the Arduino language.

Just wanted to second what @larzz11 says in the last para.  If you don't need the ADC's, running Arduino code on the device is definitely the simplest/easiest way to use the device.  The AT command firmware is challenging to get working in a stable fashion.
Also just to re-affirm the power requirements of the ESP8266 is higher than the 3v3 supply on the Arduino—you'll need a step-down converter from a sufficiently powerful 5v supply, or separate power supply, to get it working consistently.
Bidirectional comms are definitely doable, but the limited SRAM on Arduino make string parsing a real challenge, and even handling relatively small responses/requests can hit up against the available SRAM.
One of the nice things about using Arduino on the ESP8266 is that the ESP8266 has 8 times the amount of SRAM, making that more feasible also.


text:
Why the 4.7 K Ω resistor in this pitch follower sketch?
I am reading Arduino for Dummies, and I am blocked at the pitch follower exercise. It consists in making a piezo vary with a light sensor. I can't see the point of the resistor (and why 4.7?) in this sketch:

Any help for a dummy is appreciated! :-)

The resistor couples with the LDR to form a voltage divider. The voltage at the point where the resistor and LDR join will vary depending on the ratio of the two resistances - the resistance of the LDR and the 4700 ohm resistor.
The value of 4700 is chosen to allow a reasonable range of voltages when in a ratio with the LDR, and the best value depends on the resistance range of the LDR.

hi, I have read your explanation and other links (http://www.instructables.com/id/How-to-Use-a-Light-Dependent-Resistor-LDR/) many times, but I still don't get it. What would happen without the resistor? We would still have a varying resistance applied to A0 when the light applied to the LDR would vary. I mean, what's the need for anything else?

What exactly don't you get?

just edited my comment! :-)

The voltage dropped across the LDR without the other resistor is dependent on the current flowing through it. Simple Ohms Law. Since the input pin A0 is very high impedance that current will be minuscule. As a result the voltage drop will be incredibly tiny - too small for the Arduino to measure. Learn Ohms Law and these things become obvious.

ok I finally got it. it is far from trivial: Ohm's Law is one thing, but then it is a matter of getting the clever trick of the voltage divider, which took me a while to get...

The voltage divider can be derived purely with ohms law by working out the currents through the resistors for a given source voltage, then calculating the dropped voltage for each resistor.

Let us continue this discussion in chat.

Arduino measures Voltages on pins A0 to A5; but the LDR is a variable resistor (varying with Light). So we need to convert the varying resistance to a voltage that the Arduino can measure.
For more details see here.
Cheers!


text:
Arduino as voltage monitor shorts to ground
I need to monitor voltages of several DC circuits in a generator's contact box.  Whenever the generator has an alarm, a LED is lit in the box and voltage on the line drops to zero.  I successfully get readings using analogRead(), but whenever I connect a line it shorts to ground (which is shared between the contact box and the Arduino) and triggers the contact box's alarm.  I need to devise a way to monitor voltages without triggering the alarm.
Each 5V line and ground from the generator has a bus bar termination point that connects to a point in the proprietary alarm box that houses the LEDs and buzzer. I connected Arduino ground to generator ground, then used A0-A7 on a Nano to connect to individual lines on the bus bar. Arduino VCC is connected to 5V regulated DC power.

What is the voltage you are trying to measure, and how exactly are you wiring it up?

Matt, please edit that information into the question.  Also, say if you actually need to measure voltages or just want go/nogo signals as could be obtained using optoisolators.

Input impedance of the analog pins is pretty low. So either the signal is very very weak, or your connections/software is doing something wrong.

I can detect the signals without problem.  The issue is avoiding the short to ground when I add the arduino into the circuit.

Since I was able to read voltages between load and the shared ground using a voltmeter without tripping the alarm, I thought I could do the same with an arduino.

Please add a schematic of the circuitry. And how is the Arduino powered, battery as the voltmeter?

A voltmeter does not have a ground reference. An Arduino plugged into the USB port would have one. Conceivably a battery-powered Arduino might work, however a safer solution would be to use an opto-isolator to isolate the voltage being tested from the Arduino. Something like this:

In this case you connect the "data pin" to the thing you are sensing. If it is at 5V then the LED will conduct (taking around 7 mA) and the transistor in the isolator will drive the Arduino pin LOW. If the data pin goes to zero volts, the transistor will not conduct, and the 1k resistor will pull the Arduino pin HIGH. Thus you can detect if the pin has changed voltage.
The 560 ohm resistor is a current-limiting resistor for the LED in the isolator. A 1k resistor would probably also work, reducing the current draw on the data pin to around 3.8 mA.

I would think you could also delete the 1K resistor and use the Arduino internal pullup resistor.


text:
Few questions related to programming microcontrollers
I'm learning "Arduino" (I don't have previous knowledge of microcontrollers). I have few questions:

What is the difference between programming a microcontroller in C and programming in "Arduino?"
Is it a good idea for beginners to start programming microcontrollers in Arduino and then start learning to program in C?
I have Arduino Uno with an Atmega328P-PU microcontroller. What are some other microcontrollers which can be used with this board? What are differences between various microcontrollers which can be used with this board?
If a microcontroller is already programmed, can we download the program from it to a PC and edit it in Arduino IDE? Or it is like a .exe on a PC, once compiled we can't get source, all we can do is reverse engineer?

That's it :)

The Arduino IDE uses C++ primarily, which it preprocesses in order to make compilable. But you can still for the most part use C in the Arduino IDE and it will just work as normal; there's nothing requiring you to use C++ or the Arduino libraries (or even the Arduino IDE) for most tasks.
Not touching this one. And in the end it doesn't matter terribly since they're very close.
Any of the ATmegaXX8 or ATmega8 chips will fit the socket. Note that they will require separate cores if you're using the IDE. And you can use any chip without the board in the IDE as long as you can find a core for it.
Not if you use a traditional compiled language to program it. If you use a VM then you conceivably could, but you'd have the source on your system regardless.

Nothing really.  The Arduino language is C++, a super-set of C. It contains a library of routines which are automatically included and linked, as well as a small amount of pre-processing to hide some of the pitfalls of C (e.g., automatically adding function prototypes for all functions to the top of your program so function ordering isn't something you now need to think about). Other than that, it is just C++, which is C with bells.
If you learn the Arduino language you are learning C. If you learn C first then it gives you a good grounding in how to program the Arduino. Either way, by the time you have written your first Arduino program, you will be programming in C.
There are a number of chips by Atmel that will work. You need, besides the "core" that Ignacio mentions, a board definition which defines what pins do what and what chip is in use. You also need a bootloader for that specific chip and some way to install that bootloader into the chip. There are tutorials on how to do that for commonly used chips - more uncommon ones may not have a bootloader readily available.
When you program for the Arduino you are compiling the software. That is turning the source code first into object code and then linking the object code into an executable format - almost exactly the same as a .EXE on Windows. There is nothing you can do to "undo" that, only disassemble the raw instructions into assembly language and try to interpret what it is doing, which with assembly is a bit of a black art since it can be somewhat cryptic.

What is difference between programming microcontroller in C and programming in Arduino?

The difference is that the Arduino core includes a set of functions and classes (C++) to make Arduino boards easier to program.

Is it good idea for beginners to start programming microcontrollers in Arduino and then start learning programming in C?

The whole idea with Arduino is to make it much easier to start embedded programming in C and/or C++.

I have Arduino Uno board Atmega328P-PU microcontroller. What are some other microcontrollers which can be used with this board? What are differenes between various microcontrollers which are used with this board?

None. This is the controller for that board (though there are "smaller" versions).

If microcontroller is already programmed, can we download program from it to PC and edit it in Arduino IDE? Or it is like .exe on PC, once compiled we can't get source, only we can do is Reverse Eng.?

This you will have to explain better. Sounds like something bad and you should avoid that (or at least do not ask people to help you do a bad thing).

What is the difference between programming a microcontroller in C and programming in "Arduino?"

The default language is C++, but you can program in C. Thus the difference is "not much".

Is it a good idea for beginners to start programming microcontrollers in Arduino and then start learning to program in C?

Ah, if you program the Arduino you will be learning C. So "goodness" doesn't really enter into it.

I have Arduino Uno with an Atmega328P-PU microcontroller. What are some other microcontrollers which can be used with this board?

You could conceivably remove the chip and replace it with an Atmega168P. I'm not sure why you would want to.

What are differences between various microcontrollers which can be used with this board?

RAM, program memory (flash) size, and EEPROM size.

If a microcontroller is already programmed, can we download the program from it to a PC and edit it in Arduino IDE? Or it is like a .exe on a PC, once compiled we can't get source, all we can do is reverse engineer?

No. Like a PC, you can't get the source back. The compiler is a good, highly optimized one. The generated code won't look like the source.


text:
How does this eBay relay board connect to the Arduino
I bought a single channel relay on eBay and besides the NC/COM/NO, it has six pins and a jumper.

It is not possible to see the labels on the image, but the labels are:
X  X--X  X  X  X
VCC   -IN+   GND

The default jumper position is shown above with a - mark.
Which pins should I use for VCC, GND and ARDUINO? Is the jumper on the correct position?

Your module consists of both an optocoupler (large black rectangular device) and a P-channel MOSFET driver circuit for the relay.
VCC and GND are used to power the MOSFET and relay, and so should be connected to a power source suitable for driving the relay (if it's a 5V relay then the +5V and GND pins of the Arduino - if it's a 12V relay then a 12V power supply).
The interface to the Arduino is through the optocoupler. The Arduino sees that as just an LED, so you can wire it up just like any other LED.  The circuit contains a current limiting resistor already, so you don't need to worry about that at all.  So you connect the - of the input to GND and the + to an IO pin, or connect the + to +5V and the - to the IO pin, depending on which polarity of drive you want to have.
The jumper is optional to allow you to create one of those two links on the board - say connecting - to GND or connecting + to VCC so you don't need the extra wire.

I tried it and I was able to control the relay (there is a led to indicate the relay state), but the relay itself apparently didn't active (no sound) and the NC/COM didn't switch to COM/NO. Is this a faulty relay?

It may be, but unlikely. Be sure that you are providing the right voltage to VCC.

You should do a bit of testing. The Vcc and GND pins will go to power and ground respectively. They are powering the circuitry on the board that protects the Arduino from the relay coil. Then it looks like the IN pins allow you to operate the relay either from an active high or an active low signal.
If you have a DMM check the connections of the pins (see if any of them are common). The thing that is puzzling to me is the jumper, but it may be set up so that you can use only two wires to control the relay by using the IN terminal to also supply either Vcc or ground.
So start out by hooking up to power and ground, and then test by jumping the IN pins to ground and power in turn. I would expect the relay to operate when the IN+ goes to Vcc or when the IN- goes to GND.

The two VCC pins and the two GND pins are common. I was able to control it with the other answer.


text:
MQ135 Gas Sensor Calibration
I have bought a MQ135 gas sensor. I have read online from multiple sources that a calibration/warm-up period of between 12-24hrs is required for the sensor to give its most accurate readings. I currently have it attached to one of my UNO's just spitting out Analog readings to the Serial monitor and seems (just after an hour!) to have settled at a reading of 50 which it has stayed at now for a period of around 20 minutes. My questions surrounding this process really are:

What is the point in doing this process if when a project that uses this sensor is powered off for some number of hours? Will you have to let it warm-up/calibrate again before having faith in the readings?
How do I actually identify PPM for a gas such as C02? Is there some form of constant that I should be comparing the reading obtained to or something similar?

Welcome to Arduino SE.  Feel free to take the tour at https://arduino.stackexchange.com/Tour that will help you get the most from this site.  The warm-up period has to do with the physics of how the sensors work.  This is a device primarily used with Arduino so I believe it is OK here.  But you might want to edit your post to indicate which kind of Arduino you are using and show some of your code so you can pose an Arduino-specific question.

By my opinion, it is impossible to calibrate these solid electrolyte based sensors. I achieved best results when I measured the CO2 level in 5 minute intervals, by heating the sensor for 100 seconds. I cant remember these times precisely, but by heating and allowing it to cool down I was able to get quite reliable results. But then I realized that the sensor is getting some offset. If you want to do a two-point calibration, you can put it to fresh air, it should read about 0.04%, or you can breathe directly to the sensor for a short while and it shoud read 4%. But I highly recommend using NDIR CO2 sensor, those are used in home air monitoring devices.


text:
Arduino Due & Spec gas sensor - how to choose specific information from a stream of incoming bytes to store
I'm trying to build an air pollution sensor for a college project, with an Arduino Due and a series of Spec Sensors digital gas detectors. However, I'm having a little trouble getting the first one of them (Carbon Monoxide, https://www.spec-sensors.com/product/digital-co-sensor/) to behave, before I can run multiple. As they're all the same sensor setup but for different gasses, once I get the first one working, the rest should follow easily.
The code's very simple, as it uses Spec's own command system - sending the letter "c" to the sensor forces it to take one reading per second for as long as the sensor is powered, and then the serial monitor displays whatever comes back:
    void setup() {
      // sensor running via Serial1
      Serial.begin(9600);
      Serial1.begin(9600);
      Serial1.print("c");
    }

    void loop() {
      if(Serial1.available()!=0)
      {
        Serial.write(Serial1.read());
      }
    }

My problem comes with the data that's being returned. The gas reading is present, but so is a lot of superfluous information that I don't need. According to the sensor's tech document, the information returned is: serial number, reading (ppb), temperature, humidity, raw voltages, and amount of time the sensor has been running for. In the serial monitor, it looks like this:

Right now, all I want is the reading in ppb (the second value), either as the only data coming through or being stored, so that it can then be used in calculations like averages per hour. The trouble I have is that this information appears to be coming through as a stream of individual bytes, and in this format I'm having difficulty working out an effective way to specify which information I want to store, and which I want to ignore.  I've been trying, for example, to come up with a way to specify that the first 14 bytes (serial number, comma, space - as this will always be the same length) should be ignored, and then the next series (up until the next comma - as this reading could be 4-6 digits) be stored as an int, or something, but I just can't seem to get anywhere no matter what I try. Does anyone have any suggestions?

note: the 1 second continuous read seems to be undocumented

Since the length of each data varies, you should extract data using spererator like comma in the stream.
First, get one data line from sensor. Read the string until the "Line feed(LF)" character or "Carriage Return(CR)" character appears. located at the end of line(EOL), these two characters seperates each string by changing line. Without these two characters, the monitor shows the stream like this(no line change).

102617010933, 8486, 22, 35, 13464, 25716, 21962, 00, 00, 20, 06102617010933, 87216, 22, 35, 13576, 25223, 21442, 00, 00, 20, 07

So you can see there are CR, LF characters at the EOL. Utilize CR or LF as a terminator of ReadStringUntil() function.
https://www.arduino.cc/en/Serial/ReadStringUntil
Second, parsing process. This process is extracting data you want from strtok() function. strtok() is from C language. It divides string by seperator characters.
https://stackoverflow.com/questions/3889992/how-does-strtok-split-the-string-into-tokens-in-c?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa
Lastly, utilize the data and repeat whenever sensor sends the data.
I'm not expert at coding. I haven't tested the code below. But this code would be helpful.
int data[12];
int isDataReceived = false;

void setup(){
  Serial.begin(9600);
  Serial1.begin(9600);
  Serial1.write('c');
}

void loop(){
  while(Serial1.available()>0) {
    String inString = Serial1.readStringUntil('\n');
    char * pch = strtok(inString, ","); //Serial number would be ignored
    for(int i=0; pch != NULL; i++) {    //following data are stored in data[12] string
      pch = strtok(NULL, ",");
      data[i] = atoi(pch);
    }
    isDataReceived=true;
  }
  if(isDataReceived) {
    Serial.print("Data:");
    Serial.println(data[0]); //just example code. You may see ppb on the serial monitor.
    isDataReceived=false;
  }

}


text:
How to connect to MQTT broker from NodeMCU with SSL?
I cannot connect to a MQTT broker from a NodeMCU, when using SSL.
This is the error message:

Attempting MQTT connection...failed, rc=-4 try again in 5 seconds.

When connecting to the same broker via other software like MQTTX or IOT MQTT panel, it does work fine, just the NodeMCU doesn't connect. What does work is using a local IP and port 1883, but as soon as I use the public mqtt broker IP and port 8883, the NodeMCU cannot connect.
I am probably overlooking something. Is it necessary to include the server certificates in the arduino code?
This is the mosquitto.conf:
persistence true
persistence_location /var/lib/mosquitto/
log_dest file /var/log/mosquitto/mosquitto.log

include_dir /etc/mosquitto/conf.d
password_file /etc/mosquitto/passwd

listener 1883
listener 8883
certfile /etc/mosquitto/certs/server.pem
keyfile /etc/mosquitto/certs/server.key

And here is the sample Arduino Code.
#include "ESP8266WiFi.h"
#include "PubSubClient.h"
#include <SPI.h>
#include <Wire.h>

const char* ssid = "MyWiFi";
const char* password = "MyBassword";

const char* mqtt_server = "MyMqttServer";
const char* mqtt_username = "MyUser";
const char* mqtt_password = "MyBassword";
int mqtt_port = 8883;

const char* mqtt_id = __DATE__ " " __TIME__;  //compile date that is used for a mostly unique identifier

WiFiClient espClient;
PubSubClient client(espClient);

void setup()
{
    Serial.begin(115200);
    setup_wifi();
    setup_mqtt();
}

void setup_wifi()
{
    delay(10);
    WiFi.begin(ssid, password);

    while (WiFi.status() != WL_CONNECTED)
        {
            delay(500);
            Serial.print(".");
        }

    Serial.println("WiFi connected");
    Serial.println(WiFi.localIP());
}

void setup_mqtt()
    {
        client.setServer(mqtt_server, mqtt_port);
        client.setCallback(callback);

        Serial.println("Modbus RTU Master Online");
    }

void callback(char* topic, byte* payload, unsigned int length)
    {
        Serial.print("Message arrived [");
        Serial.print(topic);
    }

void reconnect()
    {
        // Loop until we're reconnected to MQTT
        while (!client.connected())
            {
                Serial.print("Attempting MQTT connection...");
                // Attempt to connect
                if (client.connect(mqtt_id, mqtt_username, mqtt_password))
                    {
                        Serial.println("connected");
                    }
                else
                    {
                        Serial.print("failed, rc=");
                        Serial.print(client.state());
                        Serial.println(" try again in 5 seconds");
                        // Wait 5 seconds before retrying
                        delay(5000);
                    }
            }
    }

void loop()
{
    delay(1000);

    if (!client.connected())
        {
            reconnect();
        }

    client.loop();
}

use WiFiClientSecure espClient;

That changes the error from rc=-4 to rc=-2. When removing the certfile and keyfile from mosquitto.conf, the NodeMCU can connect via port 8883, but that defeats the purpose of using the cert.


text:
ESP32-WROOM-32 Wifisecureclient read() result in gibberish data
We are testing our own library with ESP32-wroom-32.
In the .cpp file we have:
void HttpDownstreamClient::tokenCreate(char* URL, char* Subname, char* Suber, int expiretime) {

  Serial.print("The subscription is associated with the Subscripter: ");
  Serial.println(Suber);

  StaticJsonDocument<200> root;

  root["subscriber"] = Suber;
  root["subscription"] = Subname;
  root["expiresInMinutes"] = expiretime;
  String body2send = "";

  serializeJsonPretty(root, body2send);

  if (_networkClient->connect(URL, 443)) {
    Serial.println("Connected to the server to request token!");
    // Make a HTTP request:
    _networkClient->println("POST /notification2/token HTTP/1.1");
    _networkClient->print("Host: ");
    _networkClient->println(URL);
    _networkClient->print("Authorization: Basic ");
    _networkClient->println(_base64);
    _networkClient->println("Content-Type: application/json");
    _networkClient->print("Content-Length: ");
    _networkClient->println(body2send.length());
    _networkClient->println("Accept: application/json");
    _networkClient->println();
    _networkClient->println(body2send);

  }

while (_token.length() == 0) {
    String msg = "";
    while (_networkClient->available()) {
      char c = _networkClient->read();
      msg += c;
    }
    Serial.println(msg);
    int start_init = msg.indexOf("\"token\"");
    int start = msg.indexOf(":",start_init);
    int until_n = msg.indexOf("\"", start + 3);
    Serial.println(until_n);
    if (start != -1 && until_n != -1 ) {
      _token = msg.substring(start + 2, until_n);
      Serial.print("Token is: ");
      Serial.println(_token);
     }
  }

}

_token is an internal string style variable where the token shoud be stored.
In .h we have the following:
class HttpDownstreamClient{

 private:

 String _token;
 char* _base64;
 //char* _msgToken;
 //String _deviceID;

#if defined(ARDUINO_ARCH_ESP32)
  //Base64 encoder for ESP32
  void base64ESP(char* username, char* password);
#else
  //Base64 encoder for none ESP32 board
  void base64(char* username, char* password);
#endif

 public:

 Client* _networkClient;

The .ino file is as following:
#include <HttpDownstream.h>
#include <WiFi.h>
#include <WiFiClientSecure.h>

WiFiClientSecure wifisecure;
HttpDownstreamClient c8yclient(wifisecure); //initiate the HttpDownstreamClient

char* host = "hello.cumulocity.com";
char* username = "hello";
char* password = "hello";
char* device_id = "13225";

//Subscription Test
char* SubscriptionName = "NotificationV2Test11";
char* SubscriberName = "Test2Sub1";
char* APIs = "measurements";
char* typeFilter= "";
char* fragmentsToCopy= "";
int expiretime = 1100;

char ssid[] = "hello";        // your network SSID (name)
char pass[] = "hello";    // your network password (use for WPA, or use as key for WEP)
int status = WL_IDLE_STATUS;

void setup()
{
    Serial.begin(115200);
    delay(10);

 wifisecure.setInsecure();
 while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
    status = WiFi.begin(ssid, pass);

    // wait 5 seconds for connection:
    delay(5000);
  }

 Serial.println("Connected to WiFi");

  c8yclient.tokenCreate(host, SubscriptionName, SubscriberName, expiretime);
  //delay(6000);
  //c8yclient.connectWSS(host,SubscriberName);
  //delay(5000);

}

void loop()
{
  while (wifisecure.available()) {
    char c = wifisecure.read();
    Serial.print(c);
  }

}

The problem is that I will get a result like following:
21:31:57.993 -> The subscription is associated with the Subscripter: Test2Sub1
21:31:58.033 -> Connected to the server to request token!
21:31:58.073 -> ⸮

I really don't know that how does the gibberish "⸮" come from. The baud rate is 115200 in both begin() method and serial monitor.
What is causing this?

Shouldn't Client* _networkClient; be WiFiClientSecure* _networkClient? How do you initialise the _networkClient as your HttpDownstreamClient doesn't seem to have a constructor to initialise the _networkClient?

@hcheung WiFiClientSecure wifisecure;
HttpDownstreamClient c8yclient(wifisecure);

@hcheung But the WifiClientSecure is the subclass of Client. I have tried with other boards, it is not a problem.