Store value in EEPROM to perform different actions on reset? I want the same button to wake up (reset) and put it to sleep but this is hard if the button is tied directly to the rst pin. My thought was to read and store a value in EEPROM so tell the chip what mode we were in so it can perform the counter action. For example, on RST if the value is 0 the chip should wake up and do things. It would then set the value to 1. If the button is pressed again, the chip resets, reads there is a 1 and now just puts the chip into deep sleep after setting the value back to 0. Rinse, repeat.

Does this make sense? Will this work? Is there a better/easier way?

While it looks interesting as idea, IHMO you have keep in mind:

Include some code for button denouncing logic. Actually you will receive couple of “resets” during ~20ms during button press. Without denouncing you may end up with reset signal right at the moment you write to the EPROM. While EPROMs are pretty “solid” nowadays, it many not be good practice. One of potential solutions IMHO is to delay update EPROM with state switch for 20ms after boot, so it be done in stable state.
You may also consider to include electronic circuit to hold reset long enough to reboot the controller (it may also reduce bouncing).
EPROM has finite lifespan in terms of rewrite cycles, if your device turned on and off ~100 timers per day, it may die in a ~year.
Writing the EPROM usually consumes significant amount of energy, so it may reduce battery lifespan (if you use battery).

Probably more classic approach with sleep / wake up by button looks more reasonable, unless you have shortage of pins ;)


serial communication between several arduinos to pc Is possible the communication between several Arduinos to one serial port in the PC ?

If I have ARD_A, ARD_B,... ARD_Z running with some code like this

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

void loop()
{
    while (Serial.available() > 0)
    {
       String stringID = Serial.read()
       int nFound = stringID.indexOf("@ARD_01");
                    // ---> Id is unique for each arduino
       if ( nFound > 0 )
          Serial.print("this is @ARD_01 responding sending some data");
     }
}

And in the pc there is an exe sending a string:

"@ARD_01 I want your data"
   process the data
"@ARD_02 I want your data"
   process the data
"@ARD_03 I want your data"
   process the data

Not directly, no.  A PC's serial port - either a "real" one or a USB one, can only communicate with one device.

The Arduino, though, is a USB device, so you can just plug them all into a USB hub or a bunch of hubs - each one will get its own COM port.  Managing all those COM ports can be kind of tricky though, especially when you have a lot of devices.

Another option, one that is more widely used when you want to communicate with a lot of slave devices from one master device is to use a multidrop network.  RS-485 is the most popular of these.  It allows you to connect many slave devices to one set of serial wires and the master sends instructions to a slave, and the slave may respond with data and information on request.

RS-485 requires special hardware to interface normal TTL level RS-232 (UART) ports to the bus.

You can read more about RS-485 here: https://en.wikipedia.org/wiki/RS-485


How to Send Live Sensor Data to iOS Custom Apps with BLE I am looking for a Bluetooth Low Energy (BLE) device that could send live sensor data from Arduino to iOS custom apps, not the app that is already in the app store. I would like to create my own apps to receive the sensor data. Or are there any other ways to achieve it?

I would expect this to be pretty straight forward. Off hand, I can't think of anything that would be a major roadblock to creating your iOS apps. It seems like there are two problems you'll need to solve:

Finding a BLE chip that is relatively easy to integrate with an Arduino, and
Selecting the tools that you'll use on the iOS side to develop your app.

Since I haven't done this my self, I started off looking on the Arduino side – mostly because it seemed like the problems there would be larger. I searched on Google using the terms:

aruduino ble

I found quite a few candidates that look promising, here are some of the better ones:

Bluefruit LE - Bluetooth Low Energy (BLE 4.0) - nRF8001 Breakout - v1.0 – I put this one on the top of my list because the price is pretty reasonable (< $20 US) and Adafruit tends to do a good job of supporting their products with tutorials and at least a basic library that demonstrates the functionality of the device.
Redbear Labs - I don't know anything about Redbear, but they do well in Google searches and appear to have several products, including a BLE shield, that might do what you want.
BLEduino - this is a Kickstarter, and while it looks interesting, a very quick investigation didn't reveal a source where you can buy one.

The choice of devices will partly depend on what your ultimate goal is. Something like the BLEduino will give you an all-in-one package to build your project around. The downside of this is that you may be spending money on functionality that you don't need/want to duplicate. A breakout board like the Bluefruit LE gives you a smaller device and possibly more flexibility at the expense a bit more work to get up and running.

Next you'll need to select development tools. I started by searching with the terms:

ble swift ios

I got a number of promising results, including:

Arduino Tutorial: Integrating Bluetooth LE and iOS with Swift
Apple: Bluetooth for Developers
Adafruit - Introduction to Bluetooth Low Energy

These first three look like good starting points for "getting your bearings," the following two are specific to actual boards.

Getting Started with the nRF8001 Bluefruit LE Breakout
RedBearLab/iOS


Does toCharArray prevent a String being created on the heap? I know it's bad to use Strings due to the memory problems that can occur.
I've tried to remove all instances of strings from my code.
But I'm not sure about this line:

http.getString().toCharArray(ipAddressBuffer, lengthOfIPAddress);

Is calling toCharArray() enough to prevent memory problems? Or is there a string still being created on the heap?

If it's still created on the heap, how can I modify the code so it only deals with cstrings?

Here's my code:

void setIPAddress(char* ipAddressBuffer){
  HTTPClient http;
  http.begin("http://bot.whatismyipaddress.com/"); //Only allowed to call once per 5 mins.
  http.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36");
  int httpCode = http.GET();
  if (httpCode > 0) {
    http.getString().toCharArray(ipAddressBuffer, lengthOfIPAddress);
  }
  else {
    Serial.println("Error on HTTP request");
  }
  http.end();
}

I'm using the HTTPClient.h library btw.

The return value of getString allocates and the deletes a char array in heap for a temporary String object.

For ESP8266HTTPClient and ESP32 HTTPClient library you can use writeToStream or getStream()to read the response without using String class with getString(), where stream is WiFiClient& stream = client.getStream();

getStream, returns the underlying WiFiClient. You can read the data with classic while (stream.available()) { char c = stream.read; ... }

writeToStream copies the data to a stream. My StreamLib library has a stream wrapper over a char array. It is called CStringBuilder.


Arduino UNO with CD4510 Counter I am new in Arduino but I have experience in electronics.

I was wondering how can I make a countdown timer using a CD4510 and an Arduino UNO. I know you would suggest that I should connect my seven segment display on the IO pins but I can't do that because I will use multiple seven segment displays.

The CD4510 does not seem at all appropriate for this task. It is a counter chip that counts up or down. You can do that with the Arduino. The output (of the CD4510) would be in "binary" and not suitable for driving a 7-segment display.

You can get 8 digit 7-segment displays on eBay for around $2. Surely that fits within your budget?


Arduino....How to change text on lcd? I'm new to Arduino (and EE in general), but I am a computer programmer.
I wrote some code and I want to convert it into Arduino code.

Here is the code

# include < stdio.h>
# include < conio.h>
# include < dos.h>

void main()
{
    char *name[8]={{"Danny"},{"Johns"},{"Kim"},{"James"},{"Luci"},{"Merry"},{"Kiara"}};
    for(;;)
    {
        for(int i=0;i<7;i++)
        {
            printf("%s",name[i]);
            delay(1500);
            clrscr();
        }
    }
}

This code prints names infinitely. Now I want to print these names on an Arduino's LCD.

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

Please someone provide me code for this and also explain it....

Here is some code that demonstrates both output and input methods
It used an I2c interface board, rather than connecting a lot of pins you only need 2.SDA and SCL on the board, Google "Arduino I2C" and you will find the interface board, or on EBay, usually costs $1.00.

/* YourDuino.com Example Software Sketch
 16 character 2 line I2C Display
 Backpack Interface labelled "YwRobot Arduino LCM1602 IIC V1"
 terry@yourduino.com */

/*-----( Import needed libraries )-----*/
#include <Wire.h>  // Comes with Arduino IDE
// Get the LCD I2C Library here:
// https://bitbucket.org/fmalpartida/new-liquidcrystal/downloads
#include <LiquidCrystal_I2C.h>

/*-----( Declare objects )-----*/
// set the LCD address to 0x27 for a 20 chars 2 line display
// Set the pins on the I2C chip used for LCD connections:
//                    addr, en,rw,rs,d4,d5,d6,d7,bl,blpol
LiquidCrystal_I2C lcd(0x3f , 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C address

void setup()   /*----( SETUP: RUNS ONCE )----*/
{
  Serial.begin(9600);  // Used to type in characters
  lcd.begin(16,2);   // initialize the lcd for 16 chars 2 lines, turn on backlight

// ------- Quick 3 blinks of backlight  -------------
  for(int i = 0; i< 3; i++) {
    lcd.backlight();
    delay(250);
    lcd.noBacklight();
    delay(250);
  }
  lcd.backlight(); // finish with backlight on

//-------- Write characters on the display ------------------
// NOTE: Cursor Position: (CHAR, LINE) start at 0
  lcd.setCursor(0,0); //Start at character 4 on line 0
  lcd.print("IF YOU CAN READ");
  delay(1000);
  lcd.setCursor(0,1);
  lcd.print("THIS,I'M WORKING");
  delay(8000);

// Wait and then tell user they can start the Serial Monitor and type in characters to
// Display. (Set Serial Monitor option to "No Line Ending")
  lcd.clear();
  lcd.setCursor(0,0); //Start at character 0 on line 0
  lcd.print("Use Serial Mon");
  lcd.setCursor(0,1);
  lcd.print("Type to display");

}/*--(end setup )---*/

void loop()   /*----( LOOP: RUNS CONSTANTLY )----*/
{
  {
    // when characters arrive over the serial port...
    if (Serial.available()) {
      // wait a bit for the entire message to arrive
      delay(100);
      // clear the screen
      lcd.clear();
      // read all the available characters
      while (Serial.available() > 0) {
        // display each character to the LCD
        lcd.write(Serial.read());
      }
    }
  }

}/* --(end main loop )-- */

If you need to find the address of the interface board you can use "I2C Scanner". There are many versions of this available on the web. Hope this helps


Ultrasonic PING: multiple trig on single dig. pin This may seem a little stupid, i apologize  if so as i'm new to electronics/arduino.

I have 4, 4-pin ping sensors. I'm running out of available pins on my UNO.

I had a ponder & wondered if it was possible to link all 4 sensor's trig pins to a single digital pin, with the echo pins assigned to their own pin. In my head, on each sensor call (sorry i'm used to programming terms) all 4 sensors would send a pulse, then only the sensor (or echo pin) in question would be read. Is that plausible? each ping sensor is about 20-30 cm separated, but facing internally, in a spiral downwards.

