Pneumatic cylinders with sensors with Arduino Uno I'm working on my own project with Arduino Uno. There are controlled 4 pneumatic cylinders via 4 coils. Every pneumatic cylinder has got their own coil which switch air to the pneumatic cylinder. Every pneumatic cylinder has got 2 magnetic sensors (when the pneumatic cylinder is retracted and extended).
I created a program for arduino but it doesn't work correctly. When I write there that I want to control only 2 pneumatic cylinders, it works correctly. If I write there the others, it skip the second if statement, do the third if statement and then do the previous if. I don't know why. The behaviour is random. What's wrong with my code? Thank you for help!

// Constants for pneumatic valves
   const int dvere = 2;
   const int davkovani = 3;
   const int lisovani = 4;
   const int vyhazovani = 5;
// ----------------------------------------
// Constants for sensors
   const int vyhazovaniZasunute = 6;
   const int vyhazovaniVysunute = 7;
   const int lisovaniVysunute = 8;
   const int lisovaniZasunute = 9;
   const int dvereZasunute = 10;
   const int dvereVysunute = 11;
   const int davkovaniVysunute = 12;
   const int davkovaniZasunute = 13;

void setup() {
  // Pneumatic cylinders set as output
  pinMode(dvere, OUTPUT);
  pinMode(davkovani, OUTPUT);
  pinMode(lisovani, OUTPUT);
  pinMode(vyhazovani, OUTPUT);

  // Sensors set as input
  pinMode(vyhazovaniZasunute, INPUT);
  pinMode(vyhazovaniVysunute, INPUT);
  pinMode(lisovaniVysunute, INPUT);
  pinMode(lisovaniZasunute, INPUT);
  pinMode(dvereZasunute, INPUT);
  pinMode(dvereVysunute, INPUT);
  pinMode(davkovaniVysunute, INPUT);
  pinMode(davkovaniZasunute, INPUT);

  // Set pneumatic cylinders as they are retracted
  digitalWrite(dvere, HIGH);
  digitalWrite(davkovani, HIGH);
  digitalWrite(lisovani, HIGH);
  digitalWrite(vyhazovani, HIGH);
}

void loop() {

  if(digitalRead(dvereZasunute) == HIGH)
  {
      digitalWrite(dvere, LOW);      // extend the first pneumatic cylinder when the sensor is lighted on because the pneumatic cylinder is retracted
  }

  if(digitalRead(dvereVysunute) == HIGH && digitalRead(davkovaniZasunute) == HIGH
  )
  {
      digitalWrite(davkovani, LOW);      // extend the second pneumatic cylinder
      delay(4000);
      digitalWrite(davkovani, HIGH);    // retract the second pneumatic cylinder after 4 seconds,
      // this code works when it is alone there, the next if statements not
  }

  if(digitalRead(dvereVysunute) == HIGH && digitalRead(davkovaniZasunute) == HIGH && digitalRead(lisovaniZasunute) == HIGH)
  {
      digitalWrite(lisovani, LOW);    // extend the third pneumatic cylinder
      delay(3000);
      digitalWrite(lisovani, HIGH);   // retract the secondthird pneumatic cylinder after 3 seconds
  }

  if(digitalRead(dvereVysunute) == HIGH && digitalRead(davkovaniZasunute) == HIGH && digitalRead(lisovaniZasunute) == HIGH)
  {
      digitalWrite(dvere, HIGH);      // retract the first pneumatic cylinder
  }

  if(digitalRead(dvereZasunute) == HIGH && digitalRead(davkovaniZasunute) == HIGH && digitalRead(lisovaniZasunute) == HIGH && digitalRead(vyhazovaniZasunute) == HIGH)
  {
      digitalWrite(vyhazovani, LOW);    // extend the fourth pneumatic cylinder
  }

  if(digitalRead(dvereZasunute) == HIGH && digitalRead(davkovaniZasunute) == HIGH && digitalRead(lisovaniZasunute) == HIGH&& digitalRead(vyhazovaniVysunute) == HIGH)
  {
      digitalWrite(vyhazovani, HIGH);    // retract the fourth pneumatic cylinder
  }

  // sensors - HIGH - light on, LOW - light off,
  // pneumatic cylinders - HIGH - retracted, LOW - extended.
}

void loop() {

...

  if(digitalRead(dvereVysunute) == HIGH && digitalRead(davkovaniZasunute) == HIGH
  )
  {
      digitalWrite(davkovani, LOW);      // extend the second pneumatic cylinder
      delay(4000);
      digitalWrite(davkovani, HIGH);    // retract the second pneumatic cylinder after 4 seconds,
      // this code works when it is alone there, the next if statements not
  }

...
}

If the condition is met, then davkovani is going to be LOW 99.999% of the time. It will only briefly go HIGH, as there is no delay there. The loop will iterate and set it LOW again. So it may seem to be "not working" whereas the problem is that it "works" very briefly.


avr-g++ (or avr-gcc) and LiquidCrystal library I'm trying to run a simple Hello World program from Arduino 1.6.5 from terminal. When I run it in Arduino IDE, it works good. When I'm trying to get it by avr-g++ I have hard way to figure out how to include all libraries - so far I got this script:

avr-g++ -Os -DF_CPU=16000000UL -mmcu=atmega328p -c -o main.o main.cpp
-I"../arduino-1.6.5-r5/libraries/LiquidCrystal/src/"
-I"../arduino-1.6.5-r5/hardware/arduino/avr/cores/arduino/"
avr-g++ -mmcu=atmega328p main.o -o main
avr-objcopy -O ihex -R .eeprom main main.hex
sudo avrdude -F -V -c arduino -p ATMEGA328P -P /dev/ttyACM1 -b 115200 -U flash:w:main.hex

First line (with both -I flags) compiles, but after running second line, I get:

