Issue with simple project I'm new to Arduino and today I have a problem with this code:

int led_1 = 10;
int led_2 = 11;
int led_3 = 12;
int button = 3;
int time = 0;
byte val = 0;

void setup() {
  // put your setup code here, to run once:
  pinMode(led_1, OUTPUT);
  pinMode(led_2, OUTPUT);
  pinMode(led_3, OUTPUT);
  pinMode(button, INPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  val = digitalRead(button);

  if (val == HIGH){
    time = millis();
    while (digitalRead(button) == HIGH) {
      if (millis() - time < 1000) {digitalWrite(led_1, HIGH);}
      else if (millis() -time > 1000 && millis()-time <2000) {digitalWrite(led_2, HIGH);}
      else if (millis()-time >2000) {digitalWrite(led_3, HIGH);}
    }
  } else {
    time =0;
    digitalWrite(led_1, LOW);
    digitalWrite(led_2, LOW);
    digitalWrite(led_3, LOW);
    }
}

The code should work like this: If I press the button less than one second, led_1 will turn on. If I press it between one and two seconds, led_2 will turn on; and if I press the button more than 2 seconds, led_3 will turn on. If I don't press a button, the LEDs remain off. The time variable is used to take the time when I start to press the button and then the control millis()- time should give how long I press the button.

It works for a while, then after a random time (I think) if I push the button, only the led_3 turns on. Why?

time should be an unsigned int.  As soon as millis reaches 32768, it will be stored as -32768 in time, and your comparisons will not work. This happens after 32.768 seconds.  Here's a short sketch to illustrate:

int time = 0;

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

void loop() {
    time = millis();
    if (time % 1000 == 0) {
      Serial.println( time );
      delay( 2 ); // let millis() increment
    }
}

To see the difference, just change the first line to

unsigned int time = 0;

Note how time rolls over to 0 after 65535 (well, only 65000 is printed).

I would recommend using unsigned constants by adding a "U" after the digits: 1000U.  In your if statements, you must cast the millis to the same (smaller) type: (unsigned int)millis().  Also, parentheses make the expression more clear:

      else if (((unsigned int)millis() - time > 1000U) && ((unsigned int)millis() - tempo < 2000U)) {digitalWrite(led_2, HIGH);}


Sketch not running as expected I wrote this sketch along with an HC - SR 04 Ultrasonic transducer and a DC motor. Whenever the HC-SR 04 reads any distance less than 15 cm, the motor stops, otherwise it keeps running.

The problem is whenever I upload the sketch, the motor runs for a short while and stops. Then when I open my serial monitor, the motor runs until an object crosses the 15 cm threshold and stops right after the limit is crossed. But when I again put the object outside of the 15 cm range, the motor should start running again, but it doesn't.

I am using a this motor driver and a simple DC motor(12V).
Here's the code-

int trigPin1 = A0;
int echoPin1 = A1;
int distance1 = 0;
int E1 = 10;
int brake1 = 7;

void setup() {
  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);
  pinMode(brake1, OUTPUT);
  pinMode (E1, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  analogWrite(E1, 153);
  distance1 = getDistance(trigPin1, echoPin1);
  printDistance(1, distance1);
  delay(250);
  if(distance1 <=15){
    digitalWrite(brake1, HIGH);
  }
  else{
    analogWrite(E1, 153);
  }

}

int getDistance (int initPin, int echoPin) {
  digitalWrite(initPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(initPin, LOW);
  long pulseTime = pulseIn(echoPin, HIGH);
  int distance = pulseTime / 58.2;
  return distance;
}

void printDistance(int id, int dist) {

  Serial.print(id);
  if (dist >= 120 || dist <= 0 ) {
  Serial.println(" Out of range");
  }
  else{
   Serial.print("\t");
   Serial.print(dist);
   Serial.println(" cm");
}
}

What mistake am I doing? Moreover I am currently running it with one motor, I'll add another later on along with more sensors, so the motors are controlled by the left or right sensor. How do I make my code work with them?

Thanks...

It was too damn simple...

I just had to add a line inside the else block in the loop function.

digitalWrite(brake1, LOW);

This was happening because the first time the threshold limit was crossed the brake1 pin was left HIGH and was never set to LOW again, which caused a permanent brake in the motor.

I'm too damn stupid. But I still don't have any idea how will I use this code with multiple sensors and motors.


How to make servo rotate for angle bigger than 180° Connected servo motor (180°) to Arduino Uno R3.

Currently I am using a servo motor which have rotation angle specified as 180°, but I have a requirement to rotate to certain angles greater that 180°.

So do I need to go for a continuous rotation servo motor (360°), so that I can stop the motor at different angles greater than 180°, was my assumption true, will continuous rotation servo motor satisfy this requirement?

I am referring to Servo - Generic High Torque Continuous Rotation (Standard Size)

Current code, which I am using 180° servo motor.

Servo myservo;
int pos = 0;
void setup() {
  myservo.attach(9);
}

void loop() {
   {
    myservo.write(180);
    delay(15);
  }
}

No. The continuous rotation servo rotates continuously and you can not control where to stop. You can control the rotation direction and the speed at a little.

What you need is either a special 270 degree servo, or you can use some mechanic, e.g. gears to transform the 0..180 rotation to 0..whateverrotation you prefer, depending on the gearbox ratio.

Alternatively, you can use stepper motors, where you can control steps in 1.8 degrees, and at the same time free to move as many turns as you prefer. Note though that steppers have two disadvantages compared to servos:

steppers require electrical current to hold their current position - for servo, the gearbox works ok for this
steppers don't know their initial position. So you need an optointerrupter or other means to learn the initial position first, then drive the steps to get to any position.
steppers require a more serious driving circuit, as well as a good power supply. Not for DIY robot running on batteries.

In industrial solutions, the stepper motor + some gearbox + an absolute rotation encoder is used to compose an industrial servo drive. (Similarly as a DC motor + some gearbox + an inexpensive potentiometer works in a model servo.)


Using fluctuating voltage as an input I had an idea to hack a wireless doorbell so it could send notifications to my phone when someone rings the doorbell.

I pulled out the PCB from the doorbell and powered it using the +5v from the Arduino - so far so good

I used the (once was a wire to the speaker) as an analog input

The issue I have is that the voltage for the chime continues for a long time. eg its at 0 before push then it fluctuates for a second, then returns to 519 for a while, before eventually returning to 0.

Is there a smarter way to do this - I have included my code below.

void loop()
{
  //detect a changing voltage
  val = analogRead(sensorPin); //pin A0
  delay(500);
  oldVal = analogRead(sensorPin);//pin A0

//if the voltage changed then +1 to the ring counter
  if (val != oldVal) {
      ringCounter = ringCounter+1;
  }

  if (ringCounter > 3 && pinDevid1State == false) // someone pressed the doorbell
  {
    if(DEBUG){Serial.println("pinDevid1 is HIGH");}
    pinDevid1State = true;
    Serial.println("DingDong");
    digitalWrite(ledPin, HIGH);
    delay(5000);
    Serial.println("Notification Sent.");

    //reset vars
    val = 0;
    oldVal = 0;
    ringCounter =0;
  }

  if (ringCounter < 3 && pinDevid1State == true) // the doorbell stopped ringing
  {
    if(DEBUG){Serial.println("pinDevid1 is LOW");}
    pinDevid1State = false;
    digitalWrite(ledPin, LOW);
    Serial.println("DingDongEnd");
    //Sending request to PushingBox when the pin is LOW
    //sendToPushingBox(DEVID1);    //Here you can run an other scenario by creating a DEVID2 variable

    //reset vars
    val = 0;
    oldVal = 0;
    ringCounter =0;

  }

I wonder if there is another pin on the board I could read

I guess that would depend on the particular doorbell. The transmitter must send some representation of a button press to the receiver - a pulse train for the duration of the press, or perhaps just CW: carrier on, carrier off - which the receiver somehow passes on to trigger the audio. Look at the receiver's output side to identify that trigger signal and pass it, or a processed version of it, to the Arduino.


Seven segment display multiplexing I have written a code that displays a number into a seven segment display without manually setting the Arduino pins HIGH/LOW for each number. Now, my problem is how can I display a number larger than 9? This is my code and it works for only 1 digit number: (The seven segment display truth table is inverted because I'm using common anode 7seg)

#define SEG_A 2
#define SEG_B 3
#define SEG_C 4
#define SEG_D 5
#define SEG_E 6
#define SEG_F 7
#define SEG_G 8
#define DEC_P 12

#define SET1 9 // [!][!][x]
#define SET2 10// [!][x][!]
#define SET3 11// [x][!][!]

struct segmentmap {
  uint8_t num;
  const int segment[7];
};

const struct segmentmap segments[] = {
  // n   A  B  C  D  E  F  G
  {0, {0, 0, 0, 0, 0, 0, 1}},
  {1, {1, 0, 0, 1, 1, 1, 1}},
  {2, {0, 0, 1, 0, 0, 1, 0}},
  {3, {0, 0, 0, 0, 1, 1, 0}},
  {4, {1, 0, 0, 1, 1, 0, 0}},
  {5, {0, 1, 0, 0, 1, 0, 0}},
  {6, {0, 1, 0, 0, 0, 0, 0}},
  {7, {0, 0, 0, 1, 1, 1, 1}},
  {8, {0, 0, 0, 0, 0, 0, 0}},
  {9, {0, 0, 0, 1, 1, 0, 0}}
};

void setup() {
  Serial.begin(9600);
  for (int x = 2; x <= 8; x++) {
    pinMode(x, OUTPUT);
    Serial.print("Segment pin: ");
    Serial.print(x);
    Serial.println(" is set to OUTPUT mode.");
    digitalWrite(x, HIGH);
  }
  pinMode(DEC_P, OUTPUT);
  pinMode(SET1, OUTPUT);
  pinMode(SET2, OUTPUT);
  pinMode(SET3, OUTPUT);
  digitalWrite(SET1, 1);
}
int x = 0;
void loop() {
  if (x > 9) {
    x = 0;
  }
  updateDisplay(x);
  delay(1000);
  x++;
}

void updateDisplay(int input) {
  for (int x = 0; x <= 9; x++) {
    //Serial.println(segments[x].num);
    if (segments[x].num == input) {
      Serial.println(segments[x].segment[0]);
      ////////////Simplify this part//////////////
      digitalWrite(SEG_A, segments[x].segment[0]);
      digitalWrite(SEG_B, segments[x].segment[1]);
      digitalWrite(SEG_C, segments[x].segment[2]);
      digitalWrite(SEG_D, segments[x].segment[3]);
      digitalWrite(SEG_E, segments[x].segment[4]);
      digitalWrite(SEG_F, segments[x].segment[5]);
      digitalWrite(SEG_G, segments[x].segment[6]);
      ////////////////////////////////////////////
      //Multiplex here?//
    }
  }
}

my problem is how can I display a number larger than 9?

your first problem can be solved by pulling down / up, depending on your led configuration, the right digit pins.

your second problem would be to write your code so that it is actually usable. think about a generic module where digit / segment pins can be user defined and the routine is called periodically update the segments / digits to display the content in a buffer.


Read Serial data from an arduino with c code I am trying to receive data through the serial port from my SBC (a TS-7200), i am working with linux and handle serial communication using C/C++.To send data to the SBC  i'am using an arduino uno.

So basically the arduino is printing ASCII text data through Pin1 (Hardware Serial) in a loop with a 3ms delay.

From the SBC i read raw data in no canonical mode, ( in the code below are the parameters and configurations for the serial port) i'am trying to read one characters at a time, following the example from this page :
https:/ from this page/chrisheydrick.com/2012/06/17/how-to-read-serial-data-from-an-arduino-in-linux-with-c-part-3/.

but when i run the code it print the number 2 as 3, and the number 3 as f, I am not able to read ASCII characters.

I have tried several things but I have not been able to find the problem, Hope someone can help me.

Here is the Arduino code:

 #include <SoftwareSerial.h>
 SoftwareSerial mySerial(2,3); // RX, TX

 void setup() {

    Serial.begin(9600);
    mySerial.begin(9600);

  }

 void loop() {

   Serial.print(2);

   delay(3000);

   Serial.print(3);

   delay(3000);

}

The c code from the linux side:

#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <termios.h>

char *portname = "/dev/ttyAM1";
char buf[256];

int main(int argc, char *argv[])
{
  int fd,stop = 0;

/* Open the file descriptor in non-blocking mode */
fd = open(portname, O_RDWR | O_NOCTTY);

/* Set up the control structure */
struct termios toptions;

/* Get currently set options for the tty */
tcgetattr(fd, &toptions);

/* Set custom options */

/* 9600 baud */
cfsetispeed(&toptions, B9600);
cfsetospeed(&toptions, B9600);
/* 8 bits, no parity, no stop bits */
toptions.c_cflag &= ~PARENB;
toptions.c_cflag &= ~CSTOPB;
toptions.c_cflag &= ~CSIZE;
toptions.c_cflag |= CS8;
/* no hardware flow control */
toptions.c_cflag &= ~CRTSCTS;
/* enable receiver, ignore status lines */
toptions.c_cflag |= CREAD | CLOCAL;
/* disable input/output flow control, disable restart chars */
toptions.c_iflag &= ~(IXON | IXOFF | IXANY);
/* disable canonical input, disable echo,
   disable visually erase chars,
   disable terminal-generated signals */
toptions.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
/* disable output processing */
toptions.c_oflag &= ~OPOST;

/* wait for 1 character to come in before read returns */
/* WARNING! THIS CAUSES THE read() TO BLOCK UNTIL ALL */
/* CHARACTERS HAVE COME IN! */
toptions.c_cc[VMIN] = 1;
/* no minimum time to wait before read returns */
toptions.c_cc[VTIME] = 0;

/* commit the options */
tcsetattr(fd, TCSANOW, &toptions);

/* Wait for the Arduino to reset */
usleep(1000*1000);
/* Flush anything already in the serial buffer */
tcflush(fd, TCIFLUSH);

while(stop == 0){

  /* read up to 128 bytes from the fd */
  int n = read(fd, &buf, 128);
  usleep(3000*1000);
  /* print how many bytes read */
  printf("%i bytes got read...\n", n);
  /* print what's in the buffer */
  printf("Buffer contains...\n%s\n", buf);
 }
 return 0;
}

This is what i see:

2 bytes got read...
Buffer contains...
f
2 bytes got read...
Buffer contains...
3
2 bytes got read...
Buffer contains...
f
2 bytes got read...
Buffer contains...
3

RS232 uses +/- 12V (or sometimes +/- 5V), and is not compatible with TTL Serial, which uses 0V/5V. Also +12V in RS232 represents 0 and -12V represents 1; inverted from normal TTL.


Insane heat development with ESP8266 I have a ESP8266 on a Wemos D1 mini board. Simple "Rainbow with FastLED" animation. Shouldn't do much but the board gets so hot I can't touch it and it drains a 2500mAh battery in less than an hour.

Any idea what I'm doing wrong? Especially as a comparable micropython implementation just doesn't get that hot and the same battery keeps for about 5 hrs...

Here's the code

#define FASTLED_ALLOW_INTERRUPTS 0
#include "FastLED.h"
#include <EEPROM.h>

// How many leds in your strip?
#define NUM_LEDS 60
#define DATA_PIN 13
#define CLOCK_PIN 14
#define COLOR_ORDER RGB
int starthue = 0;
int incrementer = 255/NUM_LEDS;
CRGB leds[NUM_LEDS*2];
int address = 0;
int max_modes = 4;
int colormode;

void setup() {
  Serial.begin(9600);
  // put your setup code here, to run once:
  FastLED.addLeds<APA102, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS*2);
    EEPROM.begin(512);
  colormode = EEPROM.read(address);
  Serial.println(colormode);
  int new_mode = (colormode == max_modes) ? 1 : ++colormode;
  Serial.println(new_mode);
  new_mode = (colormode == 0) ? 1: new_mode;
  Serial.println(new_mode);
  EEPROM.write(address, new_mode);
  EEPROM.commit();
  EEPROM.end();
}

void rainbow_mid(int howfast) {
  while (true) {
    fill_rainbow(leds, NUM_LEDS, starthue, incrementer);
    for (int i =0; i< NUM_LEDS; i++) {
      leds[NUM_LEDS-i-1] = leds[i];
      leds[NUM_LEDS*2-i-1] = leds[i];
    }
    FastLED.show();
    delay(howfast);
    starthue++;
  }
}

void rainbow(int howfast) {
  while (true) {
    fill_rainbow(leds, NUM_LEDS, starthue, incrementer);
    //addGlitter(80);
    for (int i =0; i< NUM_LEDS; i++) {
      //leds[NUM_LEDS-i-1] = leds[i];
      leds[NUM_LEDS*2-i-1] = leds[i];
    }
    FastLED.show();
    delay(howfast);
    starthue++;
  }

}

void loop() {
  switch(colormode) {
    case 1: rainbow_mid(10); break;
    case 2: rainbow_mid(50); break;
    case 3: rainbow(10); break;
    case 4: rainbow(50); break;
  }

}

the heat is from the supply lines of board.

it's not the chip itself, as if it gets hot like that the chip should be destroyed.
it seems you have connected 60 LEDs strip to the board and you provide it's supply from the board's supply line. so the lines get hot, and the board gets hot too.
so the heat is not from the chip. its from power supply tracks on the PCB.

use another power source for the LED strip.


Dealing with a Signal Source The following circuit is a simplified version of a more complex system. For testing purposes, the 555 Timer was added to serve as a test signal source with frequencies set by the resistors in series. Each arbitrary signal is indicated by a push button and the Arduino needs to be able to distinguish what button has been pushed. Unfortunately, there can only be 3 buttons and more cannot be added. This is where the problem occurs. How can you reliably indicate which push button has been pressed without interfering with the arbitrary waveform?
At first, my original thought was to have the Arduino sample the signal based on that sample the Arduino would be able to tell which button is pressed.
When button 1 in the pink is pushed the Arduino receives a takes the following
sample of the signal.

843
848
849
849
849
849
   // Time 0 when button is pushed
532
414
500
373
463
346
425
370
386
476
346
442
642
788

Moving the input

    // At t = 0 the Serial Monitor reads zero
    998
    998
    998
    998
    998
    0
    0
    0
    0
    0
    998
    0
    0
    0
    0
    0
    0
    0
    0
    0
    998
    0
    0
    0
    0
    998
    0
    0
    0
    998
    998
    998
    0
    998
    0
    0
    0
    998
    0
    0
    0
    0

Moving the analog input does not make it any easier to distinguish which button was being pushed. Which is why I decided to ask the community on how to deal with this. I have tried using a relay and simply hard coding all of the cases but the result is a system is not very robust and is vulnerable to easily break over time.

There's an easy way to achieve reading multiple pushbuttons using single analog input.
All you need to do is create some voltage dividers at different voltages which can be read using analogRead. The last resistor,R6, in the diagram below ensures that the pin reads 0 when no push-button is pressed (i.e pull-down resistor).
In the diagram below, connect Vcc to 5V on the Arduino.

Try it out, you should be able to get well spaced out values for different push buttons!


Accelstepper.runToPosition() is working fine. Accelstepper.run() does nothing I have a complex sketch with Arduino Uno, Bluetooth Serial Com using altSoftSerial, serial com using SoftwareSerial and Serial communication with PC.

I want to move one stepper motor and stop it when a signal is received.
I use A4988 Pololu driver and NEMA 17 bipolar stepper motor.

This code is working fine.
      MyStepper.moveTo(position);
      MyStepper.runToPosition();

If I change the code to
      MyStepper.moveTo(position);
      MyStepper.run();
so that the running does not block my code the motor does nothing
Absolutely no movement.

The ground of the motor power supply is connected with the ground of Arduino. The motor is working fine with blocking movements.

You didn't include any code for us to see what the actual issue is, but I'm willing to guess that you didn't take into account that the run command requires repeated firing.

If your program comes to a point where there's an instance of runToPosition, the blocking function stops the program until the stepper reaches the position specified.

When your program comes to an instance of run(), it fires off a pulse and carries on reading. So you have to use a loop.

stepperMotor.moveTo(3000);
stepperMotor.runToPosition();
// reaches destination

stepperMotor.moveTo(3000);
stepperMotor.run();
// moves a single step

stepperMotor.moveTo(3000);
while (stepperMotor.distanceToGo > 0) {
stepperMotor.run();
}
// reaches destination

The reason you'd use run over runToPosition is to allow for continuous operations / parameters to be executed. For example, two stepper motors running simultaneously:

stepperMotor1.moveTo(5000);
stepperMotor2.moveTo(3000);
while ((stepperMotor1.distanceToGo > 0) && (stepperMotor2.distanceToGo > 0)) {
stepperMotor1.run();
stepperMotor2.run();
}
// Both motors will run, but will both stop when either of them reaches their destination.

Depending on the speed of your microprocessor, you can create some sophisticated instruction sets for your motor(s).


Prevent reiteration of loop instruction in Arduino/Execute instruction via off switch I'd like to make an Arduino play a (2sec).wav file once when it is powered on (via push button) and another when it is switched off i.e. when the push button is pushed there is a 2sec delay and the .wav file plays, then the arduino turns off.  What would the best way be to implement this?  So far I've come up with:

void loop()
{
//play .wav file

while(1){}
}

or:

void setup(){
//play .wav file
}

void loop(){
//empty
}

An Arduino doesn't understand the concept of "powering off".  It is either on (running) or off (not able to do anything).

Your first task must be to design a system whereby the Arduino can control its own power so the Arduino can then go "I have been asked by this external stimulus to switch off. Therefore I will play this sound and then perform whatever actions are required to remove power from myself."

Only when you have worked out how you can get the Arduino to control its own power and still have the ability to manually turn the power on can you begin to think about adding things that happen "when it powers off".


USB or external power I have an arduino mega that i am using as a clock. I would like it to detect if it is connected to a USB or external power supply (e.g. a battery). I then want to set a variable to different values depending on the result, so i can display it on an OLED.

Use a simple transistor where the Vin (external power) is connected to the base, which switches the transistor. Than connect the collector to +5V, and the emitter to a GPIO input pin and read the status with the Arduino. If it receives a HIGH you know external power (via Vin) is used.

See the useful 'good' answer as comment of Majenko below ... I will leave the answer above as is, to keep his remarks clear.


Using an Arduino as a crystal oscillator I want to overclock my Game Boy Advance SP. It has a built-in 4 MHz crystal, and I was able to temporarily replace it with an 8 MHz crystal to see if I was able to overclock it, which I was :).

However I'm wondering if it's possible to emulate/simulate a crystal using an Arduino? Like instead of a crystal soldered to the Game Boy, two output pins from the Arduino? If not, is there a such thing as a variable oscillator? Like a crystal with a potentiometer to change the frequency when the potentiometer is adjusted?

You want to use the Uno? You can set up a timer to output varying frequencies and output them on a pin. I have a page about timers which might help. The fastest you can get with a 16 MHz processor is 8 MHz output however you can get other frequencies by changing the timer parameters.

The ATtiny85 can output higher frequencies if you use the PLL clock option, I think you can then adjust the resulting frequency.

  If not, is there a such thing as a variable oscillator?

Adafruit make a Clock Generator Breakout Board - 8KHz to 160MHz. You connect that via I2C to your Arduino and then program assorted frequencies as a clock output. That uses the Si5351A clock generator chip.

Example code to output 8 MHz on a Uno or Mega2560:

#ifdef __AVR_ATmega2560__
  const byte CLOCKOUT = 11;  // Mega 2560
#else
  const byte CLOCKOUT = 9;   // Uno, Duemilanove, etc.
#endif

void setup ()
  {
  // set up 8 MHz timer on CLOCKOUT (OC1A)
  pinMode (CLOCKOUT, OUTPUT);
  // set up Timer 1
  TCCR1A = bit (COM1A0);  // toggle OC1A on Compare Match
  TCCR1B = bit (WGM12) | bit (CS10);   // CTC, no prescaling
  OCR1A =  0;       // output every cycle
  }  // end of setup

void loop ()
  {
  // whatever
  }  // end of loop

To output 4 MHz change OCR1A to 1 rather than 0.


How can i use a TFT Screen shield along with other sensors and transmitters I want to use Arduino as described in this instructable:

http://www.instructables.com/id/Uber-Home-Automation-w-Arduino-Pi/

But i thought i would give it a little twist by adding a TFT monitor to some devices. I have bought and got the following tft shield to work:
http://www.banggood.com/UNO-R3-ATmega328P-Board-2_4-Inch-TFT-LCD-Screen-Module-For-Arduino-p-945755.html

But now it strikes me:
How can i combine the screen on an arduino where i also have a sensor and a radio transmitter?

You need another layer! A breadboard shield - from the same source if you like - would seem the obvious answer.
Alternatively, take flying leads from the pins you are using to the screen & mount it elswhere, then connect the sensors.
LCD's use quite a few pins, you'll probably need to be creative with an Uno. I have one on a Mega, & have been there with the same problem!


Trouble using lcd.readButtons() in RGBLCDShield library I am trying to create a state machine that loops in whatever state it's in until a button is pressed.  I am using the Adafruit_RGBLCDShield library along with the LCD shield and 16x2 display.  For some reason the buttons aren't being detected at all.  Here is the code for one of the states:

    case STANDBY_MODE:
  lcd.clear();
  lcd.setBacklight(0x0);
  delay(100);
  noInterrupts();
  digitalWrite(fire, LOW);
  digitalWrite(chg, LOW);
  digitalWrite(trig, LOW);
  analogWrite(eprgm, 0);
  // Wait for button press
  while(1)
  {
    button = lcd.readButtons();
    if(button)
    {
      showLCD();
      t0 = millis();
      state = NO_CHARGE;
      analogWrite(eprgm, (vSet*0.0204)/5);
      interrupts();
      return;
    }
  }
break;

In this state, the system turns off all outputs and display and waits for a button to be pressed.  For some reason, though, it doesn't respond when I press the button.  Is there something missing here?

IMO, your post doesn't provide enough information to allow definitive problem diagnosis.

Why do you say noInterrupts(); at line 5?  Some versions of the Wire library might be interrupt driven[1].  If interrupts were off, such a library wouldn't detect any button presses on a TWI-interfaced shield like Adafruit's RGBLCDShield.

[1]: Per arduino.cc's WireLibraryDetailedReference page,  “"The AVR TWI is byte-oriented and interrupt based...." (section 21.6 on p. 224) ... The TWI module sends an interrupt when it finishes, to notify the processor of the change in conditions ... However, notice that the Wire library has blocking I/O. ” [Ie, the usual Wire library doesn't take advantage of TWI interrupts.]


How can I make a rotary encoder change between neopixel programs? I am making a program to use a rotary encoder instead of a button in the buttoncycler example in the Adafruit NeoPixel library.

I am using the US Digital S1-256-250-IE-B-D. Datasheet can be found here: https://cdn.usdigital.com/assets/datasheets/S1_datasheet.pdf?k=636466553771569761

#include < RotaryEncoder.h >
void setup() {
}
void loop() {
  static int change =  0;
  static int pos = 0;
  static int oldPos = 0;
  //Read the Encoder's state
  encoder.tick();
  int enc = encoder.getPosition();
  pos = abs(enc) % 2;
  change = oldPos-pos;
  if (change != 0) {

    switch (pos) {
      case 0:
      //do a program that lasts 5 seconds
      break;
      case 1:
      //do a program that lasts 5 seconds
      break;
    }
    oldPos = pos;
    change = 0;
  }
}

I was wondering if there is a way to change the program immediately after turning the rotary encoder, instead of having to wait for the program to complete.

I was wondering if there is a way to change the program immediately
  after turning the rotary encoder, instead of having to wait for the
  program to complete.

There is, but it's not completely trivial. The reason it is not trivial
is each animation is implemented as a function that takes a while to
execute. For doing what you ask, each of these animations should be
modified, with a way to exit early if needed.

One approach would be to manage the rotary encoder using an interrupt. I
let you investigate how to do that: you probably can find examples on
the Web. Once the encoder reading is interrupt-based, you would need to
do the following changes in your program:

At global scope, add

volatile bool stop_now = false;

This will be a sort of “flag” intended to inform the currently running
animation that it should return ASAP.

Then, inside the interrupt handler, add

stop_now = true;

In loop(), just after if (change != 0) {, add

stop_now = false;

In each animation, replace delay(wait) with:

uint32_t start_time = millis();
while (millis() - start_time < wait) {
    if (stop_now)
        return;
}


Does LabVIEW Linx affect the communication speed with Arduino? I am using LabVIEW to connect to Arduino Mega. I control a logic gate to switch the current On/Off and at the same time there is an I2C connection with a sensor. It came to my attention that the sensor time resolution is very low and I cannot get enough data points from the sensor (I know that the sensor is capable of much better resolutions). My question, is this a problem inherent to LabVIEW and Linx module or my program in LabVIEW? Should I turn to coding with Arduino programming language or C?
note! My reason for using LabVIEW is that I need to sync timing of data aqcuisition with another device which is connected through another VISA port.

For specific timing requirements, my recommendation is to write your own Arduino code.

The Linx module deploys its own ino program to the Arduino and uses serial IO to send it commands and receive data from it. Open NI I/O Trace to observe that traffic.


Measure lipo voltage while powering arduino I have a arduino pro micro 5V that I want to power with a 3.7V lipo. I also have a charging module to charge the lipo.
(https://www.banggood.com/nl/TP4056-1A-Lipo-Battery-Charging-Board-Charger-Module-Mini-USB-Interface-p-1027027.html?rmmds=myorder&cur_warehouse=CN).

I want to measure the battery level of the lipo.

Should I use a step up module to 5V?

How can I measure it? I read that you can't just use analogRead because the lipo itself is the reference.

Thanks in advance!

The reference voltage for analogRead should be from the regulated 5V line, not from the unregulated input to the Arduino.

The real problem is that the voltage out of the battery will drop with current load. You're supposed to measure either the unloaded battery, or under a known, controlled load.

You ask "Should I use a step up module to 5V?" The answer is yes, but that's unrelated to your voltage measurement question. An Arduino requires a source of regulated 5V. The internal voltage regulator is a linear regulator that requires somewhat more than 5V as input (7.5V is about right.) You can't power the internal voltage regulator with a single 3.7V lipo battery. You'd need a step-up regulator, and with that, you could bypass the internal regulator on the Arduino (assuming your step-up regulator puts out 5V.)


Arduino 5v output dead? i've got a bit of a problem with my Arduino UNO.

So coming back to my (pretty basic) build after a bathroom break, I go to un-assemble my circuit (on the breadboard) and grabbing the LED causes a static shock.

Since then I haven't been able to get any power to come out of the Arduino to the breadboard circuitry.

I have tried:

Different Breadboards
All new parts, LED's/cabling/buttons/resistors.
Different power and ground cables (from Arduino to breadboard)
Giving the Board more time to 'cool down' (I heard there was a
temperature based reset device?)
using the 3.5v output (I'm not sure if by doing this i should remove
the resistor? i'm VERY new to electronics
using the alternate ground input

Looking around here for 'shorts' or 'damaged Arduinos' returns mostly results about non communication to the board. the difference here is I can absolutely still upload programs to my Arduino and then run them (I've only tried the pre-existing blink, but i don't think there is any difference). And my computer's USB ports are also fine. So if there is a duplicate question i apologize, but i haven't been able to find anything related.

Any help would be much appreciated!

If you got zapped touching an LED and the circuit doesn't work any more, and since you're sure the Arduino uploads programs OK, then either the LED (or something else on your breadboard) or the pin driver within the Arduino is probably damaged.

Try changing the LED.
If that doesn't work, try changing the pin(s) the sketch uses to talk to your breadboard, rewire your breadboard to use those pins, and test again. If it works this time, the pin driver was probably damaged.
If there are any other components (e.g., not wires or resistors) on the breadboard whose failure might cause the LED not to light, replace those and test again.
If replacing the external components doesn't fix it, and if your Arduino's MCU is a 28-pin chip in a socket, a new one with the bootloader already loaded into it typically costs $5-$6 in the US.

Update:

  ...i have listed all these things as already tried.

Right - I read right past it. :( So you've done the right things (except no mention of testing other pins) so I'm not sure what your question is. The title asks about the board's 5v supply but that must be up b/c your board uploads and runs Blink. That really leaves only the the pin driver(s) you were using when you zapped it.

You can salvage the board by testing all the pins in their input, output, analog, and other functions, and make a note of what capabilities have been lost. Clearly not all of them - pin 13 still works, for instance, because Blink worked. You can't repair damage internal to the chip without replacing it, and I would always consider it suspect, but it will be fine for many hobby uses if you just avoid the damaged functions.


How to wire QRB1114 IR sensor to an Arduino Uno What's the best way to wire a QRB1114 IR sensor to an Arduino Uno? I'm attempting to use it as a white-line-on-black-background line detector. Google shows many different ways wire it to an Arduino, but I'm using this one because of its simplicity.

However, when I tested the circuit using the AnalogInput example code, I'm not getting the expected behavior. It registers a reading of 0 for both white and black backgrounds (I'm using white and black electrical tape as test surfaces), and occasionally registers between 5-10 if there's nothing in front of it at all.

What is the most likely problem? Is this circuit an improper way of wiring the sensor? Is my sensor defective? Is the code not reading it properly?

This is my test code:

#define BUTTON_PIN 2
#define LED_PIN 13

const int IR_SENSOR_PIN = A0;
int sensorValue = 0;

void setup() {
    Serial.begin(9600);
    pinMode(LED_PIN, OUTPUT);
}

void loop() {
    sensorValue = analogRead(IR_SENSOR_PIN);
    Serial.println(sensorValue);
    delay(1000);
}

It was a dumb programming/wiring problem on my end. As I discovered from this description, the signal pin needs a pullup resistor. Since my circuit doesn't have that, I need to enable the pullup resistor on A0, which I wasn't doing.

After modifying my code to do that, the sensor works as expected.


implement a circular buffer of say 30 characters.

clear the circular buffer

read into the circular buffer, char by char

when the last 13 characters in the buffer are: :4CAA0DE091B7 Then the prior 12 characters are the data of interest


Can't upload my sketch from arduino IDE I am using arduino uno and window7 64bit.I can't upload my program to arduino uno.When I upload it the warning message is show me.The warning message is"WARNING:Category 'USB' in library keyboard and mouse is not valid. Setting to 'Uncategorized'.What can I do?

Arduino IDEs v.1.6.x have recently been causing such kind of trouble on windows and mac systems. These problems seem to be caused by Java issues. Arduino IDE comes with java suit for it to work, installing java separately will cause problems. I suggest you uninstall java completely(by that i mean even the residue files that are not removed after uninstalling. For removing java completely you can use third party java remover like JavaRa ( https://singularlabs.com/software/javara/ ).
After doing so you can install the IDE again (i suggest to use .zip download of the IDE).
If it does'nt help it check this out http://forum.arduino.cc/index.php?topic=341144.0
its possible that problem is caused by out dated executables after updating the IDE.

Hope it helps.


GSM and Bluetooth modules on 1 Arduino Uno board I couldn't find anything on this topic.

Task: to connect sensors to Arduino board via Bluetooth module, process the received data and then send the data to server via GSM module.

Question: Is it possible to connect both of these modules to 1 Arduino board? If I'm not wrong, Arduino Uno has only one pair of Rx Tx pins, while for these two modules each has its own pairs on Rx Tx pins.

I need to know this before ordering them. So, please help

Take a look at the SoftwareSerial library which allows other pins to be used for Serial at speeds <= 57600

https://www.arduino.cc/en/Reference/SoftwareSerial


What is touch_pad_get_status() supposed to return? What I want to do:
I have 7 touch buttons on my board (ESP32 TTGO T-Display) and I want to attach interrupts to everyone, calling the same function.
In this function I would like to use touch_pad_get_status() or other to get which button was touched. Then a switch case would do the rest.
What I'm facing:
This code
  Serial.print("Button ");
  uint32_t touch = touch_pad_get_status();
  Serial.println(String(touch));

always returns 0, no matter what.
What I've tried:
Including this part of code to the setup
  touch_pad_init();
  touch_pad_set_fsm_mode(TOUCH_FSM_MODE_TIMER); //tried the SW MODE too
  touch_pad_io_init(TOUCH_PAD_GPIO15_CHANNEL);

But nothing seem to work. I don't want to make 7 different functions...
Thanks in advance.

As pointed out from people in the comments, things need to be different.
If you use the function touchAttachInterrupt, things are a bit simpler.
The example that comes with the ESP32 library is enough to make you understand.
If you want to do what I did, this is how:
  touch_pad_init();
  touch_pad_set_fsm_mode(TOUCH_FSM_MODE_TIMER);
  touch_pad_config(TOUCH_PAD_GPIO2_CHANNEL, 500);
  touch_pad_config(TOUCH_PAD_GPIO15_CHANNEL, 500);
  touch_pad_config(TOUCH_PAD_GPIO13_CHANNEL, 500);
  touch_pad_isr_register(TouchButton, NULL);
  touch_pad_intr_enable();

Put this code in the setup(). Of course needs the init(), but also needs to be set to timer mode, or otherwise you're going to need to start() probably.
The config() is to configure the pin as an interrupt. I've set 500 in the threshold because the readings of touch_pad_read() told me it went from 800 untouched to 50 touched, so the midterm I chose 500.
isr_register is the function that tells to call TouchButton(), with NULL as argument to it.
void TouchButton(void *arg)
{
  uint32_t touch = touch_pad_get_status();
  touch_pad_clear_status();
  Serial.print("Button ");
  Serial.println(String(touch));
}

This is the declaration of the callback function I've done. It should be noted that clear_status() should be called as soon as possible after the get_status(), preventing the system from panicking (that's the name). You'll also see in the serial monitor that each button represents a power of 2. That's because the get_status() returns the pin mask in binary. So just do something similar to this
for (int i = 0; i < TOUCH_PAD_MAX; i++) {
    if ((pad_intr >> i) & 0x01) {
        s_pad_activated[i] = true;
    }
}

and you'll get a vector of which one was pressed.


Why are begin() functions needed to initialize hardware (if they are)? I'm writing a program for an ATmega microcontroller using the Arduino framework.
While implementing an hardware-related class (one to manage LEDs), I put some hardware initialization code such as pinMode(OUTPUT) in the class constructor. Then I realized that in all Arduino libraries I know the hardware initialization is done in a begin() or init(), so I created one for my Led class as well and moved pinMode() there.

Now I'm wondering if I really should define such initialization funcitons, i.e. why they are needed - or, if they are not, why so many libraries have them. I played around a bit and found that for example this code works on an ATmega1284 (it makes the LED on pin 28 light up).

struct Test {
  Test() {
    pinMode(28, OUTPUT);
    digitalWrite(28, HIGH);
    // other stuff
  }
  // ...
};

Test test;

void setup() {
}

void loop() {
}

I presume that this code is somehow ill-conceived, letting alone the fact that it lights up a led without any code in the main function (or maybe that is exaclty the problem?), but if so I can not see why. What did I not consider?
Should the code above be rather writte as in the following snippet, as the existence of all these begin() functions leads me to believe?

struct Test {
  Test() {
    // other stuff
  }
  void begin() {
    pinMode(28, OUTPUT);
    digitalWrite(28, HIGH);
  }
  // ...
};

Test test;

void setup() {
  test.begin();
}

void loop() {
}

It's all to do with the order of execution.

Constructors are executed before normal functions. That includes the main() function which eventually calls setup() and (repeatedly) loop(). One of the other things that main() does is call init() (or some variant of) which configures the hardware.

Since that happens after any global constructors have been run anything that the constructor did to the hardware could potentially be undone.

Thus it is normal to defer any hardware configuration until after main() has done the work of setting things up, and the convention is to use a begin() function to do it.


Error with pointer in array I am currently learning pointers. I am following a book (Says Teach Yourself "Arduino Programming") in which there is an exemple about pointer and array.

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

  Serial.begin(9600);

  char string1[] = "This is my test string";
  char string2[]="This is another string test";
  char *ptr2 = string2;
  char *ptr1 = string1;

  while (*ptr1 != '\0') { // not "\0"
    *prt2 = *prt1;
    ptr1++;
    prt2++;
  }
  Serial.println(string1);
  Serial.println(string2);
}

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

}

I get an error "ptr2 was not declare in this scope."

I don't know what is wrong...

That for your help.

"ptr2" != "prt2"

You have a typo there.


Pin headers too long for the sensor i bought https://www.amazon.co.uk/Adafruit-TCS34725-Color-Sensor-Filter/dp/B00OKCRU5M/ref=sr_1_3?keywords=adafruit+rgb+sensor&qid=1559653098&s=computers&sr=1-3

Just bought this colour sensor for a project and as you can see it comes with the pins detached. There are 8 pins but only 7 holes so how do i assemble it? I'm assuming its super obvious since i havent seen anyone else ask it so im sorry!
Thanks in advance.

Cut one pin off.

Get some wire cutters and position them in the groove between the last and next to last pins in the row. Squeeze. One pin will pop off.


How to power IR LEDs with arduino? I need a circuit or something to power up IR leds as arduino only give 5v and IR leds needs 1.2V. Is there a way to make one arduino pin a power supply of 1.2 V code or something ?

Typically, rational control of an LED sets the amount of current that goes through the LED, rather than setting its voltage.  You could add series resistors so that when the desired current is flowing through the LED, about 1.2 volts is across the LED and the rest (say 3.6–3.8V) is across the resistor.  (See Google images for typical circuits, and see various LED resistor calculator, eg the LED resistor calculator at hacktronics.com.)  It also is possible to use PWM to control LED brightness.

Note that if you have 3.6V across a resistor and 1.2V across an LED, you are wasting 3/4 of the power expended.  When LEDs are low voltage (ie, like 1.2V for your LEDs, vs. 1.6 for typical red or orange LEDs, vs 3+ V for white or blue) you can put several of them in series.  For example, put three of your IR LEDs in series, and calculate R so that 1.2 V drops across a resistor and 3.6 across the series of LEDs.  Also try four LEDs in series, and calculate R to drop 0.1 to 0.3 V.

Edit 1: Ignacio Vazquez-Abrams says, a little  obscurely, “Getting warmer. But this is a IR LED” and also “Pull up the datasheet for a IR LED. Read it carefully. The AVR can't handle one of the numbers”, perhaps in reference to IR LED current requirements.

Typical 5mm IR LEDs can handle several times more current than typical 5mm visible light LEDs.  For example, a typical green LED might be rated 30 mA max sustained current and 20 mA recommended, while a typical IR LED might be rated 100 mA max and 50 mA recommended.  Also note that 50 mA is 10 mA more than the 40 mA that most Arduino pins list as absolute max.  A sustained current of 40 mA or more in or out of an Arduino i/o pin may damage the processor.  If you want to drive a high-current IR LED, use an external driver (eg a transistor).  See eg the answer to How can I efficiently drive an LED? in Electronics SE, which shows dropping resistor calculations, constant current sources, etc. Also see links given in JYelton's answer to  Infra Red LEDs - Voltage Advice.

Treesrule14 points out “IR leds ... don't emit in the visible light range”, which is true; they emit infrared radiation, or heat.  Note, using an IR LED in a remote control usually is incompatible with controlling its average brightness with PWM; the pulses used in PWM would conflict with the pulse train in typical 36, 38, or 40 KHz IR control protocols.


Arduino Nano joystick x2 / potentiometer will i be able to connect up all these parts to an arduino Nano
i noticed i will need to connect to the nanos v5 to the 2 joysticks and potentiometer slider if i share the voltage will it still function as intended

Parts

x1 = USB Arduino Nano V3.0 ATMEGA328P CH340G 5V 16M Micro-Controller Arduino

x2 = 3D Analog Joystick for Sony PSP 1000 Consol
+5v (possible 10kOhm resistance)

x1 = Electronic slider 10K potentiometer Slider Module for Arduino
Voltage: 3.3V or 5V / Resistance: 10K

Yes, this should work. The potentiometer slider will source about 5mA and each joystick axis about 50mA. In total this gives you 205mA. Here it is important, that your power source can provide enough current. If you are using an USB port from your computer, this would result in 500mA maximum that can be drawn from the bus. Since this is shared with the Arduino you can externally use about 400mA

For more information about current ratings refer to this question

EDIT: Since your previous resistance values were not correct, I edit my answer.

When all potentiometers have 10kOhm resistance (and this seems to be more likely the right values), each one draws about 5mA from the 5V pin (You can calculate this with Ohm's Law U = R * I, which gives you I = U / R. So you have to divide the voltage by the resistance.). So you aren't getting anywhere near the problematic currents. These potentiometers are designed this way. They don't want to draw a high amount of power, but only setting a certain voltage to the output pin.


Programming arduino using avrdude from command prompt Out of curiosity, I am trying to upload a simple hex file to Arduino UNO using avrdude from windows command prompt.

As per this forum, I tried to implement it. But got stuck at

  avrdude: ser_open(): can't open device "COM41": The system cannot find the file
  specified.

This command was directly imported from Arduino IDE verbose, and also it works fine when uploaded with Arduino IDE. I checked both the device and syntax are correct unless I would not be able to generate the hex file by Arduino compiler.

P.S. I have installed Winavr separately although it was pre-installed by Arduino
itself.

Here is a snapshot of the error

What could be the possible reason for it to fail? Please notify, if anything is missing.

can't open device "COM41": The system cannot find the file specified.

This means there is no device at COM41. This may be due to 2 reasons:

You may not have connected your arduino. If this is the case then you please connect the arduino and retry
Your arduino might be on a different COM port. If this is the case, then, go to device manager and check your arduino's COM port and replace COM41 with that and retry.


Do I need an Microchip ATSAM3X8E Evaluation Kit? I am intending to use the Arduino Due processors into my own designs. We have a very extensive (dozen of thousands of lines in .c code) sets of Arduino Due functional codes, and now I intend to move into a more solid form shape.
I have the following questions. What i need is some sort of feedback in order to answer those by myself and realize how to proceed.

I understand some of the Fast Speed Serial options in the Microchip IC cannot be tried in the Arduino Due (such as USBOTG?)?. What I actually need is some Serial Speed close to 2Mbps and a USB Programming Port.

Which are the main differences between the Microchip ATSAM3X8E and the Atmel ATSAM3X8E? R: No, they are the same.

I notice there are some functionalities in the Microchip ATSAM3X8E or even in the Atmel ATSAM3X8E not able to be reproduced in the Arduino Due Board?

Do The Microchip ATSAM3X8E IC have its own functionalities not present in the Atmel ATSAM3X8E? R: No, they are the same.

As note, there is a Keil ARM SAM3X-EK Evaluation Kit (also also here with its brochure), with a ATSAM3X8H, which is not the same IC series, but somehow exposes my concern (if real).

If my concern about High Speed Serial is real, how should I evaluate it?

I understand some of the Fast Speed Serial options in the Microchip IC cannot be tried in the Arduino Due (such as USBOTG?)?. What I actually need is some Serial Speed close to 2Mbps and a USB Programming Port.

What would make you think that? The chip is the chip regardless of what board it's soldered to. You have the native USB and you have all the UART connections direct to the chip. The board has no effect on that at all.  2Mbps is nothing. You can go much faster than that.

Which are the main differences between the Microchip ATSAM3X8E and the Atmel ATSAM3X8E?

The label. When Microchip bought Atmel a few years back they bought everything. That includes the Malaysian factories where the Atmel chips are made (a friend of mine had the job of inventory combining and spent quite some time in Malaysia sorting it all out). Microchip ATSAM3X8E chips are made in the same factory by the same people to the same designs on the same machines. It's just they are now labelled "Microchip" instead of "Atmel".

I notice there are some functionalities in the Microchip ATSAM3X8E or even in the Atmel ATSAM3X8E not able to be reproduced in the Arduino Due Board?

Is that a question or a statement. Or aren't you sure? The Due is just a chip on a board with some support circuitry. Everything that is in the chip is there, you can't remove it. There may be the case that a specific pin may not be brought out to a header, but you will have to compare the datasheet with the schematic in that case. The chip is not at fault here.

Do The Microchip ATSAM3X8E IC have its own functionalities not present in the Atmel ATSAM3X8E?

No. The two are 100% identical.

As note, there is a Keil ARM SAM3X-EK Evaluation Kit (also also here with its brochure), with a ATSAM3X8H, which is not the same IC series, but somehow exposes my concern (if real).

The ATSAMA3X8H is not commercially available. It was a specific custom chip made only for the SAM3X-EK kit. It is, essentially, a SAM3X8E with more IO pins and the ability to connect to SDRAM.

If my concern about High Speed Serial is real, how should I evaluate it?

Your concern is not real. Only imagined. The only possibility is that the UART to USB chip used on the Due may not be able to keep up at high baud rates. That has nothing to do with what the SAM3X8E can do, just what the interface to your PC is capable of. You can replace that with an external USB to UART interface if you want, such as an FT232R based interface. That is if it's communication with your PC that you're concerned about, in which case you would be better with the native USB interface as it's not restricted by whatever external hardware is added.


Arduino with Ultrasonic sensor integrated but vibration motor not working according to the code Here's my code after editing the measurement had error. Now the ultrasonic measurement is working but the vibration motor is not vibrating.

#define trigPin1 8
#define echoPin1 7
#define motorPin1 13

long duration, distance, UltraSensor;

void setup()
{
  Serial.begin(9600); // to use the serial monitor.
  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);
  //pinMode(motorPin1, OUTPUT);

}

void SonarSensor(int trigPin, int echoPin)
{
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration / 2) / 29.1;
  delay(100);
}

void loop()
{
  SonarSensor(trigPin1, echoPin1);
  UltraSensor = distance;
  Serial.print(distance); // print out the distance on Serial Monitor
  Serial.println("cm");
//
  if (distance <= 60 && distance >= 45) // Checking the distance, you can change the value
  {
    digitalWrite(motorPin1, HIGH); // motor on
    delay(200);
    digitalWrite(motorPin1, LOW); // motor off
    delay(200);
  }
  else if(distance < 45 && distance >=30)
  {
    digitalWrite(motorPin1, HIGH); // when greater than 100cm
    delay(100);
    digitalWrite(motorPin1, LOW);
    delay(100);
  }
  else if(distance < 30)
  {
   digitalWrite(motorPin1, HIGH);
   delay(50);
   digitalWrite(motorPin1, LOW);
   delay(50);
  }
  else
  {
    digitalWrite(motorPin1, LOW);
  }
}

I think you have to uncomment the line that defines the motor as an output device.

//pinMode(motorPin1, OUTPUT);


freeMemory() function from memoryfree library not returning decreased value in arduino UNO I burned the code written below, I expect that as we declare the local variable in the loop, freeMemory() function should return decreased value. But it remains constant..! please explain why..?  The output is attached :

#include <MemoryFree.h>
void setup()
{
  // put your setup code here, to run once:

  Serial.begin(9600); Serial.println(freeMemory(), DEC);  // print how much RAM is available.
  Serial.println("Lets Start");
}
void jack();
void loop()
{
    char c=0;
    c++;
    Serial.println("");
    Serial.println("Rajat0");
    Serial.println(freeMemory(), DEC);
    Serial.println("Rajat1");
    int x=0;
    x++;
    Serial.println("Rajat2");
    Serial.println(freeMemory(), DEC);
    Serial.println("Rajat3");
    jack();
    Serial.println("");
    delay(1000);
}
void jack()
{
    Serial.println("jack0");
    int x=0;
    x++;
    Serial.println(freeMemory(), DEC);
    Serial.println("jack1");
}

You are assuming that, just because you created a variable, it will be stored in memory. That is often not the case.

The compiler is reasonably intelligent. And there are lots of CPU registers in the AVR core. If there is a free register available for a temporary local variable like that, why would it waste time and effort putting it into memory when it can just keep it in a register?

Also, since you don't really do anything with the variable, chances are the compiler is just throwing it away.

Marking a variable volatile will remove both those problems, and you may see different results.


How to get timestamp of when the data was collected Basically I want to be able to display the time the arduino collected the data with the data value, not the time the arduino printed off the data. Theres a timestamp feature on the console, however I want to find the time the data was collected.
I'm a bit new to this so any help is greatly appreciated!

Getting a "timestamp" of when data is collected is entirely down to you.
Most Arduinos don't have any concept of the current time, only the time since the program started running. To know what the time "now" is you have to have some mechanism to tell the Arduino what the time is, along with a method of keeping track of that time.
There are devices called Real-Time Clock (RTC) modules which keep track of the time for you. They don't magically know the time - you still have to tell them at least once.
You could tell it the time through the serial port to set the clock - from then on (assuming the RTC has power) the RTC will know what the time is.
Another option to get the time into the RTC is to use an internet connection (ESP8266, WiFi shield, Ethernet shield, etc) to perform a Network Time Protocol (NTP) query to a time server on the internet (such as pool.ntp.org) to get the current time and update the RTC.  This should be done regularly to correct any drift in the RTC.
Once you have an RTC and a method of setting the time you can query the time whenever you sample some data and store that time along with the data in whatever way is most suitable for your situation.


Increasing distance of IR remote / transmitter I am trying to set up my Arduino as a replacement remote control. The setup works and I can use it to turn on/off my things, for example my fan.

However, the working distance is quite short. Around a meter. The actual remote for my fan works across the distance of my apartment.

What can I do to improve the working distance of my Arduino remote? Does the LED need a back reflector or something? Does it need a different LED?

The LED I am using is this, it came in a bundle I purchased.
https://www.amazon.com/dp/B07PJC7WSQ/#detail-bullets

I assume that the led you purchased just isn't as bright as the led that came with your remote.
As I've seen from your link you could quite easily swap the led from the board.
If the new led has the same voltage, the board should work just fine with any other led. Maybe just search for a brighter led with the same wavelength.

I don't think that a back reflector would have such a big effect to boost the range to the distance you need. Also I think it would be rather complicated to install one on the tiny board.


Arduino code won't upload with Ethernet Shield attached I've been playing with my Arduino Boards for a while. I have an Arduino Nano and a Duemilanove 328.

I've been able to program both of them without problems for weeks. Any example project I try will compile and upload with no issue.

I recently got an Ethernet shield... I'm trying some test sketches and no matter which board I try, with the shield attached I get:

avrdude: stk500_getsync(): not in sync: resp=0x00

As I said, without the Ethernet shield attached all is bliss....

Do I have a bad shield or am I just doing something stupid?

The Ethernet Shield uses the pins  D10, D11, D12 and D13 on the Arduino UNO. I presume there is a conflict and you use one or more of these digital pins in your setup already.

A nice overview of possible conflicts between shields and arduino boards can be found at:
http://playground.arduino.cc/Main/ShieldPinUsage


How can I adapt the DallasTemperature library to accept another 1-Wire class? A commonly used library is the DallasTemperature library, used to access DS18B20 sensors on a 1-Wire bus. When creating a DallasTemperature object you pass a reference to a OneWire object. OneWire can create a 1-Wire bus on pretty much any port of an Arduino.

An example of this is like so:

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

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

However, there are some issues with using OneWire to drive a 1-Wire bus, mainly around driving longer bus lengths, dealing with shorts, and other errors.

There is a commonly available chip called the DS2482-100 that can drive longer busses (hundreds of feet), deals with shorts and other errors. It is also less CPU heavy and it deals with a number of the slower aspects of 1-Wire.

For this reason, I would like to be able to pass a reference to a library that I have created instead. Currently, I am doing this by:

Calling the library OneWire
Replicating all the methods called by the DallasTemperature library
Swapping out the OneWire library for mine

This is relatively messy. I would ideally like to be able to pass either a reference to my library or a 1-Wire library, so that people can chose which interface to use.

How would I go about doing this?

The typical way to achieve what you want would normally be to create your own subclass of OneWire class and override the methods you need to change, then pass a pointer to an instance of your class to the DallasTemperature constructor.

However, for this to work, the OneWire class must have been developed with extensibility (subclassing) in mind, i.e. use virtual methods that you can override.

Unfortunately, a quick look at OneWire.h shows that no method is virtual in there.

So that means in the end you will have to perform some hacks, just as you do now.

What you could potentially do (that's still a hack, but maybe a bit less dirty) is:

replace OneWire.h to make all methods virtual (at least those you need to override)
keep the original OneWire.cpp that should still compile with the newly adapted header file
create a new MyOneWire.h / MyOneWire.cpp to define your own OneWire subclass that overrides all necessary methods as you want

Then you can pass either a OneWire or a MyOneWire instance to DallasTemperature constructor.

NB: when I see my answer, this makes me think your question is more a general C++ question than an Arduino-related one.


Setting time frame in Arduino Uno I have built the circuit below using mux ICs. In a particular interval the respective selector pins get selected and analog signal from hall sensors are read and give a particular analog value out. There is a total of 30 hall sensors which are represented by HS0 to HS31.

Now I wanted to set time as in the table below. After 8000ms I would like it to reset the time automatically and start reading. Can someone tell me which timer example would let me achieve this?

TIME IS ms  OUT1    OUT2    OUT3    OUT4
  0-1000    HS0     HS8     HS16    HS24
1000-2000   HS1     HS9     HS17    HS25
2000-3000   HS2     HS10    HS18    HS26
3000-4000   HS3     HS11    HS19    HS27
4000-5000   HS4     HS12    HS20    HS28
5000-6000   HS5     HS13    HS21    HS29
6000-7000   HS6     HS14    HS22    HS30
7000-8000   HS7     HS15    HS23    HS31

Could you tell us which multiplexer IC you are using? This way, we can help you better. Also, why do you need the 8 second cycle? Does it matter if it's a little shorter or longer? If timing does not have to be very precise it would make things a lot easier.

By the way: you say there are 30 sensors, but your table has 32...

The following pseudocode will not work on your Arduino, but you can use the same structure.

int sensorArray[32] // we will store our 32 sensor values here

// these pins control the multiplexer chips
int selectPinZero = 8;
int selectPinOne = 9;
int selectPinTwo = 10;

// these pins will receive the sensor values from the multiplexer chips
int inputPinOne = 0;
int inputPinTwo = 1;
int inputPinThree = 2;
int inputPintFour = 3;

void setup(){
    // make sure the correct pins are inputs and outputs
    pinMode(selectPinZero, OUTPUT);
    pinMode(selectPinOne, OUTPUT);
    pinMode(selectPinTwo, OUTPUT);

    pinMode(inputPinOne, INPUT);
    pinMode(inputPinTwo, INPUT);
    pinMode(inputPinThree, INPUT);
    pinMode(inputPinFour, INPUT);
}

// all done, now keep reading the sensors
void loop(){

    // set selectPins so that each Multiplexer will output its first channel
    digitalWrite(selectPinZero, HIGH); // or low, depending on your Multiplexer IC
    digitalWrite(selectPinOne, HIGH); // or low, depending on your Multiplexer IC
    digitalWrite(selectPinTwo, HIGH); // or low, depending on your Multiplexer IC

    // start reading sensors

    int i = 0;
    while(i<32){
        sensorArray[i] = analogRead(inputPinOne);
        i++; // variable i was 0, now 1

        sensorArray[i] = analogRead(inputPinTwo);
        i++; // variable i was 1, now 2

        sensorArray[i] = analogRead(inputPinThree);
        i++; // variable i was 2, now 3

        sensorArray[i] = analogRead(inputPinFour);
        i++; // variable i was 3, now 4

        /*
        use digitalWrite() on all the selectPins to make the Multiplexer IC output the next channel
        */

        delay(1000); // wait 1000 milliseconds
    }

    /*
    this will repeat until all 32 sensors are read and stored in the array
    */

}

This code is by no means optimized, but written to make it easy for you to understand. Good luck!


how to run 2 different servo (continuous rotation and regular servo) in parallel, not run one after other? I need to control 2 servos in parallel, whereas one is of continuous rotation and another is of regular positioning control (angle) on arduino IDE. I tried but it works one after another, not parallel. How can I do that, please suggest. Thanks.

I am proposing one answer
https://wokwi.com/arduino/projects/297646292038844936
Here, we are not using the delay function. We are using the millis()
Based on your actual application, you can control individual servo accordingly.
Here is the Arduino simulation:
https://wokwi.com/arduino/projects/297646292038844936

/* Sweep
  by BARRAGAN <http://barraganstudio.com>
  This example code is in the public domain.

  modified 8 Nov 2013
  by Scott Fitzgerald
  http://www.arduino.cc/en/Tutorial/Sweep
*/

#include <Servo.h>

Servo myservo;  // create servo object to control a servo
Servo myservo2;  // create servo object to control a servo

// twelve servo objects can be created on most boards
unsigned long previousMillis = 0;        // will store last time LED was updated
const long interval = 15;           // interval at which to blink (milliseconds)

int pos = 0;    // variable to store the servo position
int pos2 = 0;    // variable to store the servo position

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  myservo2.attach(10);  // attaches the servo on pin 9 to the servo object

}

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

  if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    pos = pos + 1;
    if (pos > 180) {
      pos = 0;
    }                      // waits 15ms for the servo to reach the position

    myservo2.write(pos2);              // tell servo to go to position in variable 'pos'
    pos2 = pos2 + 1;
    if (pos2 > 90) {
      pos2 = 0;
    }

  }

}