I was able to achieve the result using my suggested method in the question.
As BrettAM stated, the signals are wasted on the other 3 pins when checking 1.
This solution was suitable as a proof of concept


Read Arduino code generated by Simulink I am trying to do a Hardware-in-the-loop (HIL) system with Arduino and Simulink but the driver of my motor (Pololu VNH5019) works at 20kHz and simulink PWM block only supports 490Hz.

I would like to read and modify the code before it is sent to the Arduino to modify this and add other libraries.

It would be that possible?

If it is not possible, there is any other visual environment (with blocs, like simulink or Xcos) to generate Arduino Code?

Simulink just supplies code for all the things you could be up to, triggered by a serial command of yours. This is very slow and I think it's obvious, that you would want a fast and slim realization of everything possible, if you attempt to do HIL.

If there is a special part you think is only easy for you with blocks, just ask right away, but it is really easy to do everything you can wish for in a few simple lines.
Also this is better for you, because you really know, what's going on.

I could provide some detail code, since I'm doing HIL myself atm, but you would need to specify a bit, what you are up to.

To really answer your question: I don't know of any other visual programming tool for arduino and as stated above, my best knowledge is, that simulink uses pretty messy things. And loads them onto the board right away, right?


How do I change the default LED pin for displaying uploading I made a board for my project based on Arduino Pro Mini. The problem is, that I had to put the LED on pin 4 instead of pin 13.

What setting do I have to change to make pin 4 the default one? Or do I have to write my own Board Library?

The blinking while uploading makes the bootloader. Arduino Mini uses Optiboot. The source codes are on GitHub. You would need to change the pin in pin_defs.h and make the bootloader. Then flash it to the 328p with a programmer over ICSP.

Details what to change are in Greenonline's answer.


ultrasonic sencor give wrong distances . I used      the inbuilt basic example of measuring the distance to test my ultrasonic sensor. the object is kept at 10 - 15 cm. form the ultrasonic sensor but still the readings show 135 cm only

#include <Ultrasonic.h>
int trigPin = 5;
int echoPin = 6;
#include <Servo.h>   //servo library
Servo servo;
int servoPin = 7;
long duration, dist, average;
long aver[3];   //array for average

void setup() {
    Serial.begin(9600);
    servo.attach(servoPin);
    pinMode(trigPin, OUTPUT);
    pinMode(echoPin, INPUT);
    servo.write(0);         //close cap on power on
    delay(100);
    servo.detach();
}

void measure() {
 digitalWrite(100,HIGH);
digitalWrite(trigPin, LOW);
delayMicroseconds(100);
digitalWrite(trigPin, HIGH);
delayMicroseconds(150);
digitalWrite(trigPin, LOW);
pinMode(echoPin, INPUT);
duration = pulseIn(echoPin, HIGH);
dist = (duration/2.0) / 29.1;    //obtain distance
}
void loop() {
  for (int i=0;i<=2;i++) {   //average distance
    measure();
   aver[i]=dist;
    delay(100);              //delay between measurements
  }
 dist=(aver[0]+aver[1]+aver[2])/3;

if ( dist<15 ) {
//Change distance as per your need
 servo.attach(servoPin);
  delay(1);
 servo.write(0);
 delay(2500);
 servo.write(100);
 delay(500);
 servo.detach();
}
Serial.print(dist);
}

#include <Ultrasonic.h>
int trigPin = 5;
int echoPin = 6;
#include <Servo.h>   //servo library
Servo servo;
int servoPin = 7;
long duration, dist, average;
long aver[3];   //array for average

void setup() {
    Serial.begin(9600);
    servo.attach(servoPin);
    pinMode(trigPin, OUTPUT);
    pinMode(echoPin, INPUT);
    servo.write(0);         //close cap on power on
    delay(100);
    servo.detach();
}

void measure() {
    digitalWrite(100,HIGH);
    digitalWrite(trigPin, LOW);
    delayMicroseconds(100);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(150);
    digitalWrite(trigPin, LOW);
    pinMode(echoPin, INPUT);
    duration = pulseIn(echoPin, HIGH);
    dist = (duration/2.0) / 29.1;    //obtain distance
}

void loop() {
  for (int i=0;i<=2;i++) {   //average distance
    measure();
   aver[i]=dist;
    delay(100);              //delay between measurements
  }
  dist=(aver[0]+aver[1]+aver[2])/3;

  if ( dist<15 ) {
    //Change distance as per your need
    servo.attach(servoPin);
    delay(1);
    servo.write(0);
    delay(2500);
    servo.write(100);
    delay(500);
    servo.detach();
  }
  Serial.print(dist);
}

You have a lot of redundant code:

include Ultrasonic.h is unnecessary.
servo.attach and servo.detach without reusing pin is unnecessary
The ultrasonic code is not correct.
It should be:

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

    // measure duration of pulse from ECHO pin
    duration_us = pulseIn(echoPin, HIGH);

    // calculate the distance
    distance_cm = 0.017 * duration_us;

Refer to the Ultrasonic sensor tutorial and Servo motor tutorial


Can't extract basic data using ThingspeakHTTP I don't know anything about HTML, but I want to extract the % probability of the Northern lights being visible from this webpage
http://aurorawatch.ca/.
I entered this into the URL field, and selected HTML version 1.

When I inspect the text element I want and copy the Xpath I get the following:

"/html/body/div1/div[5]/table/tbody/tr1/td/div1/table[2]/tbody/tr[2]/td/div/table/tbody/tr/td[2]/span"

and enter this into the "parse string" field of the ThingSpeak API app, but get the following error:

"Error parsing document, try a different parse string."

Most people who get this error seem to be getting data that doesn't load with the original page, so I think I must be missing something.

If there is a better solution for pulling this number to my ESP8266 than creating a thingspeak API, I would love to hear it too!

You should use this page, since the other is the front page of the site and more likely to be dynamic:

http://www.aurorawatch.ca/index.php?option=com_content&task=view&id=28&Itemid=47

The XPath is also slightly different. The first tbody in the reported path doesn't actually exist. You should also add /text() to the end of the path to just return the textual content of the node:

/html/body/div[1]/div[5]/table[2]/tr[3]/td/table/tbody/tr/td[2]/span/text()


Global Arrays read as Zero I have written a code for my Arduino which spans multiple files, In the file containing the main task, i have a Global Array like this

addr_t childAddr[NUM_CHILDS] = { CHILD1_I2C_ADDR, CHILD2_I2C_ADDR };

where

#define NUM_CHILDS  0x02
#define CHILD1_I2C_ADDR         0x10
#define CHILD2_I2C_ADDR         0x02

Now to debug my issue, in my Task i do this

Serial.print(childAddr[0]);
Serial.print(childAddr[1]);

All i receive is

00

I looked at the issue online, someone pointed it towards overshooting the RAM, I am working on a Pro Mini with ATmega328P with 2K RAM.

Since addr_t is a character type, I suspect Serial.print() is trying to output the ASCII character representation of your two values. ASCII codes 0x10 and 0x02 are non-printing characters, so it might just be outputting 0's for lack of anything better to do.

To output the data as actual numbers, try casting them to integers:

Serial.print( static_cast<unsigned int>(childAddr[0]) );
Serial.print( static_cast<unsigned int>(childAddr[1]) );


DC Motor Speed Measurement using Rotary Encoder I have written the following code to measure the speed of a unidirectional DC Motor.I have attempted to measure the time between successive interrupts in order to calculate speed.

boolean check;
boolean start;
unsigned int angle = 5;   //angle moved per encoder tick
unsigned long volatile time1;
unsigned long volatile time_11;
unsigned long interrupt_time;

void setup() {
  Serial.begin(9600);
  while (!Serial) ;
  pinMode(21, INPUT);  //Pin#21=interrupt pin, matched to interrupt#2
  attachInterrupt(digitalPinToInterrupt(2), speed, FALLING);
  time1 = 0;
  time_11 = 0;
  interrupt_time = 0;
  check = true;
  start = false;
  time_11 = millis(); //Start Clock
}

void loop() {
  if(time1 == interrupt_time && start) //Both times same , hence bool start.
  {
    if(check)
    {
      Serial.print(millis());  //Time taken to rise to steady speed.
      check = false;
    }
    Serial.println((angle/time1)*1000);   //Display Speed.
  }
  interrupt_time = time1;
  start = false;
  while(!start)
    {}
}

void speed(void) {
  start = true;
  time1 = millis()-time_11;
  time_11 = millis();
}

I want the code to be as efficient as possible.I have around 100 ticks per 360 degrees from my encoder.Is there any chance of "missing" an interrupt?

Just a couple of remarks:

start should be volatile, but you can remove it and simply check
that time1 != 0.
there is no point in calling millis() twice inside the interrupt
service routine:

void speed(void) {
  unsigned long now = millis();
  time1 = now - time_11;
  time_11 = now;
}


ATMEGA 328P Standalone on 3.3v controlling a servo I'd like to use an ATMEGA 328P on standalone mode powered by a 3.3V supply source to control a servo (which is powered by 4 AA batteries, resulting in 6V). My question is: do I have to convert the PWM signal's peak amplitude to 5V for it to work? Or will the servo work just fine with a 3.3V amplitude signal? My servo's datasheet says its operation voltage ranges from 4.8V to 6V, but I'm not sure if that applies only to its power source or if it has implications on the control signal as well.

