I keep getting the 'expected unqualified-id before if' error message when trying to run my program This is my code:
const int Speaker = 11;
const int trigPin = 9;
const int echoPin = 10;

long duration;
int distance;

void setup() {
  // put your setup code here, to run once:
pinMode(Speaker, OUTPUT); // sets the output as the buzzer which is in pin 11
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.begin(9600);

}

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

digitalWrite(trigPin, LOW);
delayMicroseconds(2);

digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

duration = pulseIn(echoPin, HIGH);
distance = duration*0.034/2;

if (distance > 10);
  Serial.print("Distance: ");
Serial.println(distance);
}

if (distance <= 10); {

Serial.print("Distance: ");
Serial.println(distance);

tone(Speaker, 440, 750);
delay(375);
tone(Speaker, 349, 750);
delay(375);
tone(Speaker, 587, 750);
delay(375);
tone(Speaker, 523, 1500);
delay(750);
tone(Speaker, 440, 750);
delay(375);
tone(Speaker, 1500);
delay(750);
tone(Speaker, 294, 750);
delay(375);
tone(Speaker, 392, 3000);
delay(1500);
tone(Speaker, 349, 750);
delay(375);
tone(Speaker, 392, 750);
delay(375);
tone(Speaker, 440, 750);
delay(375);
tone(Speaker, 587, 750);
delay(750);
tone(Speaker, 659, 750);
delay(375);
tone(Speaker, 698, 750);
delay(375);
tone(Speaker, 523, 750);
delay(1875);

}
else {
  Serial.print("Distance: ");
Serial.println(distance);
}

}

sorry I couldn't figure out how to enter it in to look like it does on arduino.
What is my fault?
i'm new to coding so you might have to explain it as easily as you can.

The root of your problem is this line:
if (distance > 10);