How to Capture Data from a Webpage in Arduino and Display it over Serial Monitor of ESP8266? My Code is as follows->

#include <SoftwareSerial.h>

SoftwareSerial ESP8266(8,9);

String inData;
void setup() {
ESP8266.println("AT");
delay(1000);
ESP8266.println("AT+RST");

}

void loop() {
 String cmd = "AT+CIPSTART=\"TCP\",\"";
 cmd += "api.thingspeak.com";  // 184.106.153.149 thingspeak IP address
 cmd += "\",80";
 ESP8266.println(cmd);

 if(ESP8266.find("Error"))
 {
   Serial.println("AT+CIPSTART error");
   return;
}
String hostt = "GET /apps/thinghttp/send_request?api_key=689WYA85WW1VJSBA";
hostt += "\r\n";
hostt += "Host:api.thingspeak.com";
hostt += "\r\n\r\n\r\n\r\n\r\n\r\n";
ESP8266.println(hostt);

cmd = "AT+CIPSEND=";
cmd += String(hostt.length());
ESP8266.println(cmd);

if(ESP8266.find(">")){
ESP8266.print(hostt);
}
else{
ESP8266.println("AT+CIPCLOSE");
// alert user
Serial.println("AT+CIPCLOSE");
}
delay(5000);
}