Servo's datasheet:
https://www.donkeyhoute.com/UploadFiles/2014916134245511.pdf

Also, since I will be using an 8 MHz external clock, do I have to change anything in my Arduino sketch regarding the PWM signal frequency, or do I just set the board to the 'Lilypad' option when burning the bootloader and keep the sketch the way it is now?

do I have to convert the PWM signal's peak amplitude to 5V for it to work?

There is insufficient information to determine that.  It may, or it may not. You'll have to try it and see.

  since I will be using an 8 MHz external clock, do I have to change anything in my Arduino sketch regarding the PWM signal frequency

If the board you select is 8MHz then no, you don't need to change anything. The fact you have selected the right frequency for the board means that all the timing calculations the Arduino API does will be correct.


ESP8266 cannot handle struct The following code works on a range of Arduino's but not on ESP. It returns random data for ID and Pin. The other two fields are always empty.

I use the Arduino IDE for both the ESP and the Arduino's. It looks like the ESP has it's own idea when it comes to struct.

#include <RH_ASK.h>
#include <SPI.h>

#define BAUD 2000
#define RX 2
#define TX 5

RH_ASK driver(BAUD, RX, TX);

struct data {
  int id;
  int pin;
  int value1;
  int value2;
} myData;

void setup()
{
    Serial.begin(9600);
    Serial.println("Starting..");
    if (!driver.init())
         Serial.println("init failed");
}

void loop()
{
    uint8_t buf[RH_ASK_MAX_MESSAGE_LEN];
    uint8_t buflen = sizeof(buf);

    if (driver.recv(buf, &buflen)) {

      memcpy(&myData, buf, buflen);

      Serial.print("ID: ");
      Serial.println(myData.id);

      Serial.print("Pin: ");
      Serial.println(myData.pin);

      Serial.print("Value1: ");
      Serial.println(myData.value1);

      Serial.print("Value2: ");
      Serial.println(myData.value2);

      Serial.println("");
    }
    yield;
}

Bad Data

ID: 263145
Pin: 18350364
Value1: 0
Value2: 0

Should be

ID: 1001
Pin: 4
Value1: 267
Value2: 843

The issue is that Arduino boards (8 bit ones at least), an int is 16 bits, where as the ESP's (8266 and 32) and possibly other non-arduino hardware, an int is 32bits

The safest way to declare structs in any case is to use variable types with known sizes, in your case, for signed 16bit ints

struct data {
  int16_t id;
  int16_t pin;
  int16_t value1;
  int16_t value2;
} myData;

or for unsigned 16bit ints

struct data {
  uint16_t id;
  uint16_t pin;
  uint16_t value1;
  uint16_t value2;
} myData;

Note: there's also short int which I believe is "guaranteed" to be 16bit (and "long int" is always 32 bit) - but having the bit size in the declaration is a far better (future proof) solution


How do you call a class method with named parameters? I have a C++ class constructor like:

Motors(int p1=0, int p2=0);

However, when I attempt to instantiate it with named parameters like:

Motors motors(p1=123, p2=456);

the Arduino C/C++ compiler gives me the errors:

src/motors.ino:3: error: ‘p1’ was not declared in this scope
src/motors.ino:3: error: ‘p2’ was not declared in this scope

The compiler doesn't seem to support named parameters and thinks I'm referring to variables. I thought named parameters was a pretty widely supported feature, even in C++. What am I doing wrong?

C++ doesn't support named parameters, and I doubt it ever will.

It has strict calling conventions which mean you couldn't re-order the parameters at call-time without adding an unnecessary layer of data duplication/indirection (which would hurt performance). It would also need a significant change to compiler architecture, as variable/parameter names are usually stripped out long before the linker is invoked.

If you want to achieve a similar effect though, you could use comment blocks instead, e.g.:

Motors motors(/*p1*/ 123, /*p2*/ 456);


Controlling HC-05 from a sketch Hi I am making a sketch and circuit with a HC-05 BT receiver to upload sketches via Bluetooth to my Uno.  This requires giving AT commands from the sketch.  I would like to see the response from the HC-05 but so far I haven't got it to work.  I want to view the response via the standard serial connection and serial monitor.  The commands from the sketch are not being recognized by the HC-05 and I would like to see the HC-05 response to troubleshoot it.

If you have a minute would you mind giving me a tip?  I would greatly appreciate it.  See the ArdProgramModeOn() and Off functions at the end.

Thanks

int ATModePin = 2;  // pin for HC-05 AT comand mode
int HC05powerPin = 3;  // pin for powering HC-05 when high
char btserialrx;  // data through from bt connection
char myChar; // data through serial port connection
#define rxPin 8 // HC-05 bt serial pin
#define txPin 9 // HC-05 bt serial pin

#include <SoftwareSerial.h>
SoftwareSerial btSerial(rxPin, txPin); // RX, TX

void setup() {
  pinMode(ATModePin, OUTPUT);
  pinMode(HC05powerPin, OUTPUT);
  pinMode(5, OUTPUT);
  Serial.begin(9600);
  btSerial.begin(115200);

  digitalWrite(HC05powerPin, HIGH);
  delay(2000);
  }

void loop() {

  while (btSerial.available()) {
    btserialrx = btSerial.read();
  }

  if(btserialrx == '1'){  // change to upload / reset mode
    Serial.println("switching to upload mode");
    ATModeOn();
    ArdProgramModeOn();
    ATModeOff();
    btserialrx = '0';
  }
  else if (btserialrx == '2'){  // change to normal mode
    Serial.println("switching to normal mode");
    ATModeOn();
    ArdProgramModeOn();
    ATModeOff();
    btserialrx = '0';
  }
}

void ATModeOn(){  // reset HC-05 and change HC-05 to AT Command Mode
  digitalWrite(5, HIGH);
  digitalWrite(ATModePin, HIGH); // AT command mode on upon reset
  delay(2000);
  digitalWrite(HC05powerPin, LOW); // hc-05 off
  delay(2000);
  digitalWrite(HC05powerPin, HIGH); // hc-05 on
  delay(2000);
}

void ATModeOff(){  // reset HC-05 and return HC-05 to std. operation
  digitalWrite(5, LOW);
  digitalWrite(ATModePin, LOW); // AT command mode off upon reset
  delay(2000);
  digitalWrite(HC05powerPin, LOW); // hc-05 off
  delay(2000);
  digitalWrite(HC05powerPin, HIGH); // hc-05 on
  delay(2000);
}

void ArdProgramModeOn(){
  btSerial.println("AT");
  delay(1000);
  btSerial.println("AT+POLAR=1,0");  // Arduino reset mode upon HC-05 connection for programming
  delay(1000);
  btSerial.println("AT+POLAR?");  // Arduino reset mode upon HC-05 connection for programming
  delay(2000);
  while (btSerial.available()) {  // Show responses from HC-05
    myChar = btSerial.read();
    Serial.print(myChar);
  }
  delay(4000);
}

void ArdProgramModeOff(){
  btSerial.println("AT");
  delay(1000);
  btSerial.println("AT+POLAR=1,1");  // Arduino normal mode no reset upon HC-05 conection
  delay(1000);
  btSerial.println("AT+POLAR?");  // Arduino reset mode upon HC-05 connection for programming
  delay(2000);
  while (btSerial.available()) {  // Show responses from HC-05
    myChar = btSerial.read();
    Serial.print(myChar);
  }
  delay(4000);
}

Unless you've manually set the btSerial speed, you need to be at the default for AT commands which is 38400 -> btSerial.begin(38400);

If you want to read regular Serial communication, you'll need to monitor 9600 -> btSerial.begin(9600);

If you are unable to to send commands, I feel as if you wouldn't have changed the default speeds.

I used this link as a reference with my project: Modify The HC-05 Bluetooth Module Defaults Using AT Commands

Lastly, you didn't mention whether or not you soldered a jumper wire to PIN 32 for your ArdProgramOff/On. Another reference for you as well: DIY Arduino Bluetooth Programming Shield

Hope my answer helps! Good luck!


Adding zero padding to decimal values I want to add zero before the float number like this:
010.0

The code I'm using is this:
if(value < 10){
  lcd.print(F("0"));
}

lcd.print(value);

But when the value is exactly 10, it adds the zero anyway:
0010.0

I tried something like this but haven't had any luck:
if(value < 10 && value != 10){
  lcd.print(F("0"));
}

How can I solve this issue?

- EDIT:
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x3B, 16, 2);

#define turnOff 3
#define turnOn 2
#define gateStatus 8
#define btn 4

float ADC0, current, ADC1, voltage, ADC2, temp, watt;
int8_t state, btnState, btnPushed, btnToggle, lcdClear;
uint32_t deBounce = 0;

void setup() {
  analogReference(EXTERNAL);
  pinMode(turnOff, OUTPUT);
  pinMode(turnOn, OUTPUT);
  pinMode(gateStatus, INPUT);
  pinMode(btn, INPUT_PULLUP);
  pinMode(13, OUTPUT);
  lcd.begin();
}