main.o: In function `main':
main.cpp:(.text.startup+0xa): undefined reference to `LiquidCrystal::begin(unsigned char, unsigned char, unsigned char)'
main.cpp:(.text.startup+0x16): undefined reference to `Print::print(char const*)'
main.o: In function `_GLOBAL__sub_I_lcd':
main.cpp:(.text.startup+0x3a): undefined reference to `LiquidCrystal::LiquidCrystal(unsigned char, unsigned char, unsigned char, unsigned char, unsigned char, unsigned char)'
collect2: error: ld returned 1 exit status

How can I also include some libraries? I need the exact bash script.

I made a Makefile to compile the Blink program a little while back. It wasn't trivial.

#
# Simple Arduino Makefile
#
# Author: Nick Gammon
# Date: 18th March 2015

# where you installed the Arduino app
ARDUINO_DIR = C:/Documents and Settings/Nick/Desktop/arduino-1.0.6/

# various programs
CC = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-gcc"
CPP = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-g++"
AR = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-ar"
OBJ_COPY = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-objcopy"

MAIN_SKETCH = Blink.cpp

# compile flags for g++ and gcc

# may need to change these
F_CPU = 16000000
MCU = atmega328p

# compile flags
GENERAL_FLAGS = -c -g -Os -Wall -ffunction-sections -fdata-sections -mmcu=$(MCU) -DF_CPU=$(F_CPU)L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=106
CPP_FLAGS = $(GENERAL_FLAGS) -fno-exceptions
CC_FLAGS  = $(GENERAL_FLAGS)

# location of include files
INCLUDE_FILES = "-I$(ARDUINO_DIR)hardware/arduino/cores/arduino" "-I$(ARDUINO_DIR)hardware/arduino/variants/standard"

# library sources
LIBRARY_DIR = "$(ARDUINO_DIR)hardware/arduino/cores/arduino/"

build:

    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(MAIN_SKETCH) -o $(MAIN_SKETCH).o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/malloc.c -o malloc.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/realloc.c -o realloc.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WInterrupts.c -o WInterrupts.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring.c -o wiring.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_analog.c -o wiring_analog.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_digital.c -o wiring_digital.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_pulse.c -o wiring_pulse.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_shift.c -o wiring_shift.c.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)CDC.cpp -o CDC.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HardwareSerial.cpp -o HardwareSerial.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HID.cpp -o HID.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)IPAddress.cpp -o IPAddress.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)main.cpp -o main.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)new.cpp -o new.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Print.cpp -o Print.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Stream.cpp -o Stream.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Tone.cpp -o Tone.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)USBCore.cpp -o USBCore.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WMath.cpp -o WMath.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WString.cpp -o WString.cpp.o
    rm core.a
    $(AR) rcs core.a malloc.c.o
    $(AR) rcs core.a realloc.c.o
    $(AR) rcs core.a WInterrupts.c.o
    $(AR) rcs core.a wiring.c.o
    $(AR) rcs core.a wiring_analog.c.o
    $(AR) rcs core.a wiring_digital.c.o
    $(AR) rcs core.a wiring_pulse.c.o
    $(AR) rcs core.a wiring_shift.c.o
    $(AR) rcs core.a CDC.cpp.o
    $(AR) rcs core.a HardwareSerial.cpp.o
    $(AR) rcs core.a HID.cpp.o
    $(AR) rcs core.a IPAddress.cpp.o
    $(AR) rcs core.a main.cpp.o
    $(AR) rcs core.a new.cpp.o
    $(AR) rcs core.a Print.cpp.o
    $(AR) rcs core.a Stream.cpp.o
    $(AR) rcs core.a Tone.cpp.o
    $(AR) rcs core.a USBCore.cpp.o
    $(AR) rcs core.a WMath.cpp.o
    $(AR) rcs core.a WString.cpp.o
    $(CC) -Os -Wl,--gc-sections -mmcu=$(MCU) -o $(MAIN_SKETCH).elf $(MAIN_SKETCH).o core.a -lm
    $(OBJ_COPY) -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $(MAIN_SKETCH).elf $(MAIN_SKETCH).eep
    $(OBJ_COPY) -O ihex -R .eeprom $(MAIN_SKETCH).elf $(MAIN_SKETCH).hex

I basically did this by observing what the IDE does (as Ignacio Vazquez-Abrams suggested) and replicated it. Now to add libraries you have to add even more steps.


Splitting the power source between an arduino and a servo I have an Arduino board which is controlling a servo. I think I read that I could only supply about 100 mA through the Arduino's 5v pin. Because of that the power supply I use is able to deliver about 2A I would like to split the power before the Arduino. How do I do that?

Do I have to take some safety for the Aduino in concern or could I just split the wire?

If you have a 7V to 12V - 2A regulated supply, you can directly power your board using the 2.1mm connector. Do not go above 12V or you may destroy the voltage regulator on the board.

If you have a 5V to 6V - 2A regulated supply, you can supply your servo with this supply and rely on USB to supply the rest of the board (make sure you have a common ground for both the USB and the regulated supply).


Random without parameters During a programming contest, I used the following line of code:

symbols[i] = random() & 0b11;

After the contest, when I looked into the Arduino reference, I found out random takes one or two parameters. Based upon that, I would expect the code not to compile. However, this code somehow worked as I expected. (Assigning a random number from 0 to 3) How come?

Simple: random() isn't an Arduino function - it's a standard C function.

  Function random()

  long random(void)

  The random() function computes a sequence of pseudo-random integers in the range of 0 to RANDOM_MAX (as defined by the header file <stdlib.h>).

  The srandom() function sets its argument seed as the seed for a new sequence of pseudo-random numbers to be returned by rand(). These sequences are repeatable by calling srandom() with the same seed value.

  If no seed value is provided, the functions are automatically seeded with a value of 1.

  -- AVR LIBC Manual Page


turning positional servo motor more then 180 degrees My RC servo motor is capable of turning more then 180 degrees(around 200 degrees) when I physically turn it, but when I use my code it only turns 180.

Is there a way to code it so that it turns to 200 instead of 180?

First some basics to clear definitions:
A Servo Motor does not normally spin a full 360 degree rotation. Instead it is limited to a range of 180, 270 or 90 degrees depending on the make or type. A control signal is sent to the servo to position the shaft at the desired angle.

Conventional Servo Motor Timing

In a conventional analog servo motor a PWM signal with a period of 20 ms is used to control the motors. A signal of 20 ms has a frequency of 50 Hz.

The width of the pulse is varied between 1 and 2 ms to control the motor shaft position.

A pulse width of 1.5ms will cause the servo shaft to rest in the 90 degree position, the center of its travel.
A pulse width of 1ms will cause the servo shaft to rest at the 0 degree position.
A pulse width of 2ms will cause the servo shaft to rest in the 180 degree position.

Varying the pulse width between 1ms and 2ms will move the servo shaft through the full 180 degrees of its travel. You can bring it to rest at any angle you desire by adjusting the pulse width accordingly.

So if your servo is a 270 degree servo (like the domanrc DM-S0903MD or DS3218 270 Degree Digital RC Servo) the standard sweep sketch (Arduino Servo library) will let your servo sweep from 0-270 even if in the *.ino its myservo.write(180); So to simply test you could use write(map(desired_angle, 0, 270, 0, 180))
If you want to control it more precicly you use microseconds.

servo.attach(5,500,2500)
servo.writeMicroseconds(1500);

AND you have to use an extra power supply for 270 degree servos, the 5V from Arduino want make them move or only in a jittering way of.
If you just have a "defect" 180 degree servo turning to lets say 190 degree for some reason, you might try the microsecond method playing around with the values in attach, also use an extra power supply, but for real over 180 degree action get a 270 degree servo.


How to get the encoder position while the rotary motor is moving I have a question with encoder and the rotary motor. When the motor is moving, I can't access the position of the motor.  I have run the code separately, it is perfectly fine. But when I combine, these two codes, the motor is able to move but there was no position data.

Any suggestion on how can I get the motor moving and get the encoder position at the same time.

The combined code I have drafted is there:

  #include <Stepper.h>

    const int stepsPerRevolution = 4000;  // 4000 steps for one circle with 10mm increment.
    const int motorPitchPerCircle = 10;     // 10mm per circle for the linear ball screw guide for motor.

    int val;
    int encoder0PinA = 3; // Pin 15 of the cable.
    int encoder0PinB = 4; // Pin 13 of the cable.
    int encoder0Pos = 0;
    int encoder0PinALast = LOW;
    int n = LOW;

    // initialize the stepper library on pins 8 through 11:
    Stepper myStepper(stepsPerRevolution, 9, 8, A3, A5);

    void setup() {
      // set the speed at 60 rpm:
      myStepper.setSpeed(100);
      // initialize the serial port:
      Serial.begin(9600);

      pinMode (encoder0PinA, INPUT);
      pinMode (encoder0PinB, INPUT);
      Serial.begin (9600);
    }

    void loop() {
      // step one revolution  in one direction:
      myStepper.step(6*stepsPerRevolution);
      delay(2000);

       n = digitalRead(encoder0PinA);
      if ((encoder0PinALast == LOW) && (n == HIGH)) {
        if (digitalRead(encoder0PinB) == LOW) {
          encoder0Pos--;
        } else {
          encoder0Pos++;
        }
        Serial.print (encoder0Pos);
        Serial.print ("/");
      }
      encoder0PinALast = n;

    }

While your delay() function is running, you won't be able to read any data. Suggestion is to use interrupts, which basically guarantee that whenever your pin state changes (low edge, high edge, or any change, feel free to select it), some action will be performed. This action can be reading your encoder position.

Read about it here https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/

I am sure it will answer all your questions, it is quite well documented


How to find the index of the maximum value in an array? Say we have an array named myMeasurements

int myMeasurements[9]={3,4,8,12,7,2,1,67,8};

How can I find the index of the maximum element of this array?

For example the MATLAB code would be:

myMeasurements = [3,4,8,12,7,2,1,67,8];
[maxValue,Index] = max(myMeasurements);

where maxValue is returned as 67 whereas the Index is returned as 8.

For the record, I am using Teensy 3.2 and I program it with the Arduino IDE using the Teensyduino add-on.

First of all, do you really need int values for the measurements or not? If not, and you have numbers between 0 and 255, switch the values to byte, your microcontroller will thank you.

Then, there is a problem with the other answers, which is... The variables cannot be left uninitialized!!! You can use this code to get the info you need:

(I also put the size of myMeasurements in a const variable.. You can thank me later for this)

const byte maxMeasurements = 9;
int myMeasurements[maxMeasurements ]={3,4,8,12,7,2,1,67,8};

byte maxIndex = 0;
int maxValue = myMeasurements[maxIndex];

for(byte i = 1; i < maxMeasurements; i++)
{
    if(myMeasurements[i] > maxValue) {
        maxValue = myMeasurements[i];
        maxIndex = i;
    }
}


Is it safe to place a capacitor across vin and gnd? I have a 3A fan hooked up to an ATX power supply in parallel with a transformer which powers my board through VIN/GND.

The ATX is gated by a relay on its DC side and seems to cause enough of a current drain that it causes the Arduino to reset.

I have place a 470μF capacitor accross the Arduinos VIN and GND pins and it seems to have stopped the problem, but I'm not too experienced using capacitors. Is this an apropriate value? I'm not sure what difference it would make. And is this a wise move as I so think?

Standard?

EDIT:
Here's a very basic sketch..

12V Transformer powers arduino on VIN/GND pins, other pins are 5V, GND and control for relay

I have a 3A fan hooked up to an ATX power supply in parallel with a transformer which powers my board through VIN/GND.

I don't entirely follow that wording. Please draw a picture.

  I have place a 470μF capacitor accross the Arduinos VIN and GND pins and it seems to have stopped the problem, but I'm not too experienced using capacitors. Is this an apropriate value? I'm not sure what difference it would make. And is this a wise move as I so think?

470µF is fine. In this situation the bigger the better. If 470µF fixes it then 470µF is fine. Don't be afraid of going higher though. I have 3,300µF capacitors here that are commonly used for similar purposes.

What you have implemented is called a reservoir capacitor and is a common use for large value capacitors like that.


How to protect sensors used on atheletes? I'm working on a project were we are trying to attach accelerometers to soccer players and capture various aspects of movement data.  Breadboarded circuits are coming along nicely and I'm now looking for how to best protect sensors we can mount on players.  (All wire at the moment unfortunately - BT next.)

Although I can find ways to protect the sensor for sensor damaging impact (we are essentially interested in player impacts with the ball or ground) there are other aspects of protection I'm not sure about.  Any recommendations on how to protect from moisture without increasing bulk too much, minimizing cushioning which could affect the data and of course avoid adding anything that could injure the player?  I have come across other examples of movement studies, but they have been by musicians or other situations that do not include outdoor weather and sweaty bodies.

The only way this is ever done is with some kind of product casing. You can buy pre-fab cases for electronic projects, but to get something really slick and appropriate for your purpose, you're gonna have to make something yourself. You might look into 3D printing.

Something like this might work: https://www.sparkfun.com/products/8601

For protection from salt-water, this product is worth a look: http://www.corrosionx.com/

There's some different products there, but I've seen a demo of that product, where we ran an entire RC airplane system, servos, motors, and receiver, UNDER WATER.


Will the L9823 work at 3.3v with Wemos boards? Or is it 5v only?
https://www.st.com/en/automotive-analog-and-power/l9823.html
I see in the data sheet it lists under Absolute Maximum, Supply Voltage:  VDD -0.3v to 7v
Then, under Electrical Characteristics:  4.5 V < VDD < 5.5 V; unless otherwise specified.
Is the Electrical Characteristics section just listing values for an example voltage of 5v, or does the chip need 5v to work properly?

No. The undervoltage puts it in reset at 3.95V per the ST data sheet. It is a  5v only part with a wide tolerance on VCC. It was designed many years ago as an automotive part. It is a very nice part and performs well.


Variable current switch by human touch Two goals:

Make an LED turn on when a person touches two conductive pads (e.g. two square of aluminum foil)
Make the RGB LED change color depending on how hard the pads are squeezed. I will figure out the color algorithm later. For now I just need to be able to sense variable conductivity/capacitance/current (one of those?).

I have an Arduino LilyPad. I know this can be done because I've seen it before (just don't remember the code or circuit). Example image:

I know the human body is conductive, so I'm not quite sure why the LED won't go on when I contact the conductive pads. My only hypothesis is that the resistance is too high, but that must mean some current is going through, no?

Thanks.

I am going to make this answer as simple as I can, the body is not THAT conductive, you gotta use something like a touch sensor.


Combining 2 IF statements, getting nowhere and pulling hair out! ;) I`m new here so just wanted to say hi!

I have been messing about with Arduino now for about 2 weeks, picking and trying different sketches for a greenhouse project I need.

Trying all sorts with LCD, temperature etc.

But what I actualy wanted was just a simple multiple timer say setting for every hour 9-6 activate for 2 mins to turn on a misting system for my plants, and that is now what I present in the following sketch, simple enough and it works, I have just removed some of the timings to keep the code compact on here.