Is this the write code? Where am I going wrong?
I am not able to see the required fetched data.
Help me with this.

There are two basic things you are doing wrong:

Firstly your HTTP request is wrongly formatted.  You have:

GET /apps/thinghttp/send_request?api_key=689WYA85WW1VJSBA
Host:api.thingspeak.com

What it should look like is:

GET /apps/thinghttp/send_request?api_key=689WYA85WW1VJSBA HTTP/1.0
Host: api.thingspeak.com:80

Also you only need one blank line after your request, not 5 as you seem to have.

Secondly you are not actually doing anything with the data the site is sending you. You make the request with +CIPSEND= but then the response, which is in the form +IPD,<len>:<data> is completely ignored.  You need to use the SoftwareSerial's .read() and associated functions to receive that data into the Arduino so you can actually do something with it - like send it down through Serial.

Tips:

Look for +IPD, first
Read up to the : and interpret it as a number
You now now how many bytes to read from the data section
Read that data
Do something with it


Interrupt variable not getting called while executing another part volatile byte _incomingFlag = 0;

void onIncoming () {
    _incomingFlag = 1;
    Serial.println(F("You got an interrupt"));
    mySerial.println("ATH0");
}

void setup () {
    /* First Start the module */
    Serial.begin(9600);
    Serial.println(F("Initializing module..."));

    powerOn();

    mySerial.begin(9600);

    sendcommand(F("AT"), F("OK"), 1000);
    sendcommand(F("AT+CLIP=1"), F("OK"), 1000);
    sendcommand(F("AT+CMGF=1"), F("OK"), 1000);

    /* We need to attach ringing Interrupt */
    attachInterrupt(M_RING_INTERRUPT, onIncoming, FALLING);

    delay(100);
}