void loop() {
  digitalWrite(13, LOW);
  state = digitalRead(gateStatus);
  btnState = digitalRead(btn);

  if (!btnState) {
    if (millis() - deBounce > 200) {
      btnPushed = 1;
      deBounce = millis();
    }
  }
  if (btnPushed && btnState) {
    btnToggle = 1;
  }
  if (btnToggle && state) {
    digitalWrite(turnOn, HIGH);
    delay(5);
    digitalWrite(turnOn, LOW);
    btnToggle = 0;
    btnPushed = 0;
  }
  if (btnToggle && !state) {
    digitalWrite(turnOff, HIGH);
    delay(5);
    digitalWrite(turnOff, LOW);
    btnToggle = 0;
    btnPushed = 0;
  }

  for (int i = 0; i < 500; ++i) {
    ADC0 += analogRead(A0);
  }
  ADC0 /= 500;
  current = ADC0 * (2.5 / 1023.0);
  current = current / 0.211;

  for (int i = 0; i < 500; ++i) {
    ADC1 += analogRead(A1);
  }
  ADC1 /= 500;
  voltage = ADC1 * (2.5 / 1023.0);
  voltage = voltage * 20.2;

  for (int i = 0; i < 100; ++i) {
    ADC2 += analogRead(A2);
  }
  ADC2 /= 100;
  temp = ADC2 * (2.5 / 1023.0);
  temp = temp * 100.5;

  watt = voltage * current;

  lcd.setCursor(0, 0);
  if(voltage < 10){
    lcd.print(F("0"));
  }
  lcd.print(voltage);
  lcd.setCursor(5, 0);
  lcd.print(F(" V"));

  lcd.setCursor(9, 0);
  if(temp < 10){
    lcd.print(F("0"));
  }
  lcd.print(temp, 1);
  lcd.print((char)223);
  lcd.print(F(" C"));

  if (state) {
    lcd.setCursor(0, 1);
    lcd.print(F("   OUTPUT OFF   "));
    lcdClear = 1;
  }

  else {
    if (lcdClear) {
      lcd.clear();
      lcdClear = 0;
    }
    lcd.setCursor(0, 1);
    if (current < 10) {
      lcd.print(F("0"));
    }
    lcd.print(current);
    lcd.setCursor(5, 1);
    lcd.print(F(" A"));

    lcd.setCursor(9, 1);
    if (watt < 10) {
      lcd.print(F("0"));
    }
    if (watt < 100) {
      lcd.print(F("0"));
    }
    lcd.print(watt, 1);
    lcd.setCursor(14, 1);
    lcd.print(F(" W"));
  }
}

This looks like a rounding problem. If the number you want to print lies
within the open interval (9.95, 10), the condition value < 10 is true,
as the number is strictly less than 10. Obviously, value != 10 is also
true. Yet, lcd.print(x, 1) will round the number to the closest
multiple of 0.1, which in this case is 10.
I see no better solution than handling the rounding yourself. I would
use integers for the comparison, as they avoid all rounding issues:
// Print a float to the LCD in 2.1 format (xx.x), left padded with a
// zero if needed. Assume x < 100.
void printPadded(float x)
{
    // Left pad.
    int i = round(x * 10);
    if (i < 100) lcd.write('0');

    // Print the rounded value.
    lcd.print(i * 0.1, 1);
}


Power Down Interrupt Arduino Does anyone know a way to call an interrupt when an Arduino loses power to have it fire a small function real quick?

It'd be a quick EEPROM write of one variable.

I know you can use interrupts on certain pins when they get pulled low, I'm just not sure if it's possible on the power pin.

Or if there would still be enough power in the controller to finish that function.

I have the Node MCU board but it's programmed in Arduino c++.

Not directly, no.  When an Arduino or ESP8266 has lost power it's lost power. You need external circuitry to keep providing power after the power input has been removed, and alert your target chip that power has gone.

simulate this circuit – Schematic created using CircuitLab

C1 wants to be massive. The ESP8266, because of the WiFi interface in it, consumes a lot of power.  Also, writing to EEPROM or Flash (which the ESP8266 has instead of EEPROM) takes extra power.

Ideally, C1 wants to be a small Super-Cap to keep the physical size small.  For an ESP8266 you're probably talking thousands of uF.

An alternative is to use the 47L16 (or similar) EERAM chip which is designed to save its internal SRAM contents to internal EEPROM when power is lost using its own dedicated capacitor-based power reservoir.


Using 6 axis accelerometers I've been messing around with accelerometers for Arduino for a school project. I bought the SODIAL GY-521 accelerometer + gyroscope module for Arduino. It uses de Invensense MPU 6050. I managed to connect it onto my board and successfully detect it, but it returns values of -1 on all output ports. I was expecting there to be a port for every axis of acceleration and rotation but it seems that this isn't the case. How should I connect the module into my Arduino, and how should I program the Arduino to read my data?

I tried to follow the Arduino Playground example but the result was as explained above.

Thank you for all answers.

From the Arduino playground:
This sensor board has a voltage regulator. When using 3.3V to the VCC the resulting voltage (after the onboard voltage regulator) might be too low for a good working I2C bus. It is preferred to apply 5V to the VCC pin of the sensor board. The board has pull-up resistors on the I2C-bus. The value of those pull-up resistors are sometimes 10k and sometimes 2k2. The 2k2 is rather low. If it is combined with other sensor board which have also pull-up resistors, the total pull-up impedance might be too low.


RTC interrupts and coin batteries Summary

I'm having problems with my RTC draining its coin cells quickly - fresh batteries are drained in a few months. The RTC is set to signal an interrupt every 5 minutes, and I wonder - if there is no other power attached to the circuit, is that enough to drain the coin cell?

Details and my troubleshooting:

Problems with my RTC - if I leave the circuit unpowered for a few days (so that the only power to the RTC is from the coin cell backup), the time resets to 00:00 January 1, 2000. This doesn't happen immediately when I unplug it. If I disconnect it from the computer, plug it back in the next day, the time is ok. If I leave it unplugged for a few days, then plug it in, the date is reset.

This suggests the battery is bad. So I tested it with my meter (and an 100 ohm load, as described here: https://www.youtube.com/watch?v=HcikzMG7mMU). And sure enough, the batter has dropped quite a bit from its 3V start value.

That's all good, except that this battery is only a few months old, and it should last for years in an RTC. I've got two batteries purchased in the last year and used in RTC modules, and both are now drained.

My current hypothesis is that, after I unplug my circuit from the computer, the RTC continues to run on the coin cell, firing interrupts every 5 minutes, and it is these interrupts that are causing the drain. Does this make sense? If not, what else could I check?

Setup

Breadboard arduino, DS3231 RTC on a breakout, connected

RTC SDA -> Arduino A4
RTC SCL -> Arduino A5
RTC GND -> Common GND
RTC VCC -> Common 5V (from ftdi/USB cable, when plugged in)
RTC SQW -> Arduino D2

The RTC is 'active-low', and the SQW pin is held at 5V between interrupts. With my multimeter, the brief drop to 'LOW' is undetectable. I also can't detect any current flow from the SQW pin with my multimeter.

Sketch

Including only the code related to the RTC (SD card and temperature bits removed).

/*-(Import required libraries)-*/
#include <Time.h>
#include <DS3232RTC.h> //source: https://github.com/JChristensen/DS3232RTC

/*-( Declare Constants )-*/
const int wakeUpPin = 2;
#define resolution 5 // frequency in minutes to wake from sleep

/*-(Declare Variables)-*/
time_t t;
int nextLoop;

/****** SETUP: RUNS ONCE ******/
void setup()
{
  Serial.begin(9600);

  Serial.println();
  pinMode(wakeUpPin, INPUT);

  t = RTC.get();

  nextLoop = ((minute(RTC.get()) / resolution) + 1) * resolution;
  if (nextLoop >= 60) {
    nextLoop -= 60;
  }
  Serial.print(RTC.temperature());
  Serial.print(",");
  Serial.print(RTC.oscStopped());
  Serial.print(",");
  Serial.println(nextLoop); // the minutes when the next reading will be taken

}

/****** LOOP: RUNS CONSTANTLY ******/
void loop()
{
  t = RTC.get();

  Serial.print(year(t), DEC);
  Serial.print("/");
  Serial.print(month(t), DEC);
  Serial.print("/");
  Serial.print(day(t), DEC);
  Serial.print(",");
  Serial.print(hour(t), DEC);
  Serial.print(",");
  Serial.print(minute(t), DEC);
  Serial.print(",");
  Serial.print(second(t), DEC);
  Serial.print(",");

  goToSleep();
}

void goToSleep(void) {
    Serial.print("Sleeping until: ");
    Serial.println(nextLoop);
    Serial.flush();
    RTC.setAlarm(ALM2_MATCH_MINUTES, nextLoop, 1, 1);
    RTC.alarmInterrupt(ALARM_2, true);
    attachInterrupt(0, wakeUp, LOW);

    LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF);
    detachInterrupt(0);
    RTC.alarm(ALARM_2);
    nextLoop += resolution;
    if (nextLoop >= 60) {
         nextLoop -= 60;
    }
}

void wakeUp(){
  // Handler for the pin interrupt.
}

Check your battery, it is behaving like a rechargeable one without a charger.  Mine have the letter "R" at the end of the part number.  There are a lot of RTC modules that charge the battery. Conversely they are some that do not charge the battery. Are you powering it with something other then the coin cell.


L239D motor driver not able to drive motors Iam making a line follower robot , the issue is coming when making motors run.The L239D module has 4 inputs pins ( to control two motors) , 4 output pins (to drive motors) , and 6 power pins (5v,5v,GND,GND,9/12V,9/12V) . I have used one 5v pin to connect it to ardunio 5V supply and one of the 9/12v pin to series of two 9v battery. The motors are running low and when it is on ground the line follower not able to move. I even tried 3 9V batteries in series to make up the voltage 9+9+9=27V but not helping. Any help Thanks in advance.

I guess using 9 Volt battery in parallel will do your work because if the motor is moving as you quoted above means it is getting the voltage but not enough current to drive it, please connect the 9 volt battery in parallel and it will work for you


esp8266-01 and arduino UNO communicating over i2c i am not able to communicate over i2c with my esp-01 as master and UNO as slave. i get special characters sent back to esp, but my esp is sending correctly...
output on my esp-01

output on my UNO is

connections are esp-01 gpio-0 to uno A4 and gpio-2 to uno A5
is it because i am not using a level shifter or any mistake in my code..?

here is my esp master code

#include <Wire.h>
#define I2CAddressESPWifi 6
int x=32;

void setup()
{
  Serial.begin(115200);
  Wire.begin(0,2);//Change to Wire.begin() for non ESP.
}

void loop()
{
  Wire.beginTransmission(I2CAddressESPWifi);
  Wire.write(x);
  Wire.endTransmission();
  x++;
  delay(1);//Required. Not sure why!

  Wire.requestFrom(I2CAddressESPWifi,10);
  Serial.print("Request Return:[");
  while (Wire.available())
  {
    delay(100);
    char c = Wire.read();
    Serial.print(c);
  }
  Serial.println("]");
  delay(500);
}