You have an extraneous semi-colon and lack the opening bracket of the block it's intended to start.  It should read:
if (distance > 10) {

Also, later on you have something similar:
if (distance <= 10); {

Here you have remembered the bracket, but have still slipped in the semi-colon that is not wanted.
It is important to remember that every opening bracket must have a matching closing bracket, and every closing bracket must have a corresponding opening one.
If you are strict with yourself and keep your indenting strictly correct you will catch such errors much quicker.
Another trick is to start at the top and count your brackets - add one for every opening bracket and subtract one for every closing bracket. If you ever go negative then you know you have a mismatch. If you go to zero and you're still inside a function then you have a mismatch. You should end up on zero. If you don't then you know you have a mismatch.


One free pin. Need to display output for the user? I'm working with lightblue bean. I have a device that writes data to an SD card on a long button press and switches what will be written (from a list of 5 items) on short button press.

The output, printed both to the SD card and to serial looks like this:

12:38, 7/15/15, subway
12:55, 7/15/15, subway
12:38, 7/15/15, bus
12:55, 7/15/15, rail

etc. It's basically a time stamp then a vale from this list:

char* modes[]= {"walking", "subway", "bus", "railroad", "other"};

This works perfectly. But the bean has very few pins:

5 SCK  -- connected to SD card.
4 MISO -- connected to SD card.
3 MOSI -- connected to SD card.
2 SS   -- connected to SD card.
1      -- input button, takes long and short presses
0      --
A1 SDA --- connected to real time clock for timestamp
A0 SCL --- connected to RTC (real time clock) for timestamp

I have one free DIGITAL pin. I need to let the user know what they have selected. This could be done with 5 LEDs that light up next to the user's choice, or maybe displayed text? This is a portable item so a servo that points to the user's choice might be too unreliable.

I've done some research into shift registers. They all seem to need 3 digital pins min. If I could do it with 2 I could rework the button...

Ideas?

Seems you have I²C on the board you could possibly use an I²C LCD backpack, like from breakouts if you already have an LCD, this means you can have the RTC and display on the I²C bus and probably more things.

Another option seems you mentioned LEDs, you could still use the I²C bus and use an I/O expander and hook LEDs up to that and address them over the I²C. You can use a PCF8575(16 I/O), as there are Arduino libraries. There are breakouts for it. Or you could make your own from another AVR, like one from the ATTiny line, seems there is 5 LEDs.

A I²C bus example:

(source: ermicro.com)

Seems you want to use the PWM, you can use a dot/bar driver IC, such as the LM3914 it takes an analog value and shows it as a point on the strip of LEDs, example below:

The IC can also work down to 3V.

What you will need to do is add a low pass filter to convert the PWM to a smooth analog value. You will add this in place of the input circuitry(D1 & C1) there:

If there is any confusion on the LM3914, there are quite a few tutorials on google.


SendSMS example sketch hangs at PINMUNBER if statement I'm using an Arduino shield connected to an Arduino Uno for sending text messages. I'm using one of the in built examples from the Arduino IDE for sending SMS by name - sendsms in the GSM examples. However, the code doesnt work at all... it keeps hanging at the line

if (gsmAccess.begin(PINNUMBER) == GSM_READY)

and never goes beyond it.

I didn't keep any pincode for my SIM card. please help

Try this sketch:

#include <SoftwareSerial.h>

SoftwareSerial gsm(2,3);
void setup() {
  Serial.begin(9600);
  gsm.begin(9600);
  delay(1000);
}

void loop() {
  // put your main code here, to run repeatedly:
  while (gsm.available() > 0)
    Serial.write(gsm.read());
  while (Serial.available() > 0)
    gsm.write(Serial.read());
}

This sketch will help troubleshoot exactly what's wrong with your setup, without the clutter of a library.

Connect the shield's TX pin to Arduino pin 2 and the shield's RX pin to Arduino pin 3. Ensure that all GNDs are connected. Upload the sketch. Set your serial monitor to BOTH NL & CR and the baud rate to 9600. Enter AT from the serial monitor. If you recieve OK, it means comms have been established with the shield. If you receive gibberish, change the SoftwareSerial baud rate to values from 19200, 57600, etc. until you get a legible response.

Then send the command AT+CREG? to check the SIM's registration status. If you get something like +CREG: *, 1 or +CREG: *, 5 (* means 'dont care'), then your SIM has been registered on the network. Report your results here.


How to read two byte register address using arduino wire library I want to read a register 0x012A from the device I2C address 0x0A, the value stored in the register is two bytes, If the register address is one byte i can use Wire.requestFrom and give the register address and how many bytes i want to read since here register address itself 2 bytes i'am bit confused . can any one help in this regard.

i can use Wire.requestFrom and give the register address and how many bytes i want to read

So you give it 2 to ask for 2 bytes.
Then you combine them. How you do that depends on what the bytes represent.  If the first is the upper byte and the second the lower byte of a 16 bit value then you would:
uint8_t b1 = Wire.read();
uint8_t b2 = Wire.read();

uint16_t val = (b1 << 8) | b2;

If it's the other way around then just swap the variables in the combining section.
However if the values are some other arrangement (I saw something recently that had two registers with a 12 bit value with overlapping bits) you will have to combine it in the way that is required for that specific arrangement.


ESP-01 adapter and logic level converter I read that I'll need a logic level converter like this to run an ESP8266-01 from the Uno.

But I saw this ESP adapter:

http://www.ebay.com/itm/ESP-01-ESP8266-Serial-Wi-Fi-Wireless-Adapter-Module-3-3V-5V-Compatible-Arduino-/282524471281?hash=item41c7c54ff1:g:wp0AAOSwQ59ZaClP

Two questions:

The ESP-01 has 8 connections but this has only 4, how come? Will I get the same functionality?
If I'll use this adapter, then I won't need the logic level converter?

The module has a 3.3V voltage regulator circuit and 5v-3.3v onboard level conversion circuit.

Yes, the module can be used with Arduino UNO R3 or compatible board without needing an additional level converter, as it is integrated in the module.

The module has Vcc, GND, TX and RX, so it means it uses a serial protocol for Arduino communication (and you will need two pins in the Arduino). Other pins in the ESP-01 are not needed in this scenario, but you still have access to them via the 8-pins female connector on the module.

It's totally plug and play.

Addendum: The old way

This how you connect a standard ESP-01 with an Arduino. The module you are looking at include all the resistors and also connect the CH_PD pin to Vcc. You only need to connect four pins. It saves you time, money and space.


How to send data from an Arduino to PC, without using the Serial Monitor? I have an analog sensor which I want to send data from my Arduino Certified Intel Edison to PC, without using a Serial Monitor and preferably putting the data into a text file.

I believe you are looking for something like the Telemetry library.

Full disclaismer : I am the author

It allows you to send string, numbers, arrays, sparse arrays through the serial port for instance. Each sent data has a label, called topic, that is used to identify it.

The Pytelemety command line interface then allows you to connect to the serial port, plot received data in real time, write parameters to reconfigure the arduino from the computer, etc.

Example of arduino code thats send an incrementing counter

#include <Telemetry.h>

Telemetry TM;
int8_t counter;

void setup() {
  TM.begin(115200);
  counter = 0;
}

void loop() {
  TM.pub_i8("count",counter);
  counter++;
  delay(10);
}

Overview of the CLI (Command-Line Interface)

Overview of a graph (not produced by the arduino program above)

Output to file is not implemented yet, although all received data is logged to a file (but this log also contains system information). However, this is an interesting feature, quite straightforward to implement, that I might add in coming days if you are interested.

Central documentation is available here.


Dice is not showing the correct numbers I've made a dice roller (to make it easier to roll the dice) using an Arduino UNO and an LCD keypad shield but I can't get the correct numbers (1, 6 (7)) to show up, I've tried using int, float and everything in between. the buttons on the shield are connected to A0, can someone help me please?

#include <LiquidCrystal.h>
// select the pins used on the LCD panel
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

#include "DFRkeypad.h"
String line2 = "Press Select to roll"; // Scrolling line

// just some reference flags
//int stringStart, stringStop = 0;
//int scrollCursor = screenWidth;

// define some values used by the panel and buttons
int lcd_key     = 0;
int adc_key_in  = 0;
#define btnRIGHT  0
#define btnUP     1
#define btnDOWN   2
#define btnLEFT   3
#define btnSELECT 4
#define btnNONE   5

// read the buttons
int read_LCD_buttons()
{
  adc_key_in = analogRead(0);      // read the value from the sensor

  // For V1.0 comment the other threshold and use the one below:

  if (adc_key_in > 1000) return btnNONE; // We make this the 1st option
  for speed reasons since it will be the most likely result
  // For V1.1 us this threshold
  if (adc_key_in < 50)   return btnRIGHT;
  if (adc_key_in < 195)  return btnUP;
  if (adc_key_in < 380)  return btnDOWN;
  if (adc_key_in < 555)  return btnLEFT;
  if (adc_key_in < 790)  return btnSELECT;

  return btnNONE;  // when all others fail, return this...
}

void setup() {
  randomSeed(analogRead(1));
  lcd.begin(16, 2);              // start the library
  lcd.setCursor(3, 0);
  lcd.print ("Catan Dice");
  lcd.setCursor(0, 1);

  // while(line2)
  //
  // lcd.print(line2);
  // break;
}

void loop() {

  //Dice
  byte DiceOne = random(1, 7);
  byte DiceTwo = random(1, 7);

  //local varables
  int buttonState = read_LCD_buttons(); // read the button pad
  int lastButtonState = btnNONE; // previous state of the button

  // the following variables are unsigned longs because the time, measured in
  // milliseconds, will quickly become a bigger number than can be stored in an int.
  unsigned long lastDebounceTime = 0;  // the last time the output pin was toggled
  unsigned long debounceDelay = 50;    // the debounce time; increase if the output flickers

  switch (buttonState)
  {
    case btnSELECT:
      lcd.clear();
      //Row, Colum
      lcd.setCursor (0, 4);
      lcd.print(DiceOne);
      lcd.setCursor (1, 4);
      lcd.print(DiceTwo);
      break;
  }

  DELAY(100)

  // read the state of the switch into a local variable:
  int reading = digitalRead(buttonState);

  // check to see if you just pressed the button
  // (i.e. the input went from LOW to HIGH), and you've waited long enough
  // since the last press to ignore any noise:

  // If the switch changed, due to noise or pressing:
  if (reading != lastButtonState) {
    // reset the debouncing timer
    lastDebounceTime = millis();
  }

  if ((millis() - lastDebounceTime) > debounceDelay) {
    // whatever the reading is at, it's been there for longer than the
    debounce
    // delay, so take it as the actual current state:

    // if the button state has changed:
    if (reading != buttonState) {
      buttonState = reading;
    }
  }

UPDATE, i got it working now

You are calling setCursor() with:

//Row, Colum
lcd.setCursor (0, 4);
lcd.print(DiceOne);
lcd.setCursor (1, 4);
lcd.print(DiceTwo);

While your comment notes the order is Row, Column, there appear to be several LiquidCrystal libraries floating about, some of which use Column, Row order in the SetCursor() function. The official Arduino library source indicates the col, row order.

You are writing both values on row 4 (even though that doesn't exist on your display), and in columns 0 and 1, thus you are correctly computing the Dice values, but they are being written with no gap between.


MAX232 chip fails to initialize properly with arduino I have connected a MAX232 chip for RS232 communication with my Arduino.
The chip input is connected to Arduino Tx and it is getting power from external 3.3 volt dc power source.

My Arduino is also getting power from 12 volt DC external power source.

While I connect and start the device, the PC is not getting any data until I reboot the MAX232.

How do I make a robust setup so that after I turn the powers on, it starts transmitting. Even if connection to my PC has been lost.

Datasheet for MAX232

  Section 7.3 Recommended Operating Conditions VCC Supply voltage

  MIN=4.5, NOM=5, MAX=5.5 (V)

The MAX232 has a minimum supply voltage of 4.5V, typically expecting 5V.

There are other alternatives, such as the MAX3232, which supports either 3.3V or 5V supply voltage.


Problem connecting 2 74HC595 8 bit shift registers in cascading connection I have now successfully learned how to control a single 8 bit shift register 74HC595 with Arduino UNO but whenever I tried to connect another one with the first shift resistor via cascading connection just like the image shown below (well I didn't use the 10uf capacitor between positive and negative terminal), the first shift register only outputs as desired but the second shift register, connected to a cascading connection, does not seem to work...

Here is the code.
    int latchPin = 10;  // Latch pin of 74HC595 is connected to Digital pin 5
int clockPin = 11;  // Clock pin of 74HC595 is connected to Digital pin 6
int dataPin = 9;    // Data pin of 74HC595 is connected to Digital pin 4

byte leds = 0;      // Variable to hold the pattern of which LEDs are currently turned on or off

/*
 * setup() - this function runs once when you turn your Arduino on
 * We initialize the serial connection with the computer
 */
void setup()
{
  // Set all the pins of 74HC595 as OUTPUT
  pinMode(latchPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  Serial.begin(9600);
}

/*
 * loop() - this function runs over and over again
 */
void loop()
{
  leds = 0; // Initially turns all the LEDs off, by giving the variable 'leds' the value 0
  updateShiftRegister();
  delay(500);
  for (int i = 0; i <= 16; i++) // Turn all the LEDs ON one by one.
  {
    bitSet(leds, i);        // Set the bit that controls that LED in the variable 'leds'
    updateShiftRegister();
    delay(500);
  }

 /* The loop above should repeated 16 times as there are 2 shift resistors, each of them containing 8 and we need to lit up all 16 LEDs*/

}

/*
 * updateShiftRegister() - This function sets the latchPin to low, then calls the Arduino function 'shiftOut' to shift out contents of variable 'leds' in the shift register before putting the 'latchPin' high again.
 */
void updateShiftRegister()
{
   digitalWrite(latchPin, LOW);
   shiftOut(dataPin, clockPin, LSBFIRST, leds);
   digitalWrite(latchPin, HIGH);
}

so is it my code or wiring problem?
I have read many articles on internet to make myself get it understood but unfortunately, none of the articles satisfied me.
many thanks for giving me a bit of your precious time...

I am really very sorry to say that after a long inspection , i have found that
shift register clear (pin 10) pin of the second shift register remained inactivated due to loose connection of power, after fixing it, all shift registers are working very fine.
I do really apologize to all those friends who came to help me, for wasting their time, i am really very sorry for that...
all problems are solved now.


Control Brushless ESC From Arduino I am trying to build a quadcopter using an arduino. I Bought 4 30A ESC's from Ebay the link is http://www.ebay.co.uk/itm/4pcs-Brushless-speed-controller-ESC-MultiCopter-KK-Quad-rotor-X-copter-30A-S-/310950293677?pt=LH_DefaultDomain_3&hash=item486614f0ad and a A2212 2200KV motor, im also using a sparkfun arduino uno. I have connected the white (data) servo wire of the ESC to pin 9 of my arduino and the black (ground) servo wire of the ESC to gnd of the arduino. When i connect the battery to the esc i get the 3 beeps because of my 3 cell battery regardless of what code is on the arduino even if the arduino is not present. the code that is on the arduino is.

#include <Servo.h>

Servo motor;

void setup()
{
  Serial.begin(9600);
  motor.attach(0);
}
void loop()
{
  motor.write(100);
}

I'm not sure what is wrong. Can someone please help me.

I had a similar problem. I solved it by using an oscilloscope to measure the arming sequence of an out-of-the-box RC remote controller and receiver.

The arming sequence through the controller-receiver was like this:

Connect ESC to battery (arduino is connected to signal and ground prior to this)
Wait for 3 beeps
Set the throttle to the lowest possible
Wait for another beep

I then adjusted my arduino code to output the same(similar) sequence.

Here is the code:

#include <Servo.h>
#define POT A0

Servo m1;

void setup() {
  m1.attach(6);
  Serial.begin(9600);
  delay(50);
  Serial.println("Serial ready:");
  arm(m1);
}

void loop() {
  int potValue = analogRead(POT);
  int s = map(potValue,60,930,1200,1700); //Map the pot values to motor values

  m1.write(s);
  Serial.println(s);
}

void arm(Servo m){
  Serial.print("Arming.");
  m.write(0);
  delay(100);
  m.write(1224); //A value at which the motor starts turning
  delay(2000);
  m.write(1024); //A value at which the motor stands still
  delay(3000);
  Serial.println(" Armed!");
}

You can also see a video of the whole thing in action here: A2212/13T brushless motor on a pivoting arm

EDIT: Further testing shows, that it suffices to output a low non zero value to arm this ESC. Simply doing Servo.write(1024); until you hear the confirmation beep seems to work.


Program got so many errors about expected ) or ; before either This is my first time to try program arduino, and I am clueless. I have a friend who told me about things work, and he told me the programming language is C (or similar to C) which we have learned in our class. I just program as my friend examples, but it doesn't work and return error codes about expected ; before ( or ) before ; etc.

I'm not sure why this wont work. This is the hardware (simulated) I going to make.

here's the code:

#define dw 8; //buttons down
#define ri 9; //buttons right
#define le 10; //buttons left
#define up 11; //buttons up
#define ok 12; //buttons ok
#define mn 13; //buttons menu
#include <LiquidCrystal.h>
LiquidCrystal lcd(6,5,4,3,2,1);
int i=0;
char input[]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};

void setup()
{
  pinMode(dw, INPUT);
  pinMode(ri, INPUT);
  pinMode(le, INPUT);
  pinMode(up, INPUT);
  pinMode(ok, INPUT);
  pinMode(mn, INPUT);
}
void intext()
{
  int c=0, lim=16;
  for(i=0;i<lim;)
  {
    lcd.setCursor(c,1);
    input[i]=97;
    if(dw=HIGH)
    {
      if(input[i]>122)
        input[i]=97;
      input[i]=input[i]+1;
      lcd.print(input[i]);
    }
    if(up=HIGH)
    {
      if(input[i]>97)
        input[i]=122;
      input[i]=input[i]-1;
      lcd.print(input[i]);
    }
    if(ri=HIGH)
    {
      c=c+1;
      lcd.setCursor(c,1);
      lcd.print(input[i]);
    }
    if(le=HIGH)
    {
      c=c-1;
      lcd.setCursor(c,1);
      lcd.print(input[i]);
    }
    if(ok=HIGH)
    {
      lim=i+1;
    }
  }
}

void loop()
{
  lcd.begin(16,2);
  lcd.setCursor(0,0);
  lcd.print("Masukan kata:");
  intext();
}

I have no idea why it wouldn't work. I'm sorry if I'm too stupid to understand.
Thank you!

Edit: oh yeah, the errors, here:

  This report would have more information with
  "Show verbose output during compilation"
  enabled in File > Preferences.
Arduino: 1.0.6 (Windows NT (unknown)), Board: "Arduino Uno"
programyuhu.ino: In function 'void setup()':
programyuhu:14: error: expected `)' before ';' token
programyuhu:14: error: expected primary-expression before ',' token
programyuhu:14: error: expected `;' before ')' token
programyuhu:15: error: expected `)' before ';' token
programyuhu:15: error: expected primary-expression before ',' token
programyuhu:15: error: expected `;' before ')' token
programyuhu:16: error: expected `)' before ';' token
programyuhu:16: error: expected primary-expression before ',' token
programyuhu:16: error: expected `;' before ')' token
programyuhu:17: error: expected `)' before ';' token
programyuhu:17: error: expected primary-expression before ',' token
programyuhu:17: error: expected `;' before ')' token
programyuhu:18: error: expected `)' before ';' token
programyuhu:18: error: expected primary-expression before ',' token
programyuhu:18: error: expected `;' before ')' token
programyuhu:19: error: expected `)' before ';' token
programyuhu:19: error: expected primary-expression before ',' token
programyuhu:19: error: expected `;' before ')' token
programyuhu.ino: In function 'void intext()':
programyuhu:28: error: expected `)' before ';' token
programyuhu:28: error: expected primary-expression before '=' token
programyuhu:28: error: expected `;' before ')' token
programyuhu:35: error: expected `)' before ';' token
programyuhu:35: error: expected primary-expression before '=' token
programyuhu:35: error: expected `;' before ')' token
programyuhu:42: error: expected `)' before ';' token
programyuhu:42: error: expected primary-expression before '=' token
programyuhu:42: error: expected `;' before ')' token
programyuhu:48: error: expected `)' before ';' token
programyuhu:48: error: expected primary-expression before '=' token
programyuhu:48: error: expected `;' before ')' token
programyuhu:54: error: expected `)' before ';' token
programyuhu:54: error: expected primary-expression before '=' token
programyuhu:54: error: expected `;' before ')' token