void loop() {
    if (_incomingFlag == 1) {
        manageIncoming();
        Serial.print(F("_incomingFlag: "));
        Serial.println(_incomingFlag);
    } else  {
        Serial.println(_incomingFlag);
        Serial.println(F("not getting value"));
    }
    get_currentLocation();
    send_Location();
}

I am trying to check the value of incomingFlag from the loop() . When I get a call or an SMS the interrupt function is getting executed and incomingFlag is set to 1 but I am not getting that value from the loop(). Everytime it's getting 0 if I check the value while the send_Location function is executing (data uploading part). How can I access the value of incomingFlag from the main loop().

volatile byte _incomingFlag = 0;
 void onIncoming () {
             _incomingFlag = 1;
            Serial.println(F("You got an interrupt"));
            mySerial.println("ATH0");

        }

Regardless of what your purpose is there, you cannot successfully do serial prints inside an ISR. All bets are off if you do that.

In fact you are doing two prints - is one SoftwareSerial?

If you must have a debugging "flag" turn on an LED. Doing serial printing requires interrupts to be on, and they are off inside an ISR.

Note: You may get the display once, and therefore you think it works. As soon as the serial buffer fills up (probably 64 bytes) then it will just block indefinitely. Your message "You got an interrupt" is already 22 bytes if you count the trailing carriage-return/linefeed.