and here is my Uno slave code

#include <Wire.h>
#define I2CAddressESPWifi 6

void setup()
{
  Serial.begin(115200);
  Wire.begin(I2CAddressESPWifi);
  Wire.onReceive(espWifiReceiveEvent);
  Wire.onRequest(espWifiRequestEvent);
}

void loop()
{
  delay(1);
}

void espWifiReceiveEvent(int count)
{
  Serial.print("Received[");
  while (Wire.available())
  {
    char c = Wire.read();
    Serial.print(c);
  }
  Serial.println("]");
}

void espWifiRequestEvent()
{
  String ts = getTime();
  Serial.print("Sending:[");
  Serial.print(ts.c_str());
  Serial.println("]");
  Wire.write(ts.c_str());
}

String getTime(){
  int sec = millis() / 1000;
  int min = sec / 60;
  int hr = min / 60;
  String ts = "U:";
  if (hr<10) ts+="0";
  ts += hr;
  ts +=":";
  if ((min%60)<10) ts+="0";
  ts += min % 60;
  ts +=":";
  if ((sec%60)<10) ts+="0";
  ts += sec % 60;
  return(ts);
}

Perhaps the Serial.print()s in the slave's request event function are causing too much delay (clock stretching?). You should make the Wire.write() the second statement in that function right after the getTime call. Or you could use Wire.write("Hello") as the only statement in the function, so you can narrow down the problem.


How can I declare global array with its length stored in EEPROM? I am working with Arduino UNO connected with BV4612 display.
I am working on a simple code that controls several water pumps. Each pump has several modes it can run in. I store these modes in an array.
The number of water pumps may vary, and I'd like to store that value in EEPROM (either arduino's or display's).

When the pump count is fixed, I use fixed value, defined by macro:

#define     PUMP_COUNT      18      //How many pumps we have

uint8_t pumpModes[PUMP_COUNT];

void setup(){...}
void loop(){...}

I'd like to get rid of fixed defined value of PUMP_COUNT, and rather load it from EEPROM, or save the new pump count into the EEPROM if needed.
However, I can't declare an array if I can't read from EEPROM before setup() function like this (from address 32 for example):

uint8_t pumpModes[EEread(32)];

void setup(){...}
void loop(){...}

Is there a solution to get the value from EEPROM so I can declare global array's length with it?

Thanks.

You can't create variable length arrays in C. That's not how C works.

Instead you have to create an array that is big enough to store the maximum number of pumps you want to be able to deal with.

The array "size" is then just a number in a variable obtained from wherever you like (including EEPROM).

It doesn't matter if you don't use all of the array. The rest just sits there twiddling its metaphorical thumbs.

The other option, if you are only going to define the array once at startup, or very rarely change the size, is to use malloc():

uint8_t *pumps;
uint8_t nPumps = 0;

void setup() {
    nPumps = EEPROM.read(32);
    pumps = (uint8_t *)malloc(nPumps);
}

You can change the array size then with:

nPumps = 8; // for example
pumps = realloc(pumps, nPumps);

And dispose of the array with:

nPumps = 0;
free(pumps);

It's best to try not to change the array size once created, since that can make swiss cheese of your heap, and is not a friendly thing to do on a small microcontroller. If you can decide the array size once in setup and keep it the same all the time the program is running this is a safe operation. Otherwise it becomes risky.


Arduino mega 2560 Stacked with Ethernet/SD card Shield Heat up Stacked mega and ethernet/sd shield:

When I do this stacking, it heats up. I tried connecting the SPI via ports 13-10 (no stacking), it doesn't work. Also tried connecting the ICSP (red circled mark) via male-female wires without stacking, it works, but still heats up. So I think the ICSP has a defect? or does it? Is it supposed to be like this and I'm just being paranoid?
*PS: the heat in the "pain" level when I touch it, no burning IC odor. Maybe it's because I unplug it immediately after short use? IDK.
**update, I think I got it working, the problem was not about the heating, but the program. Consulted a more experienced person, he said what's happening is normal.

the heat in the "pain" level when I touch it, no burning IC odor. Maybe it's because I unplug it immediately after short use? IDK.
  So I think the ICSP has a defect? or does it? Is it supposed to be like this and I'm just being paranoid?

Well you're right in being a bit paranoid. And temperature building up is very likely to mean you've got a short somewhere, it might be a bad solder or a component that fails (like a cap that conducts).

So you've got to isolate the issue:

Isolate the faulty board: whichever board is getting hot, it might be that one that has a failure or the other one ruining it

you need to try the shield with another arduino (whatever version it is) and see if the issue is replicating
then you need to try the arduino you were using with another shield running on ICSP (like another ethernet shield, or an SDCard shield), which will confirm the hypothesis that only one component of the two is failing.

Once you've isolated the board, you need to isolate the component.

you first have to isolate which component is building up heat.
If you've got access to a thermal camera, it's a good idea to use it.
If not: start locating the area where heat is building with your finger, and then test each component of the area with a thermometer (like the ones you plug on a multimeter, or simply a "meat" thermometer for cooking).

Once you've isolated the component, then look it up on the schematics and layout, and lookup all connected components. Either that component or one on the track is failing, or there's a short on that track.

If the solution is not obvious, you can come back on Stack Exchange (get on the electronics QA site with your results), and some EE expert will help you find out what's wrong!

HTH


serial.write if condition I am trying to do a simple serial communication control via sending a char and using it as an if condition, the arduino part is below

char incomingchar;
void setup() {
    Serial.begin(9600);     // opens serial port, sets data rate to 9600 bps
//        Serial.write("g"); // does not work when I explicitly write here either as opposed to through python.
}

void loop() {
    if (Serial.available()) {
            // read the incoming char:
            incomingchar = Serial.read();
               if (incomingchar=="g"){
              Serial.println("hello world!");}
              else{
              Serial.println(incomingchar);
    }
}
}

And here is the Python code:

import serial;
ser=serial.Serial('COM3',9600,timeout=1)
ser.write(b'g')

When I run this, the python program returns a '1', and so does the arduino program in the serial monitor.

Note, if I directly set Serial.write('g'), it simply types out 'g' in the monitor and does nothing else from the loop.

You declare incomingchar as a char. In your if you compare that char to a string (double quotes) incomingchar=="g". I think you want to compare it to a char (single quotes) like this:

if ( incomingchar == 'g' ) {
  // do something
}


How to send Json to a webservice from pc/RPI with live data from Arduino(serial) I'm making a project where my plan is to take sensor input from the Arduino, and then pass that info (by serial/usb connection) through either a laptop or a Raspberry Pi and convert it to Json and send it to a webservice in asp.net c#, where it gets stored in a database, and then the data can be shown on a website, so the visitor can see live data from the Arduino sensor on the site and also be able to see what the sensor measured yesterday, last month, or the average for a extended period of time, or a graph.

It might be easier to illustrate what I'm talking about:

The PC / RPI part is optional, it can be using either one.

There are a few options, as I see it, as to which methods could work. But I am unsure about how to implement them and what programs to use for it.

First one is to log data to a file on the PC/RPI and then have some shell script either listen for changes and then combine a Json string with the newly added info to the file and send it of to the webservice.

Second one is to somehow take the Serial data from the Arduino and have some shell script or program listen for any data coming from the Arduino and converting it to Json, and sending it of to the webservice. The pro's by this method would be omitting the extra "file-step", but it would make the system more vulnerable to any interruptions in the connection.

Does anyone have experience with doing something like this? Or maybe have an idea how I can do what I'm trying to do ? Or just a nudge in the right direction, as to which approach you think is best, or what programs I could/should use.
Any help is very much appreciated!

Best regards
Daniel

I'm kind of tackling the same thing at the moment.

I have been using MQTT for a while for things like this. Including on an Netduino, an Arduino, and today a LEGO NXT.

But it is TCP based. I have been wanting to use serial, not TCP (ethernet) for a while, and when the need came for the NXT, it was time to write my own bridge to existing code.

I runs on the same host as the MQTT broker, but listens to a serial port, and mirrors the data to a TCP MQTT broker.

The code is turning out to be much simpler than I expected, I should have done this months ago.

Nxt Side

while (true)
{
    float x, y, z;
    DIMUreadGyroAxes(IMU, x, y, z);

    char json[128];
    sprintf(json, "PUBnxt/Gyro,{\"x\":%f,\"y\":%f,\"z\":%f}\n", x, y, z);
    nxtWriteRawHS(json, strlen(json), 0); // wireless serial over xbee
    wait1Msec(50);
}

PC side

 void Serial_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        SerialPort p = sender as SerialPort;
        while (p.BytesToRead > 0)
        {
            string line;
            try
            {
                line = p.ReadLine();
            }
            catch (IOException)
            {
                throw;  // +++timeout
            }
            // parse it, it should be CMDtopic[,payload]
            if (line.Substring(0, 3).Equals("PUB"))
            {
                int commaIdx = line.IndexOf(',', 3);
                string topic = line.Substring(3, commaIdx - 3);
                string payload = line.Substring(commaIdx + 1);
                Console.WriteLine("{3}: {0}, publish topic({1}) payload({2})", p.PortName, topic, payload, DateTime.Now.ToLongTimeString());
                Mqtt.Publish(topic, System.Text.Encoding.UTF8.GetBytes(payload));

            }
            else if (line.Substring(0, 3).Equals("SUB"))
            {
                string topic = line.Substring(3);
                Console.WriteLine("{0}, subscribe topic({1})", p.PortName, topic);
                throw new NotImplementedException("MQTT Subscribe not implemented yet");
            }
            else
            {
                //Debugger.Break();   // ignore it, framing error
                Console.WriteLine("{0}, Data dropped", p.PortName);
            }
        }
    }

You might also want to look at data.sparkfun.com. A similar, complete concept, already existing.


