How to calibrate and use MQ-7 gas sensor? Could anyone help me calibrate and use the MQ-7 sensor?

I've read guides, but some say I need RO, offset or heating cycles for calibration.

This is the datasheet.  The output is not in PPM, but logarithmic to the PPM.

This Instructables guide,  Arduino CO Monitor Using MQ-7 Sensor, may help you, but calibration is required, preferably using a CO meter and, yes, heating-cooling cycles are required, in order to get the most accurate results. As the guide emphatically states:

  WARNING: SENSOR REQUIRES MANUAL CALIBRATION FOR ANY PRACTICAL USE. WITHOUT CALIBRATION, DEPENDING ON PARAMETERS OF YOUR PARTICULAR SENSOR, THIS SKETCH MIGHT TURN ON ALARM IN CLEAN AIR OR NOT DETECT LETHAL CARBON MONOXIDE CONCENTRATION.

Here is the sensor calibration part of the guide (just to give you an idea of what is involved). There are additional preparatory steps beforehand, that need to be followed, so you need to read the complete guide really:

  Step 7: Sensor Calibration

  According to manufacturer's datasheet, sensor should be running
  heating-cooling cycles for 48 hours in a row before it can be
  calibrated. And you should do it if you intend to use it for a long
  time: in my case, sensor reading in clean air changed for about 30%
  over 10 hours. If you won't take this into account, you can get 0 ppm
  result where there is actually 100 ppm of CO. If you don't want to
  wait for 48 hours, you can monitor sensor output at the end of
  measurement cycle. When over an hour it won't change for more than 1-2
  points - you can stop heating there.

  Rough calibration:

  After running sketch for at least 10 hours in clean air, take raw
  sensor value in the end of the measurement cycle, 2-3 seconds before
  heating phase starts, and write it into sensor_reading_clean_air
  variable (line 100). That's it. Program will estimate other sensor
  parameters, they won't be precise, but should be enough to distinguish
  between 10 and 100 ppm concentration.

  Precise calibration:

  I highly recommend to find a calibrated CO meter, make 100 ppm CO
  sample (this can be done by taking some flue gas into syringe - CO
  concentration there can easily be in the range of several thousands
  ppm - and slowly putting it into closed jar with calibrated meter and
  MQ-7 sensor), take raw sensor reading at this concentration and put it
  into sensor_reading_100_ppm_CO variable. Without this step, your ppm
  measurement can be wrong several times in either direction (still ok
  if you need alarm for dangerous CO concentration at home, where
  normally there should be no CO at all, but not good for any industrial
  application).

  As I didn't have any CO meter, I used a more sophisticated approach.
  First I prepared high concentration of CO using combustion in isolated
  volume (first photo). In this paper I found the most useful data,
  including CO yield for different flame types - it isn't in the photo,
  but the final experiment used propane gas combustion, with the same
  setup, resulting in ~5000 ppm CO concentration. Then it was diluted
  1:50 in order to achieve 100 ppm, as illustrated in the second photo,
  and used to determine sensor's reference point.

However, how accurate this guide is, is anyone's guess, to be honest.