More detailed explanation

In your main loop, every time through it, you are printing either:

_incomingFlag: 1

or

0
not getting value

Therefore the serial buffer will be definitely full (or almost full). It can't empty the buffer if you are cramming this stuff into it every time through loop.

So now you have an incoming call. You set _incomingFlag to 1, then try to do this:

    Serial.println(F("You got an interrupt"));

That blocks, because if can't fit all that into the output buffer, and the program then hangs, because the buffer is not emptied inside an ISR.


Read float and long from external EEPROM chip I am using an Arduino to read information from an EEPROM chip over I2C with the code I found here:
https://playground.arduino.cc/Code/I2CEEPROM

It works great for int and char values but I also need to read short, long, and float values.

They are stored in this order:  1510543923
is stored as: 01011010 00001001 00010010 00110011

How can I read multiple bytes into a single variable of these types?

I tried the following but it gives me a 16 bit number:

i2c_eeprom_read_buffer(0x50, 25, (byte *)bytes, 4);
long j = (bytes[3] << 0) + (bytes[2] << 8) + (bytes[1] << 16) + (bytes[0] << 24);

1510543923 is stored as: 01011010 00001001 00010010 00110011

This is known as “big endian”, or “MSB first”, because the most
significant byte (MSB, here 01011010) comes first.