Arduino cannot communicate with PC after running servo I was messing around with my arduino uno r3 and servo today. The book I got said to run the servo through the arduino. Everything was fine. I started changing the code, and then things started to get bad. I noticed that if I did not put a delay in between the servo movements, the board would freeze, and I would have to get lucky. Well now I just can't communicate with the board. I plug the board in to my pc, windows 7 makes the connection sound, the board turns on the ON light, the L light flashes, then goes steady. In the arduino software, the COM3 port, which is where I'm plugging it in, is not coming up. Only COM1 is there. I'm not sure what to do. The board is still functioning, the servo moves. I tried to plug it in with a different port and with the servo disconnected but it still doesn't want to communicate with my pc. The code I'm using is below

#include <Servo.h>

Servo servo1;

void setup()
{
  servo1.attach(9);
}

void loop()
{
  servo1.write(50);
  delay(500);
  servo1.write(90);
  delay(500);
  servo1.write(140);
  delay(1000);

  for(int i = 50;i<140;i+=10){
    servo1.write(i);
    delay(10);
  }
}

I would also like to add that I understand that you shouldn't run the servos through an arduino. I was following the book, and began researching when things went down hill.

I've had some problems in the past reprogramming my Arduino Uno if it writes to the serial port - I don't know if the problem is the same, but here's how I got around it:

Option 1: Hold down the reset switch, then plug your Arduino into the USB port. Select the right COM port (if needed), compile your code (something ultra simple, e.g. blink led), and then, JUST BEFORE IT STARTS UPLOADING, release the reset switch. Wash, rinse, repeat, until you get it to work, through blind luck.