Here's the first line of your code:

#define dw 8; //buttons down

Here's the first error line:

pinMode(dw, INPUT);

Let's put them together and see what we get:

pinMode(8; //buttons down, INPUT);

That's not valid C++. Using the output I've shown you, modify the input until it looks correct. And then keep doing it until the code compiles.


How to convert string to byte array on arduino Well my title pretty much sums it up , how to convert string to byte array? i cant find any usefull code

Well, the C string is already byte array.

If you mean Arduino's String class, then it has c_str() method.

Both needs reinterpret cast to const byte pointer:

byte const* byteArray = reinterpret_cast<byte const*>(yourString.c_str());


Arduino UNO does not get recognized by PC(no USB connecting sound), also TX and RX not blinking, neither are lit I am trying to build a robot, which needs motors to roll around. So I was trying to control two DC motors with H-Bridge that comes with Arduino StarterKit(H-bridge motor driver [L293D]). I used Sketch that looks something like that

I did read that Arduino needs separate powering, but i did not use any only USB connection. I connected 5V that comes from arduino to where + pin from battery should have been connected and motors were controlled and working.
However when i tried using 9V battery and connecting it as seen on above picture ,H-bridge did not control mototrs and nothing was working.
There is also another aspect - when robot was touching the surface then wheels did not move aka motors did not rotate and when you picked it up motors accelerated to quite some speed. Also when robot was on the surface and connected via USB, the PC made these USB connecting sounds repeatedly.
I am not sure when RX and TX stopped working. Power LED and L13 LED do work correctly.

Any ideas? Is it Fixable?

You should definitely avoid connecting anything else than 5v to these 5v(!) PINs. The Uno has regulators, but these only work when powered through the power-dc-connector (or USB). You can easily buy a 9v-block to dc-jack cable to connect power to the right point easily.


'Serial1' was not declared in this scope for automatic plant watering #include <LiquidCrystal.h>
#include <SoftwareSerial.h>
int in1 = 2;
int in2 = 3;
LiquidCrystal lcd(14,15,16,17,18,19);
int led = 13;
int flag = 0;
int motorpin = 11;
int sensorpin = 7;

void setup()
{
  lcd.begin(16,2);
  Serial1.begin(9600);
  pinMode(led, OUTPUT);
  pinMode(motor, OUTPUT);
  pinMode(sensor, INPUT_PULLUP);
  lcd.print("Plant Watering");
  lcd.setCursor(4,1);
  delay(2000);
  lcd.clear()
  lcd.print("RCC INSTITUTE");
  lcd.setCursor(0,1);
  lcd.print("Starting....");
  delay(2000);
  gsmInit();
  lcd.clear();
  lcd.print("System Ready");
}

void loop()
{
  lcd.setCursor(0,0);
  lcd.print("Automatic Mode");
  if (digitalRead(sensor) == 1 && flag == 0)
  {
    delay(1000);
    if (digitalRead(sensor) == 1)
    {
      digitalWrite(led, HIGH);
      sendSMS("Low Soil Moisture detected. Motor turned ON");
      lcd.begin(16, 2);
      lcd.setCursor(0, 1);
      lcd.print("Motor ON ");
      digitalWrite(motor, HIGH);
      delay(2000);
      flag=1;
    }
  } else if(digitalRead(sensor) == 0 && flag == 1)
  {
    delay(1000);
    if (digitalRead(sensor) == 0)
    {
      digitalWrite(led, LOW);
      sendSMS("Soil Moisture is Normal. Motor turned OFF");
      digitalWrite(motor, LOW);
      lcd.begin(16, 2);
      lcd.print("Motor OFF");
      lcd.setCursor(0, 1);
      lcd.print("Motor OFF");
      delay(2000);
      flag = 0;
    }
  }
}

void sendSMS(String msg)
{
  lcd.clear();
  lcd.print("Sending SMS");
  Serial1.println("AT+CMGF=1");
  delay(500);
  Serial1.print("AT+CMGS=");
  Serial1.print('"');
  Serial1.print("+918xxxxxxxxx"); // number
  Serial1.print('"');
  Serial1.println();
  delay(500);
  Serial1.println(msg);
  delay(500);
  Serial1.write(26);
  delay(1000);
  lcd.clear();
  lcd.print("SMS Sent");
  delay(1000);
  lcd.begin(16, 2);
}

void gsmInit()
{
  lcd.clear();
  lcd.print("Finding Module..");
  boolean at_flag = 1;
  while (at_flag)
  {
    Serial1.println("AT");
    while (Serial1.available() > 0)
    {
      if (Serial1.find("OK"))
      at_flag = 0;
    }
    delay(1000);
  }
  Serial1.println("ATE0"); //<=== it says 'Serial1' was not declared in this scope
  lcd.clear();
  lcd.print("Finding Network..");
  boolean net_flag = 1;
  while(net_flag)
  {
    Serial1.println("AT+CPIN?");
    while(Serial1.available() > 0)
    {
      if (Serial1.find("READY"))
        net_flag = 0;
      break;
    }
    delay(1000);
  }
  Serial1.println("AT+CNMI=2,2,0,0,0");
  delay(1000);
  Serial1.println("AT+CMGF=1");
  delay(1000);
  Serial1.println("AT+CSMP=17,167,0,0");
  lcd.clear();
  Serial1.flush();
}

The UNO only has one serial port, named Serial.  You can create another one using SoftwareSerial (which you have included but not used) and you can, if you choose, name this Serial1.

#include <SoftwareSerial.h>

SoftwareSerial Serial1(4, 5); // RX, TX


Do we have to calibrate LDR before using it in a project? I am doing a project with Arduino, making a synthesizer, in which an LDR is used.

Before connecting the Arduino to a power source and use the project, do I need to calibrate the LDR like it is explained in Arduino website ?

An LDR is a pretty inaccurate device. It just gives you a number which relates to darkness or brightness. How do those numbers relate to darkness and brightness? Well, only in a very vague way. All you can really say with any confidence is that bigger numbers mean brighter light, and smaller numbers mean darker darkness.

Even after "calibration" the numbers are pretty meaningless in any real-world sense.

All the "calibration" does is give a rough guide to the range of the numbers produced in any given lighting situation. It's then up to you to program your sketch in such a way that it works within the ranges of those numbers.

And yes, those numbers will change depending on the current lighting situation.

You could incorporate some form of "calibration" routine in your sketch to adjust any relevant values and calculations, or you could just provide some interface for tweaking values. Or your system may just really not care. It's impossible to know until you actually start creating your system.


Doubt on Processing Power The datasheet of arduino mega claimed that the board has 16Mhz processing power. But the question that doubt me is what would happen to the board if the board has no enough processing power.

For example,  if the board is used in an application that involves a lot of calculation in each loop. Would it stall the board?

Personally, i think the board would just give slower response instead of stalling the board. It was due request is done in sequential method in the code. Therefore it would not accumulate up the request until stalling the device like PC and I think it would be just at most an arduino which is always busy.

Is it what would happen if the board has no enough processing power?

Processing Power is a bit of a misnomer. Clock Frequency is a better description.

In general one assembly instruction gets executed each clock cycle. That means approximately 16 million instructions per second (there are a couple that take more than 1).

Your C program gets compiled into those instructions and executed at 16 million instructions per second.

If your routine is 16 million instructions long (when loops are unrolled) then it will take 1 second to execute.

Unlike a PC, which is constantly switching between tasks, an Arduino does only one thing, and that is the one thing you programmed it to do. Because of that execution time is predictable. If it took 1 second to execute today it will take 1 second tomorrow,  and 1 second next week.


ESP32: How to run two independent PID controllers, one per core? I want to control 2 independent processes with 2 PID controllers. Is it possible to run each controller on a separate core? I'm using this PID library. According to its documentation, the PID::Compute() function should be called once every loop(). How can this be achieved when using RTOS tasks (for multi core execution)?

esp32_technical_reference_manual_en.pdf
Page 620
As mentioned before, only an elevated process with PID of 0/1 can initiate a process switch. The new process
may have any PID from 0 ~ 7 after the process switch. The key for successful proactive process switching is that
Espressif Systems 620
Submit Documentation Feedback
ESP32 Technical Reference Manual V4.3
29. PID Controller
when the last command of the current process switches to the first command of the new process, PID should
switch from 0/1 to that of the new process.
The software procedure for proactive process switching is as follows:

Mask all the interrupts except NMI by using software.
Set register PIDCTRL_NMI_MASK_ENABLE_REG to 1 to generate a CPU NMI Interrupt Mask signal.
Configure registers PIDCTRL_PID_DELAY_REG and PIDCTRL_NMI_DELAY_REG.
Configure register PIDCTRL_PID_NEW_REG.
Configure register PIDCTRL_LEVEL_REG and PIDCTRL_FROM_n_REG.
Set register PIDCTRL_PID_CONFIRM_REG and register PIDCTRL_NMI_MASK_DISABLE_REG to 1.
Revoke the masking of all interrupts but NMI.
Switch to the new process and fetch instruction.
Though we can deal with interrupt nesting, an elevated process should not be interrupted during the process
switching, and therefore the interrupts have been masked in step 1 and step 2.
In step 3, the configured values of registers PIDCTRL_PID_DELAY_REG and PIDCTRL_NMI_DELAY_REG will
affect step 6.
In step 4, the configured value of register PIDCTRL_PID_NEW_REG will be the new PID after step 6.
If the system is currently in a nested interrupt and needs to revert to the previous interrupt, register
PIDCTRL_LEVEL_REG must be restored based on the information recorded in register PIDCTRL_FROM_n_REG
in step 5.
In step 6, after the values of register PIDCTRL_PID_CONFIRM_REG and register
PIDCTRL_NMI_MASK_DISABLE_REG are set to 1, PID Controller will not immediately switch PID to the value of
register PIDCTRL_PID_NEW_REG, nor disable CPU NMI Interrupt Mask signal at once. Instead, PID Controller
performs each task after a different number of clock cycles. The numbers of clock cycles are the values specified
in register PIDCTRL_PID_DELAY_REG and PIDCTRL_NMI_DELAY_REG respectively.
In step 7, other tasks can be implemented as well. To do this, the cost of those tasks should be included when
configuring registers PIDCTRL_PID_DELAY_REG and PIDCTRL_NMI_DELAY_REG in step 3.
Espressif Systems 621
Submit Documentation


Not enough pins on Uno? I'm making touch-sensitive, light up tic-tac-toe board.

That means 9 LEDs + 9 capacitive sensors.

Each LED needs 1 pin and each sensor needs 2...meaning I'd need 27 pins to properly control each touch-and-illuminate sequence.

There aren't enough inputs on the Uno for this, so what sort of workarounds should I explore to pull this off?

There are a number of common solutions to "not enough pins".

Reduce the number of pins you need. This option is often discarded out of hand, but may be the best. For example, you may be able to reduce the 18 individual pins for the on/off capacitive sensor, with a different part, which may be able to give you an X,Y co-ordinate of where it is touched, with fewer pins.
Multiplex the pins. This seems to be the most likely to work in this case - you will use (for example) 9 Uno pins to power the LED and capacitive sensor on each cell, one at a time. So, for example, you might attach D1 to the top left cell, D2 to the top-center, and so forth. Then you use another pin (e.g. D10) to connect to ALL the cathodes of the LEDs (via a single transistor, to protect the Uno from too much current), D11 and D12 to connect to one of the data pins of ALL of the capacitive sensors. So, you "select" cell one, by switching D1 from LOW to HIGH. Then, you put D10 to LOW, so current will from across the LEDs. Read the capacitive sensor, which is now also powered on. Although all of the censors are connected to D11 & D12, only one will be powered on, so you will only be reading that one. Once read, you probably want to delay a few milliseconds, to make sure the light shows up. Then move on to the next cell. Go round and round all cells. The LEDs will be off 8/9ths of the time, but it will still be visible. NOTE: reading more about capacitive sensors, I see that one is input, the other output. You would need a transistor for each of the "select" pins, used as a switch to connect D11 to the correct sensor.
Do the same thing, but using a decade counter. Connect 2 pins from the Arduino to the decade counter - one to "count", and one to reset. First, strobe the reset - this will set the first output of the decade counter high - connected to cell 1. Then, when you want to move to the next cell, drop the "count" low, then high again. You are now on the next cell. Repeat until you get to cell 9, then send the "reset" (which guarantees you know where you are up to) to get back to cell 1.
Charlieplexing (mostly suitable for output only). This is a somewhat complicated, but very efficient (pin-count wise) way of running lots of LEDs off only a few Arduino pins, by using them in combination. For example, 3 pins could run 6 LEDs - if you have pins A, B and C, run one LED from A to B, one from B to C, and one from C to A; then, run 3 more LEDs in the OPPOSITE direction (don't forget your resistors!). Depending on which LED you want lit, you might want pin A high, B low, and C high impedance (INPUT). 4 pins will get you 12 LEDs, 10 will get you 90 LEDs. If you think this might be useful, check out the Wikipedia
Use chips that are designed specifically for the application you need. For example, TLC5940 chips will run up to 16 LEDs each, controlling the brightness of each LED independently. You set the brightness of each LED, then let the TLC5940 take care of the work. SIPO chips such as the 74HC595 (8 outputs) are similar, but only allow "on" or "off" for each pin. Both of these can be "daisy chained" - with the same number of Arduino pins, you can connect the output of one to the input of the next, to control more outputs.
Use multiple Arduinos. Yes, this might sound expensive, but you can use an AtMega (e.g. AtMega328, which is the same chip used in the Arduino) for a fraction of the cost. You might even use an AtTiny - even cheaper (but less memory). All of these can run the same code. This is the most flexible, but is also the most work - you would need to think about which chip does what, how they interact, and how they talk to each other. This also has the advantage that, rather than a chip that runs at 16mhz, you can now have multiple chips that each run at that speed, and have more memory each. Some applications work well with one "master" chip controlling one (or more) "slaves", whereas other applications work really well as peer-to-peer, either with each node running the same code, or each doing their own thing, and passing information to other nodes. For this example, you might use one AtTiny85 for each of the 9 cells, with an Arduino to be the master. Or, use an AtTiny84, for each row of 3 cells, with one Arduino to rule them all. The AtTiny84 has 14 pins: power, ground, reset, and 11 data pins - 2 is enough for a shared data bus, such as i2c, leaving 3 pins for each of 3 cells.
(not relevant for this example) For multiple on/off sensors (e.g. pushbuttons, switches), you can attach them through different values of resistors, and connect them to an ADC pin as a voltage divider. For example, connect ground via R0 to an analog pin; then connect to the same pin: pin -> resistor 1 -> pushbutton 1 -> +5v; pin -> resistor 2 -> pushbutton 2 -> +5v, and so forth. Build the circuit, and test each combination of switches/pushbuttons on/off, what the output will be. Then, in your code, figure out which combination it is closest to. Each resistor will need to be different resistance. If you only expect one switch to be on at once, it's a lot easier.


Antenna for ESP32-pico-d4 I am currently playing a bit around with the esp32-pico-4d, it does not have an onboard antenna, so an external antenna is needed, tho I don't know a lot about it so a little help would be appreciated.

I found this:

https://www.espressif.com/sites/default/files/documentation/esp32-pico-d4_datasheet_en.pdf

here one says that he literally just connected the antenna to ground and LNA_IN would that work?

and which antennas would you recommend? (as small as possible is only gonna be used for BLE and)

(datasheet: https://www.espressif.com/sites/default/files/documentation/esp32-pico-d4_datasheet_en.pdf)

here one says that he literally just connected the antenna to ground and LNA_IN would that work?

Yes. LNA_IN is the input to the Low Noise Amplifier - the input stage of the receiver / output stage of the transmitter.

  and which antennas would you recommend? (as small as possible is only gonna be used for BLE and)

You want one tuned for 2.4GHz. The simplest is a quarter wave dipole at 3.125cm in length. Better would be a proper 2.4GHz antenna of the kind you get on a WiFi router or some USB WiFi dongles.


5V DC Mini Water Pump with Arduino Mega 2560? First of all, it is my first topic and i want to say hi to you all!! Secondly, i am really a terrible noob and sorry for that  :(

I need to make a smart greenhouse project with Arduino Mega 2560, and i found a video to help me with my servomotor(MG996R) which will start working when raindrops module detect rain and 12v DC Fan which will start working when LM35 sensor calculates the weather as hot. However, my third actuator, 5V DC Mini Water Pump, which needs to become turned on when soil humidity sensor measures the soil as dry, is where i am left without an opinion. All the water pumps people use is 12 V, so i dont know which specific components i should use. I researched a bit and found that people use transistors and diodes for it. Which ones should i use and how to make the connections?

I would appreciate if someone helps me what components, specifically, should i buy and how to connect them together with Arduino 2560? It would be great if you can draw it, like with fritzing or something.

Thanks if you read this far :)

Welcome to arduino.stackexchange.com .

As motor is usually a high current load, controlling a switch to control the motor's power is the solution.

If you are not interested in h/w design just want to use a interface out of box you can use relay module like this relay. For only one load connection will be simple and I don't think Arduino current supply limit will be a problem.

see this answer for example connection using relay. It is almost similar use case I think. Also here is a Fritzing image using the relay in the first link. I have used four 3V battery pack as 12V source. It doesn't have to be battery.

If you like to do from scratch, you can use BJT(Bi polar junction transistor) or MOSFET.

Here is a possible schematic.

simulate this circuit – Schematic created using CircuitLab

Different power supplies are used for Arduino and Motor because recommended voltage range is 7-12V in Vin pin. Different sources, voltage levels like 5V from USB may be used according to your ease.

node b, c and e are base, collector and emitter of the BJT. Diode D1 is called flyback diode.

Let, the current needed for motor IL, motor voltage needed VL, collector current Ic and base current Ib and the resistor between arduino and base Rb. Note that IL = Ic

Operating mode of transistor will be saturation mode. So, the base current (supplied by arduino) will be,

Ibe = (current gain at saturation)*Ic

How to find the current gain? Look through the datasheet of transistor for hfe(sat) which is basically Ic/Ib at saturation mode. Some datasheet may use α instead of hfe(sat)

Then find the Vbe(sat) as you will be operating in saturation mode. Find the needed base resistor value Rb,

Ib = 5-Vbe/Rb

While designing this you have to be careful about these condition (I am talking about design using BJT)

Vce(max)(max) > VL
Ice(max) > IL
Arduino digital pin max I > Ib

All the devices should have same ground. Be sure to use the diode(D1) mentioned in the design as motor is an inductive load, sudden powering down may create large voltage across motor.


How to connect an RF module directly to a PC without using an arduino? I know that in xbees i can connect the xbee module directly to my pc using the USB explorer. But I'm using the nRF24L01 RF modules. I want to transmit from my pc, via the RF transmitter to my RF receiver, which is connected to my arduino. How do I connect this RF module directly to my PC?

The nRF24L01+ uses SPI. PCs don't (usually) have an SPI interface. So you will need some piece of hardware to provide the PC with an SPI interface.

That could be an Arduino, or it could be a dedicated SPI dongle, such as one based around the FT2232 chip.

Of course, you then would need to write software to use that SPI interface and work with the nRF24L01+ connected to it, including using the same message format / packet system, which won't be a simple task. So you may be better off just using a small Arduino to do the communication and present you with a simple serial interface for sending / receiving messages. That way you can then use the same nRF24L01+ software that you are using elsewhere in your setup.


May arduino hang when current is changing over time? As in title. I've got quadrocopter where Li-Po is parallely connected to motors as well as to arduino. May current driftage cause arduino hangs ?

There really isn't any such thing as "Current driftage". If you draw too much current from your battery it will cause the voltage to drop, and if it drops too much, the Arduino will stop working.

If you have high current devices like motors being switched on the same power supply as your Arduino you should add a reservoir capacitor as close to the input of your Arduino as possible. That will even out short term drops and spikes in supply voltage as your motors switch.

If you draw too much current continuously then your supply voltage will drop and stay dropped, and a reservoir capacitor won't help. In that case you need a higher current battery (or separate power supplies for your Arduino and motors.)

Edit: From your question it's pretty clear that you don't understand voltage and current and how they relate. I suggest you read up on the subject.

In short, the amount of current that flows through a component is determined by the voltage divided by the resistance: i = v/r. (Where i = current in amps, v = voltage, and r = resistance in ohms.)

The current that will flow will be limited by the max current that the power supply can provide.

For a non-regulated supply like a battery, the voltage from the supply will drop as you draw more and more current.

For a regulated supply, the supply keeps the voltage constant up to it's maximum current limit.


Powering Arduino Uno, CAN Crocodile and NeoPixels from Car I have purchased a cigarette adapter that gives me 2 USB ports, however this gives me 5v and up to 2.4A.

Thats ok for powering the Arduino Uno, I need 12/24v to power the CAN crocodile.

I also want to drive quite a lot of NeoPixels.

How can I do this?

A reasonable estimate for current consumption of 5V NeoPixels is 60mA per pixel. For 186 pixels, that means about 11.16A at 5V; well over the 2.4A of the adapter being used for your other components.

There exist modules called "DC-to-DC Buck Converters", which can step down the 12-14V of your automobile to pretty much any voltage under the input voltage. To be safe, look for a buck converter of at least a 75W rating, and which meets your criteria for input and output range (minimum of 12V input, could be rated higher; output range inclusive of 5V.)

Be sure that the Ground connections for the NeoPixel power supply and the other supply are shared/connected, but don't share the +5V line between supplies.


Audio stops playing after rtc is connected I am trying to play a song using arduino while at the same time display time using a rtc board using the tmrpcm library. However, if the rtc board is connected no sound is played.

I do understand that the tmrpcm may be interfering with the wire.h library but even commenting the same doesn't resolve the problem.

I am using the following code:

// Date and time functions using a DS1307 RTC connected via I2C and Wire lib
#include <RTClib.h>
#include<Wire.h>
#include <Arduino.h>
#include "SevenSegmentTM1637.h"
#include "SevenSegmentExtended.h"
#include "SevenSegmentFun.h"
#include "SD.h"
#define SD_ChipSelectPin 4
#include "TMRpcm.h"
#include "SPI.h"

TMRpcm tmrpcm;

const int ProxSensor=3;
int inputVal = 0;
#define CLK 8
#define DIO 7

// The amount of time (in milliseconds) between tests
#define TEST_DELAY   2000

SevenSegmentFun    display(CLK, DIO);

RTC_DS1307 rtc;

char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

void setup () {
  Serial.begin(9600);
  if(!SD.begin(SD_ChipSelectPin))
  {
    Serial.println("SD fail");
    return;
  }
  while (!Serial); // for Leonardo/Micro/Zero
  tmrpcm.speakerPin=9;
  Serial.begin(57600);
  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }

  if (! rtc.isrunning()) {
    Serial.println("RTC is NOT running!");
    // following line sets the RTC to the date & time this sketch was compiled
    rtc.adjust(DateTime(2019, 10, 19, 01,41,00));
    // This line sets the RTC with an explicit date & time, for example to set
    // January 21, 2014 at 3am you would call:
    // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
  }
  pinMode(ProxSensor,INPUT);    //Pin 2 is connected to the output of proximity sensor
  display.begin();
}

void loop(){
  DateTime now = rtc.now();
  display.print((now.unixtime() / 86400L )-17963);
  Serial.print((now.unixtime() / 86400L )-17963);
  while(digitalRead(ProxSensor)==LOW)      //Check the sensor output
  {
    tmrpcm.setVolume(5);
    tmrpcm.play("test.wav");
      repeat:
    if(digitalRead(ProxSensor==LOW))
      goto repeat;
  }
}

Can anyone please help me?

The problem is

repeat:
if(digitalRead(ProxSensor==LOW))
  goto repeat;

ProxSensor==LOW is false so 0. you read the pin 0 and the outcome is random. The surrounding wiring can affect that. If digitalRead(0) is zero the wav starts playing immediately again. At least use

while (digitalRead(ProxSensor) == LOW);


Arduino restarts when a function is called When I call a function, get_split(), the Arduino restarts. I have tried to find what is causing this, but I have had no luck. Here is my code:

std::vector<std::vector<std::vector<std::vector<float>>>> get_split(std::vector< std::vector< float > >& dataset) {
  std::vector<int> class_values; // declares vector 'class_values'
  for (int i = 0; i < dataset.size(); i++) { // loops through each value in dataset (the dataset contains vectors)  and appends the last value in each vector to class_values
    class_values.push_back(dataset[i][dataset.size()]);
  }
  std::vector<std::vector<std::vector<float>>> b_index;
  b_index.push_back(std::vector<std::vector<float>>(999));
  std::vector<std::vector<std::vector<float>>> b_value;
  b_value.push_back(std::vector<std::vector<float>>(999));
  std::vector<std::vector<std::vector<float>>> b_score;
  b_score.push_back(std::vector<std::vector<float>>(999));
  std::vector<std::vector<std::vector<float>>> b_groups;
  for (int i = 0; i < dataset[0].size(); i++) {
    for (int j = 0; j < dataset.size(); j++) {
      std::vector<std::vector<std::vector<float>>> groups = test_split(i,  dataset[j][i], dataset); // gets the split of the dataset (assigns each vector in the dataset to either 'left' or 'right')
      float gini = gini_index(class_values, groups); // calculates the gini
      if (gini < b_score[0][0][0]) {
        b_index[0][0][0] = i;
        b_value[0][0][0] = dataset[j][i];
        b_score[0][0][0] = gini;
        b_groups = groups;
      }
    }
  }
  std::vector<std::vector<std::vector<std::vector<float>>>> vals;
  vals.push_back(b_index);
  vals.push_back(b_value);
  vals.push_back(b_groups);
  return vals; // returns the values.
}

This code is meant to check the gini of splitting a certain function (the gini_index() function works fine). Then it calls test_split which assigns the vector values into two sub-vectors in the vector groups, left and right. Then I just choose the split with the lowest gini.

When I delete everything in the function it doesn't restart, but I have deleted the first for loop, and also the part where it returns a vector, but still no luck. Also when deleting the for loop underneath the declaration of b_groups, it still doesn't work. I don't think it is a memory/storage issue because the Arduino IDE says that I'm only using 3% of that.

PS: I have used the library StandardCplusplus library to include vectors.

Your code is very complex and running it in an environment where you have limited debug facilities is making life worse for yourself.

When an Arduino reboots it is usually because it has thrown a memory error.  This happens when you try and access memory that is no longer your program's to access (or never was yours).  In this case I originally suspected, based on the complexity of your code, that you were accessing a vector element that you could no longer access.

To prove this I 'ran it on a desktop', in my case a Windows 7 box with Visual Studio 2015 (but you could have used Linux, GCC and GDB).  This meant I wrote a little wrapper program and stubbed the functions you called.  This resulted in the error message shown below.

This is my 'desktop' code:

#include <vector>

std::vector<std::vector<std::vector<float>>> test_split(const int& i, const float& f, std::vector< std::vector< float > >& dataset)
{
    std::vector<std::vector<std::vector<float>>> vals;
    return vals;
}

float gini_index(const std::vector<int>& class_values, const std::vector<std::vector<std::vector<float>>>& group)
{
    return 1.0f;
}

std::vector<std::vector<std::vector<std::vector<float>>>> get_split(std::vector< std::vector< float > >& dataset) {
    std::vector<int> class_values; // declares vector 'class_values'
    for (int i = 0; i < dataset.size(); i++) { // loops through each value in dataset (the dataset contains vectors)  and appends the last value in each vector to class_values
        class_values.push_back(dataset[i][dataset.size()]);
    }
    std::vector<std::vector<std::vector<float>>> b_index;
    b_index.push_back(std::vector<std::vector<float>>(999));
    std::vector<std::vector<std::vector<float>>> b_value;
    b_value.push_back(std::vector<std::vector<float>>(999));
    std::vector<std::vector<std::vector<float>>> b_score;
    b_score.push_back(std::vector<std::vector<float>>(999));
    std::vector<std::vector<std::vector<float>>> b_groups;
    for (int i = 0; i < dataset[0].size(); i++) {
        for (int j = 0; j < dataset.size(); j++) {
            std::vector<std::vector<std::vector<float>>> groups = test_split(i, dataset[j][i], dataset); // gets the split of the dataset (assigns each vector in the dataset to either 'left' or 'right')
            float gini = gini_index(class_values, groups); // calculates the gini
            if (gini < b_score[0][0][0]) {
                b_index[0][0][0] = i;
                b_value[0][0][0] = dataset[j][i];
                b_score[0][0][0] = gini;
                b_groups = groups;
            }
        }
    }
    std::vector<std::vector<std::vector<std::vector<float>>>> vals;
    vals.push_back(b_index);
    vals.push_back(b_value);
    vals.push_back(b_groups);
    return vals; // returns the values.
}

int main(void)
{
    std::vector<std::vector<float>> dataset;

    std::vector<std::vector<std::vector<std::vector<float>>>> result = get_split(dataset);

    return fgetc(stdin);
}

Now you need to workout where it is crashing, easy in Visual Studio but very difficult on an Arduino.  However I would look at simplifying the code too.


Is it possible to run a binary from EEPROM? Say I wrote a compiled sketch to EEPROM then read it. Could I run the program from EEPROM? I guess the question is: Can an Arduino run software not in flash memory in the middle of executing the software in flash?

Short answer: No; From the atmega328's data sheet (though it applies to all AVR's):

  AVR uses a Harvard architecture – with
  separate memories and buses for program and data. Instructions in the program memory are
  executed with a single level pipelining. While one instruction is being executed, the next instruction is pre-fetched from the program memory

  ...

  Program Flash memory space is divided in two sections, the Boot Program section and the
  Application Program section. Both sections have dedicated Lock bits for write and read/write
  protection. The SPM instruction that writes into the Application Flash memory section must
  reside in the Boot Program section

It's architecture prevents using external program memory, but you can load anything into program memory at boot. At that point I would venture to say you are just programming AVR and not arduino, since you would need to replace the arduino bootloader and break the arduino IDE's ability to upload programs.

Alternately you could also use an emulator or interpreter of some intermediate language; basically code that steps through and runs other code. As a general rule an emulator runs around 8x slower.

There are micro-controllers from other brands that do support this functionality, I know a couple different PIC's do.


Connection from Arduino Uno to Microsoft SQL Server Database I would like to make a connection from Arduino Uno to Microsoft SQL Server for storing student attendance records into a table from my database.

So, what is the best way to do that? I need a suggestion or useful references and links.

I have written a web application on Visual Studio using C# language. What Arduino does is getting fingerprint through sensor, then I would like to store the attendance records of a student into database. So the attendance records can be retrieved from database to the web application and display to teachers.

This is just for project purpose only and the connectivity between Visual & SQL Server using these two lines below:

SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=DESKTOP-H7KQUT1;Initial Catalog=SAOS1;Integrated Security=True";

Using a layer between Arduino and MSSQL might give you the least headache. Would you like to do this on-premise or in the cloud?

For an easy cloud approach, look at AWS Lambda. Write a Lambda function that inserts into your MSSQL database, possibly running on AWS too. Your choice of Java, Node.js, C#, or Python. Hook it up with incoming MQTT messages from your Arduino.
https://stackoverflow.com/questions/33165045/aws-lambda-and-sql-server-integration
 could help.

For a cloud-free approach, you could run your own local MQTT server (broker, to be exact, Mosquitto being the most popular), and have your C# subscribe as an MQTT client. When the Arduino publishes a fingerprint signature, your C# script can do the database work.


When to use different variable types? There are several different types in the Arduino programming language. They each have different applications that can use up the limited RAM in the Arduino. When should i use each?

One should appreciate that the Arduino is an Embedded Processor. Specifically that it has limited resources of RAM and ROM(aka Flash/program space).

Often is the case I see coding use the "int" defaultly. Almost sloppily. If that works great.

BUT!!!!
You can run out of room REAL FAST with only 2K of RAM.

I would recommend that you size down your type to the minimum of what it needs to be describing it. One also gets a better understanding of what it really is and its limitations. There is no need for an array of int(16bits) from bytes that were recieved from the SPI, UART or I2C. Or a matrix of RGB's that consume 3 bytes each, being int's. You cut your capacity in half.

The pro/con: PRO: using default int everywhere makes it more inter changeable. The CON is that such interchangeability can lead to unintentional casting errors.

I would also recommend using C99 type def's which can be found at "avr_stdint.html">http://www.nongnu.org/avr-libc/user-manual/group_avr_stdint.html" and elsewhere. It makes things vivid, regards to this aspect. Hence a "int" would be a "int16_t", "unsigned long" be "uint32_t" etc...

It is worth knowing that in some cases a byte or char can not be replaced with int8_t, as such when used with string array functions. But they are still just as vivid.


Communication between Arduinos using USB Host Shield I'm working on a project that needs to use USB to pass serial messages between Arduinos (I can't use I2C or SPI for a few reasons – I especially need USB's support for hot-swapping and address allocation). So far I have the USB Host Shield set up on one Arduino Uno, connected to the standard USB port on another. It appears to be working, as can be seen when I run the board_qc:

The 'slave' Arduino is just running the following code:

void loop() {
  Serial.println("Hello");
  delay(1000);
}

On the master, I create a USB object from the USB Host library (https://github.com/felis/USB_Host_Shield_2.0).

USB Usb;

void setup() {
    Serial.begin(115200);
    Usb.Init();
}

void loop() {
    if (Usb.getUsbTaskState() == USB_STATE_RUNNING)
    {
        Usb.ForEachUsbDevice(&PrintAllData);
    }
}

void PrintAllData(UsbDevice *pdev)
{
    UsbDeviceAddress adr;
    adr.devAddress = pdev->address.devAddress;
    Serial.println(adr.devAddress, HEX);

    uint8_t msg = 0;
    uint16_t len = 0;
    uint8_t rcode = Usb.inTransfer(adr.devAddress, pdev->epinfo->epAddr, &len, msg);

    if (rcode && rcode != hrNAK) {
     Serial.print(F("\r\nData rcv: "));
     Serial.print(rcode, HEX);
   } else if (len > 0) {
     Serial.print(F("\r\nData Packet: "));
     Serial.print(msg[0]);
   }
}

I'm not getting any data through though. Does anyone have any suggestions? Or know of any helpful sample code?

Have you tried this lib's documentation? It looks like just doing init() and then checking the task state is not enough.

Looking at the source code makes me think you might want to add a call to the main task/state machine, e.g. add a call to Usb.Task(); to your loop, before your if statement.


Error compiling for board Arduino Uno I am relatively new to Arduino and I am trying to code some neo pixels and every time I try to verify my code this error comes up:

Arduino: 1.8.12 (Mac OS X), Board: "Arduino Uno"
loading libs from /Users/erinshankland/Documents/Arduino/libraries: reading dir >/Users/erinshankland/Documents/Arduino/libraries: open >/Users/erinshankland/Documents/Arduino/libraries: operation not permitted
Error compiling for board Arduino Uno.
This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

this is my code:
#include <Adafruit_NeoPixel.h>

#define PIN        6

#define NUMPIXELS 15

Adafruit_NeoPixel pixels(NUMPIXELS, PIN, NEO_GRBW + NEO_KHZ800);

// this constant won't change:

const int  btnRed = 2;  // the pin that the pushbutton is attached to

const int  btnBlue = 3;  // the pin that the pushbutton is attached to

const int  btnGreen = 4;  // the pin that the pushbutton is attached to

const int  btnPurple = 5;  // the pin that the pushbutton is attached to

void setup() {

  randomSeed(analogRead(A0));

  // put your setup code here, to run once:

  pinMode(btnRed, INPUT);

  pinMode(btnBlue, INPUT);

  pinMode(btnGreen, INPUT);

  pinMode(btnPurple, INPUT);

  // initialize the LED as an output:

  // initialize serial communication:

  Serial.begin(9600);

  pixels.begin(); // INITIALIZE NeoPixel strip object (REQUIRED)

    pixels.clear(); // Set all pixel colors to 'off'

    pixels.show();

    delay(1000);

}

void loop() {

if (digitalRead(btnRed)==HIGH){

    rndRed();

  delay(100);

}

if (digitalRead(btnBlue)==HIGH){

    rndBlue();

  delay(100);

}

if (digitalRead(btnGreen)==HIGH){

    rndGreen();

  delay(100);

}

if (digitalRead(btnPurple)==HIGH){

    rndPurple();

  delay(100);

}

}

void rndRed() {

  int led = random(0, 15);

  pixels.setPixelColor(led, pixels.Color(255, 0, 0,0));

  pixels.show();   // Send the updated pixel colors to the hardware.

  delay(500);

}

void rndBlue() {

  int led = random(0, 9);

  pixels.setPixelColor(led, pixels.Color(0, 0, 255,0));

  pixels.show();   // Send the updated pixel colors to the hardware.

  delay(500);

}

void rndGreen() {

  int led = random(0, 9);

  pixels.setPixelColor(led, pixels.Color(0, 255, 0,0));

  pixels.show();   // Send the updated pixel colors to the hardware.

  delay(500);

}

void rndPurple() {

  int led = random(0, 9);

  pixels.setPixelColor(led, pixels.Color(171, 0, 255, 0));

  pixels.show();   // Send the updated pixel colors to the hardware.

  delay(500);

}

I am using a new library for the neo pixels but this has been downloaded and updated.
Hopefully someone can help me!

loading libs from /Users/erinshankland/Documents/Arduino/libraries: reading dir
  /Users/erinshankland/Documents/Arduino/libraries: open
  /Users/erinshankland/Documents/Arduino/libraries: operation not permitted

This is not an Arduino problem but an OS problem.

Either your /Users/erinshankland/Documents/Arduino/libraries is not accessible by your user (check the permissions) or it's not a directory.

You can try, from a terminal:

sudo chown -R erinshankland /Users/erinshankland/Documents/Arduino/libraries
chmod -R 755 /Users/erinshankland/Documents/Arduino/libraries

which will reset ownership and file permissions on the directory and everything underneath it.

If not, then delete your libraries folder (which may in fact be a file, not a folder) and recreate it and repopulate it with your desired libraries.


SSH and web interface broken on Yun I have two Arduino Yuns that are not accessible at all on the network. I can't go to the arduinoname.local, ssh arduinoname.local, as I previously could. I know at least one it working because it sends emails as I programmed it, yet it seems there is no longer a way to ssh into it. Any ideas?

Yes, I have unplugged, plugged in the router,  and the yuns.

It turns out the problem is a fairly common one - Actiontec wireless access points break this way when set to Both, not AES - see https://superuser.com/questions/522781/unable-to-ssh-from-any-wireless-ip-to-another-wireless-ip-on-home-network

Apparently on other routers this bug is marked as a feature, "Wireless Isolation" or something.


How to get the rightmost four bits from a byte I have a byte that I am looking to break into 2 nibbles. The leftmost nibble I can get easily via shifting right 4 times. However, I can't figure out how to get the rightmost nibble. Any ideas?

Just mask it with an AND operator:

val = var & 0xF;


Play sound with speaker inside interrupt while a timer runs I'm attempting to start a timer lasting a specific interval when the ultrasonic distance sensor measures a distance lower than 25 cm. Once that occurs, I want the speaker to make sound if the distance goes above 25 cm whilst the timer is running. I am attempting to use an interrupt to do this, but I'm having trouble.

This is what I have so far:

void setup() {
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(interruptPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(interruptPin), sensor, CHANGE);
}

int makeSound() { // This function creates the sounds
  ...
}

int echo() { // This function gets the distance the sensor is measuring
  ...
}

void loop() {
  distanceCm = echo();
  if (distanceCm < 25) {
    Timer();
  }
}

int Timer() {
  half_hour_millis = millis();

  while (millis() < half_hour_millis + interval) {
    // Here goes the code that I haven't written and was hoping you could help me with
  }
}

// My interrupt function
void sensor() {
}

Andrew,

I think I see what you're trying to accomplish. I would try something like the following, and I'll explain afterward:

boolean timerRunning = false;
unsigned long start_millis;
unsigned long end_millis;

boolean tripped() //was int Start()
{
  dist = echo1();
  if (dist < 25 && dist > 0) {
    return true;
  else
    return false;
}

void loop()
{
  if(tripped())  //check for < 25cm
  {
    //if tripped and timer not running, start
    //keeping track of time
    if(!timerRunning)
    {
      timerRunning = true;
      start_millis = millis();
      end_millis = start_millis + half_hour;
    }
    //if timer already running, print millis
    else
    {
      Serial.println(millis()); //or Serial.pringln(millis()-start_millis);
                    // for time since timer started
    }
  }
  else  //not < 25cm, not tripped
  {
    //if not tripped and timer running, time for sound
    if(timerRunning)
    {
      timerRunning = false; //might as well stop timer
      alert();
    }
    //if timer not started and not tripped nothing to do
  }

  //finally, lets check time, if past half hour, stop tracking
  //elapsed time
  if(timerRunning)
  {
    if(millis > end_millis)
    {
      timerRunning = false;
    }
  }
}//end void loop()

In general, you don't want to block the loop() from looping. Some of the Arduino functions do their processing outside that loop (the interrupt pin possibly too).

I know I'm not using the interrupt, but for a couple reasons. First, it looks like the pin can only change if you call your echo1() function, as you have to trigger the ultrasonic transmitter. Secondly, the state of the pin will not reflect the distance, only that it's receiving sound. As an aside, for what it looks like you were trying to do, you would have wanted to attach the interrupt and detach the interrupt only when the timer started or ended, as opposed to in the setup. Otherwise it could interrupt at any time, such as everytime the echo1() was called.

Hopefully my code comments help explain the flow. Basically I'm keeping track of the state of things, mostly with 'timerRunning'. Based on whether the timer is running and the ultrasonics are tripped (measuring less than 25cm), the appropriate actions are taken. The only way to stop the timer is the elapsing of half an hour, or the alert condition.

Double check my math, but i think there are 1,800,000 milliseconds in half an hour, so you will want to change your constant. Also, I don't know how long you plan on having your device run, but the millis() function will rollover back to 0 after about 50 days. Your end time will end up calculating out to less than the current time and the timer will not be able to run properly (will immediately stop) for that last half hour until rollover. Just something to keep in mind.

Hope this helps and good luck!


Wifi rssi converting char[] to uint8_t I am trying to get RSSI of a network without connecting to it directly but I get an error " error: cast from 'const char*' to 'uint8_t {aka unsigned char}' loses precision [-fpermissive]"

   char ssid[]="GreenNET";
    long rssi = 0;

    void updateRSSI(){
      rssi = WiFi.RSSI(ssid);
    }

I am following this: https://www.arduino.cc/en/Reference/WiFiRSSI except I am not passing password since it is not required WiFi.RSSI(wifiAccessPoint);

The argument passed to RSSI() must be an integer indicating the array index of the SSID of the WiFi network whose RSSI you want to get. To get that integer, you must first scan for networks.

char ssid[] = "greenNet";
byte num_ssids = 0;
long rssi = 0;

num_ssids = WiFi.scanNetworks();
for (byte net = 0; net < num_ssids; net++){
    rssi = WiFi.RSSI(net);
    Serial.print(WiFi.SSID(net)); Serial.print(": ");
    Serial.println(rssi);
}


Controlling Servo Motors with push button. Problem though I have this setup where I have and Arduino Uno, a mini servo motor, and a pushbutton. I use a single pushbutton to control the servo motor to go to one position, then push it again to go back. It first goes to 0 degrees, then if you push it it goes to 180 degrees then vice versa. The problem is that in its initial state (which is 0 degrees), the servo motor makes noise. Like it's running or something then it gets hot.

I've seen other servo motors that never do this. Here is my code by the way:

#include <Servo.h>

const int buttonPin = 8;
const int servoPin = 9;
int buttonState = 0;
int directionState = 0;
Servo servoOne;
int pos = 0;

void setup() {
  servoOne.attach(9);
  servoOne.write(directionState);
  pinMode(buttonPin, INPUT);
}

void loop() {
  buttonState = digitalRead(buttonPin);
  if (directionState == 0) {
    if (buttonState == HIGH) {
      directionState = 1;
      for (pos = 0; pos < 180; pos = pos + 1) {
        servoOne.write(pos);
        delay(5);
      }
    }
  } else if (directionState == 1) {
    if (buttonState == HIGH) {
      directionState = 0;
      for (pos = 180; pos > 1; pos = pos - 1) {
        servoOne.write(pos);
        delay(5);
      }
    }
  }
}

I really need all the help I can get.

You might need to add more time to the delay. Also, check how your powering the servo. If you're powering from the Arduino, it might be drawing to much current and causing issues. If it's a bigger servo, try to hook it up to an external power source and just connect the PWM line and it's ground.


How to get rid of low quality sound out from DFPlayer plus amplifier? I use my Seeeduino V4, DFPlayer mini, and this speaker module from AliExpress to create an automatic doorbell.  The problem is that it seems that this speaker module's Yurobot amplifier is not powerful enough to create a noise-free loud sound. Also, the bundled speaker is 0.5W, 8 Ohm.
There is a volume selector on the speaker module. If it is selected to a value a bit higher than 0 then the sound's quality is quite high (click here to listen), but the volume is not enough by far for a doorbell, even though the DFPlayer's programmed volume is set to maximum. But if I increase the amplifier's volume selector to something near maximum, I start hearing some very scary noises (please click here to listen).
How can I increase the volume without having hard-to-listen-to noises? Maybe I need to buy another, better amplifier?

The DFPlayer already has a 3W amplifier on it, so you can connect a speaker directly to the DFPlayer. There is no need for an extra amplifier.
If you do connect an extra amplifier to the DPlayer, and turn the volume of the DFPlayer up too far, the input of the second amplifier will clip and it won't sound good. Also, the output of the DFPlayer is probably from a class-D amplifier designed to be connected directly to a speaker; it won't play nice with other amplifiers.
You should try how the DFPlayer sounds when you connect a speaker directly to it. The 0.5W speaker you have is not a good fit; it can't handle the power of the DFPlayer's amplifier.
A 3W (or more), 8Ω speaker would be good for this if you want to use the maximum power the DFPlayer can deliver. According to most publications on the interwebs a 2W, 8Ω speaker will also do, but I would be careful with turning the volume all the way up.
Note that the DFPlayer can pull a fair bit of current (about 25mA in standby, and in the order of 200mA when playing) and it needs a power supply that can deliver that.


How can I replace pulseIn with interrupts? I have an HC-SR04 sensor and I need to get the distance from it. I use this code:

digitalWrite(trig, LOW);
delayMicroseconds(2);
digitalWrite(trig, HIGH);
delayMicroseconds(10);
digitalWrite(trig, LOW);
duration=pulseIn(echo, HIGH, 24000L);
cm=duration/2/29.1;

Pulsein takes too much time and I would like to use interrupts to prevent code from being blocked. From the beginning, I had no idea how to do it. I did not want to ask this question without trying on my own so here is my miserable attempt:

 while(digitalRead(echo)==LOW){
 }
if(digitalRead(echo)==HIGH){
      lowTimer=millis();
}
while(digitalRead(echo)==HIGH){

}

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

Obviously, this does not work. I don't know if I am on the right track, but I do know that even if this worked, it would still block my code for a long time. Can someone help me, point me in the right direction? Please don't just write it for me - I want to learn. I would like someone to point me to the right direction till I get it. Thank you!

EDIT:

I tried on of the suggestions:

unsigned long duration;
int cm;
const int echo = 24;
const int trig = 22;
bool doPing=true;

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

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

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

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

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

    last_state = state;
}

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

You do not want the reading of the incoming pulse to block your
program execution. This is the very key requirement: you want a
non-blocking pulse reading. You can write a non-blocking replacement
for pulseIn(), but you will have to use it differently. You cannot
expect a non-blocking pulseIn() to return the pulse length whenever
you call it: instead, it would return that value only when you call it
right after the pulse falling edge. On all other circumstances it will
return a dummy value meaning “the pulse is not finished yet, thus I
cannot give you its length right now, please call me later”.

Below is an example of a function implementing this approach. You have
to call it on every loop iteration: the more often you call it, the
better resolution you will have. This function uses 0 as the dummy value
meaning “no answer available right now”:

/*
 * Non-blocking pulseIn(): returns the pulse length in microseconds
 * when the falling edge is detected. Otherwise returns 0.
 */
unsigned long read_pulse(int pin)
{
    static unsigned long rising_time;  // time of the rising edge
    static int last_state;             // previous pin state
    int state = digitalRead(pin);      // current pin state
    unsigned long pulse_length = 0;    // default return value

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

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

    last_state = state;
    return pulse_length;
}

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


Baud rate of Arduinos bootloader I am learning UART  and the problem that i have is understanding what happens when i send serial data to my PC via USB which is built in to the Arduino uno board.

For incoming serial data i am using Terminal v1.9b and it basically lets me to set some parameters and listen to incoming data on Software serial port and or write to it.

The process:

Atmega328p's Baud rate is set to 9600
Terminal connects to it (it performs a reset) and i get my data in.

Very simple, it all works and i don't have a problem with it. What my question is: I assume that my PC doesn't talk to atmega328p directly since it has no USB interface. it talks to a bootloader chip which converts the USB to UART and then i receive that message on my atmega328p. How does that chip know which baud rate we agreed to. OR "Terminal" sends the baud rate to that bootloading chip via usb protocol and it sets its UART settings ?

The bootloader runs in the 328, and just as your application programs do, it sets a UART baud-rate for uploading programs to the Uno.

Current bootloaders use 115200 baud for upload; the most recent previous ones used 57600 baud. Setting that is part of the bootloader code. Whatever your application program last set for a baud-rate doesn't matter; if you reset the Uno, the bootloader sets the UART to the known upload baud-rate, and waits briefly for the PC to begin an upload, and jumps to the currently loaded application program if no upload is begun.

Your PC's Arduino IDE configuration is written to use the known bootloader baudrate (you can see that in the avrdude command). In fact, since I have some boards with soldered-in chips with the older, 57600 baud bootloader burned in them, I have two Uno-board configurations in my IDE; one for those older chips, and one for the current ones.


How to convert byte *payload to String I would like to convert a byte *payload to a String, because I want to compare the content of payload to another String.

void mqttCallbackHandler(char *topic, byte *payload, unsigned int length) {
  String payloadstr = ???
  ...
}

Depending on what is setting the message on the topic, payload may, or may not be, a NULL-terminated string.  This is why they provide the length parameter.

You could consider comparing the data with memcmp() which is like strcmp() but doesn't look for a NULL termination - instead it takes a length parameter.  This is good if you may have NULL bytes in your payload.

An alternative is strncmp() which both looks for a NULL termination and also limits the length using a length parameter. Better for payloads you know are strings, but you aren't sure if they have NULL termination or not.

Here is a callback (for PubSubClient on ESP8266) I have in one of my projects which uses strncmp():

void callback(char *topic, byte *payload, unsigned int length) {
    if (!strcmp(topic, SUBTOPIC)) {
        if (!strncmp((char *)payload, "on", length)) {
            digitalWrite(POWERPIN, HIGH);
            powerState = true;
            client.publish(PUBTOPIC, "on", true);
        } else if (!strncmp((char *)payload, "off", length)) {
            digitalWrite(POWERPIN, LOW);
            powerState = false;
            client.publish(PUBTOPIC, "off", true);
        }
    }
}

Simply casting your payload to (char *) is enough for the functions to take it as a string, and the length parameter will prevent looking past the end of the payload if there is no NULL termination.

It's not perfect - a single byte payload of o will falsely match the first on, but if that is a critical problem I am sure you can find a way to work around it by checking what length equals.


Can I read using an analog pin on an arduino Mega whether or not there is a high (5v) voltage on a wire from another board's digital pin? I am making a peer-to-peer network of initiating devices and a common hub, which controls most of the hardware. It sends a number over Serial to Mega's Serial1 (Mega's Serial is used for communicating to the computer), but as a fallback it initiates a general alarm by sending a 5v signal (using digitalWrite(pin, HIGH)) to the main board. In order to complete the circuit and get the read, how would I do this?

Thanks!

Yes of course you can. Better to use digitalRead() than analogRead() however.

You just need to tie the grounds of the 2 Arduinos together, and set up the pin on the Arduino you want to sense the input as INPUT or INPUT_PULLUP. Then do a digitalRead on the pin. It will return LOW if the other Arduino is setting the pin LOW, and HIGH if the other Arduino is setting it HIGH.

And, as Juraj points out in their comment, CMOS devices like Arduinos respond to voltage, not current. Their inputs are capacitive. They react to a voltage potential, not current. (When you initially change a CMOS input from one state to another a small amount of current flows in to change the state of the capacitor and after that the only current that flows is a very tiny amount of leakage current through the capacitor on the input.)


Can I run ESP8266 via Arduino using the PWM pins? First question: Since we can control the volts that we can throw via PWM pins on Arduino, can we use it to power the 3.3 V ESP8266?

Second question: Can we also use these PWM pins as software serial pins i.e. they will be sending instructions at 3.3 V?

First question, Since we can control the volts that we can throw via PWM pins on Arduino, can we use it to power the 3.3v ESP8266?

No. The ESP8266 draws far too much current (in excess of 200mA) to use anything other than a proper supply.

  Second question, Can we also use these PWM pins as Software serial pins i.e. they will be sending instructions at 3.3v?

We'll drop the "also", since we've decided that you're not doing that.

You can use SoftwareSerial on any GPIO pins you like, provided the RX pin supports pin change interrupts.


Arduino IDE COM Port error on Windows 10 I have an Arduino micro, uno, and mega and none of them will connect to the com port on the Arduino IDE. I went to the device manager aand it is recognized but when I try to update the driver I get this:

Any help of how to fix this problem?

An easy thing to try but might not help: Use another USB port of your computer and see if the driver is reinstalled.

Otherwise, go to control panel and find the drivers (Device Manager), search for the Ports (COM & LPT) drivers and remove the driver for the Arduino manually, reconnect the Arduino and check if it is installed correctly. Possibly a wrong version of an Arduino driver is installed. If another driver is installed at COM3 (where is my Arduino), remove that driver and try again.


need to get values from a function with structure pointer argument and print on serial terminal I am developing a code in which I need to print value of structure pointer on serial terminal.
Below is my code snippet:

typedef struct
{
  uint8_t AB;     ///< Address byte (Start byte)
  uint8_t CB;     ///< Command (index) "ASCII-byte"
  uint8_t SI;     ///< Action (sub index) "ASCII-byte"
  uint8_t PH_1;    ///< Payload "ASCII-byte" of the high nibble of the high byte of the raw payload
  uint8_t PH_2;    ///< Payload "ASCII-byte" of the low nibble of the high byte of the raw payload
  uint8_t PL_1;    ///< Payload "ASCII-byte" of the high nibble of the low byte of the raw payload
  uint8_t PL_2;    ///< Payload "ASCII-byte" of the low nibble of the low byte of the raw payload
  uint8_t CS1;    ///< Checksum "ASCII-byte" of the high nibble of the raw checksum
  uint8_t CS0;    ///< Checksum "ASCII-byte" of the low nibble of the raw checksum
} rs485_message_t;

int proto485ComposeMsg(rs485_message_t* msg, uint8_t address, uint8_t command, uint8_t action, uint16_t value){
  msg->AB = address;
  msg->CB = command;
  msg->SI = action;
  msg->PH_1 = (int)((value & 0xF000) >> 12) ;
  msg->PH_2 = (int)((value & 0x0F00) >> 8);
  msg->PL_1 = (int)((value & 0x00F0) >> 4) ;
  msg->PL_2 = (int)(value & 0x000F);
  int checksumRaw = (msg->CB) + (msg->SI) + (msg->PH_1) + (msg->PH_2) + (msg->PL_1) + (msg->PL_2);
  setCheckSum(msg);
}

uint8_t proto485Write(uint8_t address, uint8_t command, uint8_t action, uint16_t value)
{
  int i = 0;
  int stringOne[9] = {int(0x00), int(0x00), int(0x00), int(0x00), int(0x00), int(0x00), int(0x00), int(0x00), int(0x00)}; ;
  rs485_message_t rs485Msg;
  proto485ComposeMsg(&rs485Msg, address, command, action, value); // value is passed in "raw" format
  Serial.write(rs485Msg);       // getting error on this line
}

Please help... Thank you

You can't just print a structure. After all, how is the program supposed to know how it is supposed to be displayed?

Do you want just the raw data, or do you want it formatted in a human readable form?

For just the raw data you need to cast the pointer to a type that can be printed as an array. For example:

Serial.write((uint8_t *)&rs485Msg, sizeof(struct rs485_message_t));

To print it in a human readable form you will need to take each value that you want to see and print it separately with any data manipulation that you may want.  For example:

Serial.print("Checksum 0: ");
Serial.println(rs485Msg.CS0, HEX);

Another thing you can do is to change your structure into a class and inherit the Printable class.  You can then implement the size_t printTo(Print &p); member function which sends the data to the p object for printing in the format you want.  Then you can just print it directly as you are trying to do in your code.


Arduino Obstacle Avoiding Shield controlor motor L293D I am a beginner with Arduino . I wanted to make a Arduino obstacle avoiding so I commanded last week an L293D Shield Motor Driver and I don't know if what I receive is the good ithem . First picture is how it looks on the site and the second picture is what I get .

I saw that if you search for this motor you get resolts for both motor , but they are not the same . And I saw in this tutorial , this persone use a motor as mine https://www.youtube.com/watch?v=ydDvoknlJ9M and than he switch to the motor in the first picture . Questions : This motors are the same ? Should I request a return ? If they are the same , how can I add ... I don't know how to say ... that thing that is in the third picture ?

Again , I am a beginner and I would apereciate if someone can help me .

To complete @chrisl answer: Yes you need these pins to make the same robot as in the video. You can order them online and solder them (if you know how to solder and if you have the soldering material). Be careful with soldering ;)

For your information, the pins you circled in red are used to communicate with the Arduino pins A0 to A5, and provide +5V and GND. In the video, they are connected to the ultrasound sensor.

And please clarify what is your motor??? Do you mean the Shield motor driver? It is not the same. A shield is an eletronic board that you plug to your Arduino to do a specific task (control a motor, connect to wifi...). A motor driver is the electronic to control the motor. On your pictures, they are mainly the 3 components with 16 legs each.


How can I loop for a set amount of time when a condition is met? I'm trying to create an Arduino project with a light sensor and a buzzer. The idea is that when the sensor detects that the lights have gone off, the buzzer will sound for 5 seconds. At some point, the lights will come back on, but when they go back off, I need the buzzer to sound again.

At the moment the buzzer does sound the first time the lights are turned off but after the lights have come back on and then off again, it won't sound and I can't figure out why.

int lightSensor = 2;
int buzzer = 3;
long startTime,stopTime;
long myDesiredTime = 5000;

void setup()
{
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(lightSensor, INPUT);
  pinMode(buzzer, OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  int sensorState = digitalRead(lightSensor);

  switch(sensorState)
  {
  case 1:
    while (sensorState == 1)
    {
      if(stopTime-startTime<=myDesiredTime && sensorState == 1)
      {
        runBuzzer();
        stopTime=millis();
      }
    }
  }
}

void runBuzzer()
{
  tone(buzzer, 1000); // Send 1KHz sound signal...
  delay(1000);        // ...for 1 sec
  noTone(buzzer);     // Stop sound...
  delay(1000);
}

You have two major issues here:

void loop() {
  // put your main code here, to run repeatedly:
  int sensorState = digitalRead(lightSensor);

  switch(sensorState)
  {
  case 1:
    while (sensorState == 1)
    {
      if(stopTime-startTime<=myDesiredTime && sensorState == 1)
      {
        runBuzzer();
        stopTime=millis();
      }
    }
  }
}

The first is that you never re-read sensorState. The second is that you are comparing stopTime before setting a value to it. Try re-arranging like this:

void loop() {
  // put your main code here, to run repeatedly:
  int sensorState = digitalRead(lightSensor);

  switch(sensorState)
  {
  case 1:
    while (sensorState == 1)
    {
      stopTime=millis();
      if(stopTime - startTime <= myDesiredTime)
      {
        runBuzzer();
      }
    sensorState = digitalRead(lightSensor);  // read sensorState again
    }
  }
}

  In your example, the buzzer does not sound when the light has been switch on and then back off again.

Good point. Well, we can simplify somewhat:

void loop() {

  if (digitalRead(lightSensor) == HIGH)
    {
    startTime = millis ();  // remember when we started
    while (digitalRead(lightSensor) == HIGH &&
           millis () - startTime <= myDesiredTime)
      {
      runBuzzer();
      }  // end of while switch still closed and time not up
    while (digitalRead(lightSensor) == HIGH) { } // wait for sensor go to LOW
    delay (200);  // debounce
    }    // end of switch being closed
}      // end of loop


Problem Uploading to the Arduino Nano board ]2I am using an Arduino Nano board. It has an ATmega 328P processor. For running the codes I use Arduino 1.8.6 Software. The issue is that when I am uploading my sketch to the board it shows me the following errors:

 Using Port                    : COM7
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x9b
avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x9b
avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x9b
avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x9b
avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x9b
avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x9b
avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x9b
avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x9b
avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x9b
avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x9b

avrdude done.  Thank you.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

I have turned on the show verbose output option turned on.

Also, sometimes the following errors pop up:

collect2.exe: error: ld returned 255 exit status

Using library SoftwareSerial at version 1.0 in folder: C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.14.0_x86__mdqgnx93n4wtt\hardware\arduino\avr\libraries\SoftwareSerial
exit status 1
Error compiling for board Arduino Nano.

I have referred the following links to solve my issue:

collect2.exe: error: ld returned 5 exit status
Why I can't upload my programs to the Arduino board?

I am making an application wherein I have to control two DC motors via Bluetooth module HC-05

In one of the troubleshooting questions, the solutions contained the possibility of the bootloader not being installed where the problem can be verified by pressing the reset button and checking the bootloader LED to blink. Can someone help me with this?

Also, there are two processors shown for ATmega328P:

The ATmega328P
The ATmega328P (old bootloader)

I tried using then both options for uploading the sketch but still, the errors pop up.

I have also downloaded and installed the latest FTDI drivers from their site.

A common solution is to actually switch the board type to the Arduino Uno. It is a known problem but I have yet to see any other viable fix.


Standalone ATmega clock continuous lifetime Here I have made a standalone ATmega328p clock without
any RTC module using the breadboard ATmega328p , LCD I2C , and some buttons which I would like to turn on for atleast an year (supposed to be without any reset or power-interrupts).
I am powering my ATmega using an old mobile charger (5v , 500mA) of a old broken Android.
However I am not using any millis() or something alike these in the clock code,
So how long will my clock run if is it supposed to be online 24/7
Should I reset it sometimes?
If yes , when, after how many days should I reset it?
And do I need a coolant system for it? (I guess not)
Thanks for your precious time .

So how long will my clock run if is it supposed to be online 24/7

Until you turn it off or a stray neutrino corrupts the flash memory, or the flash memory degrades (20-100 years or so depending on temperature).

Should I reset it sometimes? If yes , when, after how many days should I reset it?

No.

And do I need a coolant system for it? (I guess not)

No. Not unless it's in a sealed container with no ventilation and a hot environment.
However
Your RTC-less "clock" will probably not be particularly accurate, unless you have some external source of time (NTP, GPS, etc) as the Arduino's internal timing is not very accurate, and built on a breadboard it's even less so due to excess stray capacitance.


How to attach interrupts to Arduino UNO timers? I understand there are 3 timers on the Arduino UNO.  What specific registers do I need to use to access them?

My goal is to use these timers to poll different sensors I am using with a ms period. Are there any pre-made libraries out there to do this?

For the UNO, use Timer1.

An example of the way you can use it is as follows:

Download the TimerOne library: https://code.google.com/p/arduino-timerone/downloads/list

/*
 *  Timer1 library example
 */

#include "TimerOne.h"

void setup()
{
  pinMode(10, OUTPUT);
  Timer1.initialize(500000);         // initialize timer1, and set a 1/2 second period
  Timer1.pwm(9, 512);                // setup pwm on pin 9, 50% duty cycle
  Timer1.attachInterrupt(callback);  // attaches callback() as a timer overflow interrupt
}

void callback()
{
  digitalWrite(10, digitalRead(10) ^ 1);
}

void loop()
{
  // your program here...
}