I recommend against this order. If you can, swap all the bytes and store
the value LSB first, i.e. with the least significant byte first, and the
most significant byte last. This will make your life easier since it's
the order used internally in the Arduino. If you can go little endian,
then you will be able to read the data straight into the required
variable, with no conversion needed, as in:

i2c_eeprom_read_buffer(0x50, 25, (byte *) &j, sizeof j);

and it will work identically with any data type.

If you cannot choose the byte order (maybe you cannot control what is
inside the EEPROM), then you will have to reverse all the bytes. You can
do this either with bit shifts or by explicitly moving bytes.

  bytes[1] << 16

This will not work. Per the rules of the C++ language, bytes[1] is
implicitly promoted to int type before the shift, then it is shifted
as an int. But on your Arduino an int is 16-bits long, thus by
shifting it 16 positions you are dropping off all of the bits.
Actually, this is even worse: you are invoking what is known as
undefined behavior, meaning that it is considered nonsense and the
compiler is free to interpret however it wants.

To do this properly, you first have to explicitly cast bytes[i] to
unsigned long. It has to be unsigned because changing the sign bit on
a long by bit shifting is also undefined behavior. Thus, the proper
way of reconstructing the number via bit shifts is:

long j = ((unsigned long) bytes[3] << 0)
       | ((unsigned long) bytes[2] << 8)
       | ((unsigned long) bytes[1] << 16)
       | ((unsigned long) bytes[0] << 24);