How to program for two Arduinos with different code but share one same .h? I am now programming for two Arduinos. One is used as Tx and the other is Rx. Of course they are programmed by different codes, but they share some same .h files I programmed(let's say 'share.h'), which are not libraries and shouldn't be put in Arduino's 'library' folder.

So I put 'share.h' and main.ino in one folder, and the ino is like:

#include "share.h"
#define TX
#ifdef TX
void setup(){...something for Tx...}
void loop(){...}
#else
void setup(){...something for Rx...}
void loop(){...}
#endif

The shortage is that every time I want to update my code to the two unos, I have to: first change the board port to 40(the Tx uno) in ide, add the #define line, and upload. Then I have to change port to 42(the Rx one), comment the #define line and upload. So inconvenient!

So do you have any good ideas? Much appreciation!

I confronted this exact issue a little while back when writing some sketches that hard shared information. In particular github.com/nickgammon/arduino_sketches

Whilst another IDE may help, I wanted to make my sketches usable by people with the default IDE.

There are a few (annoying) issues here:

You can't use relative folders as suggested in another answer, because the IDE copies your current sketch folder to a temporary folder and compiles from there. It won't copy other nearby folders that happen to be mentioned in .h files.
You can make soft links (in Linux anyway) as suggested, however that makes it hard to do Git control on them. My first attempt had the link (only) appear in GitHub, which meant that the links didn't compile, once you downloaded them (via the .zip file option in GitHub).
I switched to hard links, but then had another issue. If you edit a file in the IDE, and save it, evidently this becomes a new file, and so the files in other folders, which are now hard-linked, have the older version and not the newer version.

The best solution I could come up with (and I am open to suggestions) was to have a "master" sketch - which has the "real" files you want to include. The other folders have links to them. However if you change the master folder you have to recreate the hard links. I wrote a shell script to do that, but it is still an ugly solution. However since it is a manual process anyway, under Windows you could simply make a copy of the files, when you change the master one.

The other (simpler) alternative would be to make a library, and then simply change the files in that library. That gives you better Git management. The only thing is that you have to edit the library, and then go and test the sketch. It's not that bad.

  And I found that after I added the h as library, no matter how I change the content of the h, the first version is always used in ide.

That shouldn't happen unless the IDE doesn't expect the library to change in-between compiles. If that is the case, even the library idea has flaws.


State Machine with If/Else? I am trying to make a state machine with if/else. But some of the code does not seem to be executing. I have information being displayed on an LCD screen so I know where it is, and it stays on Todo=1 and does not go to the next state. I have tried using switch/case and it works. But I think it might be better for my project if I use if/else. Can I do this using if/else?

Void loop{
  if (state == PLAY) {
    Todo = 1;
    Mastermachine(Todo);
  } else if (state == TRYAGIN) {

  }
}

void Mastermachine(int Todo) {
  if (Todo == 1) {
    lcd.setCursor(16, 2);
    lcd.print(String(Todo));
    SongSeq[largestindex];
    for (int index = 0; index < largestindex; index++) {
      SongSeq[index]();
    }
    Todo = 2;
  } else if (Todo == 2) {
    for (learnindex = 0; learnindex < largestindex;) {
      MIDI.read();
      if (learnindex >= largestindex) {
        Todo = 3;
      }
      lcd.setCursor(16, 2);
      lcd.print(String(Todo));
    }
  } else  if (Todo == 3) {
    if (array_cmp(learn, note, largestindex, largestindex) == true) {
      largestindex++;
      delay(2000);
      Todo = 1;
    } else {
      delay(2000);
      Todo = 1;
    }
    lcd.setCursor(16, 2);
    lcd.print(String(Todo));
  }
}

Inside Mastermachine(), Todo is a copy whatever is passed as its paramter. Even if you make a global named Todo, it will be 'hidden' by the parameter of the same name. That parameter goes out of scope - disappears - when Mastermachine() exits, including any changes made to it within the function.

There are a few choices to accomplish what you want to do, but the easiest is probably to make a global Todo and get rid of the parameter Todo in Mastermachine(); i.e., make it void Mastermachine(void). Then the name Todo inside the function will refer to the global by that name.


Send HTTP get request from GSM SIM800c and Arduino I am trying to send Get request from my GSM Module but after connecting to server it is not responding any thing

#include <SoftwareSerial.h>
SoftwareSerial myGsm(2,3);
void setup()
{
myGsm.begin(9600);
Serial.begin(9600);
delay(500);
myGsm.println("AT+CGATT=1");
delay(200);
printSerialData();
myGsm.println("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"");//setting the SAPBR,connection type is GPRS
delay(1000);
printSerialData();
myGsm.println("AT+SAPBR=3,1,\"APN\",\"wap.mobilinkworld.com\"");//setting the APN,2nd parameter empty works for all networks
delay(5000);
printSerialData();
myGsm.println();
myGsm.println("AT+SAPBR=1,1");
delay(10000);
printSerialData();
myGsm.println();
myGsm.println("AT+SAPBR=2,1");
delay(10000);
printSerialData();
myGsm.println("AT+HTTPINIT");
delay(2000);
printSerialData();
myGsm.println("AT+HTTPPARA=\"URL\",\"http://sensor.somee.com/api/Data/GetData?SensorID=1\"");// setting the httppara,
delay(1000);
printSerialData();
myGsm.println();
delay(10000);//the delay is important if the return datas are very large, the time required longer.
printSerialData();
delay(9000);
printSerialData();
delay(1000);
Serial.println("done ");
printSerialData();
}
void loop()
{
}
void printSerialData()
{
while(myGsm.available()!=0)
Serial.write(myGsm.read());
}

and the Out put is

AT+CGATT=1

OK
AT+SAPBR=3,1,"CONTYPE","GPRS"

OK
AT+SAPBR=3,1,"APN","wap.mobilinkworld.com"

OK

AT+SAPBR=1,1

OK

AT+SAPBR=2,1

+SAPBR: 1,1,"10.209.122.68"

OK
AT+HTTPINIT

OK
AT+HTTPPARA="URL","http://sensor.somee.com/api/Data/GetData?Sen
done

You haven't instructed the module to make a request yet.
With the AT+HTTPPARA command, you are just configuring the request you want to make. In your case, you just specified the URL you want to call.
Next, you have to send
AT+HTTPACTION=1

to make the actual request using the HTTP GET method, and then you can read the HTTP response using
AT+HTTPREAD

Keep in mind that after AT+HTTPACTION you will receive an unsolicited result code in the format
+HTTPACTION: <Method>,<StatusCode>,<DataLen>

this will happen after the module will actually do the request and will have the response.


Why does my Arduino Nano send the wrong voltage on a digital output PIN? Adruino nano powered by 12v through VIN pin.

Normally I expect ~12v on digital output pin, when i write HIGH to this pin, and ~0v when i write LOW. But what I have instead

digitalWrite(pin, HIGH); // I have 1.5v on pin
digitalWrite(pin, LOW);  // I have 0.5v

Algorithm is quite simple - On push button toggle output pin state.
Connections:

VIN - +12v
GND - ground
d2 - input pin (0 0, 12 - 1, button);
d3 - output pin (we change state of this pin)

Input works as expected.

simulate this circuit – Schematic created using CircuitLab

The microcontoller in an Arduino operates on 5 Volts (or perhaps 3.3 Volts).  An on-board voltage regulator reduces the 12 Volt input to 5 volts for the ICs on the board.

Connecting the pull-up resistor (R1 in your drawing) to 12 Volts may damage the microcontroller (especially if it is really 100 Ohms as your drawing shows).  The pullup resistor must be connected to the 5 Volt pin on the Arduino board.

The output voltage of an Arduino pin should be near 5 Volts, but may be less if you place a heavy (high-current) load on it.


Code for ESP32 without Development Board I'm very new to microcontrollers. I'd like to start developing for the esp32, as it has integrated wifi & bluetooth for quite cheap. This being said, i don't have a board yet. Is there a way i can emulate an esp32 board, so i can start programming and debugging my code?
As i'm very new, any advice is welcome.
Thanks

Welcome to Arduino Stack exchange. There are a lot of discussions and half-completed, or project-specific models available for the ESP32 simulator. My sincere advice is to go ahead and buy real hardware. By the time you take to set up the simulators (download the repo, set environment variables, connect GDB debugger or other), you would have received the ESP32 hardware itself.
Why you should go for real hardware?

An emulator can never match the timing of real ESP32 hardware. if you
have any timing-related issue, you cannot fix it using an ESP32 emulator
Real issues in hardware (bounce/debounce of switches, surge current and brownout voltages, rise time and reflections etc - won't appear in the ESP32 simulators
EMC issues due to floating inputs, Port pin current limits or even self-heating of components are not considered in most the simulators
A code running on the emulator can't always run on the real hardware without modifications, especially when it involved multiple threads and priorities

Still, other options are available online but it depends on your comfort

ESP32 simulator from mireq - ESP-IDF contains a small amount of hardware-specific code, FreeRTOS and few multi-platform libraries. This project uses FreeRTOS port for POSIX, LWIP for TCP/IP layer and mbedtls for cryptography functions.
In addition, several useful APIs from esp-idf are implemented eg. logging. With this project, you can write a program, which will be runnable and testable on Linux.

ESP32 machine emulator - The purpose of this package is to enable you to test-drive (TDD) your MicroPython code in an IDE running on your computer. It seems a lot of people are test-driving python, but not many are test-driving MicroPython. That’s understandable, since many MicroPython projects are simple, and emulating real hardware in a test environment is difficult.

Bridges - Pretend your PC a Raspberry Pi or an ESP32 to connect I2C / SPI / GPIO / UART peripherals.

Note You should also check when is the last time the projects were updated. THe latest ones and active ones are always a better choice as they are expected to have better usability, and stable simulations.


Which library to use for 23LC1024 SRAM 1 Mbit I noticed there are quite some libraries for the 23LC1024 SRAM 1 Mbit memory:

SpiRam Extended library
SpiRam library
Direct SPI ?

I tried 1 and 3 so far. What I noticed was that to read 1 byte took around 18 us for the 3th solution and around 25 us for the first library. However, the first has possibilities to read multiple bytes and that considerably speeds up the time.

Also there are other libraries like MQTT and possibly I missed some.

However, in all cases I would expect speeds around just a few us. Since I maybe need to read 100 of different small groups of bytes preferably within 10 us (and process them), it might get problematic in worst case scenarios.

Does anybody know where the speed differences come from or if there are ways to increase the speed or which library is fast?

SPI RAM has two modes of operation: single byte and "page mode".

In single-byte mode you first send the read or write command followed by the (typically 3-byte) address and then read a byte. That's 5 bytes per transaction, or 40 SPI clock cycles. At the maximum of 8MHz (SPI_CLOCK_DIV2 on a 16MHz MCU) that would be at absolute best (1/8000000*40) 5µS per byte read or written. That's not including the time taken to toggle the CS pin and perform the other software-level parts of controlling the SPI peripheral.

In page mode it is possible to send one start address and then read or write sequential data from that address upwards. Ideal if you need to read a larger number of bytes that are sequentially in memory. For instance, to read 100 bytes sequentially it would take 104 SPI bytes - one for the read/write command, three for the start address, and 100 for the data. That is 832 SPI clocks, or at 8MHz, 104µS.

As you can see, reading 100 bytes within 10µS is not possible on an Arduino with SPI SRAM. There just isn't enough speed. Even 100 sequential bytes. 100 "small groups of bytes" just ain't gonna happen.

There are other technologies that are faster which may be more suited to your use, but they require different peripherals in the chip (namely SQI), and the chips with that in tend to be more powerful and have more RAM anyway, so your 1Mb of external SRAM would be redundant.


Yún boot from SD card I have an Arduino Yún, and it only has 16mb flash onboard for the Linux. I was wondering of it is possible to put a bootloader on the flash that uses the sd card as a rootfs? i want to be able to do more projects on it than those that can fit in 16 MB flash.

And the Arduino team finally figured it out:

http://blog.arduino.cc/2014/05/06/time-to-expand-your-yun-disk-space-and-install-node-js/


Using a 16 bit ADC chip with arduino I need to measure voltage between 0-10 volts using my Arduino Due.  I have an ADS7805p chip, which I believe will work, but am not sure how to wire it on my breadboard.  I'm used to just using the chip on the arduino, but that only goes 0-5 volts and I can't loose the resolution by converting.  Can someone, please, point me to or instruct me on how to wire something like this to my arduino?

The ADS7805 is old but still a pretty good ADC. I could imagine that you just have a few lying around that you want to use. I would simply wire it to two parallel in / serial out chips like the 74HC589 or CD4021 as used in this example:
http://www.arduino.cc/en/Tutorial/ShiftIn

Start the conversion as described in Duncan C's answer and then simply clock in all 16 bits. I think you could then probably get away with 4 or 5 control lines.


How to get current Date How to get Current date, month and year. I have used RTC, NTPClient, but it didn't work. This gives default output of 1970. What can I do for fixing it.

time_t now = time(nullptr);
struct tm* newtime = localtime(&now);
String tmpNow = "";
tmpNow += String(newtime->tm_year + 1900);
tmpNow += "-";
tmpNow += String(newtime->tm_mon + 1);
tmpNow += "-";
tmpNow += String(newtime->tm_mday);
tmpNow += " ";

An example how to use NTPClient is available at the projects github

#include <NTPClient.h>
// change next line to use with another board/shield
#include <ESP8266WiFi.h>
//#include <WiFi.h> // for WiFi shield
//#include <WiFi101.h> // for WiFi 101 shield or MKR1000
#include <WiFiUdp.h>

const char *ssid     = "<SSID>";
const char *password = "<PASSWORD>";

WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP);

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

  WiFi.begin(ssid, password);

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

  timeClient.begin();
}

void loop() {
  timeClient.update();

  Serial.println(timeClient.getFormattedTime());

  delay(1000);
}

Form what I found TimeRTC requires an external device called DS1307RTC to keep track of the time as shown in video here and with it we should be able to get the real time as seen in github example

#include <TimeLib.h>
#include <Wire.h>
#include <DS1307RTC.h>  // a basic DS1307 library that returns time as a time_t

void setup()  {
  Serial.begin(9600);
  while (!Serial) ; // wait until Arduino Serial Monitor opens
  setSyncProvider(RTC.get);   // the function to get the time from the RTC
  if(timeStatus()!= timeSet)
     Serial.println("Unable to sync with the RTC");
  else
     Serial.println("RTC has set the system time");
}

void loop()
{
  if (timeStatus() == timeSet) {
    digitalClockDisplay();
  } else {
    Serial.println("The time has not been set.  Please run the Time");
    Serial.println("TimeRTCSet example, or DS1307RTC SetTime example.");
    Serial.println();
    delay(4000);
  }
  delay(1000);
}

void digitalClockDisplay(){
  // digital clock display of the time
  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  Serial.print(" ");
  Serial.print(day());
  Serial.print(" ");
  Serial.print(month());
  Serial.print(" ");
  Serial.print(year());
  Serial.println();
}

void printDigits(int digits){
  // utility function for digital clock display: prints preceding colon and leading 0
  Serial.print(":");
  if(digits < 10)
    Serial.print('0');
  Serial.print(digits);
}

If what I understand from your code you are actually not using any RTP or NTP. You are only creating a Time object with no values and you read it default values.

Check some more examples here


Arduino and XBee Series1 I have actually reap 3 numerical values (3 sensors) from a remote XBee module and then manipulate these 3 signal with an Arduino card attached to another XBee module. To do this, I chose to use the IO line passing because it proved the easiest. My problem is this: for the XBee transmitter, I set:

ATID 3001
ATDL 2
ATMY 1
ATIU 1 / / to activate the IO option
ATD0 3 / / where is plugged a pushbutton
ATD1 3 / / where is plugged another pushbutton
ATD2 3 / / where is plugged proximity sensor (presence)

For the XBee receiver (the one connected with the arduino board):

ATID 3001 ATDL 1 ATMY 2 ATIA 1
ATD0 4
ATD1 4
ATD2 4

Where I'm stuck is on the Arduino programming. Which command is used to determine the change of state of xbee remote? because I want to know if the states of the sensors on input are high or low.

There are two ways this could be tackled:

physically through connections between the xbee and arduino and read the xbee pins directly (I've never done this, and it comes down to your shield supporting it). Each of the desired output pins of the receiving xbee would be tied to a GPIO pin of the arduino. Alternatively,
serially using AT commands via the serial connection.

I have never worked with series one, but essentially:

setup a serial connection to your arduino
send the desired AT command requesting the pins value
read the serial port response

Make sure to read the manual for the series 1 xbees for the right AT commands and in how to interpret the results. Register at digi and download the datasheet.

Also, just realise reading the xbee data is going to be different depending on how you have the xbee setup, ie API vs AT mode.

Here is someone who has done some work with series 1: http://www.johnhenryshammer.com/WOW2/pagesHowTo/xbeeSeries1.php#index

I'll leave the actual implementation to you since this sounds a little like a homework assignment. Give it a go using the second method above and see how you go. Then post back here (ie update the question) including source code and exact layout (schematic preferred) and we'll see where we can help you from there.

Hint: google such terms as: "read data pins xbee arduino" (without the quotes).


Problem with String& argument of a function I am trying to send SMSs using a GSM module with Arduino Mega. I have followed a tutorial and downloaded the SIM908IDE100 library. I am using the function

SendSMS(String&, const char [27]);.

It works fine when I type:

sms.SendSMS("1234567890","Text message");

where "1234567890" is the telephone number I want to send the SMS to and "Text message" is the text of the SMS.

If I instead try to pass to the function a String containing the telephone number

String number = "1234567890";
sms.SendSMS(number,"Text message");

I get the following error:

exit status 1
no matching function for call to 'SMSGSM::SendSMS(String&, const char [27]);'

I don't understand what String followed by an ampersand means. What am I supposed to pass the function as its first argument?

The function prototype in sms.h is

char SendSMS(char *number_str, char *message_str);

if number is String, you should have

sms.SendSMS((char*) number.c_str(),"Text message");

c_str() is a function of the Strinng class. It returns a pointer to internal char array of the String object.

The cast to char* is necessary because the author of the library didn't make the parameter constant with const char*. (It is a good practice, to declare pointers and references as constants.)

The error message no matching function for call to 'SMSGSM::SendSMS(String&, const char [27]); shows the arguments you try to use. String& is reference to some instance of the String type


Wiring 5V ultrasonic sensor to Arduino Due Is it possible to use the 2760342 ultrasonic range sensor with an Arduino Due? The docs say it takes a 5V input, but doesn't specify the output, but I'm assuming it also outputs a 5V signal. Does this make it incompatible with the Due?

I've tested it with an Uno, it it works flawlessly. I've been researching using a Due and some other ARM based single-board computers, but they all seem to use 3.3V, while almost all Arduino shields and sensors use 5V. I'm hesitant to "upgrade" to these boards if I have to purchase an entire new set of shields and sensors. And I have no interest in hacking in some clunky custom voltage level shifter. Why isn't everything standardized on 5V?

Is this too clunky?

https://www.adafruit.com/products/735

Breadboard Friendly 8-bit Logic Level Shifter, $1.50.


Can an Arduino power itself off [not low power mode] via software? I'm working on a sketch where an Arduino UNO performs no useful work after the first 10 minutes following power on.  It is not needed again until power to it is shut down, then re-enabled.  This may not happen for hours or even days.  No wake-up function is required, or deemed useful.

Of course, the Arduino could simply be left on as long as it's connected to its power source, but it will be placed remotely, and it seems [to me] safer to have it powered off. when not in use.

In essence, the Arduino is powered by a wall wart and plugged in with other devices fed by a switchable 120v power source.

I found a couple of possible hardware/software solutions to the problem but it isn't clear whether they would work in this situation.  Power consumption is not the issue here.

In general, an Arduino by itself has no control over its power input.  It can, of course, enter various Sleep modes, such as the Power-down mode with watch-dog-timer off, which uses 0.1  μA.

It isn't clear from the question what will turn the Arduino back on after it is off for a while, but if you have either a push-button or a signal to turn it back on, the Pololu 2808 Mini Pushbutton Power Switch will work as an Arduino-controlled off switch.  This board has On, Off, Ctrl, and button-contacts inputs.  If your Arduino raises the Off input, power shuts off cleanly.  To turn it back on, either connect the  button-contacts inputs together, or raise the On input, or pulse the Ctrl input.


Issues with CO2 sensor SEN0159 I followed the sketch example for the SEN0159 CO2 sensor as precised in the data sheet  https://www.dfrobot.com/wiki/index.php/CO2_Sensor_SKU:SEN0159. It's powered by a 9V/2A DC power supply more than 48h and it still reads 2.81V on the analog ouput pin even if i exhaust on the sensor during long time, nothing happen, giving - 1ppm CO2 value.

Can you explain me why i cannot observe CO2 variations ? Is there troubles with the board ?

Thanks!

Yes, i made a mistake... The arduino board should be powered by a 7-12V power supply to support high current from 5V pinout in order to power the sensor card... I'm very lucky, my sensor is not broken. I have powered it with 5V and it works fine!!! Thanks


How to combine Leonardo with Ultrasonic sensor? I am working on an Arduino project that replaces the computer mouse. I want to do this in combination with an ultrasonic sensor. I found some nice examples on youtube, but they didn't post the code. And an example on this website. But I don't get it completely. I don't have much Arduino skills, but do have some. How can you attach for example echoPinScroll to a board?

I hope someone can give me advice on how to use this ultrasonic to control my mouse!

#include <Mouse.h>

int echoPinCursor=2;
int trigPinCursor=3;

int echoPinBtn=4;
int trigPinBtn=5;
int echoPinScroll=6;
int trigPinScroll=7;
int x;
int y;
long duracionCursor, distanciaCursor;
void setup() {
 Serial.begin(9600);
 pinMode(trigPinCursor, OUTPUT);
 pinMode(echoPinCursor, INPUT);
 pinMode(trigPinBtn, OUTPUT);
 pinMode(echoPinBtn, INPUT);
 pinMode(trigPinScroll, OUTPUT);
 pinMode(echoPinScroll, INPUT);

}

void loop() {

//mover el cursor
int direccionx=moverx();
int direcciony=movery();

Mouse.move(direccionx, direcciony,0);
delay(2);

}

int moverx(){
distanciaCursor=obtener_distanciaCursor();
if (distanciaCursor >= 1  || distanciaCursor <= 11){
   x--;
 }
if (distanciaCursor >= 12 || distanciaCursor <= 24){
   x++;
  }
 return x;
}

int movery(){
distanciaCursor=obtener_distanciaCursor();
if (distanciaCursor >= 25 || distanciaCursor <= 37){
   y--;
   }
if (distanciaCursor >= 38 || distanciaCursor <= 50){
   y++;
  }
return y;
}

long obtener_distanciaCursor(void)
{
digitalWrite(trigPinCursor, LOW);
delayMicroseconds(2);

digitalWrite(trigPinCursor, HIGH);
delayMicroseconds(10);

digitalWrite(trigPinCursor, LOW);
duracionCursor = pulseIn(echoPinCursor, HIGH);

distanciaCursor = duracionCursor/58.2;
return(distanciaCursor);

}

What is your hardware setup?

From your code, it looks like you're not using the pins trigPinBtn, echoPinBtn, trigPinScroll, echoPinScroll. Weird. I can't figure out:

which ultrasound module you're using
what do you expect, eg which movement(s) in front of which ultrasound sensor shall generate which mouse action(s)

I would recommand having an iterative approach:

Play with your ultrasound sensor(s), eg understand properly how to wire them to the arduino, how to interface them (software/lib), what kind of values you can get from them, etc... This will depend on the HW module you have chosen (if any yet).
Read the documentation that comes with the mouse lib of the Leonardo and play with it independently/with existing, working examples.

That is divide and conquer: understand each bit before trying to assemble them.

THEN, and only then, you will have a better understanding of the different part of your project. You will then be able to formulate an overview of your project goals, and how you can do it. That is, start documenting your project before it is done: doing so will force help you to have a clear idea of what it is that you're trying to achieve... and thus how to achieve it.

But yeah, the overall project might look something like this:

// Ultrasound distance sensor #1, hooked to the arduino with xxx and yyy; generates movement along the x axis
// Ultrasound distance sensor #2, hooked to the arduino with zzz and ttt ; generates movement along the y axis
// Something for the wheel? The buttons?

//global values & objects
setup()
//initialize hardware& libs

loop()
//get raw ultrasound distances
//translate these into x and y movements
//do something about buttons & wheel?
//update mouse values


read CID of SD card with SD.h library I would like to be able to read the serial numbers of SD cards using the SD.h library. Only reading the values is enough, I am not looking to modify the CID.
This should be possible but I do not have the programming skills to get it running.

I am using an esp8266 and already have the SD card running and working correctly. Only the chipselect needed to be modified for the SD library to work.

So far I have found this in Sd2Card.h

      /**
   * Read a cards CID register. The CID contains card identification
   * information such as Manufacturer ID, Product name, Product serial
   * number and Manufacturing date. */
  uint8_t readCID(cid_t* cid) {
    return readRegister(CMD10, cid);
  }
  /**

And in Sd2Card.cpp there is this:

/** read CID or CSR register */
uint8_t Sd2Card::readRegister(uint8_t cmd, void* buf) {
  uint8_t* dst = reinterpret_cast<uint8_t*>(buf);
  if (cardCommand(cmd, 0)) {
    error(SD_CARD_ERROR_READ_REG);
    goto fail;
  }
  if (!waitStartBlock()) goto fail;
  // transfer data
  for (uint16_t i = 0; i < 16; i++) dst[i] = spiRec();
  spiRec();  // get first crc byte
  spiRec();  // get second crc byte
  chipSelectHigh();
  return true;

 fail:
  chipSelectHigh();
  return false;
}

So it seems that the underlying code has been prepared in the library already, my question is how would I include it into a sketch like CardInfo.ino?

The method is visible from within your sketch. You just need to first create a cid_t struct like this in your sketch:

cid_t cid;  // at the top with the other globals

Then call readCID() anywhere in setup() after the card has been initialized.

card.readCID(&cid);
Serial.print("Serial number: "); Serial.println(cid.psn); // psn is the serial number field of the struct

Check out SdInfo.h for the other struct members.


Want to add an LCD display screen for the output motor I want add an LCD display screen at output motor. When the motor runs the LCD display show like "motor 1 run forward" and "motor 1 run reverse". I want it display for all motor but I don't know how code using arduino using 16x2 LCD display screen.

int motor_forward1 = 7;
int motor_reverse1 = 6;
int motor_forward2 = 5;
int motor_reverse2 = 4;
int motor_forward3 = 3;
int motor_reverse3 = 2;
int sensor1 = 13;
int sensor2 = 12;

 void setup()
{

   pinMode(motor_forward1, OUTPUT);
   pinMode(motor_reverse1, OUTPUT);
   pinMode(motor_forward2, OUTPUT);
   pinMode(motor_reverse2, OUTPUT);
   pinMode(motor_forward3, OUTPUT);
   pinMode(motor_reverse3, OUTPUT);
   pinMode(sensor1, INPUT);
   pinMode(sensor2, INPUT);
 }

 void loop()
 {
   if (digitalRead(13) == HIGH)
   {
     print
     digitalWrite(motor_forward1,1);
     digitalWrite(motor_reverse1,0);
     delay(5000);
     digitalWrite(motor_forward1,0);
     digitalWrite(motor_reverse1,1);
     delay(5000);
     digitalWrite(motor_forward1,0);
     digitalWrite(motor_reverse1,0);
     delay(1000);
   }
   else if (digitalRead(12) == HIGH)
   {
     digitalWrite(motor_forward2,1);
     digitalWrite(motor_reverse2,0);
     delay(5000);
     digitalWrite(motor_forward2,0);
     digitalWrite(motor_reverse2,1);
     delay(5000);
     digitalWrite(motor_forward2,0);
     digitalWrite(motor_reverse2,0);
     delay(1000);
   }
   else
   {
     digitalWrite(motor_forward3,1);
     digitalWrite(motor_reverse3,0);
     delay(5000);
     digitalWrite(motor_forward3,0);
     digitalWrite(motor_reverse3,1);
     delay(5000);
     digitalWrite(motor_forward3,0);
     digitalWrite(motor_reverse3,0);
     delay(1000);
   }
   delay(5000);
 }

From this instructable:

// include the library code:
#include <LiquidCrystal.h>

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

void setup() {
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.print(" **Text for line 1 of LCD**");
  lcd.setCursor(0, 1);
  lcd.print(" **Text for line 2 of LCD**");
  // THE REST OF YOUR SETUP
}

void loop() {
    if (digitalRead(13) == HIGH) {
        // I assume this is the motor going forward
        lcd.print("motor 1 run forward");
    }
}


C++ Adding Two 16 bit binary numbers together I am trying to add two 16 digit binary numbers together. Each binary number will have been entered by the user and saved as: int binaryOne[16] and int binaryTwo[16]. Originally,

int binaryOne[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
int binaryTwo[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};

are the values declared. Then, the user has the option to change these values using buttons that I implement before the Solution() function. So, once the used gets to the Solution() function, the numbers may be stored as:

int binaryOne[16] = {0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1};
int binaryTwo[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};

This is what I have so far:

void Solution() {
  /*
    Rule of binary addition:
    0 + 0 = 0
    1 + 0 = 1
    0 + 1 = 1
    1 + 1 = 1 and carry = 1
   */
   lcd.clear();
   lcd.setCursor(0,0);
   lcd.print("Solution");
   lcd.setCursor(0,2);

    int a[16] = binaryOne[16];
    int b[16] = binaryTwo[16];
    int i = 0;
    int remainder = 0;
    int sum[32];

    while(a[16] != 0 || b[16] != 0){
      sum[i++] = (a[16] % 10 + b[16] % 10 + remainder) % 2;
      remainder = (a[16] % 10 + b[16] % 10 + remainder) / 2;
      a[16] = a[16] /10;
      b[16] = b[16] / 10;
    }
    if(remainder != 0){
      sum[i++] = remainder;
    }
    i--;
    while(i>=0){
      lcd.print("%d", sum[i--]);
   }
   return 0;
}

I believe I am doing something wrong with calling the arrays since I am renaming them to a[16] and b[16] within this function. I'm also curious, since I only have 16 bits of space on the screen, what if the user enters a binary number such as 1111111111111111 + 1000000000000000 and therefor there is going to be a carry on that first digit? Would it be best just to have an error message?

A few issues here:

The way you “rename” the arrays is wrong, and furthermore there is no
point in doing such renaming.
There is no reason to divide by 10 (ten, in decimal) within your
code: as everything you do is binary, the number ten has nothing to
do with what are trying to accomplish.
While doing the addition, you forgot to loop over the bits.
You shouldn't return 0 in a function of type void. In fact, you
shouldn't return any value.

Fixing those issues should give you something similar to this:

void Solution() {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Solution");
    lcd.setCursor(0, 2);

    // Compute the sum.
    int sum[16];
    int remainder = 0;
    for (int i = 0; i < 16; i++) {
        int s = binaryOne[i] + binaryTwo[i] + remainder;
        sum[i] = s % 2;
        remainder = s / 2;
    }

    // Print it.
    for (int i = 15; i >= 0; i--) {
        lcd.print("%d", sum[i]);
    }
}

Note that there is no point in computing a 32-bit result if you can only
print 16 bits: just accept that the computation is done modulo
216, just like a 16-bit ALU would do, or the unsigned int
data type in the Arduino.

Of course, the whole idea of doing the computation one bit at a time is
highly inefficient. See Majenko's answer for a more idiomatic and
efficient way of managing numbers bit-wise in C and C++.


Can I mix 22awg and 26awg hookup wire in the same circuit? I'm still fairly new to Arduino projects, and am only just now getting into building circuits where I want to cut and place my own hookup wire instead of using the precut jumper wires. I inherited some supplies from a friend who abandoned the hobby, and about half of the wire he gave me is 22awg and the other half is 26awg. All of it is solid core copper. Is it ok to mix wire gauges like this in the same circuit/project?

Assuming you won't ever put more current through it than the 26AWG wire can handle, you'll be safe.


How to connect a LiFePO4 battery directly to an esp32? If I want to connect a LiFePO4 battery (as the power supply) directly to an esp32 - would this be the correct way: the plus of the battery to the 3.3 volt pin and the minus to a ground pin?

No. Absolutely not.
A LiFePO4 battery is 4.2V when fully charged. The absolute maximum voltage of an ESP32 is 3.6V.
You will kill the ESP32.
Instead you need to have a voltage regulator with a very low dropout. Ideally a switching ("buck") regulator with a zero-dropout "pass" mode to give the maximum life from your battery.
Even better is a "buck/boost" battery regulator that will boost the voltage up to a stable 3.3V once the battery voltage drops too low.
If all this is beyond you then you're better off using a powerbank to do the regulation to 5V for you then convert that back down to 3.3V with a simple buck regulator.


How to call a file from the arduino? I am aware of the simplicity of the question.  Nevertheless...

I need to code into the arduino the execution of a file.  More precisely a .exe.
To put things in perspective.  I have little to no knowledge of coding.  Yet I need to put together a photocabin.  I have the arduino to count the coins inserted to my coin collector and I need to take a picture when the precise ammount is reached.  Then reset the ammount to avoid taking more pictures.
here is what my code looks so far: (taken from the examples on the arduino page)

const int coinInt = 0;
//Attach coinInt to Interrupt Pin 0 (Digital Pin 2). Pin 3 = Interrpt Pin 1.

    volatile float coinsValue = 0.00;
    //Set the coinsValue to a Volatile float
    //Volatile as this variable changes any time the Interrupt is triggered
    int coinsChange = 0;
    //A Coin has been inserted flag

void setup()
{
  Serial.begin(9600);
//Start Serial Communication
  attachInterrupt(coinInt, coinInserted, RISING);
//If coinInt goes HIGH (a Pulse), call the coinInserted function
//An attachInterrupt will always trigger, even if your using delays

}

void coinInserted()

//The function that is called every time it recieves a pulse
{
  coinsValue = coinsValue + 0.05;
//As we set the Pulse to represent 5p or 5c we add this to the coinsValue
  coinsChange = 1;
//Flag that there has been a coin inserted
}

void loop()
{
  if(coinsChange == 1)
//Check if a coin has been Inserted
  {
    coinsChange = 0;
//unflag that a coin has been inserted

   if(coinsValue >= 0.30)
  {
       here goes the code to open a file, then the code to reset coinsValue

  }
  }
}

Thanks a million.

First of all you need to develop a windows app. You can achieve this by downloading visual studio express for windows desktop from here. Then you must create a project in your language of your preference. You will have to add a serial port component and set the properties to match your arduino serial ones. Then from the event that handles the "data available" of your serial port you can check if there is an incoming character from your arduino and create an if statement that runs the .exe file. Then you must add serial.print('c') to your code when there is a coin inserted. By doing so, you will manage to communicate between arduino and your windows app.

More info and full guide can be found here


How to setup OpenCV with Arduino? My question is how to do it (set it up), not if I can do it or with what Arduino.

I've previously setup OpenCV with Visual Studio 2015. It was a tough one, but I made it through. Now I want to set it up so that it would work with the Arduino and its IDE.

How should I proceed? Is there any specific things to do?

My setup:

Windows 7
Arduino IDE 1.8.1
OpenCV 3.1

If you are thinking of using OpenCV with a "normal" Arduino, such as the Uno or Mega, then think again. OpenCV runs on a computer - be that a desktop computer or an embedded computer. Basically you need an operating system; "normal" Arduinos don't have an operating system.

It may be possible to run OpenCV on an Arduino that runs Linux (some of the strange Intel things that are being marketed as Arduino do, as does the Yún), but in that case you will be writing a Linux application, not working in the Arduino IDE. You would need to treat it as a normal Linux computer and use the normal Linux tools for developing on it (note that OpenWRT that the Yún runs is tricky to develop for - the best way is to cross-compile on a real computer running Linux using the OpenWRT "Buildroot" system).


How to build circuit to switch to other power source if primary source dies? I would like to have a backup battery connected to a device that requires an uninterrupted power supply, like an Arduino or Raspberry Pi, so that if my primary power source (USB plug) gets pulled, the device will switch to being powered by the battery.

I need a solution that I can either build on a breadboard or buy for only a couple dollars. Does anyone know a solution? I'm assuming this is a common need and think I perhaps am not searching with the correct key words.

Edit:

I would like to add that I may also use 4AA batteries and a DC-DC step down module to produce 5V exactly to power a 5V device, so I'm looking for a solution that accepts 5V. Assume the device, let's say Raspberry Pi, takes 5V, the power supply is 5V, and the battery backup is 5V.

Your $2 budget rules out some of the more-effective possible solutions, such as using an actual UPS (uninterruptible power supply) system.

One affordable approach is to connect the plus side of a 3.7 V lithium-polymer battery through a Schottky diode [such as MBR0520, SS14, 1N5819] to the +5 V line of an Arduino board.  (I haven't looked at Raspberry Pi schematics and don't know if this will apply there.)  Hook the minus side of the battery to Arduino ground.

Ideally, the battery voltage less the voltage drop through the diode (say .4–.5 V) should be just less than the voltage that USB supplies.  Ie, just under 5 V if you have a 5 V board, or just under 3.3 V for a 3.3 V board.  Note, most 3.3 V Arduino systems are specified to run at 8 MHz rather than 16.  There's a good chance a 5 V Arduino running at 16 MHz would continue to run ok when powered by about 3.3 V, but it's out of spec.

If your battery voltage exceeds 5 V you won't be able to make the connection quite so directly.  Besides certain risks of damage (see eg Method #5 and Method #8 of 10 Ways to Destroy An Arduino) there will be the practical matter that the higher battery voltage will cause its power to be used preferentially to the USB power, thus discharging the battery so that it won't act as a backup.

Edit: The question-edit says the system uses 5 V, and seems to suggest the primary 5V power supply uses 4 AA batteries and a DCDC converter.

If the DCDC converter is a step-down buck converter it will go out of regulation when the input voltage from the four AA's goes below 5 V, which is 1.25 V per cell.

As you can see from the following graph, if the discharge rate of a typical alkaline cell is 100 mA, it still has about half its power left when its voltage goes below 1.25 V.  To fully use up the alkaline batteries, you could use a buck-boost converter or could test if your buck converter just passes the voltage on through, as opposed to shutting down when the input voltage is low.

(Note, the AA-battery discharge curves shown above and below are from the powerstream.com's “AA tests”  web page.)

For the backup battery, where you also want 5 V output, an economical possibility is use of four AA NiMH cells, with nominal voltage 1.2 V per cell. However, initial voltage officially can exceed 1.4 V per cell, giving 5.6 V total:

A Schottky diode in series will bring that down to say 5.2 V, an acceptable level for powering a 5 V system.  But if the primary supplies 5.0 V, the backup will end up discharging slightly until its output voltage goes below that of the primary.  If that's acceptable, fine.  Otherwise, you could use a diode like 1N4001, with 0.7 to 0.8 volts of drop at 0 to 150 mA output.  Instead of losing some backup power at first (due to higher backup than primary voltage) you will lose some at the end, due to backup voltage going too low slightly sooner. That won't be a problem, however, if you restore the primary supply and recharge the backups in time to prevent over-discharge damage to the backup batteries.


Best buffering practice for continuous SD card writing In a simplified example, I have a microcontroller functioning as a data acquisition device - sensor data is received over UART, and then saved to an SD card.
This received data is in the form of a 12 byte struct, received at 1kHz. The microcontroller receiving the data is an esp32, with an SD card connected over spi. Not an uncommon issue, but if a typical SD card write is triggered everytime new data is received, it will take longer than the gap between samples to  write the data.
What is typically considered the best practice for this type of system, presuming the data will always be received faster than it can be written. I have seen examples of circular buffers, but presumably these will eventually fill completely and samples will be missed.
In my particular example, I have the bonus second cpu core in the esp32. Therefore, my thinking is to use 2 alternating buffers. Data will be received on core 1, and placed into the active buffer. When the buffer is full, incoming data will be written to the second buffer, and the first will be written to the SD card by core 2.
Is this a sensible solution to the problem? I am hesitant to implement anything that simply relies on an improvement in SD write speed, as I will likely need to increase the size of the data payload in the future and don't want to run into this issue again later on.

Is this a sensible solution to the problem?

No, unfortunately not. The size of the buffer is limited by the available RAM on your chip. Jumping between multiple buffers or cores will not change that, since it is a hardware limitation.

I am hesitant to implement anything that simply relies on an improvement in SD write speed, as I will likely need to increase the size of the data payload in the future and don't want to run into this issue again later on.

When you are continuously receiving faster than you can write, you only have 2 options:

Improve write speed
Reduce the needed data size

There is no other way, and that's a logical conclusion, not so much a programmical or hardware conclusion. It that situation the amount of "buffered" data will increase indefinitely, so you would need an infinite amount of memory. And that doesn't exist in real world. The same principle would apply to a high end PC with lots of memory, it will just be full after longer time, than with an ESP.

Improving write speed:

On various sites I have read, that you can use the SD card with different SPI frequencies. A higher frequency would mean a higher transaction speed. You can investigate further at this point.
Writing a full 512 byte page at once and only closing and opening the file again, if really needed, will improve the overall speed.

Reduce the needed data size

Maybe you can compromise with your data resolution and then pack those values as dense as possible (like packing two 4-bit values into a single byte of transmission).
You can research for compression code, so that you can compress your data lossless before transmitting it. Though the result will always depend on the kind of your data. Also mind, that in this case you are trading transmission size for computation time and RAM.

About buffers:
I would say, a normal circular buffer does not bring you much advantages here, since with the SD card you don't want to do bytewise data transmission. The 2 buffer approach, that you mentioned, seems good to me. Though doing handling with different cores does not make much sense to me. The UART receiving itself is done by hardware and some ISRs. You can do all the SD card transmissions in your main code, just making sure, that you regularly copy the received data from the Serial buffer into your buffer.


avr/io.h No such file or directory error when compiling using avr-gcc I am trying to use the atmega328p as standalone microchip and program it. I ama using an Arduino Uno as ISP. I have written a simple program to test it however when I try to compile it using

avr-gcc -mmcu=atmega328p -o main.out main.c

I get the error:

main.c:1:20: fatal error: avr/io.h: No such file or directory
compilation terminated.

I am running OpenSUSE Leap 42.3 and i have installed avr-gcc, avr-libc.

My code:

#include <avr/io.h>

int main() {
    DDRB = 1;
    PORTB = 1;
}

Thank you in advance!

I’m guessing you started with the toolchain Arduino put on your machine.

Try explicitly including the header files on the include path with the -I switch.

avr-gcc -mmcu=atmega328p -I /path/to/avr/include -o main.out main.c

Just search for the io.h file. It should be somewhere close by to where you found the compiler.


Using Arduino as ISP to burn sketch directly to ATmega328 without first installing a bootloader on the ATmega328 Is it possible to take a bare ATmega328 chip, and with an Arduino as ISP, burn a sketch directly to the chip (e.g. not needing a bootloader), or is the bootloader required to run Arduino sketches? I want to embed the ATmega328 into a different device, and do not want the overhead of the entire Arduino board.

I have looked at https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard and https://www.arduino.cc/en/Tutorial/ArduinoISP, and want to do the "minimal circuit" approach (as my application does not require 16MHz).

The tutorial described has steps to first burn a bootloader, then remove the chip from the Arduino, and then install the sketch. Ideally, I would like to skip the bootloader and removing the chip from my Arduino. Ideally, I would like to do it all from Arduino Studio (not AVRDUDE CLI).

I don't mind "dedicating" my Arduino to this (as I assume it's just burning the ArduinoISP sketch whenever I want to burn to a new ATMega328).

Thanks

It is possible to skip the Burn Bootloader step. When you do Upload Using Programmer the bootloader is overwritten and thus serves no purpose. However, there is another reason for the Burn Bootloader step, to set the correct fuses for your board selection. The fuse settings configure things on the ATmega328 such as clock speed and clock source. If the ATmega328 you are using doesn't happen to have the correct fuse settings for the board selection you're using in the IDE then things may not work or may not work correctly. For this reason it's best to always do the Burn Bootloader step the first time you use the ATmega328 and any time you change the board selection or other settings related to that board selection(such as custom Tools menu settings). Since you're not using an external clock source for your ATmega328 make sure that you don't select a board that is configured for an external clock as this will cause the chip to no longer work until you have connected an external clock.


Barebones Arduino Zero with ATSAMD21G18 I have been using the ATmega328P TQFP32 chip for quite a while and I would like to try something new. I came across the ATSAMD21G18 used by Arduino Zero and M0. However, there aren't any information online regarding how to develop a standalone, very basic setup of it.

Previously, I have used...

ATmega328P TQFP32
For the crystal: 16Mhz and 22pF caps
For bootloading: 10 11 12 13 for Arduino ISP
For uploading programs: TX and RX of an Arduino Uno with its chip removed.

For the ATSAMD21G18, I am also looking for a similar setup. I checked out the Sparkfun Mini breakout schematics, but I am not good at reading them and there seems to be a lot of components just for protection and to make it more stable, which I don't need as you can probably know from the setup I used for the 328.

https://cdn.sparkfun.com/datasheets/Dev/Arduino/Boards/sparkfun-samd21-mini-breakout-v10.pdf

What are the basic required components for it to work properly?

For bootloading, am I required to use the Atmel Ice? If so, what are the pins and components needed for burning the Arduino Zero bootloader?

For uploading a program, am I required to use the USB functionality built in? How can I use it (components pins and connections)? Can I use Arduino ISP using an Arduino Zero?

Finally, what should I bear in mind when switching from an ATmega328P to an ATSAMD21G18?

Thanks in advance!

This seems to be the simples form of the Arduino M0 I could find.

From this tutorial site

The ICE programmmer makes it very easy to program and all you need is the SWD pins to program the bootloader.

ISP is for AVR chips where as with ARM chips like SAMD21 you will need to use JTAG/SWD to program it.

I am also try to make a home brew Zero but I am getting stuck after the bootloader where the board just does not want to expose a Serial port.


Arduino Protothreads by Example I am trying to get Arduino working with Protothreads and wanted to confirm I have the basic setup correct. If I have understood the API correctly, then the following code should be what I need to start 2 concurrent threads from inside an Arduino program:

#include <pt.h>

static struct pt t1, t2;

void setup() {
    PT_INIT(&t1);
    PT_INIT(&t2);
}

void loop() {
    doSomething(&t1, 500);
    doSomethingElse(&t2, 500);
}

static int doSomething(struct pt *pt, int interval) {
    PT_BEGIN(pt);
    sleep(100);
    PT_END(pt);
}

static int doSomethingElse(struct pt *pt, int interval) {
    PT_BEGIN(pt);
    sleep(250);
    PT_END(pt);
}

Does anyone see anything that jumps out at them as missing or wrong?

Check this example: rather than sleep(), it uses PT_WAIT_UNTIL

  while(1) {
      PT_WAIT_UNTIL(pt, millis() - timestamp > interval );
      timestamp = millis();
      doSomething();
  }

That should be the proto-thread way of waiting: PT_WAIT_UNTIL will make sure that your thread sleeps in a way that allows other threads to run.

The rest looks fine, but I have not tried to run the code.


Elechouse Mo3 Shield Play Random Song using this code to try and play a random song when someone walks by my distance sensor I get an error, the same song(track 0001)  plays every time. Any advice?

#include <SoftwareSerial.h>
SoftwareSerial Geno(7,8); // Rx , Tx

unsigned char Data[10];
unsigned char i;

// defines pins numbers
const int trigPin = 8;
const int echoPin = 9;

// defines variables
long duration;
int distance;

void setup() {
  delay(1000);
  Geno.begin(9600);
  delay(1000);
  SetVolume(30);
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input
  Serial.begin(9600); // Starts the serial communication
}

void playTrack(int num){

    delay(100);

    Data[0] = 0x7E;
    Data[1] = 0x04;
    Data[2] = 0xA0;
    Data[3] = 0x00;
    Data[4] = 0x00 + num;
    Data[5] = 0x7E;
   Command(Data,5);

    play_pause();

    delay(10000);

}

void SetVolume( int vol){
   Data[0] = 0x7E;          // START
   Data[1] = 0x03;          // Length Not 0x02
   Data[2] = 0xA7;          // Command
   Data[3] = vol;          // new volume
   Data[4] = 0x7E;          // END
   Command(Data,5);
}

void play_pause(){
  Data[0] = 0x7E;          // START
  Data[1] = 0x02;          // Length
  Data[2] = 0xA3;          // Command
  Data[3] = 0x7E;          //Mode parameter
  Command(Data,4);
}

void Command(unsigned char *Data, int length){
    for(int i=0; i<length; i++){
    Geno.write(Data[i]);
    }

    }

void loop() {
  //Assigns a random number
  int song = random(0,200);
  Serial.print("Song is:");
  Serial.print(song);
  Serial.print("\n");
  // Clears the trigPin
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);

  // Sets the trigPin on HIGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);

  // Calculating the distance
  distance= duration*0.034/2;

  Serial.print("Distance: ");
  Serial.println(distance);
  if(distance < 20){
    playTrack(random(1,25));
  }
  //playTrack(1);
  //playTrack(2);
}

Disclaimer: I know nothing about this media player except what's in this question.  I'd never heard of it before.  The following is simply from observation of the code you posted.

Look at your play_pause() function where the meanings of all the elements are described.

Data[0] = 0x7E;          // START
Data[1] = 0x02;          // Length
Data[2] = 0xA3;          // Command
Data[3] = 0x7E;          //Mode parameter
Command(Data,4);

It seems a message starts with 0x7E, followed by the length , followed by a command and whatever else, followed by another 0x7E.

The length field is 1 less than the total length, so I guess it doesn't include the 'start', or whatever - there are various equivalent ways you could look at it.

In playTrack() you set 6 elements, but with the length element set to 4. You then tell Command() there are 5.  So the last element (0x7E) won't get sent, and the length element which you have sent is wrong anyway.

The receiver is going to get into some weird state, I presume. Perhaps that explains the problem you're seeing.


why my arduino uno r3 restart when plugged in to a battery(9v) i have a personal challenge that is to make a arduino avoidance robot it has a"hc-sr04 ultrasonic sensor, a servo, bread board(for the sharing of vcc and gnd), l9110s motor driver, and two dc motors, and also the arduino uno itself"
but when i assembled it and upload the code it works if it's plugged in my laptop but if i plugged it in to a battery it keeps on restarting and doesn't run

Let me guess: the Arduino resets just as one of the motors starts (or should start) right?

The 9v battery is incapable of supplying enough current for much of anything but a few LEDs. When the Arduino first turns on a motor, it needs, and tries to draw, more current than the battery can supply, resulting in the battery voltage dropping below the Arduino's voltage-regulator's minimum input voltage, and the Arduino is shut off. That stops the current draw, the battery voltage recovers, power up the Arduino, which resets (as they always do on power-up), and the cycle keeps repeating.

Try powering it from a more capable battery of greater than 7 volts. 5 AA cells in series, for example would provide 7.5 volts. This won't last terribly long but should work for a while. A second (third, ...) string of 5 in parallel with the first should double the life. Using C or D cells instead will increase the life a lot more.


How to flash/blink I2C LCD backlight without delay function? Since I am an using I2C LCD backpack, I'm unable to call in for pinmode to set variables like #define BACKLIGHT_PIN 13. I know lcd.setBacklight(HIGH); and lcd.setBacklight(LOW); controls the I2C LCD backlight, but if I use delay in the loop it slows down the whole loop.

How do I flicker the LCD backlight without using delay? I tried for example to blink without delay, but I don't know how to assign a global variable to lcd.setbacklight so as to control it.

I want to use an if statement to warn the user that so and so has happened, eg:

#include <Ticker.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

//Ticker flashBacklight(toggleBacklight, 100);
// when I use ticker here am getting not declared in scope
const int buttonPin = 3;
int buttonState = 0;
// pls declare flashBacklight, long flashBacklight = 100; ??
// pls declare toggleBacklight

void toggleBacklight() {
  // lcd.setBacklight(!lcd.getBacklight());
  // !lcd.getbacklight() spelling mistake ? or it is setbacklight?
}

void setup() {
  lcd.begin(20, 4);
  lcd.setBacklight(HIGH);
  pinMode(buttonPin, INPUT);
 }

void loop() {
  buttonState = digitalRead(buttonPin);
  if (buttonState == HIGH) {
    // if button goes high the back light must keep on flashing until it's released
    flashBacklight.start();
    //flash the lcd backlight
  } else {
    flashBacklight.stop(); // Stop flashing the backlight
  }
  flashBlacklight.update();
}

But delay slows down the whole loop, so how do I flash the backlight without it? Thank you.

Besides the standard 'compute a target millis() and compare' standard, which can get clunky when you have to handle more than 1 repeating or delayed event, there are also more than one decent library that abstract the concept, but also add features.

One example is the Ticker library.

With these methods, you create a callback function and pass that function name into the object constructor, along with the timing parameters.

So you might:

[various #include, #define, etc.]

Ticker flashBacklight(toggleBacklight, 100); //call toggleBacklight() every 100ms

// Create the callback function, which just toggles the backlight each call.
void toggleBacklight() {
  lcd.setBacklight( !lcd.getBacklight() );
}

setup() {
  [...]
}

loop() {
  // Start or stop the ticker based on your own situation. Once started, it will call your callback function at the specified interval until stopped.

  if (warningSituation) {
    flashBacklight.start();
  } else {
    flashBacklight.stop();
  }

  flashBlacklight.update();
}

Another related library is SimpleTimer

EDIT

Your code example, updated:

#include <Ticker.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

void toggleBacklight();

Ticker flashBacklight(toggleBacklight, 100); //when i use ticker here am getting not declared in scope

const int buttonPin = 3;
int buttonState = 0;
                      // pls declare   flashBacklight   , long flashBacklight = 100;   ??
                      //   pls declare toggleBacklight

void toggleBacklight() {
 // lcd.setBacklight( !lcd.getBacklight() );  // !lcd.getbacklight() spelling mistake ? or it is setbacklight?
}
void setup() {
   lcd.begin(20, 4);
 lcd.setBacklight(HIGH);
 pinMode(buttonPin, INPUT);
 }
void loop() {
      buttonState = digitalRead(buttonPin);
   if (buttonState == HIGH)          // if button goes high the back light must keep on flashing untill its released
   {
    flashBacklight.start();          //flash the lcd backlight
  } else {
    flashBacklight.stop();           // Stop flashing the backligh
 }
   flashBacklight.update();
  }


Unable to send SMS from interrupt routine I am trying to develop a burglar alert system. I am using PIR sensor, Arduino Mega and SIM800L. I have connected PIR sensor to interrupt pin. Whenever motion is dected, a function corresponding to the interrupt will be called. In that function I am sending a SMS to notify with an alert message. If motion is detected 2 times, I will call the emergency contact number.

This is the code I have written.

#include <SoftwareSerial.h>
#define PIR1 2
#define SIREN 13
#define statusLED 12

SoftwareSerial SMS(11, 10);// rx(11-arduino) connect to tx(gsm module)
                         // tx(10-arduino) connect to rx(gsm module)

String CONTACT1 = "xxxxxxxxxx";  //mobile number

boolean status;
byte motionCtr = 0;
unsigned long latestMovementTime = 0;

void setup() {
  pinMode(PIR1,INPUT);
  pinMode(SIREN,OUTPUT);
  pinMode(statusLED,OUTPUT);

  Serial.begin(9600);
  SMS.begin(9600);
  SMS.println("AT+CNMI=2,2,0,0,0");

  delay(5000);
  activateSystem(0);
}

void loop() {
  unsigned long currentTime = millis();
  //If motion is not dected for 5 minutes, turn off the siren.
  if(currentTime - latestMovementTime > 300000 && motionCtr>=1){
    stopSiren(0);
  }
  delay(500);
}

void activateSystem(byte manual){
  delay(60000); //warm up time for PIR sensor
  attachInterrupt(0,motionDetected,RISING);

  status = true;
  digitalWrite(statusLED,HIGH);

  if(manual){
    Serial.println("System ACTIVATED by SMS.");
    notifyBySMS("System ACTIVATED SMS.");
  }else{
    Serial.println("System ACTIVATED.");
    notifyBySMS("System ACTIVATED.");
  }
}

void deactivateSystem(byte manual){
  detachInterrupt(0);

  status = false;
  digitalWrite(statusLED,LOW);

  if(manual){
    Serial.println("System DEACTIVATED by SMS.");
    notifyBySMS("System DEACTIVATED SMS.");
  }else{
    Serial.println("System DEACTIVATED.");
    notifyBySMS("System DEACTIVATED.");
  }
}

void motionDetected(){
  startSiren("Motion at bedroom door.");
}

void startSiren(String msg){
  //Record the time of latest motion dected.
  latestMovementTime = millis();

  motionCtr++;
  Serial.print("Ctr="+motionCtr);
  Serial.println(msg);
  notifyBySMS(msg);

  //Start the siren only if motion is detected 2 times
  if(motionCtr==2){
    digitalWrite(SIREN,HIGH);
    Serial.println("Siren STARTED.");
    notifyBySMS("Siren STARTED.");
    call(CONTACT1);
//    call(CONTACT2);
//    call(CONTACT3);
  }
}

void stopSiren(byte manual){
  motionCtr = 0;
  Serial.println("Ctr="+motionCtr);
  digitalWrite(SIREN,LOW);
  if(manual){
    Serial.println("Siren STOPPED manually.");
    notifyBySMS("Siren STOPPED manually.");
  }else{
    Serial.println("Siren STOPPED");
    notifyBySMS("Siren STOPPED.");
  }
}

void sendSMS(String mobileNumber, String msg){
  Serial.println("Sending SMS to "+mobileNumber);
  //AT command for text mode of gsm module
  SMS.println("AT+CMGF=1");
  delay(100);
  SMS.println("AT+CMGS=\""+mobileNumber+"\"\r");
  delay(100);
  // the text you want to send
  SMS.println(msg);
  delay(100);
  // ASCII code of CTRL+Z
  SMS.println((char)26);
  delay(5000);
  Serial.println("SMS sent to "+mobileNumber);
}

void call(String mobileNumber){
  Serial.println("Calling..."+mobileNumber);
  SMS.println("AT+CMGF=0"); //AT command for PDU mode of gsm module
  SMS.println("ATD"+mobileNumber+";");
  delay(45000);
  SMS.println("ATH");
}

void notifyBySMS(String msg){
  sendSMS(CONTACT1,msg);
  delay(1000);
//  sendSMS(CONTACT2,msg);
//  delay(1000);
//  sendSMS(CONTACT3,msg);
//  delay(1000);
}

I am receiving the SMS from setup(). But I am not receiving the SMS that I have sent from interrupt routine. Also I am receiving the call only sometime, it is random. I guess this is because I am using delay() in interrupt routine.

How can I implement such logic without delay().

As mentioned in the comments Serial won't work in an ISR. Generally, you should do as little as possible in an ISR. Often an ISR will just set a flag to be handled in loop()

You will then need to refactor loop() to handle the flag set in the ISR. A common method is to use a finite state machine.


What pins to use on a Teensy to get data from multiple peripherals? I'm using a Teensy to keep records on the location, speed, altitude, and direction of a weather balloon I'm hoping to launch. I have an Adafruit LSM9DS1 and a Ublox NEO-M8N with compass (HMC5833L) so to get all the data from these I need to connect to a total of 6 pins to get the data. I also want to use a Pixhawk radio telemetry unit to send these data to the ground so I can see them in realtime, so that will involve at least 2 more pins I believe.
The Teensy appears to have plenty of IO pins for all of this, but I've noticed that in all the libraries I've installed to try to use with these things, the pins to use aren't explicitly set. The libraries I've played with include the Adafruit LSM9DS1 library, NeoGPS, Pixhawk Arduino link, RadioHead, Grove HMC5833L, and others. I've been able to get some serial data in by using pins 18 and 19, but I can't attach all the periperhals to the same pin.
It feels like I'm missing something very basic here but I haven't been able to figure out how to use these libraries with inputs on different pins. Even when I look into the code of the libraries themselves, I can't find where the pins are being set. Most of the documentation that mentions which pins things use is written for specific Arduino models, like the Uno, and don't mention the Teensy.
What pins do I use if I want to read and write on more than one peripheral from my Teensy? How can I get data on more than just the two "default pins" that these libraries seem to expect?

The first thing to look at when determining which pins to connect a peripheral to is what protocol that peripheral uses - e.g. I2C, SPI, analog voltage via ADC, etc. The Teensy pinout for the version you have (e.g. the 3.2 pinout) lists which pins can function as which protocol functions. For example, pin 19 can act as an analog input (A5) or as part of the 0th I2C unit, SCL0. Your LSM9DS1 can use I2C, so you could connect it to that I2C unit. Typically Arduino libraries will default to using the default peripheral type. In Arduino, an I2C bus is called Wire, so a library for an I2C device will typically use the Wire device. Well-written libraries will also let you pass in your own peripheral, which is how you change the pins. Each library will do this differently.


Temperature Sensor not giving proper values In my current project I am reading temperature through sensor which is having only two wires.

To read sensor values, I have used below schematic which I have found on Arduino Project Hub site.

In my project I am using below Arduino program.

#include <OneWire.h>
#include <DallasTemperature.h>

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

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

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

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

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

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

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

After doing all this I am getting this output on serial monitor.

At which step I am doing wrong?

The -127 for your temperature reading is actually the error code for DEVICE_DISCONNECTED_C.
In the library's example code, they put an if that checks for this error code before printing the temperature:
if(tempC != DEVICE_DISCONNECTED_C)
{
  Serial.print("Temperature for the device 1 (index 0) is: ");
  Serial.println(tempC);
}

Since your sensor has only 2 wires, according to Wikipedia, you need a capacitor to power the sensor:

One distinctive feature of the bus is the possibility of using only two wires — data and ground. To accomplish this, 1-Wire devices include an 800 pF capacitor to store charge and power the device during periods when the data line is active.

This should hopefully resolve your issues.


How to connect MPU6050 with Arduino Uno without using A0-A5 pins? Connecting MPU6050 with Arduino without using A0-A5 pins.

You could use a Software I2C library, like this one on github, which can be used on almost any pin of a board. But keep in mind, that doing such communication in software imposes some limits (for example the linked library can only be a master). Keeping it in hardware is often the better choice, depending on your requirements.


How to get a specific value from an unknown number of JSON representations? I am using ArduinoJson and ESP8266HTTPClient.
Say I have a DynamicJsonDocument that has an unknown number of entries with information on different persons:
[
    {
        "ID": "12345",
        "name": "John Smith",
        "Address": "Street 1"
    },

    .
    .
    .

    {
        "ID": "00345",
        "name": "Paul Anderson",
        "Address": "Street 2"
    }
]

I would like to somehow store the values associated with the key "name" for all the different persons. For example, have something like:
String name1 = "";
...
String nameN = "";

.
.
.

Serial.println(name1);
...
Serial.println(nameN);

To print a list of all the names:
John Smith
Paul Anderson

The only information of the JSON I have beforehand is the keys each entry will have. I do not know how many entries there will be.
How can I go about this?
EDIT: Why I want to do this:
I am using the ESP as a client to get information from a server in the form of a JSON similar to what I wrote above. At the same time, I am serving a simple HTML website by doing server.send(200, "text/html", HTML_code); using the ESP as an AP. I was able to just cram the whole JSON into the HTML as text, but I would like to just have specific information from the JSON, as explained above.
I am aware what I am doing is far from elegant or the "correct way to do it", but I am learning all of this, so any criticism and help is more than welcome :)

Directly from the ArduinoJson Assistant:
// Stream& input;

StaticJsonDocument<384> doc;
deserializeJson(doc, input);

for (JsonObject elem : doc.as<JsonArray>()) {
  const char* ID = elem["ID"]; // "12345", "13244", "00345"
  const char* name = elem["name"]; // "John Smith", "Jason Statham", "Paul Anderson"
  const char* Address = elem["Address"]; // "Street 1", "Street 2", "Street 3"
}

See also:

How to use ArduinoJson with HTTPClient?
How to deserialize a very large document?


How do I use Arduino and node.js? I am new to Arduino, however I have experience in web development, lately I have been using, meteor js and the mean stack for different projects. However, I am open to trying any language for development.

What I am trying to do is build a simple application to control the LED on the Arduino over the web.

I am working with another person, and the Arduino will be behind a firewall so I am not sure how to access it via the internet. I do have access to an Arduino Uun that I can use for testing at home which does have linio connected via bridge, which I don't quite understand what that does.

I've also heard of this, but would like to stay away from third party builds as much as possible if I can do it myself.

Whats the common way to do this with an Arduino behind a firewall? How do I do this with a Arduino Yun? Is it easier with a Yun?

I am working on similar project that uses internet to communicate with external device (mobile). I am reading data from sensors and passing them over the web with web sockets. I am using Arduino Yun for this project and Spacebrew (for web sockets communication). It's very interesting approach but quite a challenge in some cases. You will probably run into asynchronous/synchronous problem, which in my case lead me to running some Python scripts on Yun triggered from Processing code. I am currently running Spacebrew server on my VPN, so I can connect my Yun left at home and use my iphone from everywhere to get the readings.

It's also worth mentioning Yun comes with pre-installed Temboo library, which is great starting point for web communication. The configuration is really easy and quick. You will also find official documentation very handy and easy to understand. It's really great starting point for experimenting with web-like applications integrated with Arduino Yun.

Spacebrew

http://docs.spacebrew.cc/

Spacebrew is an open, dynamically re-routable software toolkit for choreographing interactive spaces. Or, in other words, a simple way to connect interactive things to one another. Every element you hook up to the system can subscribe to, and publish data feeds.
http://github.com/Spacebrew/pySpacebrew

This repo contains the Spacebrew Library for Python along with documentation and example apps.
http://github.com/julioterra/yunSpacebrew

The Spacebrew Yun library features two main components - a set of python scripts that run on the linino, and a library that runs on the atmel chip. You find there information how to install both of these components so that you can connect to Spacebrew from an Arduino sketch.

Temboo

Yun has also build in Temboo library, it's a great way to start experimenting, once you prove the concept you can start narrowing your environment and moving away if you don't want to use 3rd parties software.

http://www.temboo.com/arduino

The Temboo Library makes it easy to connect to over 100 web-based resources and services with Processing. Currently you can find libraries for Android, Arduino, iOS, Java, Node.js, PHP, Processing, Python, REST API, Ruby, Twyla

Node.js

You can also run node.js on the Yun itself, here's good article and some packages ready to install:

http://giorgiocefaro.com/blog/installing-node-js-on-arduino-yun
https://github.com/giorrrgio/nodejs-linino

This is an openwrt package for node. It probably only works on mips (not mipsel, or arm). It runs an outdated v8 as well.

What is Bridge library for Arduino Yun?

You also asked about Bridge library. As you know Yun has two processors on board, one is running your Processing code, the other one has Linux on it (Linino). Bridge basically simplifies communication between them so they can "talk" to eachother, more information here:

http://arduino.cc/en/Reference/YunBridgeLibrary

(Taken from arduino.cc documentation:)

The Arduino Yún has two processors on board. One is an ATmega32U4 like on the Arduino Leonardo. The other is an Atheros 9331, running Linux and the OpenWRT wireless stack, which enables the board to connect to WiFi and Ethernet networks. It is possible to call programs or custom scripts on the Linux system through the Arduino to connect with various internet services.

The Bridge library simplifies communication between the ATmega32U4 and the AR9331. It inherits from Stream, and many of the methods should be familiar from Serial and other derivatives of Stream.

Bridge commands from the 32U4 are interpreted by Python on the AR9331. Its role is to execute programs on the GNU/Linux side when asked by Arduino, provide a shared storage space for sharing data like sensor readings between the Arduino and the Internet, and receiving commands from the Internet and passing them directly to the Arduino.

Bridge allows communication in both directions, acting as an interface to the the Linino command line.

Where to start?

I would start with Temboo if I were you, it's a great learning curve and quite simple step to start. You will also learn and understand how the board works and how you can communicate with "external world". Once you have proof of concept, start experimenting with different libraries and improving the approach. Perhaps you will find Spacebrew more handy later or even discover different solutions.


Are Arduino's truly OSH? I keep reading how Arduinos are "open source", but my understanding of OSH is that all its components must be open source.

Arduino uses an Atmel 8-bit CPU - but Googling this shows the Atmel is proprietary!?

So I ask: how can Arduino be OSH if it's chief component - its Atmel CPU - is proprietary?!?

I just scanned over the TAPR and CERN open hardware licenses and I didn't see such a provision. My quick take on OHLs is that they are specifications for building the hardware - and therefore, information - not the hardware itself. And it only makes sense when we consider the incredibly expensive and complicated (from an experimenter's point of view) infrastructure that is a chip foundry necessary to create the kinds of hardware we take for granted and have reduced to commodity parts, CPUs, & MCUs being a prime example.

Thus "Arduino" is an open source specification for building microcontroller boards or board-sets based on ATMEL MCU chips, as well as the products of the Italian company SmartProjects. That is why there are so-called Arduino clones, otherwise, why wouldn't any clone of an Arduino be an Arduino?


Tiny RTC module doesn't work properly when connected to an Arduino Uno together with 16x2 LCD I am trying to make a digital clock using a tiny RTC, 16x2 LCD, and Arduino Uno. The RTC module works fine if 16x2 LCD is not connected to the Arduino. Both RTC and LCD are I2C modules and hence are using the same A4 and A5 pins of the Arduino. I have been informed that the I2C devices if connected in parallel should work. But, in this case, the clock doesn't show the time properly.

An I2C scanner sketch can help to identify the actual addresses in use. I would use a sketch like on this page https://playground.arduino.cc/Main/I2cScanner or on this page http://gammon.com.au/forum/?id=10896&reply=6#reply6 . Or google 'arduino i2c scanner'.

Hook up the RTC by itself and run the scanner, then hook up the LCD by itself and run the scanner. The output will be on the serial monitor. If the devices have the same address, then that is your problem.

If one of the devices does not show up at all, then perhaps it is defective.


How to use 2 serial port when WifiEsp library uses one of both I try without success to receive datas from DataPort and transmit them to my computer via WifiPort, using ESP8266 wifi module. Each second, serial datas income on DataPort from another device.

Initialization as follow:

#include <SoftwareSerial.h>
#include "WiFiEsp.h"
SoftwareSerial DataPort(10, 11); // RX, TX
SoftwareSerial WifiPort(8, 9); // RX, TX

In setup:

Serial.begin(9600);
DataPort.begin(9600);
WifiPort.begin(9600);
WiFi.init(&WifiPort);

In loop, i do:

//WIFI PART
WifiPort.listen();
WiFiEspClient client = server.available();
if (client) {
 //.... bla...bla...bla...
}

//INCOMING SERIAL PART
DataPort.listen();
while (DataPort.available() > 0)
{
   char c = DataPort.read();
   str += c;
   if(c == '/')
   {
      Serial.println(str);
      str="";
      break;
   }
}

WIFI PART runs fine if i isolate INCOMING SERIAL PART and INCOMING SERIAL PART runs fine without WIFI PART.
So how can i receive datas on DataPort and transmit them when my computer ask them via the ESP8266 on WifiPort ?

The esp8266 AT firmware doesn't wait until you listen on the SoftwareSerial instance. If there is a connection to the server it sends +IPD and data. If the SoftwareSerial instance doesn't listen the information about client connection is lost.

You must listen to esp8266 all the time, so you can't use two SoftwareSerial instances.

You could use the RX pin of Uno to received data over hardware Serial, if you only receive on DataPort and only print to SerialMonitor.


Error with led Blinking I am new with Arduino and I made something very basic and I don't know why it is not working . I placed the positive led in pin 13 and the negative in GND and wrote this code :

#define LED 13
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(LED, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
}

I verified if it 's connected to Arduino Uno and when I upload the code I have this errors :

Sketch uses 924 bytes (2%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
avrdude: ser_open(): can't set com-state for "\\.\COM4"
An error occurred while uploading the sketch

Sometimes IDE has problems ? What I did wrong ?

You do not have a problem with LED blinking (although there seems a resistor missing for your led), but with uploading a sketch.

Hard test: switch off your computer, remove USB cable, switch on computer, check the COM port appearing when connecting the Arduino via USB cable. Then start IDE and try upload again.

Eventually something else was blocking the COM port.


Multiple slave(sender) to one master (receiver) I beg your help to my project
I wish to send the data from slave to master but only one data is receive out of two slaves.

//master

#include <Wire.h>

void setup() {
  Wire.begin();        // join i2c bus (address optional for master)
  Serial.begin(9600);  // start serial for output

}

void loop() {
  Wire.requestFrom(8, 1);    // request 6 bytes from slave device #8

  while (Wire.available()) { // slave may send less than requested
    char c= Wire.read(); // receive a byte as character
    char q= Wire.read();

  Serial.print(c);         // print the character
  Serial.print(q);
  }

  delay(1500);
}

////slave 1

#include <Wire.h>

void setup() {
  Serial.begin(9600); // Starting Serial Terminal
  Wire.begin(8);                // join i2c bus with address #8
}

void loop(){
  Wire.onRequest(requestEvent); // register event

  delay(1500);
}
void requestEvent() {

  Wire.write('Q');
  Serial.println("Sent");
}

////slave 2

#include <Wire.h>

void setup() {
  Serial.begin(9600); // Starting Serial Terminal
  Wire.begin(8);                // join i2c bus with address #8
}

void loop() {
  Wire.onRequest(requestEvent); // register event

  delay(1500);
}
void requestEvent() {

  Wire.write('Y');
  Serial.println("Sent");
}

You cannot have 2 devices with the same address at the I2C bus. If they both try to send at the same time with different data, the data will either get corrupted, or one of the slaves will stop to send. You cannot request data from more than 1 device at once with I2C.

You have to give the slaves different addresses. Then you have to do the requests sequentially, first a request (with the corresponding read) to the first slave and after that is done, you can start a second request (with the corresponding read).

Besides that, the reading code is not good. You are testing in the condition of the while loop, if there is anything to read (which can be only 1 byte), but then you read 2 bytes. In your case you only have to read 1 byte, since you also request only 1 byte. In the case, when you request more than 1 byte, you can either check, if there are enough bytes in the buffer (with something like if(Wire.available()>=2) ), or you can just work through the buffer byte by byte (with while(Wire.available()){ data = Wire.read();} , note the single read in the while loop).


Arduino Uno powers off when circuit plugged in to +5V and GND pins I have a max7219 driving an 8 digit 7 segment LED array with forward current of 20mA and typical forward voltage of 1.85V. I'm trying to power this through my arduino UNO (which itself is drawing power from USB), and have the max7219 chip's +5V and ISet(+resistor) and ground pins connected to the respective pins on the arduino.  When I try to plug this in, the arduino will not power up, but removing the jumpers from +5V and GND allows the arduino to power up.

I have confirmed with my multimeter that there is no short between any of the power cables on my led circuit.

The voltage supplied by the arduino works normally if I connect it up to a simple resistor and led on a breadboard.

The voltage across the +5V & GND pins on the arduino drops from 5V to 0V if the jumpers are inserted whilst the arduino is powered up.

I thought perhaps the circuit was trying to draw too much power from the USB, so tried higher resistor values than my initial resistor (20K), to no effect.

What else could be causing this?

and have the ... ISet(+resistor) and ground pins connected to the respective pins on the arduino.

What pin on the Arduino?

The ISet resistor should go to +5 V - don't connect it to an Arduino pin (unless you mean the +5 V Arduino pin). See diagram:

I had a 7-segment display working fine on an Arduino via the USB, see photo:

More details here: Interfacing LED displays with the MAX7219 driver


ESP8266 error: espcomm_upload_mem failed while uploading sketch First of all, I would like to apologize for posting this error once again to this community. However, I have been studying articles for last many days to resolve this error. Unfortunately, I did not get any solution which could resolve my problem.

Below is the error which I get when uploading a sketch (even the example sketch):

warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed

Here are the connections:
Vcc - 3.3V
RST - 3.3v
CH_PD - 3.3v
Tx - Rx
Rx - Tx
GPIO0 - GND
GND - GND

I tried various combinations like Tx to Tx, Rx to Rx, pulling off GPIO0. Pulling off reset and ch_pd. Supplying external power source, supplying power directly from Arduino using 3.3V. Supplying power from Arduino 5V using an LD33V regulator. I have even tried uploading the code using USB to TTL. But every time I get exactly the same error.

Well, first of all you should make sure that the voltage on both Tx and Rx pins of the ESP8266 is 3.3V (the Tx and Rx voltage on Arduino is 5V). Personally, I've never succeded in using an Arduino to program the ESP (even though there are plenty of examples of this setup in the web). After a while, I just gave up and bought a converter to do the job for me (it's totally worth it).

Even so, I got this error a few times. You must keep two things in mind:

In operation mode, the CH_PD pin must be connected to 3.3V, but it won't do any harm to let it connected during the flashing, so I just soldered a wire between these two pins to make things easier.
In flashing mode, GPIO0 must be connected to GND. It won't work otherwise. I strongly recommend you using a usb converter for this, and only connect it to your computer once GPIO0 has been set to GND. This has solved this issue for me, in fact I even soldered a switch on my converter between GPIO0 and GND.

Hope this answers your question.

EDIT: Here are some photos of the setup


Connect multiple modules to arduino micro I have an Arduino Micro and I want to connect an LCD and Bluetooth module to it. The problem I face is that there are not enough power pins for them both.

I understand that I probably need some external power supply for them, but I have no idea how to do this properly.

You can design/build/deploy a power supply that provides to each board (arduino included) the voltage it needs (but it's advisable to have modules working at the same voltage level) and that should be sufficient.
As long as you have a shared Vcc-to-GND reference, it's enough.

To verify that the power supply you choose is ok, do the following:

check that the modules are compatible with its voltage (ex: all at 5V)
check that the combined power consumption of each module (you get that from the datasheet) is lower than the total power output of the power supply.

Additional checks:

check that the maximum voltage ripple provided by the power supply is lower than what the modules can tolerate
check that the peak current the power supply can provide is larger than the combined peak current of all the other devices.


Duplicate libraries while compiling for ESP32 in the Arduino IDE I have just added the ESP32 toolchain to the Arduino IDE (v1.8.0) on Windows 10.  To get the IDE to allow me to select ESP32 chips I had to place the Espressif folder in "D:\Program Files(x86)\Arduino\hardware" (Yes my C drive is called D, its a long story)

I managed to compile and run Blink and after several minutes of celebration I tried the ESP32 Example Wifi->WifiScan.  It failed to compile because

WARNING: Category '' in library OneWire is not valid. Setting to 'Uncategorized'
In file included from D:\Program Files (x86)\Arduino\libraries\WiFi\src\utility\spi_drv.cpp:21:0:

D:\Program Files (x86)\Arduino\libraries\SPI/SPI.h:16:26: fatal error: avr/pgmspace.h: No such file or directory

compilation terminated.

Multiple libraries were found for "WiFi.h"
 Used: D:\Program Files (x86)\Arduino\libraries\WiFi
 Not used: D:\Program Files (x86)\Arduino\hardware\espressif\ESP32\libraries\WiFi
Multiple libraries were found for "SPI.h"
 Used: D:\Program Files (x86)\Arduino\libraries\SPI
 Not used: D:\Program Files (x86)\Arduino\hardware\espressif\ESP32\libraries\SPI
exit status 1
Error compiling for board ESP32 Dev Module.

If I am reading this correctly, there are a couple of duplicate libraries, Arduino versions and ESP32 versions and the IDE picked the Arduino versions.

Is there a way of telling the IDE to prefer the ESP32 libraries rather than Arduino ones?  I suspect all I need to do is change the order of the -I and -L commands, but I don't have a clue how, or if that's the right thing to do.

#include "filename.h" will look in the sketch folder

#include <filename.h> will look in the path, defined in File | Preferences, edit preferences.txt, search for sketchbook.path


Using lambdas as callback functions Using the Ticker library for the ESP32, how can I use a lambda as an argument to the attach method?
tickerSystemManager.attach(1000, [&](){
  systemManager->sync();
});

Attempting to use the above, I get the following error:
Matrx.cpp:11:4: error: no matching function for call to 'Ticker::attach(int, Matrx::setup()::<lambda()>)'
...
Ticker.h:40:8: note: candidate: void Ticker::attach(float, Ticker::callback_t)

How can I capp a lambda into this method?

As @timemage explains in a comment, you cannot pass a capturing lambda
to a function that expects a plain pointer to function. There is,
however, a way out of this: the Ticker class provides an overload of
the attach() method that allows you to provide a parameter of any type
to tour callback:
template<typename TArg>
void attach(float seconds, void (*callback)(TArg), TArg arg)

You can use this version of attach() and provide it both

a non-capturing lambda that gets a pointer to systemManager
that pointer as a third argument.

Edit: I did a few tests, and it seems my compiler cannot properly
perform template argument deduction in this case, but the approach works
if you explicitly specialize the template. Namely:
tickerSystemManager.attach<typeof systemManager>(
    1000,
    [](typeof systemManager p){ p->sync(); },
    systemManager);


WindowsError(31, 'A device attached to the system is not functioning.') in arduino Having board esp32 devkit v1, to get started with arduino ide (installed recommended boards for esp32) I marked board asDOIT ESP32 DEVKIT V1 (as no other options as like ESP32 DEVKIT V1 ) so upload gets this error

    esptool.py v2.6
Serial port COM3
Traceback (most recent call last):
File "esptool.py", line 2959, in <module>
File "esptool.py", line 2952, in _main
File "esptool.py", line 2652, in main
File "esptool.py", line 222, in __init__
File "site-packages\serial\__init__.py", line 88, in serial_for_url
File "site-packages\serial\serialwin32.py", line 62, in open
serial.serialutil.SerialException: could not open port 'COM3': WindowsError(31, 'A device attached to the system is not functioning.')
Failed to execute script esptool
the selected serial port Failed to execute script esptool
 does not exist or your board is not connected

so how do I upload my programs?
I would be highly obliged if you could please help me solve this problem.
Thank you.

I got this error.  Then switching USB ports fixed the problem.  Showed up on COM3 in either place. I just switched from a built-in USB port to on off a hub, and it started working.


Which platform is better to debug Arduino memory problems? Linux or Windows? I am developing a product. I developed every module in the firmware individually. Now I am integrating them but getting memory issues. I am not able to see how the memory is allocated inside the MCU during the runtime.

Can Linux help me debug issues better, using its command than Windows platform?

Thanks in advance.

The operating system is irrelevant. If you want to debug the target you need a debugger and a debugging environment. That means a proper hardware debugger interface, not an Arduino's USB serial port, and a proper IDE like Atmel Studio not the Arduino IDE.  All are available for both Linux and Windows.


How do I turn off the blinking cursor/caret in the Arduino IDE? I just purchased a RedBoard, knowing that it would work on Linux, and knowing that it could allow me to easily interface with some electronics project. I am aware of the ino command line tool but I wanted to try interfacing with my board using the Arduino IDE because the latter seems to be somewhat standard. However, when I open the IDE I see a blinking cursor and for whatever reason I can't deal with this. How do I turn off the blinking cursor in the IDE?

I've managed to fix the blinking cursor problem in Firefox, GNOME, KDE, and my terminal... just not sure what to do with Java applications like Arduino IDE.

Note: does not work with version 1.6.11. Works with 1.0.6

Open the Arduino IDE
Go to File
Then go to Preferences
At the bottom of the page is the file location you can enter to set additional preferences
Exit the Arduino IDE
Go to the preferences file location then set editor.caret.blink=false
Then save
Then restart the IDE and the caret will not flash