Now the tricky bit, I want the misting system to come on in those hours chosen, but only if the Humidity is below a certain thresh hold, thats where I`m running into issues.

If anyone can look over the code and advise me where to put "if(h < humLowTrigger){"

I have tried before the times, included it in each line of the times and after the times and still not working.

So all help and knowledge greatly appreciated.

Cheers for now Alan

#include <Wire.h>
#include "RTClib.h"
#include "DHT.h"

#define humLowTrigger 70
#define DHTPIN 7
#define DHTTYPE DHT22

DHT dht(DHTPIN, DHTTYPE);

RTC_DS1307 rtc;

void setup () {

Serial.begin(9600);
dht.begin();
Wire.begin();
rtc.begin();

pinMode( A2, OUTPUT);
digitalWrite(A2, LOW);
}

void loop () {

float h = dht.readHumidity();
float t = dht.readTemperature();

DateTime now = rtc.now();

if (now.hour() == 15 && now.minute() == 5) {
digitalWrite(A2, HIGH);
}
if (now.hour() == 15 && now.minute() == 8) {
digitalWrite(A2, LOW);
}
if (now.hour() == 15 && now.minute() == 10) {
digitalWrite(A2, HIGH);
}
if (now.hour() == 15 && now.minute() == 12) {
digitalWrite(A2, LOW);
}

Serial.print(now.year(), DEC);
Serial.print('/');
Serial.print(now.month(), DEC);
Serial.print('/');
Serial.print(now.day(), DEC);
Serial.print(' ');
Serial.print(now.hour(), DEC);
Serial.print(':');
Serial.print(now.minute(), DEC);
Serial.print(':');
Serial.print(now.second(), DEC);
Serial.println();
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %");
Serial.println();
Serial.println();
delay(2000);

}

If you want to do something when two or more conditions meets , use an and operator (&&), like this:

if (h < humLowTrigger && now.hour() == 15 && now.minute() == 5) {
... do something ...
}

If you have a lot of conditional statements, you can simplify:

if (h < humLowTrigger) {
   if (... other conditions 1 ...) {
     do something 1
     }
   ...
  if (... other condition n ...) {
     do something n.
     }
}

In your specific case:

if(h < humLowTrigger) {
  if (now.hour() == 15 && now.minute() == 5) {
    digitalWrite(A2, HIGH);
  }
  if (now.hour() == 15 && now.minute() == 8) {
    digitalWrite(A2, LOW);
  }
  if (now.hour() == 15 && now.minute() == 10) {
    digitalWrite(A2, HIGH);
  }
  if (now.hour() == 15 && now.minute() == 12) {
    digitalWrite(A2, LOW);
  }
}

Better version

But there is a problem with the previous code, beacuse the mister must turn off no matter what the humidity level is.

// Turn on only if humidity below threshold.
if (h < humLowTrigger && now.hour() == 15 && (now.minute() == 5 || now.minute() == 10)) {
    digitalWrite(A2, HIGH);
  }
}
// Turn off always.
if (now.hour() == 15 && (now.minute() == 8 || now.minute() == 12) {
    digitalWrite(A2, LOW);
   }


Arduino only supports 140 LEDs I've a problem with an Arduino Uno board. It only supports 140 LEDs using the FastLED library. Any LED which is higher than that number can't be turned on or off using FastLED.

Is this related to the board, the library or any other  circumstances? And help or advice would be appreciated.

Depending on how fast you need to go, the apa102-arduino library by Pololu doesn't seem to have a hard limit on their LED capacity.  They say the refresh rate goes down after 60 LEDs, but don't say anything about the maximum amount of LEDs you can have.

https://github.com/pololu/apa102-arduino

The max I'm doing at a time is only a string of 48, so I haven't checked how many it can update at once.  I am, however, running a total of 180 LEDs with this library, over 5 separate "channels".

To make it even a tiny bit harder, I'm doing it with a Nano.

This library has a "slow" and "fast" way to update the LEDs.  So far, the "slow" way is faster than the BlueTooth connection I'm sending data over to update the LEDs.

They state that the "fast" method is something like 20x faster than the "slow" way, but takes a little more in-depth programming.  Since the "slow" way works for me, so far, I haven't bothered trying the "fast" way.

Other option:

Talking with a friend at my local maker space, he said that it could be due to the speed of your board vs the timing of your LEDs. If your board isn't running fast enough, it can prevent the LEDs from being updated correctly after a certain amount of LEDs.

He was also saying that if you don't have enough available memory, it can affect how many LEDs you can update.

Seeing as you have an Arduino Uno, you shouldn't have a problem with speed or memory. Without knowing what else you are running on your Arduino (code, sensors, GPS, other shields, etc.), it's hard to say what could be holding you back.

My friend's son uses the FastLED library, so I'm going off other-than-first hand knowledge here.


Why FIFO is important in camera? I want to buy a camera module for Arduino. I came across this OV7670 CMOS Camera Module Lens CMOS 640X480 SCCB W/ I2C Interface Arduino and CMOS With AL422 3M-Bits OV7670 FIFO Camera .

I want to know what difference does FIFO makes in a camera? If I dont use a FIFO will the quality of video be compromised?

Its not FIFO that is the issue, its the FIFO Buffer that you need with an Arduino.  The Arduino can't download the data from the camera at the same speed as the camera can send it.  Adding this extra buffer in lets the camera generate the data and the Arduino download it (in the same order that it was generated) at its own pace.

You might not need the FIFO buffer for faster microprocessors, but you do need it for the Arduinos.  You could get your own buffer and rig that up, but for a few extra bucks let them do it for you.


Code for mapping voltage on a sensor and outputting a value in liters I got a Resistive sender fuel gauge sketch off the internet that I have adapted.  The Resistive sender is a floating magnet that activates read switches to vary the resistance.  Using a stable 5v power source and 100-ohm resistor I have a voltage bridge that is connected to the sender and pin A1.  The original sketch uses this to get the voltage into liters:
TankValue0 = map(sensorTankValue0, 352, 824, 0, 100);
if (TankValue0 < 0) {
  TankValue0 = 0;
}
if (TankValue0 > 100) {
  TankValue0 = 100;

The lower range is not too far off but as you get to the top it is out to lunch.
I have mapped the segments of MY float sensor's intervals, and have found there to be 17 distinct points-- I measured the voltage at each point and made a table (I mean like on paper) to relate the measured voltage at a given point to a distance in mm, and then converted that to the relevant metric of liters in a tank when the float switch is reading a given voltage.

V
L

4.04
94

3.981
88

3.902
84

3.81
81

3.703
77

3.637
72

3.564
69

3.483
65

3.393
61

3.293
57

3.18
53

3.053
50

2.908
46

2.546
42

2.192
38

1.726
35

How do I get that information into the sketch to give me a read-out of L in my tank?
I have no programming knowledge really. I work with Arduino IDE a lot, but only using sketches other people have written.  So, I have a huge basic knowledge gap.  So, please bare that in mind.
This is the whole sketch:
#include <LiquidCrystal_I2C.h>

int TankValue0;
int TankValue1;

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

void setup() {
  lcd.init();                          // initialize the lcd
  lcd.init();
  lcd.backlight();
  lcd.setCursor(1, 0);
  lcd.clear();
  lcd.print("WORD");
  lcd.setCursor(0, 1);
  lcd.print("TO");
  delay(1500);
  lcd.clear();
  lcd.print("YO ");
  lcd.setCursor(0, 1);
  lcd.print("MOMMA");
  delay(2000);
  lcd.clear();
  pinMode(A0, INPUT);
  Serial.begin(9600);               // starting the Serial Monitor

}
void loop() {
  int sensorTankValue0 = analogRead(A0);
  int sensorTankValue1 = analogRead(A1);
  TankValue0 = map(sensorTankValue0, 352, 824, 34, 94);
  TankValue1 = map(sensorTankValue1, 785, 310, 0, 100);
  if (TankValue0 < 0) {
    TankValue0 = 0;
  }
  if (TankValue1 < 0) {
    TankValue1 = 0;
  }
  if (TankValue0 > 100) {
    TankValue0 = 100;
  }
  if (TankValue1 > 100) {
    TankValue1 = 100;
  }
  lcd.print("S.V. SAVANNAH");
  lcd.setCursor(0, 1);
  delay(100);
  lcd.print("DAY TANK   ");
  lcd.print(TankValue0);
  lcd.print("%");
  lcd.setCursor(0, 0);

  delay(1000);
  lcd.clear();
}

Curve fitting
Well, a lazy way to do it is just to fit a curve to it, using Excel, or Libreoffice, Google Docs or whatever.  Here's gnuplot being used that way to fit a cubic polynomial to it:
"points.txt" containing your data, tab-delimited:
4.04    94
3.981   88
3.902   84
3.81    81
3.703   77
3.637   72
3.564   69
3.483   65
3.393   61
3.293   57
3.18    53
3.053   50
2.908   46
2.546   42
2.192   38
1.726   35

Gnuplot session:
gnuplot> f(x) = A*(x**3) + B*(x**2) + C*x + D
gnuplot> fit f(x) "points.txt" via A, B, C, D
iter      chisq       delta/lim  lambda   A             B             C             D
   0 1.8323200047e+01   0.00e+00  9.28e+01    2.818423e+00  -1.100151e+01   1.447650e+01   2.873579e+01
   1 1.8323200047e+01  -4.65e-10  9.28e+00    2.818423e+00  -1.100151e+01   1.447650e+01   2.873579e+01
iter      chisq       delta/lim  lambda   A             B             C             D

After 1 iterations the fit converged.
final sum of squares of residuals : 18.3232
rel. change during last iteration : -4.6534e-15

degrees of freedom    (FIT_NDF)                        : 12
rms of residuals      (FIT_STDFIT) = sqrt(WSSR/ndf)    : 1.23569
variance of residuals (reduced chisquare) = WSSR/ndf   : 1.52693

Final set of parameters            Asymptotic Standard Error
=======================            ==========================
A               = 2.81842          +/- 1.156        (41.02%)
B               = -11.0015         +/- 10.22        (92.86%)
C               = 14.4765          +/- 29.11        (201.1%)
D               = 28.7358          +/- 26.52        (92.27%)

correlation matrix of the fit parameters:
                A      B      C      D
A               1.000
B              -0.998  1.000
C               0.990 -0.997  1.000
D              -0.974  0.987 -0.996  1.000

And here's what looks like against the actual data with plot "points.txt" with linespoints, f(x):

So you have a function:
float f(float x) {
  static const float A =   2.81842;
  static const float B = -11.0015 ;
  static const float C =  14.4765 ;
  static const float D =  28.7358 ;
  const float x_squared = x * x;
  const float x_cubed   = x * x_squared;

  return A * x_cubed + B * x_squared + C * x + D;
}

If you don't care about the code size and the slowness of float arithmetic, then that might be okay.
Otherwise you may want to convert that function to something like fixed point arithmetic.
A cubic polynomial may be overkill, but then whole technique may be also.
Peicewise Linear
You can make a table of you points and just do what graphing programs typically do, linear interpolation between the points.
float f(float x) {
  static const struct pt {
    float v;
    int l;
  } points[] = {
    {0.0  ,  0},  // I put this here for testing, but put a better value here.
    {1.726, 35},
    {2.192, 38},
    {2.546, 42},
    {2.908, 46},
    {3.053, 50},
    {3.18 , 53},
    {3.293, 57},
    {3.393, 61},
    {3.483, 65},
    {3.564, 69},
    {3.637, 72},
    {3.703, 77},
    {3.81 , 81},
    {3.902, 84},
    {3.981, 88},
    {4.04 , 94}
    // you should probably have another entry here so that readings up to 5V work.
  };
  static const size_t table_len = sizeof points / sizeof points[0];

  for (size_t i = 0; i < table_len - 1; ++i) {
    if (x >= points[i].v && x < points[i + 1].v) {
      return
            (x - points[i].v)
          / (points[i + 1].v - points[i].v)
          * (points[i + 1].l - points[i].l)
          + points[i].l;
    }
  }

  return -1;
}

Sitting in the center of this in the return statement is basically a crude implementation of Arduino's map(), but for floating point, which again, you don't really need floating point, even if you want to use this piecewise approach.
In short, you find which two entries of the table you're sitting between, and apply what amounts to map() on the line segment formed by the two table entries.
PROGMEM
Either of the curve fitting or piecewise approach could be used to generate a much larger lookup table out of which you could just chose the nearest point.
If you're doing this on an AVR-based Arduino, the table for the piecewise linear approach or a pure lookup table approach could use PROGMEM for the array.
Regarding float and fixed point
Any of these techniques could be adapted to fixed-point math.
Which ever you use, if you're on AVR based Arduino, keep in mind that there's no hardware floating point support at all, and although double exists as a type it is implemented in avr-gcc as a single precision float.
If you're using one of the non-AVR based Arduinos, it may have support for float (and maybe for double), in which case the generated code may not be so bad, though may still be slower than using integers.
If you can do everything with integers, resulting code should be a lot smaller and faster.  I'm guessing for what you're doing, if either of them are more important, it's probably being smaller.
For using integers, you may be able to keep your input "voltage" as an ADC count, not having an intermediate voltage calculation.  And even if you want single digit liters when you're done, the intermediate interpolation, curve fitting, or table lookup may require that you work in something like centiliters, milliliters, so that values like the A constant from the curve-fitting example can be represented as an integer, e.g.  2818 mL  rather than a cruder 3 L.  If you're not using a plain lookup table and finding the nearest entry, that is if you're using the curve or piecewise linear approach, doing everything in integer arithmetic from ADC count to mL.  Although you'll need to run another curve fitting, since the A, B, etc will representing mL-per-ADC-count not L-per-Volt.  Or scale them from the value given.
And there are other options, piecewise cubic splines, etc.


Unstable analog sensor readout I have the Arduino Uno (non-original replica) board, general SPI lcd, and GUVA-S12SD analog UV sensor module.
The board (powered via USB) reads the data from the analog pin 0, converts it to voltage (multiplying the readout by (5.0/1023.0) ) and prints out to the LCD.

Being illuminated with an UV-flashlight, the sensor gives unstable readouts varying for around 0.03-0.04 V each readout cycle. I am a complete noob in electronics, so I want to ask how can I check where the problem is? Is this my error in wiring, faulty module, just normal behaviour of an analog sensor or something else?

Mine sensor module isn't from Adafriut and looks a bit different, the one in the diagram is just to show the general wiring.

Thanks!

(Sensor module description: https://www.electroschematics.com/11509/guva-s12sd-uv-sensor-module-circuit/ )

The code of the sketch is:

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
int sensorValue;
float sensorVoltage;
LiquidCrystal_I2C lcd(0x27,16,2);  // display setup
void setup() {
  lcd.init();
  lcd.backlight();
  lcd.setCursor(0, 0);
  lcd.print("");
}

void loop() {
  sensorValue = analogRead(A0);
  sensorVoltage = sensorValue * (5.0 / 1023.0);
  lcd.setCursor(0, 0);
  lcd.print(sensorVoltage/0.1); // rather low voltage is expected
  delay(1000);
}

Update: I tried to measure the output with a multimeter (as Vasekdvor suggested in answers) and it showed very similar results: continuous 0.04-0.07 V oscillations. Their magnitude seems to grow along with the intensivity of the illumination.

With sensor being dark, multimeter shows 0.006 V (changing to 0.007 V occasionally) between A0 pin and the ground.

the sensor gives unstable readouts varying for around 0.03-0.04 V each
  readout cycle

If your sensor outputs 0 to 5V and you're only getting 0.03 to 0.04 variance then I would say that it's working pretty well.  You can get a more stable output by averaging several readings before printing them.

Additionally, for even more stable readings consider powering your Audrino from a battery.  USB power can induce a considerable amount of noise if it's coming from a PC or Laptop USB port.  Also, there is a low noise mode where you can put the Arduino to sleep during your ADC reading (and it wakes up afterwards) which helps a lot with ADC noise reduction.


Can I force a function to live in the boot sector without overwriting the bootloader? Not for any practical purpose but just out of curiosity, I want to abuse the flash memory and write it dynamically at run-time.  This is, in a sense, what the bootloader does.  If I understand it, the only way to modify flash is to do so from instructions written to the boot sector.  Is it possible to stick a simple function in there that writes to flash memory, and call it from running code?  If so, how do I put it there?  I have no issue with calling functions from function pointers, so I don't think I'll have an issue actually calling the function once I get there, but I need to know how to stick into flash in the first place.

The Optiboot version 8 has a do_spm function which can be called from application. The Optiboot repository contains an example for the use of this function.
SPM is the AVR CPU instruction to write to flash memory. The Optiboot wraps this in a function. A pointer to this function is put in a 'vector table' at the beginning of the bootloader. The first pointer jumps to main, the second pointer jumps to do_spm. The optiboot.h then has the function as (version for small Optiboot)
typedef void (*do_spm_t)(uint16_t address, uint8_t command, uint16_t data);
const do_spm_t do_spm = (do_spm_t)((FLASHEND-511+2)>>1)

I made an enhancement of this, a copy_flash_pages function with reset option to bootload an AVR from its own flash. It is added as third entry in the 'vectors table' of Optiboot. It is used in my ArduinoOTA library for AVR MCUs.
typedef void (*copy_flash_pages_t)(uint32_t dest, uint32_t src, uint16_t page_count, uint8_t reset);
const copy_flash_pages_t copy_flash_pages = (copy_flash_pages_t)((FLASHEND-1023+4)>>1);


Why is resolution 20? I am using an amazing code to send/read infrared pulses without any external library. The code is fine and I took about 1 hour to fully understand it. The only thing I didnt understand is the variable RESOLUTION. I believe it should be 0 not 20. I think it should be as low as possible.

You can see the code at:

https://learn.adafruit.com/ir-sensor/using-an-ir-sensor

or below:

/* Raw IR decoder sketch!
This sketch/program uses the Arduino and a PNA4602 to
decode IR received. This can be used to make a IR receiver
(by looking for a particular code)
or transmitter (by pulsing an IR LED at ~38KHz for the
durations detected
Code is public domain, check out www.ladyada.net and adafruit.com
for more tutorials!
*/

// We need to use the 'raw' pin reading methods
// because timing is very important here and the digitalRead()
// procedure is slower!
//uint8_t IRpin = 2;
// Digital pin #2 is the same as Pin D2 see
// http://arduino.cc/en/Hacking/PinMapping168 for the 'raw' pin mapping
#define IRpin_PIN PIND
#define IRpin 2
// for MEGA use these!
//#define IRpin_PIN PINE
//#define IRpin 4

// the maximum pulse we'll listen for - 65 milliseconds is a long time
#define MAXPULSE 65000

// what our timing resolution should be, larger is better
// as its more 'precise' - but too large and you wont get
// accurate timing
#define RESOLUTION 20

// we will store up to 100 pulse pairs (this is -a lot-)
uint16_t pulses[100][2]; // pair is high and low pulse
uint8_t currentpulse = 0; // index for pulses we're storing

void setup(void) {
  Serial.begin(9600);
  Serial.println("Ready to decode IR!");
}

void loop(void) {
  uint16_t highpulse, lowpulse; // temporary storage timing
  highpulse = lowpulse = 0; // start out with no pulse length

// while (digitalRead(IRpin)) { // this is too slow!
    while (IRpin_PIN & (1 << IRpin)) {
     // pin is still HIGH

     // count off another few microseconds
     highpulse++;
     delayMicroseconds(RESOLUTION);

     // If the pulse is too long, we 'timed out' - either nothing
     // was received or the code is finished, so print what
     // we've grabbed so far, and then reset
     if ((highpulse >= MAXPULSE) && (currentpulse != 0)) {
       printpulses();
       currentpulse=0;
       return;
     }
  }
  // we didn't time out so lets stash the reading
  pulses[currentpulse][0] = highpulse;

  // same as above
  while (! (IRpin_PIN & _BV(IRpin))) {
     // pin is still LOW
     lowpulse++;
     delayMicroseconds(RESOLUTION);
     if ((lowpulse >= MAXPULSE) && (currentpulse != 0)) {
       printpulses();
       currentpulse=0;
       return;
     }
  }
  pulses[currentpulse][1] = lowpulse;

  // we read one high-low pulse successfully, continue!
  currentpulse++;
}

void printpulses(void) {
  Serial.println("\n\r\n\rReceived: \n\rOFF \tON");
  for (uint8_t i = 0; i < currentpulse; i++) {
    Serial.print(pulses
* RESOLUTION, DEC);

    Serial.print(" usec, ");
    Serial.print(pulses[1] * RESOLUTION, DEC);
    Serial.println(" usec");
  }

  // print it in a 'array' format
  Serial.println("int IRsignal[] = {");
  Serial.println("// ON, OFF (in 10's of microseconds)");
  for (uint8_t i = 0; i < currentpulse-1; i++) {
    Serial.print("\t"); // tab
    Serial.print(pulses[1] * RESOLUTION / 10, DEC);
    Serial.print(", ");
    Serial.print(pulses[i+1][0] * RESOLUTION / 10, DEC);
    Serial.println(",");
  }
  Serial.print("\t"); // tab
  Serial.print(pulses[currentpulse-1][1] * RESOLUTION / 10, DEC);
  Serial.print(", 0};");
}

Most IR remotes send pulses that are at least 400 micro seconds long. E.g. on a NEC IR remote you get pulses that are 560 or 2240 microseconds long (depending on whether it's sending a 1 or a 0).

So with a RESOLUTION of 20 you get at least 20 'pulse counts' for a 0 and 80 for a 1. Because remotes aren't that precise in you'll get somewhere between e.g. 18 and 22 or 78 and 82. Those values are different enough to easily detect whether a 0 or 1 was send.

Changing this RESOLUTION to e.g. 2 will give you 200 or 800 pulsecounts. You'll get a more precise timings from a still imprecise source. But this better precision is useless.

PS setting it to 0 could break the code, as the highpulse and lowpulse are only 16 bit integers so they will overflow after 65536, which will happen pretty fast.

Hope that helps somewhat. Just let me know is anything is still unclear.


How do we connect 2 FSR sensors to an Arduino Mega? One can connect an FSR sensor (a force-sensitive resistor) to an Arduino via 5V, Gnd,  and A0 port (as below, according to an adafruit.com page), but how will it work for two of them instead of one?

Attach the second FSR mostly the same as the first, but connect the second analog voltage to A1 instead of to A0.

You can use several copies of  the circuit (below left) with each circuit's analog voltage going to a different analog-converter input (A0, A1, A2, ...).

To connect up multiple 5V and ground connections, you can:

•  use almost any popular shield
•  use breadboards like those illustrated above
•  cut and solder Dupont cables to add extra pins or sockets in or out (for example, cut two M-F Duponts in half, and connect both F halves to one M half)
•  connect to the extra 5V and Gnd pins on Uno or Mega boards.  (On a Mega, besides 5V and Gnd pins on programming headers, there are two 5V sockets next to 22 and 23, and two Gnds next to 52 and 53.)

The diagrams above right show the location of the 5V pins on the programming headers found on the Uno.  Most Arduino boards have at least one AVRISP header like that.


Resetting millis() and micros() I want to know how much time has elapsed since a certain event, and I do not want to use any external timers. It seems logical to reset an internal timer whenever the event occurs (using an interrupt). Unfortunately, as far as I can tell, millis() and micros() cannot be manually reset. Obviously, I could save a time stamp whenever the event occurs; however, I want to avoid overflow problems (micros() will overflow every ~71 minutes, and millis() will overflow every ~50 days).

Is there a way to manually reset these built-in counters? If not, how can I manage the overflow?

millis() and micros() overflow periodically. However, this is not a
problem: as long as you compare durations instead of
timestamps you can
forget about the overflows.

The liked answer also gives the trick for resetting millis(). Can be
handy for testing purposes, but you do not need this to handle the
millis() rollover problem. Notice that there is no clean way to reset
micros(): it relies on a static variable, i.e. a variable private to
the file defining it.


Both red and blue led of ESP8266 stays on I've connected ESP8266 to Arduino UNO. After a getting a huge trouble I successfully managed to run some AT commands. I have also tested AP mode.

Then I got some trouble with software serial communication with Arduino and decided to change baud-rate to 9600 (previously it was 115200).

I used AT+IPR=9600 command to change it.

After that blue led of esp stays on and not taking AT commands any more, but output some gibberish to serial monitor with few ascii text like below:

ets Jan  8 2013,rst cause:4, boot mode:(3,6)

wdt reset
load 0x40100000, len 1396, room 16
tail 4
chksum 0x89
load 0x3ffe8000, len 776, room 4
tail 4
chksum 0xe8
load 0x3ffe8308, len 540, room 4
tail 8
chksum 0xc0
csum 0xc0

2nd boot version : 1.4(b1)
SPI Speed      : 40MHz
SPI Mode       : DIO
SPI Flash Size & Map: 8Mbit(512KB+512KB)
jump to run user1 @ 1000

Note: I know it consumes a lot power tried external 3.3V power supply and voltage divider for rx pin.

Any help would be appreciated.

If you have too, you can find the firmware for the ESP8266 here and re-flash it.

There's some good info here about the instruction set.

With respect to your issue of the blue (traffic) light staying on, I can't imagine that the baud command would have caused an issue. Perhaps you need to double check your circuit and make sure that the Rx pin of the ESP8266 is not being held high.

What happens with only 3.3V and GND connected to the ESP8266?

Also the output you're getting is similar to the output from “AT+GMR”. Are you sending it that in a loop by chance?


serial port through Rx and Tx want work my serial connection prints rubbish, but it systematic, so it's not just random as you see on image 1, any help would be appreciated

other info:

the first image of the serial monitor of COM6 is my own serial connection, image nr. 2 is the serial monitor of COM4 which already uses the onboard serial to USB
the last image shows how I made my own serial connection

the 2 black cables are providing around 4 volts, I know these are not necessary cause the USB already provides 5 volts and ground

and oh ye, normally the USB on the last image would be connected to my pc ofc

You're using a USB to RS-232 adaptor. That is wrong.

RS-232 is not (electrically) the same as UART.  Not only is the logic inverted, but it uses ±10V NRZ signalling.

That means that when the UART expects a 3.3V HIGH signal the adapter is sending it a -10V signal. When it's expecting a 0V LOW signal it's being sent a +10V signal.

So yes, it's gibberish - it's getting the opposite of what it expects to see - and the excess and negative voltages risk damaging your ESP. Fortunately the currents involved are usually so low that it doesn't damage it straight away, but with prolonged use you can probably kiss your ESP goodbye.

Disconnect that dongle immediately and get a proper USB to UART adapter.


Not able to convert String to Integer when receiving data from pubnub? I did managed to upload mpu9250 sensor data on PubNub and nodeMcu but not able to use the received data to control servo

Look at the Port reading and see that servo angle is still showing '0'

Code:-

IMU.readSensor();
char buf[500] = {};
int imu = IMU.getAccelX_mss() * 10;

sprintf(buf, "\"%d\"", imu);

Serial.print(buf);

PubNonSubClient *pclient = PubNub.publish(pubchannel, buf);
if (!pclient) return;
PublishCracker cheez;
cheez.read_and_parse(pclient);

/** You're mostly interested in `outcome()`, and,
    if it's "failed", then `description()`.
*/

Serial.print("Outcome: "); Serial.print(cheez.outcome());
Serial.print(' '); Serial.println(cheez.to_str(cheez.outcome()));
Serial.print("description: "); Serial.println(cheez.description());
Serial.print("timestamp: "); Serial.println(cheez.timestamp());
Serial.print("state: "); Serial.print(cheez.state());
Serial.print(' '); Serial.println(cheez.to_str(cheez.state()));
Serial.print("IMU Reading: "); Serial.println(IMU.getAccelX_mss());

pclient->stop();

/* Wait for news. */
PubSubClient *sclient = PubNub.subscribe(subchannel);
if (!sclient) return; // error
String msg;
SubscribeCracker ritz(sclient);
while (!ritz.finished()) {
    ritz.get(msg);
    if (msg.length() > 0) {
        Serial.print("Received: "); Serial.println(msg);
        pos = msg.toInt();
        Serial.print("value of servo angle: "); Serial.println(pos);
        myservo.write(pos);
    }

}
sclient->stop();

delay(1000);

How do I convert a string to integer so that it can be used in servo?

This is the code which worked for me:-

        msg.remove(0,1); msg.remove(msg.length());
        pos = msg.toInt();
        Serial.print("value of servo angle: "); Serial.println(pos);
        myservo.write(pos);

I had to remove this character (" ") by using msg.remove(0,1) & msg.remove(msg.length()) that removes starting and ending string.


Why can the Xbox360 not detect the Arduino Leonardo as keyboard? Arduino Leonardo as keyboard in the computer works! But not with the Xbox360.
The Teensy works perfectly on the PC but how to emulate a keyboard device for the Xbox360.

I know the Xbox360 has security IC, but a simple USB keyboard works!

What is the diference ?

How i can emulate an usb keyboard for the Xbox360?

Like Juraj and Majenko said. Arduino Keyboard library does emulate "Boot Keyboard".

I use NicoHood HID library and now it works.


Reading analog value while generating PWM signal I'm trying to generate dim two LED strips simultaneously by generating two PWM signals based on potentionmeter value. The pot sets how bright each of the LED strips will be. To drive this I'm using Arduino Pro Micro equipped with Atmel 32u4 chip.

I'm using following code:

int sensorValue = 0;
int outputValue = 0;

void setup() {
}

void loop() {
  sensorValue = analogRead(A0);

  outputValue = map(sensorValue, 0, 1023, 0, 255);
  analogWrite(5, outputValue);
  analogWrite(6, 255 - outputValue);

  delay(2);
}

The problem is, the analogRead never returns 1023 when the pot is fully open. The value is always around 980. This itself would not be a big deal.

The main issue is that the analogRead is incredibly noisy. The value returned for the maximum position is in range of [940-1020].

When I don't use the analogWrite to generate PWM, the problem goes away an the input is crystal clear in range [0-1023] as expected.

I have tried to turn off the PWM before reading the value in, but this generates flicker, as the LEDs are temporarily off.

Is there any HW or SW solution to this? I don't mind writing some assembly if required.

It was an issue with the power source. It's an USB led strip, so I was powering it through Arduino, which was a bad idea as it turns out.

When I have added external power source to the circuit everything started working correctly.


Flash esp8266 from SPIFFS filesystem I'm searching for a way to flash an esp8266 programmatically, i.e, without user interaction (and especially without Arduino IDE)?
Assuming I can put the program to be flashed on the SPIFFS filesystem, is there a way to flash the esp with that file?

Yes, it is (or at least WAS possible a few years ago) to have an ESP8266 self-program if you can get the file onto the file system, by using the Update core that is used by OTA and httpUpdate. This was a example program to do it, but I don't know if it still works. I would also suggest that you look at using LittleFS instead of SPIFFS as the latter has been depreciated.
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <FS.h>

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

  SPIFFS.begin();
  Dir dir = SPIFFS.openDir("/");

  pinMode(BUILTIN_LED, OUTPUT);
  digitalWrite(BUILTIN_LED, LOW);

  File file = SPIFFS.open("/firmware-update.bin", "r");

  uint32_t maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000;
  if (!Update.begin(maxSketchSpace, U_FLASH)) { //start with max available size
    Update.printError(Serial);
    Serial.println("ERROR");
  }

  while (file.available()) {
    uint8_t ibuffer[128];
    file.read((uint8_t *)ibuffer, 128);
    Serial.println((char *)ibuffer);
    Update.write(ibuffer, sizeof(ibuffer));
  }

  Serial.print(Update.end(true));
  digitalWrite(BUILTIN_LED, HIGH);
  file.close();
}

void loop() {
}


WARNING: Category '' in library *any library* is not valid. Setting to 'Uncategorized' I'm using Ubuntu 14.04 with arduino Galileo and the newest arduino IDE from arduino.cc and every time I compile I got this warnings with any library in place of EEPROM, SD, Wire, Wifi and a lot of others.

When I check the boards manager I got the following:

Invalid library found in /home/User/.arduino15/packages/Intel/hardware/i586/1.6.2+1.0/libraries/Wire: /home/User/.arduino15/packages/Intel/hardware/i586/1.6.2+1.0/libraries/Wire

Anyone knows how to solve this?

Edit or add library.properties to that folder so that you specify a valid category.

Example of library.properties:

name=WebServer
version=1.0
author=Cristian Maglie <c.maglie@example.com>, Pippo Pluto <pippo@example.com>
maintainer=Cristian Maglie <c.maglie@example.com>
sentence=A library that makes coding a Webserver a breeze.
paragraph=Supports HTTP1.1 and you can do GET and POST.
category=Communication
url=http://example.com/
architectures=avr


Which Protocol to use to control WiFi (ESP8266) enabled Led Light I am developing a Wifi based Led light (Got Inspired from Philips hue, Lifx). I have little knowledge about web server, clients, Web protocols. I will be using ESP8266 as Controller cum WiFi module.

There are two ways to control Led light over WiFi.

Locally
Remotely

Android/iOS app will be handling all the control part.

Which protocols can I use to control Led light, locally? HTTP or Websockets?

  Note :- The speed is critical, android/iOS app can send around 50-60 values per second.

Also, which protocol should I go with if Led light is controlled Remotely.? So far, MQTT seems reliable. Any suggestion?

Kindly help!

UDP :D

Seriously though, ESP8266 is limited in resources, AND you want to send 50-60 updates a second, just UDP will be the most lightweight, and you won't run out of connections (5 I think on ESP), because UDP has no connection state.

This is what was used here to control a RGB strip: https://github.com/cnlohr/esp8266ws2812i2s , it just listens for UDP packets on port 7777, and each packet contains rgb values, one byte for R,G,B, etc.

MQTT is nice, but it doesn't work well for 60hz updates, I Tried :D
It resulted in un-smooth animation, and frames out of order.


How to (optimally) fetch a button press? For my hardware, I need to check if the button was pressed, but I need to do things only once every half a second.

if (digitalRead(pin) == HIGH)
{
    doStuff();
    delay(500);
}

The above does not work, because I have to check other things in the main loop as well.

You should use the millis function (see millis).

Create a variable of type unsigned long and check it against the current time, with some offset.

See also the debouncing example, how to use this function and maybe you want to implement the debouncing too.


How to calibrate Mpu6050 using library? I am using i2cdev library

Code:(i did not know this code is correct or not)

#include <Arduino.h>
#include <MPU6050.h>
#include <kalman.h>
#include <stdint.h>

#define ACCELLSB  2048
#define GYROLSB   16.4

#define CONSOLE
#define CALIBRATE

#ifdef  CALIBRATE
int16_t Accel_X_offset;
int16_t Accel_Y_offset;
int16_t Accel_Z_offset;

int16_t Gyro_X_offset;
int16_t Gyro_Y_offset;
int16_t Gyro_Z_offset;
#endif

MPU6050 mpu6050;

Kalman  AngleX;
Kalman  AngleY;

void setup()
{
   mpu6050.initialize();
   mpu6050.setFullScaleAccelRange(MPU6050_ACCEL_FS_16);
   mpu6050.setFullScaleGyroRange(MPU6050_GYRO_FS_2000);

   #ifdef CALIBRATE
   mpu6050.CalibrateAccel();
   mpu6050.CalibrateGyro();

   Accel_X_offset = mpu6050.getXAccelOffset();
   Accel_Y_offset = mpu6050.getYAccelOffset();
   Accel_Z_offset = mpu6050.getZAccelOffset();

   Gyro_X_offset  = mpu6050.getXGyroOffset();
   Gyro_Y_offset  = mpu6050.getYGyroOffset();
   Gyro_Z_offset  = mpu6050.getZGyroOffset();
   #endif

   int16_t AccelX, AccelY, AccelZ;
   int16_t GyroX, GyroY, GyroZ;

   mpu6050.getMotion6(&AccelX,&AccelY,&AccelZ,&GyroX,&GyroY,&GyroZ);

   // I am going to use this values in kalman filter
   #ifdef CALIBRATE
   AccelX -= Accel_X_offset;
   AccelY -= Accel_Y_offset;
   AccelZ -= Accel_Z_offset;

   GyroX  -= Gyro_X_offset;
   GyroY  -= Gyro_Y_offset;
   GyroZ  -= Gyro_Z_offset;
   #endif
}

void loop()
{

}

What is the correct way to calibrate mpu6050(Correct me what i am wrong or this is correct)?

Thanks.

I personally suggest you MPU6050_tockn library.https://github.com/tockn/MPU6050_tockn

If you use calcGyroOffsets() in setup(), it will calculate calibration of the gyroscope, and the value of the gyroscope will calibrated.

#include <MPU6050_tockn>
#include <Wire.h>

MPU6050 mpu6050(Wire);

void setup(){
  Wire.begin();
  mpu6050.begin();
  mpu6050.calcGyroOffsets();
}

If you use calcGyroOffsets(true) in setup(), you can see state of calculating calibration in serial monitor.

#include <MPU6050_tockn>
#include <Wire.h>

MPU6050 mpu6050(Wire);

void setup(){
  Serial.begin(9600);
  Wire.begin();
  mpu6050.begin();
  mpu6050.calcGyroOffsets(true);
}

Serial monitor:

Calculate gyro offsets
DO NOT MOVE MPU6050.....
Done!
X : 1.45
Y : 1.23
Z : -1.32
Program will start after 3 seconds

If you know offsets of gyroscope, you can set them by setGyroOffsets(), and you don't have to execute calcGyroOffsets(), so you can launch program quickly.

#include <MPU6050_tockn>
#include <Wire.h>

MPU6050 mpu6050(Wire);

void setup(){
  Serial.begin(9600);
  Wire.begin();
  mpu6050.begin();
  mpu6050.setGyroOffsets(1.45, 1.23, -1.32);
}

But if want to do it with Kalman filter goto https://github.com/jarzebski/Arduino-KalmanFilter/blob/master/KalmanFilter_MPU6050/KalmanFilter_MPU6050.ino It will guide you.


Difference between Arduino.cc and Arduino.org Recently I have noticed that there are two arduino sites, arduino.cc and arduino.org.  They both have the Arduino logo and both sell what seems to be official Arduino boards. Also, arduino.org came out with the Arduino Zero board first. What is the deal here? Has Arduino partnered with another site? Any ideas appreciated.

The short of it is that there was a falling out within the Arduino people and now there are two groups laying claim to the "Arduino" name.

Arduino LLC runs arduino.cc. They are the steward of the Arduino IDE and libraries and own the "Arduino" trademark in the United States, and also owns the "Genuino" trademark outside of the United States. Arduino SRL (fka Smart Projects SRL) is the company that assembles(assembled) the majority of Arduino boards for Arduino LLC, runs arduino.org, and owns the "Arduino" trademark inside Italy and all of the other countries they have registered the "Arduino" trademark.

Arduino SRL recently decided that they are no longer beholden to Arduino LLC and has stopped paying licensing fees for using the Arduino name. Whether this is justified or not has not been fully tested in court yet.


Powering two stepper motors with A4988 drivers New to this site and wanted advice and sanity checking on my project design. I know there are similar questions to this but I couldn’t find one that was closely similar to mine.

I’m creating a device the uses two NEMA 17 stepper motors (https://www.omc-stepperonline.com/nema-17-stepper-motor-bipolar-l48mm-w-gear-raio-1001-planetary-gearbox-17hs19-1684s-pg100.html) with chunky 100:1 gearboxes in addition to using 1/16 microstepping. The end result of this is to achieve a stepper motor that turns very slowly (minutes per revolution).

Each motor is rated at 2.8V and 1.68A per phase (3.36A total since two phase) and I’m using an A4988 driver for each of them (https://www.amazon.co.uk/gp/product/B07FKXXJ41/ref=ppx_yo_dt_b_asin_title_o00_s00?ie=UTF8&psc=1) (note that these are Chinese versions where RCS = 0.1Ω). Since the A4988 drivers are limited to 1A without additional cooling, I’ve used the onboard potentiometer to reduce Vref to just below 0.9V to prevent overheating (using the equation Vref = 8 x Imax x RCS from Pololu).

This should mean that consequentially the torque output from each motor is reduced by a factor of 1/(3.36) = 0.3 (as torque α current) since each motor is only being supplied with 1A (which is not an issue due to the large gearing ratio giving a suitable output torque). I think 1/16th microstepping might also reduce the torque slightly, but I couldn’t find any conclusive sources that didn’t contradict each other on this.

This gives a power requirement of 2.8 x 1 = 2.8W per motor, hence 5.6W in total. So, I plan to use a power source that provides at least 3A (surplus on the 2A required by the drivers) and rated at a voltage of 12V-24V to run the stepper motors. I’m also aware that I need to make sure I power the drivers in parallel from this source, and not in series to reduce strain / overheating.

I’ve included two power sources I was thinking of using:

1: 24V, 4A, 96W Desktop Switching Power Supply (https://www.amazon.co.uk/DTK-Charger-90-240V-Switching-Transformers/dp/B07K85GJ54/ref=sr_1_1_sspa?crid=362Z7XFFLAYLL&keywords=24v+3a+dc+power+supply&qid=1565084176&s=electronics&sprefix=24V+3A+dC%2Celectronics%2C124&sr=1-1-spons&psc=1&spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUFHM1hUTjRTOUhYVDcmZW5jcnlwdGVkSWQ9QTA5NzA5MzQzM09IT05IR1JITEpQJmVuY3J5cHRlZEFkSWQ9QTA0NjgyMTUyQjY0UEYzRFI5OVBFJndpZGdldE5hbWU9c3BfYXRmJmFjdGlvbj1jbGlja1JlZGlyZWN0JmRvTm90TG9nQ2xpY2s9dHJ1ZQ==)

2: 24V, 15A, 360W PSU Transformer Adaptor (https://www.amazon.co.uk/NEWSTYLE-Universal-Regulated-Switching-Transformer/dp/B0758BNMLH/ref=sr_1_3?keywords=PSU+24V&qid=1565084433&s=electronics&sr=1-3)

Overall question is: would either of these power supplies be suitable, I think the second might be a bit overkill but i'm not sure.

Here’s the circuit diagram for reference:

Apologies for the long post, just needed to get all the information out of my head. I’m curious to see if I’ve made any errors in my calculations / assumptions, so any help is greatly appreciated.

Both power supplies are suitable.

The actual 12V/24V current required is not comparable to what the driver current is set at, since the stepper motor coils do not have those 12V/24V across them.

My first 3D printer came with a 12V 5A power supply, which proved suitable for simultaneous use of four stepper drivers, the control board, a display, and the heater cartridge (40W).


Using SoftwareSerial along with FastLED library to control WS2812 LEDs I am controlling WS2812 LEDs with Arduino nano using FastLED library. I want the LED patterns to change on receiving a command from another Arduino Nano over software serial, I don't have the option to use he hardware serial.

I have read that in order to write data to LEDs, the library disables all the interrupts. However the SoftwareSerial library also uses interrupts to transmit data properly. Is there any possible way to achieve this? Presently, when I am trying to do this I am getting garbage data.

The FastLED and NeoPixel libraries turn off interrupts for the specific timing of the WS2812. The Adafruit NeoPixel has a few extra options to be able to still handle some interrupts. The FastLED has a wiki that describes the problem with interrupts: FastLED wiki interrupts

The SoftwareSerial requires interrupts. When the SoftwareSerial is busy, the Arduino is occupied.

To me it seems impossible to make both libraries work at the same time. I think you have to change something. For example use a Arduino Micro or Pro Micro and use the spare hardware serial port. Or use a ledstrip with leds that have a clock signal and don't need specific timing.

If that is not possible, you might have to use pin 0 (RX) and pin 1 (TX), which are also used by the serial monitor and to upload a sketch.
It is possible to split RX and TX. The only thing that RX and TX have in common is the baudrate, but you can use them for seperate tasks.
For example, use TX to send (debug) messages to the serial monitor, and use the RX to receive commands from another Arduino board. Disconnect that other Arduino board to upload a sketch.

[ADDED] After reading the answer by @Andrew and the FastLED wiki about interrupts, I think that my answer and @Andrew's answer are equally good answers. Perhaps the best way is to do it all: faster Arduino board, hardware serial port for commands, do one thing at a time, implement some kind of XON/XOFF in software, and if possible use other leds.


View Arduino M0 SD card content on a computer Recently I bought an Arduino M0 board and I'm using it in one of my projects, which logs GPS data into an SD card.

Can an Arduino M0 be programmed as a USB SD Card reader? So that I don't have to remove the SD card from the system and use the same USB port from M0 to see the contents of the SD card directly on my computer.

Yes, in at least some way, but what is realizable and best depends on a few things.

A traditional "card reader" is a USB Mass Storage device which basically exports the logical blocks of the card to the USB host computer.  While this is active, nothing on the embedded system may interact with the card.  The embedded system will need a USB device port which can operate in this mode, suitable software, and whatever data is recorded on the card will need to be a in a filesystem (FAT or whatever) that the host PC can read, and a data format in the files that existing or custom software for that PC can make sense of.
A different option would be to still store data on the card in a way that would be PC-compatible if the card were removed and placed in a PC, but not to be a USB Mass Storage device.  Instead, you might use the existing quasi-serial interface that is the typical role of an Arduino-type board's USB port, to send or summarize the data, either directly or by interpreting it first.  This could either flow into a simple terminal program, or into something custom.  Typically this means less work on the Arduino side, more but more work on the PC side.  Additionally, since there is never a direct export of the card's block, the embedded system continues to have access to the card the whole time, rather than having to surrender control of the card to the PC operating system as USB Mass Storage requires.
A variation of the above could leverage the fact that if only the Arduino ever reads the card for its own purposes or to report the data to a PC, it doesn't necessarily need to store things in a PC compatible file system, or even in a file system at all.


How long will program stay in memory without power? Let's say we program an arduino uno or nano and then stop using it for a while. How long can we expect the program to last on the arduino?

More than 20 years, and probably more than 100 years.

That's the guaranteed minimum:

  Data retention: 20 years at 85°C/100 years at 25°C(1)

  (1)  Reliability Qualification results show that the projected data retention failure rate is much less than 1 PPM over
  20 years at 85°C or 100 years at 25°C.


Why are my objects losing their member's values? I have a Channel class which on instantiation receives a _type via new Channel("type", ...). I can read the type back out via channelObject->getType() which returns a string.

This has always worked fine until today. I have no idea what changed but if I Serial.print(channelObject->getType()) I get a nasty amount of garbage in the terminal:

���QQ���� 00@��������'����������������������(�����������b���������������������������������������H���E���������������������������������������������������������������uD��DESC  initializedOoops, no LSM303 detected ... Check your wiring!Ooops, no BMP180 detected ... Check your wiring!Setting IMU ground: Setting front: !! set ground kalman initConnect Powerbooting up...SWATBOT SETUP COMPLETEtype_xelevatoraileronthrottlerudderaux1aux2serial in: DISARMED!E;1
B��LSM303(>.a+a+8L.�S2E/��BMP085.qL3GD20���T �4&�'�%�%�%&
naninfovf�!,�!H�!��!��!Њ!�D�s6/&������?)m((a&l1=#k2���_
X� +�����+����=� ��J�5�.d�6s'���z :����������-/�type_xtype_x    elevatoraileron    throttlerudderaux1aux2�F�OX4Vjx 7���2�?�xr����:~aileronaux1
�:~  elevator
 ~ throttle:):~rudder������=�@��>�̀?��=�=�@��>�����=�=�@��>�f�B��=�i�?�k��BMP085QF��D�C
�#<}D������D]v� ,B����^v�QF����P}D .?P���f�B.s�D2m .?�oIB��P��(=:@���A�A�@9�@ A@�@�?�A0SB0N�>dC9�@ A@�@�?�A ��A��dC��L?��L>s����C�B(��"�  (�  �"��
(�

"elevator", "aileron", "throttle", and "rudder" are types for objects that I know exist but why is it coming out like this? I'm also seeing other unrelated parts of my program being spit out too like "Ooops, no LSM303 detected ...". This is all so strange.

If I had to guess, there must be an awry pointer somewhere in my application but I'm having no luck finding it. Worst case I'll rollback my application and retrace my last implementations (a couple days worth of work).

Can anyone give me a clue as to what is going on here?

My broken application is online at: https://github.com/jacksonkr/SwatBotSpine/tree/master

Emphasis on Channel.h:68 which is where all the garbage is coming from.

Related code:

RemoteControl.h:37
RemoteControl::getChannel

You might be running out of RAM. I suggest you change all lines like this:

 Serial.println("SWATBOT SETUP COMPLETE");

to use the F macro like this:

 Serial.println(F("SWATBOT SETUP COMPLETE"));

There seem to be a lot of places you could change.

Also I would not put code (implementation) into the .h files. That belongs in .cpp files. The .h files are for declarations.

Inside a class function, using this-> all the time just makes things look cluttered, eg.

StabilityController::StabilityController(RemoteControl* rc, ROSController* ros, IMUController *imu) {
  this->_rc = rc;
  this->_ros = ros;
  this->_imu = imu;


Nothng Written to Serial when using sprintf I'm using sprintf to use a format specifier myTemplate with some strings. The result will then be written to Serial. Although the sketch compiles fine, it does not write any thing to the serial, nothing is seen in the Serial monitor.

Is sprintf being used wrongly here?

char* result;
char* myTemplate;

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

void loop() {
    myTemplate = "Welcome %s. You have slept %s times";
    sprintf(result, myTemplate, "Jane", "many");
    Serial.println(result);
    Serial.println("hello");

}

When I try the follwing sketch and write something to the Serial monitor, I receive gibberish echoed back to me!  Why is this?

Sketch

char received;
char* message = "";

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

void loop() {

    // Echos back
    if(Serial.available() > 0) {
        received = Serial.read();
        Serial.println(message);

        if(received == '\n') {
            message = "";
        }  else {
            message += received;
        }

    }
}

When you use sprintf(), you need to have some space allocated for it to write the result to. At the moment, you're just passing an uninitialised pointer (result), meaning the behaviour of sprintf() is undefined. It might appear to work under some circumstances, but not others (and even if it did seem to work, it could have some nasty side effects on other parts of your code).

The simplest approach is to allocate a static char buffer. You need to be sure it's big enough to contain all of the text you want it to store though (plus an extra null character at the end).

For example:

char* myTemplate = "";
char result[64] = {0};

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

void loop() {
    myTemplate = "Welcome %s. You have slept %s times";

    sprintf(result, myTemplate, "Jane", "many");
    Serial.println(result);
    Serial.println("hello");
}

As a side note, it's usually a good idea to initialise your variables. This is especially true for pointers.


Arduino String problem Hello I am using the u8glib library to draw text on the string but it keeps giving me an error with the string

 String name1 = "";
 ...
 void draw(){
  u8g.setFont(u8g_font_micro);
  u8g.drawStr(22, 37, name1);
 }

why dosnt this work?

Here is the error:

  C:\Program Files (x86)\Arduino\libraries\U8glib/U8glib.h:200:16: note:
  no known conversion for argument 3 from 'int' to 'const
  __FlashStringHelper*' no matching function for call to 'U8GLIB_PCD8544::drawStr(int, int, String&)'

String is evil and should be avoided at all costs (http://hacking.majenko.co.uk/the-evils-of-arduino-strings)

The author of u8glib knows that and has refused (quite rightly) to implement them.

You should not use String either.  If you really must for some obscure reason then you will have to pass the internal "C string" reference to the drawStr function instead of the whole String object:

u8g.drawStr(22, 37, name1.c_str());

The only reason people use String is because they are too lazy to learn the proper way of handling textual data in C.


How can I tell how large my program is? Scenario

When I upload my project via the Arduino ide I see this at the bottom:

Writing | ################################################## | 100% 4.14s

avrdude: 25698 bytes of flash written
avrdude: verifying flash memory against /var/folders/r4/s_j4c02s3wvcx6wy41__rnwh0000gp/T/build5447a2e9a95ee46ba2ad71abe5de02d6.tmp/SwatBotSpine.ino.hex:
avrdude: load data flash data from input file /var/folders/r4/s_j4c02s3wvcx6wy41__rnwh0000gp/T/build5447a2e9a95ee46ba2ad71abe5de02d6.tmp/SwatBotSpine.ino.hex:
avrdude: input file /var/folders/r4/s_j4c02s3wvcx6wy41__rnwh0000gp/T/build5447a2e9a95ee46ba2ad71abe5de02d6.tmp/SwatBotSpine.ino.hex contains 25698 bytes

Question

I'm uploading to an Arduino Uno, does this mean I have 32256 - 25698 bytes left?

Short answer: Yes.

At the end of a successful compilation (not upload), at least in ArduinoIDE 1.6.9, the final 2 messages look like:

  Sketch uses 23,442 bytes (72%) of program storage space. Maximum is
  32,256 bytes. Global variables use 1,093 bytes (53%) of dynamic
  memory, leaving 955 bytes for local variables. Maximum is 2,048 bytes.

In this case, 8814 bytes of flash remain unused, and 955 bytes remain for the use of the stack and the heap, combined.


Did I overheat my Arduino while soldering to perfboard? So this is the second time that I've had a circuit that worked perfectly on a breadboard, but as soon as I connected it to a perfboard and soldered the joints together, the Arduino stopped working and wouldn't let me upload sketches (though I could see a COM port for it).

I'm using lead-free solder for the first time, and had the temperature at 750 deg Fahrenheit, and I'm thinking that while I had quick joints to connect the Arduino to the perfboard, when bridging two joints with solder, the iron might have been heating the header pin for 4-10 seconds... Is that enough to break the board?

(note - I'm using jumper wires on the other side to connect everything up, and I've already checked the board's connections using a multimeter and they're all as intended, and there are no accidental shorts/bridges)

I would like to clarify that my only question in ENTIRE post was: "Is that enough to break the board?"

The answer to that narrow question is that heat from soldering with an iron is extremely unlikely to have done this.  IC's are in practice (vs data sheet) quite heat tolerant, and further the pins you are soldering on are not even the pins of the IC or any electronic components, but rather those of the module headers.  You'd be more likely to melt the plastic web between those headers pins, but even that won't be a great problem since they are already in place. Or if you were soldering directly on the board, lifting a pad or trace - but you were not doing that.

Your actual problem is something else, what that might be is presently unanswerable due to the lack of detail in your question.


printing data from gps on Serial1 and sensors into Serial I am having some trouble using my gps (on Serial1) with my other sensors.
They both work great independently but when I use them in the same code, it's either the gps or the sensors that get to write on the Serial monitor.
For my gps I am using TinyGPS++, but I have a feeling that's not what's causing this problem here.
To simplify the code I'll be replacing what the sensors are supposed to write with this:
Serial.println("Hello there");

Here is the code
  if (Serial1.available() > 0) {
    gps.encode(Serial1.read());
    if (gps.location.isUpdated()){
      Serial.println("Satellite Count:");
      Serial.println(gps.satellites.value());
      Serial.println("Latitude:");
      Serial.println(gps.location.lat(), 6);
      Serial.println("Longitude:");
      Serial.println(gps.location.lng(), 6);
      Serial.println("Speed KT:");
      Serial.println(gps.speed.knots());
      Serial.println("Altitude Feet:");
      Serial.println(gps.altitude.feet());
      Serial.println("");
    }
  }
  Serial.println("Hello there");

I get this
Hello there
Hello there
Hello there
Hello there
Hello there
Hello there
Hello there
Hello there
Hello there
Hello there
Hello there
Hello there
Hello there
Hello there

If the line is removed, I get this
Satellite Count:
5
Latitude:
xx.xxxxx
Longitude:
-xx.xxxxxx
Speed KT:
0.19
Altitude Feet:
331.69

Thank you

This looks like another case of serial spam.  I recommend changing to a frame-based approach and controlling that rate with checks to millis.
That limits the spam.  Alternative is to limit it outright to 1:
//a static global:
static int isaidHELLO = 0;

//later in the loop
if (Serial1.available() > 0) {
    gps.encode(Serial1.read());
    if (gps.location.isUpdated()){
      Serial.println("Satellite Count:");
      Serial.println(gps.satellites.value());
      Serial.println("Latitude:");
      Serial.println(gps.location.lat(), 6);
      Serial.println("Longitude:");
      Serial.println(gps.location.lng(), 6);
      Serial.println("Speed KT:");
      Serial.println(gps.speed.knots());
      Serial.println("Altitude Feet:");
      Serial.println(gps.altitude.feet());
      Serial.println("");
      isaidHELLO = 0;
    }
  }
  if(isaidHELLO == 0)
  {
      Serial.println("Hello there");
      isaidHELLO = 1;
  }


Two sensors using I2C We have two sensor one of them(MPU6050-gyro) is communicating using I2C, the other is via SPI(SD card reader). Now, we need an additional component as a sensor that the barometer which communicates via I2C.

Can we use all three modules without any problem? I wonder if two I2C modules is used in a hassle-free manner? Otherwise, what can be done?

Yes, that's the idea behind bus protocols like i2c. You only require the sensors on i2c to have different bus adresses. A sensor's address usually can be chosen by soldering a jumper (the mpu6050 provides this feature on pin AD0). If you can't avoid an address collision you could use an i2c multiplexer or a microcontroller in between the sensor and the actual mcu (but probably that's not neccessary when using only two sensors).

Using SPI and I2C at the same time is absolutely no problem on the atmega!


Buzzer+Push button+arduino I want to stop the sound of a buzzer after I push the push button. I tried a code, but when the button is not pushed, the buzzer continue to make sound. How can I fixed it?
const int pin_contact= 6;
const int buzzer = 9; //buzzer to arduino pin 9

void setup(){
  pinMode(buzzer, OUTPUT); // Set buzzer - pin 9 as an output
  pinMode(pin_contact, INPUT);
  Serial.begin(9600);
}

void loop() {
  tone(buzzer, 200);

  int stare_contact = digitalRead(pin_contact);
  if (stare_contact == HIGH) {
    noTone(buzzer);
  }
}

Try this
int LEDState = 1;
int SwitchPin = 6;
int LEDPIN = 9;

void setup()
{
  pinMode(LEDPIN,OUTPUT);
  pinMode(SwitchPin,INPUT);
  digitalWrite(LEDPIN,LEDState);
}

void loop()
{

  int SwitchState = digitalRead(SwitchPin);

  if(LEDState==1 && SwitchState==HIGH){
   LEDState = 0;
  }

  digitalWrite(LEDPIN,LEDState);
    delay(10);
}


Arduino Micro "Keyboard Not Found" This is my first script written with Arduino. I wrote a simple Hello World program but I'm getting the following error.

Test:18: error: 'Keyboard' not found. Does your sketch include the line '#include <Keyboard.h>'?
   Keyboard.begin();
   ^
exit status 1
'Keyboard' not found. Does your sketch include the line '#include <Keyboard.h>'?

Here is the code:

#include "Keyboard.h"

void typeKey(int key)
{
  Keyboard.press(key);
  delay(50);
  Keyboard.release(key);
}

void setup()
{
  // Begining the Keyboard stream
  Keyboard.begin();

  // Wait 500ms
  delay(500);

  delay(400);

  Keyboard.print("Hello World!");

  // Ending stream
  Keyboard.end();
}

void loop() {}

I have Arduino/Genuino UNO selected as my board on the IDE. Any suggestions on how I can fix this? Thanks

Based on the documentation :

  These core libraries allow a 32u4 based boards or Due and Zero board to appear as a native Mouse and/or Keyboard to a connected computer.

Core libraries (such as Keyboard.h) are not availabe if your board doesn't mentioned.

I don't know which one is right, since your question title mentioned "Arduino Micro" while at the end of your question, the board is "Arduino Uno".

Just for further information, Arduino Uno is based on - ATmega328P, and Arduino Micro is based on - ATmega32U4. So sure, that "hello world" program will works on Arduino Micro, but not on Arduino Uno.


Arduino LCD is displaying gibberish, sometimes Below is my code and a picture of the gibberish.  It's different every time.  If i pull out the temp sensor, i still get gibberish, sometimes.  I'm at a loss as to what to even be looking at now. Any ideas?

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

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

//set capacities
int keg1_volume = 19;
int keg2_volume = 19;
const int temperaturePin = 0;

void setup() {
  //initial delay
  delay(1000);

  //set contrast
  pinMode(9, OUTPUT);
  analogWrite(9, 100);

  // set up the LCD's number of columns and rows:
  lcd.begin(20, 4);

  // Print header to the LCD
  lcd.setCursor(6, 0);
  lcd.print("BeerView");
  lcd.setCursor(0,1);
  lcd.print("Keg (C)");
  lcd.setCursor(10,1);
  lcd.print("Keg (F)");

  //initialize serial for debugging
  Serial.begin(9600);

  //get voltage and calculate temp
  float voltage, degreesC, degreesF;
  voltage = getVoltage(temperaturePin);
  degreesC = (voltage - 0.5) * 100.0;
  degreesF = degreesC * (9.0/5.0) + 32.0;

  //display temp
  lcd.setCursor(0,2);
  lcd.print(degreesC);
  Serial.println(degreesC);
  lcd.setCursor(10,2);
  lcd.print(degreesF);
  Serial.println(degreesF);

}

void loop() {
}

float getVoltage(int pin)
{
  return (analogRead(pin) * 0.004882814);
}

Used a pot instead of the PWM from pin 9.  Thanks for the help!!


avrdude: ser_open(): can't open device "\\.\COM4": Access denied I installed the new IDE Environment 1.6.6 and I got this error when compiling a program. I am using an Arduino Uno

avrdude: ser_open(): can't open device "\\.\COM4": access denied

I need your help.

I think you used "Eclipse" and "Arduino" at the same time. so, I guess that a "com4 Port" conflict has occurred and the upload could not was done.

restart  your computer and try to open "Arduino" first and upload. not open "Eclipse" at the same time.


ADXL345 becomes 0g when plugin MicroSD Adapter using SPI Try SD SPI code and ADXL345 SPI code separately and both are fine. When merge the codes, ADXL345 reading okay (not plug in MicroSD Adapter). Pin should bo okay.

Every time MicroSD is plugged (the same pin working with above code), ADXL345 reading suddenly becomes 0g, 0g, 0g. Pull it out then reading is good.

See https://forum.arduino.cc/index.php?topic=360718.0 and not sure if this is due to a hardware defect on MicroSD Adapter.

Already read many post like https://forum.sparkfun.com/viewtopic.php?f=14&t=38072 and the code produce 0g result, too.

Is it purely a hardware problem? Anyone suggest another one?
Is there any way to fix in software?

More details: I am using Nodemcu v1. and arduino library. The connected pins for SD and ADXL345 both at HSPI pins. I understand Nodemcu has another SPI (or even for SD card (SD0, SD1, ...etc), but I did not see any example by using those two and integrate with ADXL345 on HSPI.

You may have the same problem as my answer in Multiple SPI device answer ... not all devices supports another SPI device on the same port

That is (one of the) reasons I use STM32 instead of Arduino, since the Arduinos have 'only' one SPI port.


On my lcd my characters collide, how can i remove one(because of the programming) My code means that when i press a button it displays a word, but by default words are already there and i need to get rid of those default words.

#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(7,8,9,10,11,12);

int buttonApin = 4;

void setup() {
 pinMode(buttonApin, INPUT_PULLUP);
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.print("Mission Control ");
}

void loop()
{
  if (digitalRead(buttonApin) == LOW)
  {
    lcd.setCursor(0, 1);
    lcd.print("Test");
  }

  lcd.setCursor(0, 1);

lcd.print("launch in ");
lcd.print(millis()/1000);

Either clear the display first, or print enough spaces after to overwrite the existing text.


Relay for controlling a water pump motor I want to switch on and off a motor with arduino, used for pumping water. I need to have a idea which relay could be used with arduino.

Here is a photo of a similar motor:

Fairly cheap and quite reliable relays which operate at 5V (5mA to switch closed/open) can be had at a decent price. Mine have an upper limit of 10A, either 250VAC or 30VDC.


Help with Flappy Bird Sketch I am compiling the sketch found here. I just downloaded the .ino and .h files and opened them, so I have not modded the code at all. I keep getting the following error.

In file included from flappyDuino.ino:7:0:
Sprite.h:3: error: variable 'flappybird_frame_1' must be const in order to be put into read-only section by means of '__attribute__((progmem))'
 static unsigned char PROGMEM flappybird_frame_1[] = { 0x03, 0xF0, 0x0C, 0x48, 0x10, 0x84, 0x78, 0x8A, 0x84, 0x8A, 0x82, 0x42, 0x82, 0x3E, 0x44, 0x41,0x38, 0xBE, 0x20, 0x41, 0x18, 0x3E, 0x07, 0xC0 };

                                                 ^
In file included from flappyDuino.ino:7:0:
Sprite.h:4: error: variable 'flappybird_frame_2' must be const in order to be put into read-only section by means of '__attribute__((progmem))'
 static unsigned char PROGMEM flappybird_frame_2[] = { 0x03, 0xF0, 0x0C, 0x48, 0x10, 0x84, 0x20, 0x8A, 0x40, 0x8A, 0x40, 0x42, 0x7C, 0x3E, 0x82, 0x41, 0x84, 0xBE, 0x88, 0x41, 0x78, 0x3E, 0x07, 0xC0 };

                                                 ^
Sprite.h:5: error: variable 'bar_bottom' must be const in order to be put into read-only section by means of '__attribute__((progmem))'
 static unsigned char PROGMEM bar_bottom[] = { 0xFF, 0xFF, 0xFF, 0x42, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E };

                                         ^
Sprite.h:6: error: variable 'bar_top' must be const in order to be put into read-only section by means of '__attribute__((progmem))'
 static unsigned char PROGMEM bar_top[] = { 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x42, 0xFF, 0xFF, 0xFF };

                                      ^
variable 'flappybird_frame_1' must be const in order to be put into read-only section by means of '__attribute__((progmem))'

I'd appreciate any help.

The arrays need to be tagged with the keyword const.  It is possible that the original sketch was written using an earlier version of the IDE that you are using (or a later version?) and your version requires the const keyword whereas the author's doesn't.

Basically any arrays that are PROGMEM need the word const adding to them.  For instance, lines that start:

static unsigned char PROGMEM ...

need changing to:

static const unsigned char PROGMEM ...


Does UNO and Nano have the same pins? Do Arduino Nano Atmega328p have the same pins as Arduino/Gizduino Uno Atmega328p?

The '328P uC on the boards is the same die. The 328P in DIP has 4 fewer pins brought out (Vcc, Gnd, A6, A7) compared to the surface mount parts. The boards themselves then bring the pins out to edge connectors in physically different locations.


Measuring Lithium ion cell voltage used to power Arduino via a boost module Can I measure lithium ion cell voltage with Arduino ADC which is used to power the same Arduino through a boost module (XL6009)? The output voltage of boost module is 9 volts.

I'm the author of a library called BatterySense and you can use it to achieve your goal. In the repository Readme you can also find wiring diagrams and usage examples, but to give you a rough idea...

Verify the negative side of your battery has continuity to the GND pin of your Arduino: you need to identify if the boost module is messing the common ground, but if you have continuity then you are fine
Add a connection from the battery positive terminal going into one of the Arduino analog pins
Use the BatterySense library to get the battery voltage and percentage level


How can I easily see which COM port is used by Arduino? I'm rather disappointed because I just bought arduino and I am unable to upload any projects. The error I get is:

avrdude: ser_open(): can't open device "\\.\COM3": Časový limit semaforu vypršel.

Can be translated as:

avrdude: ser_open(): can't open device "\\.\COM3": Semaphore time out

Am I expected to brute-force all available ports to see which one is reserved for arduino? How can I, on Windows 7, quickly determine which port to use given that the IDE for some reason can't do that for me.

Start | Control Panel | System | Device Manager | Ports (COM & LTP).

Watch the list change as you plug / unplug the Arduino. The new port is the Arduino.


Can I set arbitrary SPI clock speeds? I would like to interface an ADC (in particular this one: http://www.linear.com/product/LTC1400) with an Arduino Nano via SPI. The specified max clock speed for the ADC is 6.4 MHz. The Nano can do up to 8 MHz clock speed, but I'm not able to set 6.4 MHz. If I try this

SPI.beginTransaction(SPISettings(6400000, MSBFIRST, SPI_MODE0));

I get 4 MHz at the clock pin, which means the achievable acquisition rate of the ADC is reduced. Is there a way to get the 6.4 MHz going for maximum acquisition rate with the ADC? Or is there a different approach to get fast data transfer with the ADC (e.g. external clock)?

You are limited to what your microcontroller supports. You could use a 12MHz oscillator to clock your Arduino and set the SCK divider to fOSC/2 = 6MHz (even if it was possible, I wouldn't go higher. Having some margin just to be on the safe side is generally a good advice).
Drawback of this solution is that you lose CPU performance. Please consider also that just collecting ADC data is not enough. You also have to do something with it. Therefore the question should rather be:
"What minimum ADC acquisition rate do I need for my application?"


Cannot retrieve data from homemade ECG For the past couple of weeks, I have not been able to find a solution to my problem.  My problem is that I cannot retrieve the data from my homemade ECG that I created from Arduino.  I am a total amateur at this, but I'm pretty sure it's a circuitry issue.  Here is what my circuit looks like now.  (Note: the thing that says 'Dual O' on the far left is the instrumentation amplifier, not an operational amplifier like the one near the middle)

Here is the code I'm using:

const int  signal = 5;    // Pin connected to the filtered signal from the circuit
unsigned long currentBeatTime;
unsigned long previousBeatTime;

unsigned long frequency;

// Internal variables
unsigned long period = 0;
int input = 0;
int lastinput = 0;

void setup() {
pinMode(signal, INPUT);
Serial.begin(9600);

previousBeatTime = millis();
}

void loop() {
delay(500);
input = digitalRead(signal);

if ((input != lastinput) && (input == HIGH)) {
    // If the pin state has just changed from low to high (edge detector)
    currentBeatTime = millis();

    period = currentBeatTime - previousBeatTime; // Compute the time between the previous beat and the one that has just been detected
    previousBeatTime = currentBeatTime; // Define the new time reference for the next period computing
}

lastinput = input; // Save the current pin state for comparison at the next loop iteration

// Detect if there is no beat after more than 2 seconds
if ( (millis() - previousBeatTime) > 2000 )
{
    Serial.println("dead");
}
else
{
    if (period <= 0)
    {
        frequency = 0;
    }
    else
    {
        frequency = 60000/period; // Compute the heart rate in beats per minute (bpm) with the period in milliseconds
    }

    Serial.print(frequency);
    Serial.println(" : alive! ");
}
}

I would appreciate if someone could get back to me as soon as possible.  Thank you!

EDIT:
Here's a schematic.  I used Fritzing, and since I am a total beginner at this, it looks like a complete mess.  Anyways, here it is:

Thank you for your help.

Has any part of it ever worked? What have you done to it since?
My approach to debugging this would be to
 - Temorarily replace the Bluetooth with wired serial communication;
 - Comment out, or stub out(*), anything you aren't utterly and completely confident in.
 - Get some minimum amount of hardware and software working.
 - Add back one piece of hardware or one section of code at a time, fixing whatever you have to to get it working again.
 - Repeat, until everything is back together and playing nicely.

(*) Stubbing is the technique of replacing a function or a section of code with something trivial (and therefore hard to get it wrong!) that lets the rest of the code mostly work.
Suppose you had written a digitalRead() function. (I know it's a library function and we have total confidence in it, but for a moment, just suppose....) You might replace the contents of your digitalRead() with a single statement:

int digitalRead(uint8_t pin){
   // untested code commented out here
   // ...
   return(4);  // any value that means something to the calling code
}

Now you can work on the code that calls your digitalRead() without having a working digitalRead(). The caller will only ever get the same value every time it calls, but that may be enough get some part of it working until you can come back and fix your digitalRead() function.