This is portable (it should also work on big-endian architectures) but
only works with integral types, not with floats.

For reconstructing a float, my preferred option would be to use a
union, in order to access the bytes of the variable explicitly. Then
you just have to copy the bytes from the buffer to the union in
reverse order:

union { float f; byte b[4]; } data;
data.b[0] = bytes[3];
data.b[1] = bytes[2];
data.b[2] = bytes[1];
data.b[3] = bytes[0];
float x = data.f;

One nice thing about this approach is that it works with any data type.


exit status 1 'Time' does not name a type #include <DS3231.h>
#include <Wire.h>  // i2C Conection Library

// Init DS3231
DS3231  rtc;
// Init a Time-data structure
Time  t;
uint32_t targetTime = 0;

uint8_t hh = 0, mm = 0, ss = 0, dd = 0, bb = 0; //variable Unsignet int 0-255
int yy = 0; //variable integer
String Day = "  "; //variable string

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

void loop() {
  t = rtc.getTime(); // gate all data time & date from RTC
  Day = rtc.getDOWStr(); //get name of day
  hh = t.hour,DEC; //pengambilan data jam
  mm = t.min,DEC; //pengambilan data menit
  ss = t.sec,DEC; //pengambilan data detik
  dd = t.date,DEC; //pengambilan data hari
  bb = t.mon,DEC; //pengambilan data bulan (dalam desimal)
  yy = t.year,DEC; //pengambilan data tahun
  //Buka Serial Monitor Arduino untuk melihat hasilnya
  Serial.print (Day);
  Serial.print (F(" Time = "));
  Serial.print (hh); Serial.print (F(" : "));
  Serial.print (mm); Serial.print (F(" : "));
  Serial.print (ss); Serial.print (F("  Date = "));
  Serial.print (dd); Serial.print (F(" . "));
  Serial.print (bb); Serial.print (F(" . "));
  Serial.println (yy);
  delay (1000);
}

When I verify the code, this error appears:

  exit status 1
  'Time' does not name a type

What does it mean?

You don't mention which library you are using (which library does #include <DS3231.h> refer to?)

The DS3231 library here https://github.com/NorthernWidget/DS3231 defines a DateTime object which appears to have similar elements to what you are trying to access in 't' (hour, min, sec etc).

I would try defining 't' as a DateTime object.


Nothing received from function returning array of strings My read function returns an array of strings. i.e ssid and password

String* configuration::read() {
    String rw_ssid = "";
    String rw_pswd = "";
    const int keys = 2;
    String read_ssid_pswd [keys];
    if (EEPROM.read(0) != 0) {

      for (int i = 0; i < 32; ++i) {
        rw_ssid += char(EEPROM.read(i));
      }
      for (int i = 32; i < 96; ++i) {
        rw_pswd += char(EEPROM.read(i));
      }
      Serial.print("rPASSWORD: ");
      Serial.println(rw_pswd);
      read_ssid_pswd[0] = rw_ssid;
      read_ssid_pswd[1] = rw_pswd;
      Serial.print("Sending ssid:");
      Serial.print(read_ssid_pswd[0]);
      Serial.print(" Pswd: ");
      Serial.println(read_ssid_pswd[1]);
      return read_ssid_pswd;
    } else {
      Serial.println("Data wifi not found!");
      return read_ssid_pswd;
    }
}

I can see the print in the serial monitor.

Sending ssid:SSID Pswd: password

but where this function is called from I have set it up like this:

void setup() {
  Serial.begin(115200);
  Eeprom::configuration::initialize();
  String* ssid_password = Eeprom::configuration::read();
  Serial.print(">SSID: ");
  Serial.println(ssid_password[0]);
  Serial.print(">Password: ");
  Serial.println(ssid_password[1]);
  Funcs::connection::connectWifi(ssid_password[0], ssid_password[1]);
}

and I get thing in the prints  I thought its not giving any error at compile time so it should be correct.

You can't return locally defined arrays like that. The array only exists in the function, and all you do is return a pointer to where that array was. As the array has gone when you leave the function your pointer just points to garbage.

Instead you should pass an array to the function that the function then populates.


file directory for saving .cpp & .h for the Arduino IDE for short #include statement I am trying to write a class/function that I think I will be using often in my Arduino IDE, I know the code but where should i save the file so that the IDE picks it up without a full directory address in the #include line, as you may guess I'm a little new to this....

If you think you will be reusing this code frequently, you might want to make a library as suggested by Joachim. Your library can then be added to any sketch you write using a #include statement.

The arduino website has a nice guide on writing libraries, check it out here.

If you would just like to include your header file in a sketch without writing a library, placing the header file in the same directory as your sketch should compile if you use #include "header_file_name.h".


Cheapest and easiest Arduino board for 12 bit ADC, thinking of M0 I need an Arduino board for simple ADC, but 10 bits of resolution is sadly not enough. I am going to buy a board with 12 bits of resolution, but really couldnt decide on the exact model. It needs to be easily accessable and wont be used for anything else other then ADC. I have my eye on MO, but cant decide if i should buy the pro or the normal one, or just another Arduino board.

I take the data through USB port and the instrument will also be powered with the same USB cable.

* My only option is to use an Arduino*

I know i can use the Aref pin or do oversampling but i really am not intrested in those options. thanks for your input

Use a Teensy 3.x. Those have 13 bit ADCs


How can we know the status of the DC Motor whether it is ON or OFF A DC motor is operated using an L298n driver and Arduino UNO. How can I get to know whether the Motor is ON or OFF? Using a code in Arduino.

Unfortunately, the L298N does not return a status, so you are going to have to add sensors to detect motor movement.
Here are a few options you can try:

Current sense. Add a small resistor to the output of the L298N and measure the voltage differential across that resistor. If there is current being supplied to the motor then you will have a voltage differential.
Rotation sensor. This can be in the form of a quadrature encoder wheel, tooth sensor or Hall effect sensor detecting a magnet on the shaft. If you see pulses from the sensor then you know the motor is spinning.
Optical sensor. A camera system or other optical sensor to detect motor movement. Probably too complex for a simple application. There are however off the shelf sensors that will turn on an output if they see movement in their field of view. Alternatively you could use a PIR sensor from a home alarm system if the movement is course enough.


How to read a specific amount of data via serial? I'm trying to send data via serial from my Arduino nano to my ESP. Its an integer from 1 to 4 digits
so something like 0, 13, 1234, 123, ...

Every thing works fine but when the data comes too fast it stopps the output and  then it print all the data on the screen.

I use this method to recieve data.

void loop() { // run over and over
        if (Serial.available()) {
                incomingByte = Serial.readString();
                Serial.println(incomingByte);
        }
}

From what you have posted, assuming this is the ESP code in the question, it is clear that for every character the Arduino sends the ESP the ESP will send 3 back. So at some speed this will likly stop working


Trinket Pro 5V red light flashing when battery attached I am using Trinket Pro 5V to run a simple i/o code. The input from the piezo vibration sensor is read by the Trinket and Translated into a servo position.
It works fine powered through a USB connection, however as soon as I try to power it using a 9V battery (plugged into the Bat+ and G terminals), the code stops running and the red light on the Trinket starts to blink.

Is the power source not sufficient - 9V?

Has anyone faced a similar problem?

Please consider reading the "https://learn.adafruit.com/trinket-gemma-servo-control/wiring" tutorial.

It says

  It is suggested you use an external wall or battery supply and not
  power the servo via the regulator. servos can draw up to 500mA and the
  Trinket regulator can only source 150 milliamps (USB power generally
  500 milliamps).

No matter what power supply you hook to the "Bat+" battery pin, if you hook the servo power to the "5V" pin on the trinket, the trinket's on-board 5V regulator will temporarily collapse under the load of the servo, which typically causes the system to reset over and over again.

Instead, please hook the servo power directly to the battery.
Alas, a typical partially-drained 9V battery has enough internal resistance that the battery's voltage will temporarily collapse under the load of the servo, which typically causes the system to reset over and over again.

Instead, use a better power source.

Many people, even when they intend to eventually run their system on batteries, start out using a wall-wart power supply, so they don't have to keep wondering "Is this glitch because of a bug in my software, or is the battery just going dead?".

The "Adafruit 16-Channel Servo Driver with Arduino" tutorial says:

  Good power choices are:

  5v 2A switching power supply
  5v 10A switching power supply
  4xAA Battery Holder - 6v with Alkaline cells.  4.8v with NiMH rechargeable cells.
  4.8 or 6v Rechargeable RC battery packs from a hobby store.

You might also want to look at other Battery holders that hold lots of AA batteries in a convenient package.

Related:
"How to get high current from 9 volt batteries"
and
"What is the max current I could draw from a 9V battery?".


nRF24L01 6TXA_1RXA network + 6TXB_1RXB network with arduino How to build nRF24L01 network shown above with arduino ?
SPI pins are shared between RXA,RXB and separate pins for both CE, CSN, IRQ.

Which nRF24L01 library supports my requirements ?

You can use the RF24 library that you can install right away from the Arduino IDE. It provides you all you need. Just use two instances of RF24 with different CSN and CE pins assigned to get started.

RF24 radioA(7, 8); // CE, CSN
RF24 radioB(5, 6); // CE, CSN

Use the simple ping sketch as a starting point and add a second radio to it.