Option 2: Get hold of a ICSP (such as the one I got, USBASP made by FreeTronics  http://www.freetronics.com.au/products/usbasp-icsp-programmer-for-avr-arduino#.VL8Vv3WjlIc which I am v. happy with), plug it into the serial port, plug the other end onto your Arduino UNO ICSP header (6 pins, opposite end of the board from USB), then select Tools -> Burn Bootloader. Overwrites any program, works 100% of the time. Now you can unplug your USBASP, and plug your Uno back in and program it normally. This is also a great tool if you end up using AtMega (or AtTiny) chips directly (AtMega is the chip used to do all the work on the Arduino).

To avoid this, I have gotten into the habit of putting a 5 second delay as the first thing in the startup code.

FOR FUTURE GENERATIONS: I got mine here in New Zealand, so that will probably not help most people. FreeTronics makes them, and I am very happy I got their one (they have a "slow clock" jumper that is very convenient when programming Atmel chips not on an Arduino board), I expect that any USBASP would do the trick too - in response to the question, Amazon has a couple under $4, and I expect that the price will not go up.

Search for "USBASP". Make sure you get a ribbon cable. For Arduino Uno, you need a 6-pin ribbon cable. It is also possible to use these cables to communicated directly with a running Arduino over these same pins.


How to program Fio v3 without MicroUSB port I got given a Fio V3 but unfortunately the MicroUSB port is missing, not sure why.  Is there any other way to program it?  I'm thinking perhaps those 6 pins under the microcontroller?

Also can I still power the board?  I notice it doesn't have a VCC or RAW pin like the Pro Micro version.  I'm not to worried about using a battery, can I plug any matching voltage into the battery plug?

I tried looking through the schematics and tutorials on Sparkfun but don't really know what I'm looking at.  Here are some relevant links anyhow:

Product page
Schematics
Datasheet

The board runs at 3.3V, so you can provide 3.3V directly into the 3.3V pin on the side. Also the black connector next to the USB socket is a battery connection for a Li-Ion battery or similar. It will take any voltage between 3.6V and 5V. Any higher and, according to the schematics, you need to remove the solder link that's just below the battery connector (silver blob). With that link removed you can theoretically go up to 20V on the battery input.

Yes, you can program through the 6-pin header below the main chip if you have a suitable hardware programmer (e.g., USBASP). That is a normal ICSP header like most Arduino boards have.


LED fade class strobes for unknown reason Okay, so here is what I'm trying to accomplish:

I have four LEDs, under my fish tank, that I want to fade in and out.  I want each LED to fade at a different rate, start at a different "brightness" with PWM, and get a "new" fade-rate every once in a while.  Ultimately, it'll make the bottom of the fish tank "pulse" in a "natural" way.

The code I'm using to accomplish this can be found in my GIT repo.  There is also a GIF of it "working," there.

Now, here is my problem:

Every once in a while, one of the LEDs (not a specific one) will stop fading and start blinking like a strobe light.  I'm not sure what's causing this blinking, since it seems to happen randomly.

The other three LEDs seem to continue to fade in/out while the "bad" LED is spaz-ing out, and it doesn't seem to be isolated to a specific LED.  It also doesn't seem to affect only one LED at a time, although it's usually only one LED "blinking" and any given time... but I have seen two going at the same time.

It also doesn't seem to be specific to the "high" or "low" PWM levels, either... it can happen at "bright" levels, "dim" levels, or even in the middle of the fading transition.

Here's what I've tried:

I've tried different Arduino boards, and I've taken the LED count down to a single LED.  I've changed variable types from bytes to ints, and back and forth with that tactic.  I've been combing through this sketch all day, and I don't see anything that stands out to me as causing the problem.

So, now I'm turning to you all, hoping that someone will be able to see where I've screwed up my code.

Thank you, in advance!

EDIT:  Since I've been asked for direct posting of my code, instead of just a link to the source code:

Here is the main .ino file:

#include "led_controller.h"

// Set pin numbers for each LED
byte led1 = 3,
           led2 = 6,
           led3 = 9,
           led4 = 11;

void setup(){
    pinMode( led1, OUTPUT );
    pinMode( led2, OUTPUT );
    pinMode( led3, OUTPUT );
    pinMode( led4, OUTPUT );
}

// Initialize our four classes for our four LEDs
LED a( led1 ),
    b( led2 ),
    c( led3 ),
    d( led4 );

void loop(){
    a.ledChange();
    b.ledChange();
    c.ledChange();
    d.ledChange();

    delay( 60 );
}

And the header file with the class:

// Create our custom LED class
class LED{
    private:
        // Set higest and lowest brightnesses for LEDs
        byte highest = 250,
             lowest = 5;
        byte pin, brightness, isNeg; // Random necessary variables
        int change; // Set the inc/decrement rate for the LED
        int checkNeg(); // See if our change rate is negative, or not
        void changeChange(); // Get a new change rate
    public:
        LED( byte led ); // Define our constructor
        void ledChange ();
};

// Define our constructor
LED::LED( byte led ){
    pin = led;
    changeChange();

    // Set the initial LED brightness by random
    brightness = random( lowest, highest );

    // Randomly determine if the LED will start brightening or darkening
    if( random( 1, 2 ) == 1 )
        change *= -1;
}

// Get a new change rate
void LED::changeChange(){
    change = random( 1, 4 );

    if( isNeg )
        change *= -1;
}

int LED::checkNeg(){
    if( change < 0 )
        return 1; // If `change` is negative, return true
    return 0;
}

void LED::ledChange(){
    // Flip LED change value between brightening and darkening
    if( brightness <= lowest || brightness >= highest ){
        change *= -1;

        isNeg = checkNeg(); // Determine if we're brightening/dimming the LEDs

        // A 1-in-25 chance to change the fade-rate
        if( random( 25 ) == 13 )
            changeChange();
    }

    brightness += change; // Adjust the LEDs brightness

    analogWrite( pin, brightness ); // Brighten/darken the LED
}

I added some Serial.print() statements to your code to point out the bug:

This is the modified LED::changeLed() function I used:

void LED::ledChange() {

  /**/Serial.print(brightness);

  // Flip LED change value between brightening and darkening
  if ( brightness <= lowest || brightness >= highest ) {
    change *= -1;

    isNeg = checkNeg(); // Determine if we're brightening/dimming the LEDs

    // A 1-in-25 chance to change the fade-rate
    if ( random (25) == 13 )
      changeChange();

  }

  brightness += change; // Adjust the LEDs brightness

  analogWrite( pin, brightness ); // Brighten/darken the LED

  /**/Serial.print("\t+ ");
  /**/Serial.print(change);
  /**/Serial.print("\t= ");
  /**/Serial.print(brightness);
  /**/Serial.print("\t");
  /**/for (int i = 0; i < (brightness / 5); i++) Serial.print("*");
  /**/Serial.print("\n");
}

I marked the additional lines with /**/.

Here is a piece of the serial monitor output, where the bug occurred.  The columns are organised as follows: brightness before the function changed it + change = brightness at the end of this function. The * lines graphically represent the LED brightness (i.e. the last number); this allowed me to run your sketch without a physical LED, at much higher speed (I deleted the delay(60) in loop()).

183        +    3         =    186  *************************************
186        +    3         =    189  *************************************
189        +    3         =    192  **************************************
192        +    3         =    195  ***************************************
195        +    3         =    198  ***************************************
198        +    3         =    201  ****************************************
201        +    3         =    204  ****************************************
204        +    3         =    207  *****************************************
207        +    3         =    210  ******************************************
210        +    3         =    213  ******************************************
213        +    3         =    216  *******************************************
216        +    3         =    219  *******************************************
219        +    3         =    222  ********************************************
222        +    3         =    225  *********************************************
225        +    3         =    228  *********************************************
228        +    3         =    231  **********************************************
231        +    3         =    234  **********************************************
234        +    3         =    237  ***********************************************
237        +    3         =    240  ************************************************
240        +    3         =    243  ************************************************
243        +    3         =    246  *************************************************
246        +    3         =    249  *************************************************
249        +    3         =    252  ************************************************** #####
252        +    -1          =    251  **************************************************
251        +    1         =    252  **************************************************
252        +    -1          =    251  **************************************************
251        +    1         =    252  **************************************************
252        +    -1          =    251  **************************************************
251        +    1         =    252  **************************************************
252        +    -1          =    251  **************************************************
251        +    1         =    252  **************************************************
252        +    -1          =    251  **************************************************
251        +    1         =    252  **************************************************
252        +    -1          =    251  **************************************************
251        +    1         =    252  **************************************************
252        +    -1          =    251  **************************************************
251        +    1         =    252  **************************************************
252        +    -1          =    251  **************************************************
251        +    1         =    252  **************************************************
252        +    -1          =    251  **************************************************
251        +    1         =    252  **************************************************
252        +    -1          =    251  **************************************************
251        +    1         =    252  **************************************************
252        +    -1          =    251  **************************************************
251        +    1         =    252  **************************************************
252        +    -1          =    251  **************************************************
251        +    3         =    254  **************************************************
254        +    -3          =    251  **************************************************
251        +    3         =    254  **************************************************
254        +    -3          =    251  **************************************************
251        +    3         =    254  **************************************************
254        +    -3          =    251  **************************************************
251        +    3         =    254  **************************************************
254        +    -1          =    253  **************************************************
253        +    1         =    254  **************************************************
254        +    -1          =    253  **************************************************
253        +    1         =    254  **************************************************
254        +    -1          =    253  **************************************************
253        +    1         =    254  **************************************************
254        +    -1          =    253  **************************************************
253        +    1         =    254  **************************************************
254        +    -1          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************

The bug begins at the line I marked with ####. I'll try to narrate the events from the point of view of your function, starting from line #### (1):

Is brightness 249 in range? yes -> don't invert sign | add 3 | return
Is brightness 252 in range? no -> invert | change fade rate? yes, new fade rate = ±1 | add -1 (we just inverted the sign) | return
Is brightness 251 in range? no -> invert (here's the bug!) | change fade rate? no | add +1 (ve should subtract, but we just inverted the sign...) | return
It continues like that until a fade rate change occurs, oscillating between 251 and 252. That looks out like a constant brightness.
The fade rate increases and the oscillation values change, maybe approaching 255 (if the smaller value goes below 250 the led will continue to behave properly, but that's not our case).
Another fader rathe change causes the program to make brightness greater than 255 (in our case 254 + 2). And if you add 2 to a one-byte unsigned variable holding a value of 254 you won't get 256 (the variable can't hold that value) but 0. That's something called "integer wraparound", as Majenko pointed out in his comment to your question.

So, that was a long description of a very simple problem.
To solve it you cold for instance prevent the brightness value to be greater than 250 and smaller than 5 adding two lines to your ledChange function:

void LED::ledChange(){
    // Flip LED change value between brightening and darkening
    if( brightness <= lowest || brightness >= highest ){
        change *= -1;

        isNeg = checkNeg(); // Determine if we're brightening/dimming the LEDs

        // A 1-in-25 chance to change the fade-rate
        if( random( 25 ) == 13 )
            changeChange();
    }

    /**/ if(brightness > highest) brightness = highest;
    /**/ else if (brightness < lowest) brightness = lowest;

    brightness += change; // Adjust the LEDs brightness

    analogWrite( pin, brightness ); // Brighten/darken the LED
}


Need help on HC05 and Nano I am new to Arduino programming and currently working on this instructable
http://www.instructables.com/id/Control-Led-RGB/ (following this diagram http://cdn.instructables.com/F6Q/IMHF/I0LCDK6B/F6QIMHFI0LCDK6B.LARGE.jpg)

I have ordered these parts as well.

Arduino Nano: www.ebay.in/itm/Arduino-Nano-SOLDERED-PINS-V3-0-ATmega328-CH340G-BUY-2-GET-1-USB-CABLE-FREE-/172117729247?
HC-05: www.amazon.in/Bluetooth-Transceiver-Module-TTL-Outputs-HC05/dp/B00R95Y0AK?ie=UTF8&psc=1&redirect=true&ref_=ox_sc_act_title_2&smid=A1NDZY44BCNIQJ

My questions are:

Is there need to add voltage divider? If yes can you please provide link?
Can I connect two 5050 RGB modules?
Will 12 V, 1 A will be enough to power this board.

1A will be enough to power you arduino but the total powerconsumtion will depend on the amount of leds that you want to drive. If you follow the instuctable, it should be enoug but it's never a good idea to use your power source at max capacity all the time.

It allows you to connect 2 modules indeed.

Why would you need a voltage divider?


Receiving garbage value when sending a Json object from Arduino Uno to NodeMCU using SoftwareSerial I am trying to send a Json Object from Arduino UNO to NodeMCU using SoftwareSerial. I am using Arduino IDE. I am getting garbage value on Serial monitor of NodeMCU. Tried it with different garbage values, couldn't receive data from Arduino UNO. Below is the code. PLease help. Thank you in advance. I haven't made a common ground. I have referred this webpage here.

Arduino UNO code:

    #include <SoftwareSerial.h>
    #include <ArduinoJson.h>
    SoftwareSerial s(5,6);

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

    void loop() {
     StaticJsonBuffer<1000> jsonBuffer;
     JsonObject& root = jsonBuffer.createObject();
      root["data1"] = 100;
      root["data2"] = 200;
      if(s.available()>0)
      {
       root.printTo(s);
      }
    }

NodeMCU code:

    #include <SoftwareSerial.h>
    SoftwareSerial s(D6,D5);
    #include <ArduinoJson.h>

    void setup() {
      // Initialize Serial port
      Serial.begin(9600);
      s.begin(9600);
      while (!Serial) continue;

    }

    void loop() {
      StaticJsonBuffer<1000> jsonBuffer;
      JsonObject& root = jsonBuffer.parseObject(s);
      if (root == JsonObject::invalid())
        return;

      Serial.println("JSON received and parsed");
      root.prettyPrintTo(Serial);
      Serial.print("Data 1 ");
      Serial.println("");
      int data1=root["data1"];
      Serial.print(data1);
      Serial.print("   Data 2 ");
      int data2=root["data2"];
      Serial.print(data2);
      Serial.println("");
      Serial.println("---------------------xxxxx--------------------");

    }

The problem with ArduinoJson.h is that it doesn't ensure robust and reliable transfer over UART serial.

Instead, you should use SerialTransfer.h to automatically packetize and parse your data for inter-Arduino communication without the headace.The library is installable through the Arduino IDE and includes many examples.

Here are the library's features:

  This library:

  can be downloaded via the Arduino IDE's Libraries Manager (search "SerialTransfer.h")
  works with "software-serial" libraries
  is non blocking
  uses packet delimiters
  uses consistent overhead byte stuffing
  uses CRC-8 (Polynomial 0x9B with lookup table)
  allows the use of dynamically sized packets (packets can have payload lengths anywhere from 1 to 254 bytes)
  can transfer bytes, ints, floats, and even structs!!

Example TX Arduino Sketch:

#include "SerialTransfer.h"

SerialTransfer myTransfer;

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

void loop()
{
  char buff[] = "hi";

  myTransfer.txObj(buff, sizeof(buff));
  myTransfer.sendData(sizeof(buff));
  delay(100);
}

Example RX Arduino Sketch:

#include "SerialTransfer.h"

SerialTransfer myTransfer;

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

void loop()
{
  if(myTransfer.available())
  {
    char buff[40];

    myTransfer.rxObj(buff, sizeof(buff));

    Serial.println("New Data: ");
    Serial.write(buff, sizeof(buff));
    Serial.println();
  }
  else if(myTransfer.status < 0)
  {
    Serial.print("ERROR: ");

    if(myTransfer.status == -1)
      Serial.println(F("CRC_ERROR"));
    else if(myTransfer.status == -2)
      Serial.println(F("PAYLOAD_ERROR"));
    else if(myTransfer.status == -3)
      Serial.println(F("STOP_BYTE_ERROR"));
  }
}


What is the difference between Accelerometer, Gyro, and Magnetometer Sensor? I'm starting in the arduino world and I'm building an autonomous smart vehicle.

So, after some weeks building and adjusting the vehicle, I got to a point in this project that I want to log it's movements. Talking with a friend, he showed me an Gyro/Accel sensor and I really think that it would be an awesome upgrade to my vehicle

After reading some articles, I'm failing to understand the difference between an Accelerometer Sensor, a Gyro Sensor and a Magnetometer Sensor

So what is the main difference between those sensors?

The Accelerometer measures total acceleration on the vehicle, including the static acceleration from gravity it would experience even when its not moving.

The magnetometer measures the magnetic field around the robot, including the static magnetic field pointing approximately north caused by the earth. Being placed in/around a metal frame or any large motors, diving over/around underground metal pipes or electrical equipment will all make large and noticeable effects on its measurements.

The Gyroscope measures your instantaneous angular momentum around each axis, basically how fast its rotating. Note that angular momentum is not directly compatible with euler angles, but works out similarly for small angles. Very high quality signal in the short term because there isn't much noise, but since your angular position has to be integrated off of the gyroscope, it will build up error.

Gravity is your best reference for angular position, because it doesn't drift like the gyroscope and since your robot is operating in (and causing) a sea of magnetic disturbances, using north is risky. It will not work if you are experiencing a significant acceleration though.

The simplest code would just use the accelerometer for rotations around x and y, the mag for z, and ignore disturbances. The basic idea is "I know gravity is actually down, but its being measured on the accel X axis, so I must be pitched by some amount". The Better sensor fusion algorithms will use the accelerometer/magnetometer to correct for drift in the gyro, but get most of its information about rotational position from the Gyroscope.

Tracking lateral position using a standard 9-dof IMU is not possible. Only the accelerometer measures lateral motion at all, and it needs to be integrated twice to get position. Error builds so fast your position estimate is complete garbage within seconds.

Tracking angular position is possible because all three sensors measure it in one way or another. Angles are tricky though because they are not commutative. If the gyro measures a 90 degree yaw then a 90 degree pitch from north, you are facing down; if it measures a 90 degree pitch and then a 90 degree yaw from north, your facing east turned on your side. Be careful with the math, or download an arduino IMU library that has it taken care of for you.


How does input from IR receiver to Arduino UNO board work? I have a very simple circuit with an Elegoo IR receiver module connected to an Arduino UNO. The three wires are connected correctly with the data wire (Y) connected to pin 8. The code works fine, as every time I press button on the remote, the Serial Monitor displays the corresponding button description.

However, I do not understand how Arduino's pin 8 knows which IR button has been pushed. My understanding is that pin 8 can read either 5V or 0V, but to know which of 20+ remote buttons has been pushed it would have to read PWM. But pin 8 does not the PWM icon next to it and yet it works fine. Unless the PWM icon applies only to pin output? Or is there another way I have failed to find info about?

Thanks!

You confuse the different technologies here.

PWM is only an output, not an input. So every pin marked with the PWM symbol can OUTPUT a PWM signal. Reading a signal is a totally different task with different hardware involved.
The IR receiver does not output a PWM (meaning Pulse Width Modulation) signal to the Arduino. It ouputs the demodulated IR signal.

So here is what happens: The remote a code, that consists of different periods of "light on" and "light off" (giving pulses of different length, which encode the data from binary format). Since you want to seperate the remotes signal from any other IR signal, that might roam through the air, the remote also modulates the pulses with a special frequency (often this is 38kHz, but might be another frequency around that). This means that every pulse will be chopped into shorter pulses at the specified frequency. This translates to something like: "light on and off with 38kHz for duration x" --> "light off" --> "light on and off with 38kHz for duration y" --> ...

The receiver module senses the IR light comming in and will electronically discard all signals, that don't have the special frequency, and does the demodulation on this. The outputted signal does not have the 38kHz frequency in it anymore. Just the pulses of different length, that encode the data, meaning

The Arduino then reads the length of the pulses (that only consists of sequences of 0V and 5V) and decodes them into a number. This number represents the pressed button.

A proper library for the Arduino can read the different data protocols used in common IR remotes.


Why do some pins have a different PWM frequency? According to the Arduino reference for analogWrite(), the PWM frequency on most pins is ~490 Hz. However, it's ~980 Hz for pins 5 and 6 on the Uno, and for pins 3 and 11 on the Leonardo.

Why are these different? Is it a deliberate design feature, or is it somehow dictated by the hardware?

Those aren't the only frequencies available for the PWM signals. However, they are the frequencies as determined by the applied prescaler (which you can readily change as detailed below).

Each of the 3 pairs of PWM pins is tied to one timer, each of which has its own base frequency, as follows:

Pins 5 and 6 are paired on timer0, with base frequency of 62500Hz
Pins 9 and 10 are paired on timer1, with base frequency of 31250Hz
Pins 3 and 11 are paired on timer2, with base frequency of 31250Hz

Then each set of pins have a number of prescaler values that can be chosen, that will divide the base frequency of that pair of pins. The prescaler values available are:

Pins 5 and 6 have prescaler values of 1, 8, 64, 256, and 1024
Pins 9 and 10 have prescaler values of 1, 8, 64, 256, and 1024
Pins 3 and 11 have prescaler values of 1, 8, 32, 64, 128, 256, and 1024

The different combinations yield different frequencies in a given PWM pin. Notice that timer 2 (tied to pins 3 and 11) have more prescaler values available, resulting in more frequencies available.

Now, why timer 2 is different, that's a separate question.

Edit: Here's a list of possible PWM frequencies per pin (from this article):

  For pins 6 and 5 (OC0A and OC0B):

  If TCCR0B = xxxxx001, frequency is 64kHz
  If TCCR0B = xxxxx010, frequency is 8 kHz
  If TCCR0B = xxxxx011, frequency is 1kHz (this is the default from the Diecimila bootloader)
  If TCCR0B = xxxxx100, frequency is 250Hz
  If TCCR0B = xxxxx101, frequency is 62.5 Hz

  For pins 9, 10, 11 and 3 (OC1A, OC1B, OC2A, OC2B):

  If TCCRnB = xxxxx001, frequency is 32kHz
  If TCCRnB = xxxxx010, frequency is 4 kHz
  If TCCRnB = xxxxx011, frequency is 500Hz (this is the default from the Diecimila bootloader)
  If TCCRnB = xxxxx100, frequency is 125Hz
  If TCCRnB = xxxxx101, frequency is 31.25 Hz

TCCRnB is where you set the prescaler bits for timer n, replacing n by 0, 1 or 2, depending on the timer you want to set. If you are still unsure about bitwise operations, read this bit math tutorial.

My sources:

http://playground.arduino.cc/Code/PwmFrequency
http://arduino.cc/en/Tutorial/SecretsOfArduinoPWM
http://arduino.cc/en/Tutorial/PWM
http://arduino-info.wikispaces.com/Arduino-PWM-Frequency

Note that there seems to be divergence in those sources about whether pins 9 and 10 have the same behavior as 5 and 6 or 3 and 11, but you get the idea anyway. I'm reading the datashet to try and figure out which is correct, or whether this is a difference between boards.


LiPo battery charger Is it possible to build a battery charger with just an arduino UNO board (and perharps some passive components)?. It's a 3.7V 550 mAh LiPo Battery. I understand I need to monitor the charge and the current flowing into the battery to properly (as in safely) charge it.

I'll assume that you are trying to charge from a 5V "USB" source.

If you only want to use a UNO + passive components then the hardware intensive method of application note AVR146: Lithium-Ion Battery Charging via USB with ATmega16/32U4 which Ignacio suggests does not meet your need. This is a capable charger but the UNO would not be the major part of it.

"Normal" charger

The use of any of the available LiIon charger ICs is an easy and low cost way of adding a charger. These ICs and all related components can cost as little as a few dollars. But ...

UNO + one resistor very low current charger:

If using a UNO with no external active parts the current drive rating of the UNO pins limits the maximum current able to be provided. If you really want to meet your specification you can achieve a few ten's of mA charge using with a UNO and a few resistors (possibly just one.)

Super simple good capability charger

But, a good compromise can be achieved using a UNO (or similar) + one transistor plus a few resistors and capacitors. This can achieve all the usual basic capabilities

Low current "trickle up" for very low voltage cells
Constant current charge until Vmax is reached
Constant voltage charge until I_cutoff is reached.
Terminate and stay active until recharge needed.

I will only outline the basic system here. More can be said as and if required.
The main point of note s that in its simplest form the charger uses a linear charging mode so a modest amount of heat needs to be dissipated in the control transistor. Max power dissipation for a A max charge rate would be 2 Watts when the battery was at 3V and full charge was wanted from 5V in.
Power dissipation = (Vin - Vbattery) x Icharge
Worst case here = (5V - 3V) x 1A = 2 watts.
A buck converter could be used (UNO controlled) if desired.

A transistor Q1 connects Vin to battery

Q1 can be PWM controlled by the Uno.

Battery current is monitored by a small resistor Rcur from B- to ground (or in B+ lead)

Vbattery is monitored with an ADC channel (ADC1 or ADC_V)

Current is measured by measuring voltage across Rcur with an ADC (ADC2 or ADC_I).

If Rcur is from B- to ground then V Rcur = V ADC2. If Rcur is in B+ lead V across Icur = V_ADC2 - V_ADC1.

Q1 on state can be varied by PWM from Uno to control battery current. PWM voltage is smoothed by an RC low pass filter to allow smooth DC control.

Charging:

The following steps constitute the standard LiIon charging algorithm implemented by most charger ICs. Variations can be made.

If Vbat < 3V set Ichg to Itrickle by PWMing Q1 and reading battery current.

While 3V <= Vbat <= 4.2V chg at Imax for battery.

When Vbattery = V-max = 4.2V adjust Ichg with PWM to hold Vbat at 4.2V until   Ichg falls to desired fraction of Imax.

Turn off chg voltage fully and monitor Vbat to restart charge at Vbat = Vrestart - maybe 4.0V or as desired.


ws2812b NeoPixel - how to address it? How Arduino knows the correct order of LEDS on the stripe? How to get a One-Wire address of a given WS2812B pixel? I bought several of these, and I cannot make them light. On the other hand, when I connect the addressable LED strip made of these diodes, I have no problem controlling it.

Here is my set-up:

I tried many programs, e.g. AdaFruit_NeoPixel -> simple, setting number of LEDS to 1, but no effect. No blinks, nothing - as if the diodes were dead.

If every One-Wire device is identifiable by 64 bit ID, how does the Arduino know the correct "order" of the LEDS on the ribbon? How to tell the Arduino the new sequence of the LEDS on the strip that would result if I replace one (broken) LED with another?

The WS2811/2812/2812B is not a 1-Wire device but is in fact a timing-based shift register with 3 LEDs (external in the case of the WS2811) connected to it.

As long as valid bit pulses are sent to the input of one of these devices it will shift the data through it and subsequently out of its data output. Connecting this output to the input of another device will shift data into that device as well, with the latest data sent being transmitted towards the furthest device in the chain.

Provided 24 bits per device are sent before the latch signal, The first 24 bits will be shifted into the first device, the second 24 bits into the second device, and so on until the last 24 bits into the last device in the chain. Once the latch signal is received, the devices will switch to the color indicated by the 24 bits currently shifted into them.

Since all of the devices use the same signaling (the only differences being supply level and the presence of a built-in RGB LED), they can be replaced freely with devices of the same or different make between the three.


LCD displays wrong temperature Hi I have a program that does not work right as I aspect:

v = tempC;
h = tempC * 10;
h = h % 10;
memset(stempCA, 0, sizeof(stempCA));
sprintf(stempCA, "%+.2d.%d", v, h);

it works fine on positive temperature "+11.22"
but not for negative values : "-02.-1"

where is my mistake?
 thanx

I think, that -1%10=-1, not 9 as you would like. I use

if (tempC<0) {print'-';tempC=-tempC;};
print tempC as usual for positive numbers


What happens to the board if you connect the +5V pin directly to a digital input configured as input I have maybe a very stupid question but connecting the +5V pin to a digital input pin programmed as input ( let's say pin2) . Will it destroy the board? Cause after i did this my board doesn't work anymore and i can also not upload a sketch to it. it does nothing anymore, yet nothing has burned or no smoke.

??

Thanks

Will it destroy the board?

No, it will just read HIGH. That's what HIGH is - 5V.

  Cause after i did this my board doesn't work anymore

Then you probably did something else.