Data from RC522 to firebase real time database #include<ESP8266WiFi.h>
#include<SPI.h>
#include "MFRC522.h"
#define RST_PIN D3
#define SS_PIN D4
MFRC522 mfrc522(SS_PIN, RST_PIN);

void setup() {
  Serial.begin(9600);
  SPI.begin();
  mfrc522.PCD_Init();
}

void loop() {
  if ( !mfrc522.PICC_IsNewCardPresent() ) {
    delay(50);
    return;
  }

  if ( !mfrc522.PICC_ReadCardSerial() ) {
    delay(50);
    return;
  }

  Serial.print(F("Card UID: "));
  dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
  Serial.println();
}

void dump_byte_array(byte *buffer, byte bufferSize) {
  for ( byte i = 0; i< bufferSize; i++ ) {
    Serial.print(buffer[i] < 0x10 ? " 0" : " ");
    Serial.print(buffer[i], HEX);
  }
}

I am able to get the unique ID of the RFID tag & card. But now the problem is that how can I send the unique ID from ESP8266 to the firebase realtime database.

The hexadecimal values that are generated are they unique? or they are something else? Because in some youtube videos I saw people using only numbers as a unique ID from RFID to distinguish between 2 cards or tags.

The wifi connection and firebase auth all are set peoperly ony the unique id number is the problem.

The "UID" of the card is supposed to be unique. Most RFID chips also have blocks of readable/writable space, but some systems do only use the UID from the chip as the complete identifier.

It may be that you come across RFID chips that have utilized random bytes as the UID, in which case there is a chance of duplication. Depending on the number of possible cards to be used in your system, this may or may not be a big worry for you. If it is a big worry, you may want to use the actual memory on the RFID chips to store your user's ID data.

Regarding HEX versus numbers -- Hexadecimal is just one way to represent numbers.
Your code:

Serial.print(buffer[i], HEX);

tells the print command to take the byte at buffer[i] and print its value in Hexadecimal format. You could replace HEX by DEC to see the base-10 (decimal) value instead. The actual bits underneath would be the same -- it's just one way to display/represent the underlying number.

One byte (8 bits) of data can be represented in decimal as the numbers 0 through 255. The same byte can be represented in Hexadecimal as 0x00 through 0xFF. ('0x' is one way to denote that what follows are hexadecimal values.) Each 'digit' in hex represents 4 bits of data (0-15 in decimal), so 2 hex digits can represent 16^2 values (256 decimal), hence 0-255 as the 1-byte range of decimal values.

(That explanation assumes un-signed types.)


Serial read multiple digits and always reading 10 at the end? So I'm trying to make a program that allows you to enter a number in decimal and it displays it in binary, and it's going fairly well after some initial struggles (for some reason it read integers as 48 more than they are (5 read as 53)) but there's something I still don't understand, and I'm scared that it may be a hardware issue.

For some reason, I can't display two-digit numbers. For example, if I input 12, it displays 1, and THEN it displays 2. Also, to make things worse, it ALWAYS outputs 10 after I input ANY number. For example, if I input 5, it displays 5, and then ALWAYS 10.

    void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);

}

void loop() {
  // put your main code here, to run repeatedly:
  int number;
  if (Serial.available() > 0) {

    number = Serial.read();
    Serial.print("Number to display: ");
    Serial.println(number);

    if (number <= 15){
      int LEDPin = 2;
      digitalWrite(2, LOW);
      digitalWrite(3, LOW);
      digitalWrite(4, LOW);
      digitalWrite(5, LOW);
        for (int n = 0; n <= 4; n++){
          int binval = bitRead(number, n);
          Serial.println(binval);
          digitalWrite(LEDPin, binval);
          LEDPin++;
      }
    }
    else{
    Serial.println("Number must be less than 16!");
    }

    delay(1000);
  }
}

EDIT: And of course, after asking the question I re-ran the code and its AGAIN showing ints as 48 bigger than they are (5 as 53).

At this point, I'm extremely confused. Am I doing something wrong? Is this a hardware issue? What can I do?

for some reason it read integers as 48 more than they are (5 read as 53)

That's because you're not entering numbers, you're entering ASCII characters that represent numbers.

Everything you see on a computer or similar device is not really what is there. It is all translated into a form that we mere humans can see.  Every number is translated into readable characters, and readable characters have to be converted into numbers.

For example, the number 165 is the characters 1 (49), 6 (54) and 5(53).  When you enter that number you are sending those three individual characters.

You see the entire ASCII table here.

Another effect of sending individual characters is that you also send a marker to say "This is the end of the line". That can either be character 13 (Carriage Return), character 10 (Line Feed), or a combination of the two.  You can select which is sent in the Serial Monitor.

You should really use that line ending character or combination of characters to work out how many characters there are in your number so you can convert them into a proper integer value.

Some further reading:

Reading Serial on the Arduino (my blog)
The atoi() function


Digital pin output voltage, not triggering 71mA relay coil I have a relay (VRS4H-S-DC5V-C), for which the triggering voltage required is 5V Min.  If I directly use the 5V voltage of Arduino  I'm able to trigger it, but if I use any digital pin in OUTPUT mode in digitalWrite I'm not able to trigger the relay.

Earlier I thought that it must be that because it's a small board its digital pins would be giving HIGH state as 3.3.V, but the fact is when I checked both the voltage of 5V (which is obviously shown 5V on multi meter) and that digital pin one, both show 5V. So the question is why the hell is digital pin not able to trigger the relay, since trigger the relay by 5V is of no use for me since I can't control it, i.e., when it should trigger and when not?

The digital output pin cannot output sufficient current to drive the relay directly. Iirc this question was already asked. You need to add between the Arduino and the relay a driving stage, for example with a FET. Or you can use a shield that already has this additional circuitry.

Just google for "Arduino relay driver circuit" and you will get various options.

This is pretty close to your setup.


I2C LCD displaying weird characters I have connected an LCD with an I2C backpack to my Arduino Uno but it prints the wrong characters. The weird thing is that it worked fine for a while and when I updated the code (but didn't change anything to do with the LCD) it started displaying the wrong characters. This happened earlier today too. That time, reinstalling the LiquidCrystal library worked, but it doesn't now.

Does anyone know what might be the problem so I can fix it permanently?

The LCD's SDA and SCL are connected to A4 and A5 respectively and I'm running this code:

#include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27,20,4);  // set the LCD address to 0x27 for a 16     chars and 2 line display

void setup()
{
  lcd.init();
  lcd.backlight();
  lcd.setCursor(0,0);
  lcd.print("Hello, world!");
}

void loop()
{
    }

and this is what's displayed on the screen:

If you look up the ASCII codes for what you sent vs what was displayed, and also look at "Table 4 Correspondence between Character Codes and Character Patterns (ROM Code: A00)" in an HD44780U spec sheet, you will find hexadecimal values like the following.

e 65, V  56
l 6C, ニ C6
o 6F, θ  F2
o 6F, π  F7
r 72, &  26
d 64, B  24
and so forth.

It appears that the high nibble of what you sent is being used as the low nibble of what is displayed, and the low nibble is being used as the high, but with some bits sometimes going wrong.  Note, a space is 0x20, and the reverse of that is 0x02, which would access a character from the character-generator RAM, which will contain random bits and produce a random blob as in your picture.

If your mis-specification of display size (20, 4 vs 16, 2) isn't responsible for the problem, then maybe there is a hardware problem with the backpack you've soldered on to the LCD.  Look at it under a bright light, using a binocular parts-examination microscope if you've got one, and see if there are loose solder particles, extra solder flux, or loose solder connections on that board.  If you have an oscilloscope, check if your I2C signals are clean and have full swing.


How do I convert 0-5v PWM to a 0-12v PWM I have a Arduino which I would like to use to control a 12v PWM fan for speed control.
I know about the 0-3.3v to 0-5v logic level shifter, is there a similar option for 0-5v to 0-12v? Or is there a circuit using a IC that I need to make?
Thanks in advance for your help.

I advice you to learn about basics of how to connect external components to MCU.
Anwser to your question is simple transistor amplifier... So you can use bipolar transistor (NPN/PNP) or MOSFET... MOSFETs is better for switching like your case, switching via PWM.
If you switching inductive load with MOSFET like motors or coils, don't forget add antiparallel flyback diode. Otherwise your MOSFET will burn out.

If you need switching with higher frequency or load with more voltage or power I advice to use push-pull logic to drive mosfet gate.
Something like this:


Saving library example sketch getting error "you cannot save a sketch into a folder inside itself.." I'm writing a library, and that library .cpp/.h code is in devel/arduino/libraries/LightBrightLib/.  I have test code that calls that library, and an example program using the library.  Right now they're in /devel/arduino/lightbright/LightBrightMain/ and /devel/arduino/lightbright/LightBrightLibTest/.

I see most libraries have an examples directory inside the library, so I tried moving mine to /devel/arduino/libraries/LightBrightLib/examples/LightBrightMain/ and /devel/arduino/libraries/LightBrightLib/examples/LightBrightLibTest/

When I do that, and try to save my LightBrightMain.ino file into /devel/arduino/libraries/LightBrightLib/examples/LightBrightMain/, it says "You cannot save a sketch into a folder inside itself. This would go on forever.".  And of course it won't let me select the examples directory or any other directory above it.

How do other library makers do this?  Maybe they don't use the IDE, or they copy it in outside the IDE, or use symlinks?
What does the IDE think it's doing and why is it fighting putting the file where it already is?

NOTE: This is not a file permission problem as I own all files

What I normally do is make the examples in their own folders (ie. inside the sketchbook folder). Then when they are tested I just use the file system to move the folders into the "examples" folder under the library.

  When I do that, and try to save my LightBrightMain.ino file into /devel/arduino/libraries/LightBrightLib/examples/LightBrightMain/,

The IDE makes the folder, so you would (if this works at all) save LightBrightMain into the examples folder. Don't make a folder of the same name as the sketch. The IDE does that.


Cannot start Arduino IDE after playing with several versions of it On my Linux Mint 17 Quiana I have manually downloaded and ran several versions of the arduino IDE (1.05 which is in the repo, 1.6.x for some time, now 1.8.3). Things worked like a charm.

Now I am trying to get the IDE 1.8.5 going, but I cannot get the IDE started. Started means: I download, extract the files to a directory and run the install.sh command such that the desktop icon gets created. This finishe with a success message. Now I am clicking on the desktop icon, but nothing happens.

Need to say that the IDE 1.05 which comes as a package with Qiana works just fine. I have run the install.sh of both to and fro, but only the 1.05 will start properly. I checked on the desktop link, the execution rights, user, group etc. They are all looking fine for 1.8.5 but it wont start.

I tried to start the 1.85 arduino IDE from the command line - hoping to get some clue from error messages:

java -DAPP_DIR=/opt/arduino-1.8.5/ Dswing.defaultlaf=com.sun.java.swing.plaf.gtk.GTKLookAndFeel processing.app.Base

--> running this it tells me, that the main class cannot be found.

Any hints where I am going wrong? Are there any config files to be cleared up, paths to be set ...?

You do not need to install Arduino at all. In fact I have never had it work right due to things not being found.

All you need to do is, from a terminal, run the arduino command in the extracted directory:

fred@computer:~/arduino-1.8.5 $ ./arduino

Any errors that then throws will be a clue as to why it doesn't want to work.