text:
What is the best and most reliable way to detect if a book is pulled out of a book case?
What is the best and most reliable way to detect if a book is pulled out of a book case?
I have a book case which I want to mount sensors to so that I can detect when certain books are pulled out, I don't need to know how much, all I need is a boolean trigger if the book has been pulled out 2+ cm or so (works with lower too). I would preferably also want to know when they have been replaced but that is just a bonus.
The goal of the project is to move a servo which may or may not open a secret door when 3 books are pulled out in a certain order.
The sensors need to be able to work continuously 24/7 for years.
Here is a masterfully drawn picture to explain it even better.

So far I have been thinking of mechanical switches, Ultrasonic Sensor (HC-SR04), or possibly some sort of infrared light and sensor that can detect a change in intensity (where a lower intensity is book being pulled out).
The mechanical switch I could easily do, but I would prefer something that is less obvious, and less "clicky" when it's triggered. I don't want to give away that there is something special with a book if someone picks it up on accident.
Any ideas on how it can be done?
Would love tips for specific components as I'm not native to the arduino world and have a hard time finding exactly what I'm looking for.

IR proximity is probably the most discrete - the kind of thing that's built into your phone to detect if a case closes or opens.

Great idea for an Arduino project by the way :)

best way would be multiple cameras connected to a CV system ... seriously, best is meaningless .... specify some parameters, such as cost, speed, need for expandability, etc.

I'd suggest a Photo Reflective Sensor.

As Majenko stated in the comments, an easy and discrete way would be using IR proximity sensors behind each book. The IR light from them is invisible to the eye, they are easy to read with an Arduino and often the casing of the IR LED and IR sensor are black, so that you could easily hide them in a black backplate of your book case.
The IR sensor will output one pin state (HIGH or LOW depending on the sensor), when something (the book) is near it (on most sensor modules you can change to threshold to your liking), and the other, if nothing is near it (empty place in the book case)
Searching "ir proximity sensor" at amazon gives multiple good looking results for ready to use sensor boards.

Another - more hacky - way would be to build your own switches at the top of the book case. As a switch is nothing more than 2 electrical contacts with some mechanic suroundings, you could add a small piece of cardboard above each book, which falls down a bit, when the book is removed, but not enough, that it is easily spotted (a few millimeters should be enough). At the top of the case and on the cardboard piece you put some piece of tinfoil or aluminum tape. When the book is put in the box, the tinfoil pieces get pressed together by the book, thus make contact. Wire one piece to ground, the other to an Arduino pin.
I find the IR sensor solution better, but I wanted to include a solution, where you don't need to buy extra sensor modules.

If you want the book and shelf to look normal, then use tiny magnets in the books and either reed switches or hall magnetic sensors embedded in the bookshelf. You can even discriminate two books by minding the magnet's polarity.

Simple and reliable, this would be my solution.

The range of magnets isn't great, so the books have to always be precisely aligned. I'd advice against this.

Why not use RFID tags and sensor. You can do an inventory any time you want. The RFID tags are inexpensive and the sensor is not that much and available for the Arduino. Nothing shows if you put the tag in the spine of the book.

a tag in the spine would be perpendicular to an under-shelf RFID sensor, which won't scan. Also, you only have about 2cm of range with a tag, so you would need 3 such sensors for three books, and a tag in the spine is probably out of the question due to limited range. Neat idea though, and if you can get them to scan, this is the only way to have different combos do different things...

Depends on the sensor and tag. Using a system in the 865 - 960 MHz – Ultra High Frequency (UHF) – A short, high-energy wavelength of about a one meter which translates to long read range. Passive UHF tags can be read from an average distance of about 5 - 6 meters, but larger UHF tags can achieve up to 30+ meters of read range in ideal conditions. If he goes to active tags the distance is much greater. If that is to far you can adjust the sensitivity down.

I assume all these solutions need to know exactly what book is where (positioned).
A solution could be a long LED strip (or other light) above the books, and at the bottom a strip of photo resistors (LDR), placed at every 2 cm. Place this photo resistors far enough backwards to cover the end of the shortest book (unless you do never change the order of the books you can place them exactly at the width of the book minus a cm or so).

My original plan was to place thicker books that are easy to detect in certain spots and drill holes as needed for the sensors behind them.

In the solution with LDRs, it's better to have the LDR under the books, or place the LDR directly behind each book, but then the LDR should (almost) has to touch the book to prevent light getting on the LDR.


text:
Use Raspberry and Arduino IDE to programm ESP8266
I currently use Arduino IDE to generate binaries for ESP8266. Afterwards I copy the binaries with SFTP to my Raspberry Pi and flash the binaries using esptool.py.
These are lots of steps I need to do manually. Is it possible to automate this and use the Raspberry Pi as a programmer known to the Arduino IDE?
The goal is, that the "Upload" button in Arduino IDE does the full job.

Are you running the Arduino IDE on Windows, Linux or macOS ?

IDE is running on Windows.

You could try using serial over IP ( http://playground.arduino.cc/Interfacing/SerialNet ). Alternatively add the OTA updating to the ESP so you can do away with the Pi entirely.

You could switch over to an entirely command-line workflow, and then a Makefile would suffice. You will bash/cygwin/some other *nix environment on Windows.

Thanks for your suggestions. The OTA option looks interesting.

I was able to find a solution based on this post: http://www.linuxquestions.org/questions/linux-networking-3/serial-over-lan-from-linux-to-windows-825334/#post4062960
Following steps are necessary.

Install com0com and com2tcp on the Windows machine and socat on the Raspberry.
Then add a virtual COM-pair (COM0 <-> COM25) on the Windows machine with the help of com0com.
Execute following command on the Raspberry. socat file:/dev/ttyAMA0,raw,echo=0,b115200 tcp-l:3016,fork& (adjust the device /dev/ttyAMA0, baudrate b115200 and port 3016 according your needs)
Start com2tcp on the Windows PC with following command. com2tcp --baud 115200 --ignore-dsr \\.\COM25 192.168.0.1 3016
Now you can use COM0 in Arduino IDE to flash the ESP8266 attached to /dev/ttyAMA0 on the Raspberry

Have you tried installing Python for Windows?
http://docs.python-guide.org/en/latest/starting/install/win/
In theory it should work and you should be able to run esptool.py on a Windows command line like you do on your Pi (provided that your usb to serial in recongnized by Windows).
If esptool.py fails to run under Python for Windows I would first suggest to open a ticket with the esptool maintainer and then try under a cygwin environement (https://www.cygwin.com).

I think, I forgot to mention, that I don't have a USB UART Interface on my PC. So there is no way to program over UART and without the Raspberry Pi.

Get a FTDI adapter. Here is a blog post I wrote a while ago about it : http://net-forces.blogspot.ca/2016/07/flashing-esp-01-under-osx.html?m=1

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Help in "An error occurred while uploading the sketch"
Trying to test THIS. Got following error:
esptool v0.4.13 - (c) 2014 Ch. Klippel <ck@atelier-klippel.de>
    setting board to nodemcu
    setting baudrate from 115200 to 9600
    setting port from COM1 to COM3
    setting address from 0x00000000 to 0x00000000
    espcomm_upload_file
    espcomm_upload_mem
    setting serial port timeouts to 1000 ms
opening bootloader
resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
Uploading 356000 bytes from C:\Users\PRAMIT~1\AppData\Local\Temp\arduino_build_521093/testPersWiFiManager.ino.bin to flash at 0x00000000
    erasing flash
    size: 056ea0 address: 000000
    first_sector_index: 0
    total_sector_count: 87
    head_sector_count: 16
    adjusted_sector_count: 71
    erase_size: 047000
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    setting serial port timeouts to 15000 ms
    setting serial port timeouts to 1000 ms
    espcomm_send_command: receiving 2 bytes of data
    writing flash
................................................................................ [ 22% ]
................................................................................ [ 45% ]
................................................................................ [ 68% ]
.......................An error occurred while uploading the sketch

All libraries are included, no compile error.
Steps followed:
1st uploaded the data using Tools>ESP8266 Sketch data upload.
Then Sketch>upload
After failing this, I tried a basic example similar to THIS. This uploaded successfully. The same configuration is used for both scenarios.
What am I missing? I am getting no clue.
Settings:

Any change in Erase Flash settings?

the data upload was successful? try 115200 baud or more for upload

@Juraj, you are right, I updated the baud rate to 115200 and it worked. However, I first tried to change it in the code, but not helped.

upload speed for flashing has nothing to do with the value in sketch.

The upload to esp8266 with esptool used in IDE doesn't work good on slow baudrate. It fails for larger sketches. You can upload to NodeMcu at 921600 baud.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Read function in Software Serial
I have a question regarding how the read function works in Software Serial.
recv reads the bits a receiver picks up into a serial buffer. than read returns a uint8_t. However, when i set read() equal to a variable and print it, it doesn't necessarily always print out a byte.
For instance:
int x = rx.read(); //if the read is supposed to read 60, x prints 111100
int x = rx.read(); //if the read is supposed to read 226, x prints 11100010
How come the first statement doesn't print 00111100?
Sorry, i realize this might be a very dumb question. I looked into the software serial library, and couldn't identify what I'm missing.

For the very same reason that you don't normally write 00000069 instead of just 69. The leading 0's are completely meaningless and can be omitted or included without any change to the value.

I understand they can be omitted, but does the variable just do that for me?

No it is the print that does it. An int is 16 bits and that is set in stone.

OO that makes sense. So int returns the whole byte, but print discards leading 0s. Gotchya, thanks.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Gain on a receiver
I'm doing a project on the arduino with simple 433MHz antenna modules. And I was wondering if someone could offer clarifications on how receivers work.
I read that high gain receivers can pick up a very narrow beam of radio power and thus, can transfer data at high rates. Given that this signal is tightly focused to the transmitting end.
And a low gain receiver can pick up a much wider beam of radio power.
My question is the following. When they say "narrower beam" does that represent the amplitude of the signal or the number of different waves that are being transmitted? OR does it refer to the number of DIFFERENT frequencies it can pick up? Sorry, if my question is confusing. Happy to clarify any part of it.
My Source: http://www.qrg.northwestern.edu/projects/vss/docs/communications/2-what-are-high-and-low-gain.html

Think of the receiver as a camera with a telephoto lens.
With the lens zoomed out you can see a large area.  You get visual information from all over.
With the lens zoomed in you can only see a very small area. The visual information you receive is only from a very small field of vision and things outside that field never get to you.
It's exactly the same with radio waves except that the shape of the antenna affects the zoom instead of lenses.

Oh ok, that makes more sense. So just to clarify, with a low gain receiver then, it can pick up many different frequencies from all directions while HGAs do the opposite right?

Low gain is zoomed out. It can receive from many directions. High gain is zoomed in, and receives from less directions. Both are tuned to a specific range of frequencies. Eg a satellite dish is high gain but a car aerial is low gain.


text:
arduino project for c programming language
i am a student from 2nd semester BCA (Bachelor in Computer Application). My group need some project for presentation from c programming language so i thought of using #ARDUINO project for our presentation . i really don't have any idea in this project so any ideas, answer, guides will be helpful to us.

Great idea - choose something you know nothing about and then beg others for help.  At least start with having a clue what you want to achieve, then we may be able to help you achieve it. Until then you're on your own.

I must say. Kind of a silly question. It indicates you've done virtually no reasearch on your own. Kind of like saying, I have a pencil and paper. I need some guidance as to what types of marks I can make on the paper with the pencil. :) Here's something that may give you some insight: see the latter 3 links that I posted in my answer here: http://arduino.stackexchange.com/questions/16413/how-to-change-variable-when-a-button-connected-to-pin-2-is-pressed.

Good luck with this! Arduino is awesome. I really enjoy using it. You may find this at least a little insightful: http://www.electricrcaircraftguy.com/2014/01/the-power-of-arduino.html.
Arduino is a small computer. It can do essentially whatever you want it to do: drive robots, fly airplanes, control motors, turn on or off TVs, get on the internet, make a home alarm, buzz a speaker, make a touch lamp, fade LEDs, play music (even with no music chip; just using a skillfully-written library), control HollyWood action cameras, talk to your smartphone, read your heartbeat, make a bike speedometer or odometer, read a GPS receiver, etc. Cool stuff!

I am not going to list example-projects as the possibilities with an arduino are endless. If you are looking for inspiration: take a look at websites like www.instructables.com and www.hackaday.io. Those are websites with mostly starter arduino projects that contain step-by-step guides on how they are created. I would suggest that you browse through those projects and look for something that peaks your interest and then think of your own similar project. You should however think of a project with a certain complexity as it is for your bachelor's. Most projects on instrucables lack the challenge. For getting parts: take a look at ebay. Ebay has some webshops that sell arduino's and arduino extension modules really cheap.
Good luck

Instructables is the worst site. Please rethink your answer.

I do agree with you that instructables is not a website for someone looking for a project with a challenge of some sort. Instructables contains examples of easy to follow and replicatable projects. It also has tutorials like "how to upload blink to an arduino" or "How to install the arduino IDE and the UNO drivers". And those tutorials come with step by step instructions and pictures. That's exactly what a total beginner needs. So I stand with by my answer. Your comment however is short and lacks any form of explanation. Maybe you are the one that has some rethinking to do.


text:
Using Arduino UNO as FTDI programmer for 9DOF Razor IMU
I am trying to upload some code to the ATmega328 on Sparkfun's 9DOF Razor IMU. Because I don't have an FTDI board at hand I was trying to use my UNO by "grounding" the RESET pin. Communicating with the 9DOF works well (it has some sample firmware loaded):

So here's the problem:
When I try to program the ATmega328, the Arduino IDE gives e the following error:
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x0d

What am I doing wrong?

What you're missing is the signal that resets the ATMega so it can enter the bootloader.  That signal is the one that goes to the DTR pin of the 9DOF and would normally be sent to the reset pin on your Arduino (that you are grounding).
What you need to do is reset the 9DOF just as it's about to start trying to upload the code.  Timing is critical - you get about a second or so of leeway where the bootloader is actually available for avrdude to talk to.
Alternatively you can try and find a point on your Arduino board where the DTR signal from the USB interface chip is available before it passes through the capacitor to the RESET pin of the Arduino and take a wire from there (wherever that may be) to the DTR pin of the 9DOF.

Perfect, thank you for the quick answer! I  won't get around to trying anything, but I'll verify it as soon as I can! Thanks again!

I simply removed the ATMega and connected RESET and DTR, works well! Thanks again!


text:
Pro Micro Voltage regulator burned
I'm using Arduino Pro Micro (5v version) in one of my project for my car. The car's 12V +ve connected to RAW input of ProMicro and everything seems to work perfectly until I crank the ignition of my car.
Here's what actually happened, my circuit works perfectly fine when car's ignition is in ON state. However, as soon as I started my car the voltage dropped from 12v to between 9-10volt and the LG33 (SMD voltage regulator) burned out. Now, I want a good solution as what should I do now?
I have already LM2596 DC 3A Step-Down regulator. So should I use that to step-down 12v to 5v OR is there anything else I can do which might be a better solution?

What happened was the ignition caused massive spikes on the 12V power. You require an automotive grade regulator that can cope with spikes in excess of around 70V or more.
Your best bet is probably a car USB charger adapter since they are cheap and easy to get hold of.

You are right, I think using a car USB charger should do the trick to maintain a steady 5v current. I will try that over this weekend and let you know how it goes :) Thanks.

I cannot disclose the make, but I've seen a chinese brand send spikes of more than 100V to its car dashboard.


text:
Why the MPU6050 gyroscope read write register value is 0x08 for a full scale of 500 degrees per second?
I am trying to connect a gyroscope MPU6050 to arduino ATmega2560 and read its raw values from its 6DOF (gyro and acc).
I found the following code:
//Activate the MPU-6050
  Wire.beginTransmission(0x68);                                        //Start communicating with the MPU-6050
  Wire.write(0x6B);                                                    //Send the requested starting register
  Wire.write(0x00);                                                    //Set the requested starting register
  Wire.endTransmission();                                              //End the transmission
  //Configure the accelerometer (+/-8g)
  Wire.beginTransmission(0x68);                                        //Start communicating with the MPU-6050
  Wire.write(0x1C);                                                    //Send the requested starting register
  Wire.write(0x10);                                                    //Set the requested starting register
  Wire.endTransmission();                                              //End the transmission
  //Configure the gyro (500dps full scale)
  Wire.beginTransmission(0x68);                                        //Start communicating with the MPU-6050
  Wire.write(0x1B);                                                    //Send the requested starting register
  Wire.write(0x08);                                                    //Set the requested starting register
  Wire.endTransmission();                                              //End the transmission

I am trying to break it line by line, to understand what is going on during the setup of the gyroscope.
According to MPU6050 datasheet, the I2C is at the register 0x68. The I2C helps us to access all registers and communicate with the master connected to. Which gives the following 3 lines:
Wire.beginTransmission(0x68);
Wire.write(0x6B);
Wire.write(0x00);

According the the sheet, the 0x6B is the register designed to enable and disable the gyroscope:

This register allows the user to configure the power mode and clock
  source. It also provides a bit for resetting the entire device, and a
  bit for disabling the temperature sensor. By setting SLEEP to 1, the
  MPU-60X0 can be put into low power sleep mode. When CYCLE is set to 1
  while SLEEP is disabled, the MPU-60X0 will be put into Cycle Mode. In
  Cycle Mode, the device cycles between sleep mode and waking up to take
  a single sample of data from accelerometer at a rate determined by
  LP_WAKE_CTRL (register 108). To configure the wake frequency, use
  LP_WAKE_CTRL within the Power Management 2 register (Register 108). An
  internal 8MHz oscillator, gyroscope based clock, or external sources
  can be selected as the MPU-60X0 clock source. When the internal 8 MHz
  oscillator or an external source is chosen as the clock source, the
  MPU-60X0 can operate in low power modes with the gyroscopes disabled.
  Upon power up, the MPU-60X0 clock source defaults to the internal
  oscillator. However, it is highly recommended that the device be
  configured to use one of the gyroscopes (or an external clock source)
  as the clock reference for improved stability. The clock source can be
  selected according to the following table.

So why we set its value to 0x00 ?
And the same for setting up the gyroscope at register 0x1B where datasheets specify the full scale ranges as:

The code is setting the range of 500 dps, so why the coder set the register to 0x08 and not 0x01 where the FS_SEL[1:0] should contain decimals from 0 to 3 right ?

The i2c address is 0x68 or 0x69. Some modules with the MPU6050 have indeed 0x69, but most have 0x68.
When searching the datasheet for the word "sleep", this sentence is easy to find: "Note: The device will come up in sleep mode upon power-up".
When the MPU6050 powers up, the SLEEP bit is 1 and the sensor is in sleep mode. Therefor writing a 0 is to get it out of sleep mode. After that you can set the sensor as you want.
The FS_SEL[1:0] is a notation that is used a lot in datasheets. It is an indication that only two bits are used. It is not the bit-position in the register. Those bits are located at Bit3 and Bit4. To turn on the lower bit of FS_SEL, Bit3 has to be set to 1, thus a value of 0x08 is needed for the register.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Reading from an oven humidity sensor
I have been trying to solve the problem of humidity sensors in a harsh environment (BBQ/Pizza Oven) and I came across this:
enter link description here
But I don't see any documentation on how to connect such a sensor to an arduino.
Are there any examples of how to integrate this?

I doubt you'll find a documentation, because it is a spare part for a microwave oven. I also think, it can not be used in hot environment. The air in an microwave oven is cold compared to a pizza oven ;-). The isolation of the inner wires could melt away and you have a short circuit. I don't know if the sensor itself (without the wires)  is made for hot environments. I haven't found any specification too. As I have written, its a spare part and used to replace defect ones in a microwave oven. See https://www.youtube.com/watch?v=akQ8zCFk_VY .

The title also say is a "Microwave Humidity Gas Steam Temp Sensor". I would interpret that, as if it can measure the temperature of the humidity gas (i.e the vaporized water).  But perhaps I'm wrong.

In general, it's always better to try something first - then ask here. I think what you are asking for is difficult as humidity detection at pizza / baking temperatures 400+ F are likely not kind to COTS humidity sensors. My guess, humidity control is empirically arrived at using the ambient room temperature & humidity and the oven's current temperature plus the amount of water squirted into the oven plus the water content of the food. If you want, you could start looking for academic papers like this one.


text:
Serial communication between python and arduino
I am working on object tracking robot. I am using python and OpenCV to detect the object and send the proper data to the arduino that controls two servo motors.
The data which should be sent to the arduino are servo motors angles ranging between 0-180. I am using sample codes to understand how python and arduino communicate using serial bus.When I send a single digit, the arduino receives it and work as intended, but when I send more than one digit nothing happens.
This is the arduino code:
#include <Servo.h>
int data;
Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards
int pos = 0;    // variable to store the servo position

void setup() {
  Serial.begin(9600); //initialize serial COM at 9600 baudrate
  pinMode(LED_BUILTIN, OUTPUT); //make the LED pin (13) as output
  digitalWrite (LED_BUILTIN, LOW);
  myservo.attach(9);
  Serial.println("Hi!, I am Arduino");
}

void loop() {
while (Serial.available()){
 //to receive more than one character
 char buffer[] = {' ',' ',' ',' ',' ',' ',' '}; // Receive up to 7 bytes
 while (!Serial.available()); // Wait for characters
 Serial.readBytesUntil('n', buffer, 7);
 data = atoi(buffer);

}
myservo.write(data);
}

And here is the python code:
import serial
import time  # Required to use delay functions

arduinoSerialData = serial.Serial('com14', 9600)  # Create Serial port
object called arduinoSerialData
time.sleep(2)  # wait for 2 secounds for the communication to get
established

print arduinoSerialData.readline()  # read the serial data and print it as
line
print ("Enter 1 to turn ON LED and 0 to turn OFF LED")

while 1:  # Do this forever

    var = raw_input()  # get input from user
    print "you entered", var  # print the intput for confirmation

    arduinoSerialData.write(var)

the only debugging code that you have is Serial.println("Hi!, I am Arduino"); .... put in more debugging code to determine what is being received

If the python Serial write function sends byte, then you should read it in Arduino with Serial.read().
void loop() {
  if (Serial.available()){
    byte data = Serial.read();
    myservo.write(data);
  }
}

If python sends the number as text, then you can read it with parseInt().
void loop() {
  if (Serial.available()){
    int data = Serial.parseInt();
    myservo.write(data);
  }
}

The parseInt is one of the blocking functions and will by default wait one second for next char after the last sent digit was received. But the number is sent at once from python so the delays between digits are small. Set in setup() Serial.setTimeout(10);

I need to update the servo's angle continuously. Is there something wrong with that?

I don't know. I never controlled servos.

How arduino saves the received data? in what data type?

I edited the answer

please check this post:
https://arduino.stackexchange.com/questions/55986/delay-in-serial-communication-between-python-and-arduino

read the last paragraph of this answer

Besides timeout, parseInt also returns on a non-valid characters for an integer. If you send the number as a line, there shouldn't be any delay. You just need to clear the leftover characters from the buffer, because parseInt doesn't consume them.

but here it is machine to machine. and perhaps manual entry from Serial Monitor for test.


text:
end measure process of HX711 with Door Lock magnetic sensor
I'm doing a program that starts the measuring process, using an HX711 when the door lock magnetic sensor spits and, when ends the measuring process when the door lock magnetic sensor joins.
if (analogRead(A0) > 50){
    scale.power_up();
    lcd.setCursor(0, 4);
    lcd.print("Peso: ");
    lcd.print(scale.get_units(), 3);
    Serial.print(scale.get_units(), 3);
    lcd.print(" kg");
    Serial.print("\t");

    myRTC.updateTime();
    Serial.print(myRTC.dayofmonth);
    Serial.print("/");
    Serial.print(myRTC.month);
    Serial.print("/");
    Serial.print(myRTC.year);
    Serial.print("  ");
    Serial.print(myRTC.hours);
    Serial.print(":");
    Serial.print(myRTC.minutes);
    Serial.println("");
    delay(3250);
    digitalWrite(pinR1, LOW);
    lcd.clear();
    lcd.setCursor(0, 1);
    delay(2000);

    if( analogRead(A0) < 50){
    lcd.print("   Peso Registado   ");
    delay(3500);
    lcd.clear();
    lcd.setCursor(0, 1);
    lcd.print(" O planeta agradece ");
    lcd.setCursor(0, 2);
    lcd.print("    a sua ajuda!    ");
    delay(3000);
    lcd.clear();
    }

    lcd.print("------TI-Trash------");
    lcd.setCursor(0, 1);
    myRTC.updateTime();
    lcd.print("   ");
    lcd.print(myRTC.dayofmonth);
    lcd.print("/");
    lcd.print(myRTC.month);
    lcd.print("/");
    lcd.print(myRTC.year);
    lcd.print("  ");
    lcd.print(myRTC.hours);
    lcd.print(":");
    lcd.print(myRTC.minutes);
    lcd.setCursor(0, 4);
    lcd.print("LOADING...");
    delay(2500);
    lcd.setCursor(0, 4);
    lcd.print(">APROXIME SEU CARTAO");
    }
 }

The problem is that I don't know how can I control the end of the measuring process because the process ends after a few seconds.
How can I controll the end of the measuring process

You need a variable for the state of the door. If state of the door is closed and the sensor shows that the door is open that is the moment where the you update the state of the door to open and start to measure. When the door state is open and the sensor shows that it is closed that is the moment when you change the state of the door to closed and stop measure.

Can you help me with examples of the code you're talking about?


text:
LCD write a line at bottom without lcd.setCursor and without deleting any char above already there?
lcd.cursor and lcd.noCursor won't work for what I want to use it for since it seemed to be "global" sort of speak and follow lcd.setCursor which I don't want it to but it is otherwise exactly what I want to be done; just to put a line at the very bottom and also remove the line whenever I want to but without removing the entire char above.
Just like lcd.cursor do but as said it won't work in the code since the line has to reside where it is even if lcd.setCursor is used elsewhere but then the cursor line follow to that other point which I don't want and such a controllable cursor that sits at the place even if lcd.setCursor is used elsewhere. But the char there first and then the line of vice versa doesn't matter just as long as there it a line. And I cant create custom chars with a line under them since its numbers from 0 - 9 and so many custom chars can't be made.
It's fully possible to write to the bottom row though and I thought it would be possible to do something with lcd.createChar by not no write anything at all at the bytes rows but the lowest one, but that surprisingly failed. This is what I tested:
byte line[8] = {

  B,
  B,
  B,
  B,
  B,
  B,
  B,
  B11111,
};

And that writes on the lowest row as expected, but strangely enough STILL deletes any char that is written above even if nothing should have been written there as I see it.
The test here put out pretty much garbage and pretty much delete the char written but something still remain but the line is written at top instead of bottom and I guess it all goes out of the normal bounds in the registry or something:
#include <LiquidCrystal.h>
LiquidCrystal lcd(40, 42, 28, 26, 24, 22);

byte line[1] = {

  B00000,
};

byte noline[1] = {

  B11111,
};

byte sure[8] = {   //It didn't like to use "square" as name by whatever the reason

  B00000,
  B00000,
  B01110,
  B01110,
  B01110,
  B01110,
  B00000,
  B00000,
};

void setup() {

  lcd.createChar(0, line);
  lcd.createChar(1, noline);
  lcd.createChar(2, sure);

  lcd.begin(20, 4);
  lcd:clear:
}

void loop() {

  delay(500);
  lcd.setCursor(0, 0);
  lcd.write(byte(2));
  delay(500);
  lcd.setCursor(0, 0);
  lcd.write(byte(1));
  delay(500);
  lcd.setCursor(0, 0);
  lcd.write(byte(0));

}

Any tips on how to do the same with create.Char or any other simple way? I mean the lcd.cursor and lcd.noCursor can do it, how do that do it then? It's an ordinary 20X4 LCD if that would matter.

Often instead of using a cursor you would just blink the character that is currently the "selected" one.

I do not really understand what you mean by your first sentence. Did you succeed in getting a "hardware" cursor to display together with a character or not? And if you do, why doesn't this fulfill your requirements?
You have to realize that your LCD cannot display partial characters, like a line at the bottom, leaving the rest of the character that was already there intact. An exception is a hardware generated cursor.
You also have to realize that createChar always expects a full character with 8 rows.
Your code examples
In your first example, starting with byte line[8] = {, the first 7 "empty" B, lines actually produce a value of (binary) zero. So here you create an empty character with a line at the bottom, exactly like you said you see on the display.
In your second piece of code, you define characters byte line[1] = and byte noline[1] = consisting of just 1 byte. createChar expects 8 bytes. createChar will fill the characters with the single byte defined in your character definition, plus whatever it finds in the 7 memory locations following your actual definition (which will probably contain some random data). This explains the "garbage" you see on the screen.
Possible solution
One solution would be to re-create each character you want your cursor to display under, on the fly. I.e. if you want your cursor to be displayed under the letter "A", you create a complete custom character which contains "A", plus a cursor underneath and you display it in place of the real "A" at this location. When you move the cursor, you replace the "custom" A with the real "A" again.
This will be cumbersome in code complexity as well as code size (you'd have to create a complete character map for every character you wish to display), but should be a feasible solution.


text:
Encode & decode boolean values into a single integer?
I'm trying to record the state of some pins over time. To save memory, I'm thinking about encoding the pin states into a single integer, like this:
Pin 1: TRUE
Pin 2: FALSE
Pin 3: FALSE
Pin 4: TRUE

Pin 1 = 1, Pin 2 = 2, Pin 3 = 4, Pin 4 = 8
1 + 0 + 0 + 8
Result: 9

This is pretty efficient.
But how do I decode the pin states from this best?
Or do you recommend a better way to do this?

Use the AND operator.
For example:
Pin 2's state would be: (result & 0x02) ? TRUE:FLASE

It took me a minute (well, more like 5 ;) ) to figure out these are hex values, but the solution is simple and working perfect. Thank you!

You are almost there with that. Personally I'd use OR not +:
This is a better way of defining the pins instead of using 1, 2, 4 etc. It results in the same thing, but you can see the bit number in there. The << is left shift.
#define PIN0 (1 << 0)
#define PIN1 (1 << 1)
#define PIN2 (1 << 2)
#define PIN3 (1 << 4)

Now you can combine:
uint8_t val = PIN0 | PIN3; // 9

And you can check if one is set:
if (val & PIN3) {
    // ....
}

To loop through the pins you can use the << again:
for (uint8_t pin = 0; pin < 8; pin++) {
    if (val & (1 << pin)) {
        // ....
    }
}

etc.

Pretty cool. I will keep that in mind as another great solution, thank you for your help.


text:
digitalRead influenced by touches
  const int BUTTON      = 8;

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

void loop() {

  Serial.println(digitalRead(BUTTON));

}

I have connected a cable to pin 8. It's not connected to anything else nor have I any other cables connected.
I am expecting constant zeros, but I keep getting ones and zeros all the time, e.g. when shortly touching the cable.
I didn't experience that before. Did I accidentally damage my Arduino?

Why are you expecting constant zeros? Do you have a pulldown on the pin? Unconnected inputs are undefined, unless something is driving the pin it'll float around at random. A person is a good 50/60 Hz antenna and so when you touch the wire you'll get random noise.

Google the phrase "Floating Input"

If you don't connect it to anything, it can be a result of a flipping 'input' ... try to use a pullup or pulldown resistor.
Or better:
PullUp
Use something like:
 pinMode(BUTTON, INPUT_PULLUP);

The pin is floating. Use pull up or pull down to help define its logic state.


text:
Less hardware dependent development?
I'm working on a little Arduino game project that uses neopixel strips as a display. Uploading every code change to the Arduino and testing it on the LEDs is slow and drains hardware lifetime.
Usually I test as much I can using the Serial Monitor, but I can't get it to clear from code which I learned is only possible e.g. when using a terminal. I did that, but it comes with other issues.
Is there a better way to test code on the dev machine instead of the Arduino?
Is there a best practice to have a Serial Monitor (or anything else) act like a display that I can actually refresh/clear? Serial.println() empty lines to scroll the content is not very practical.

I personally always use either a terminal emulator (screen) or cat on a terminal if it's only for logging. I find a terminal quite handy for that sort of work.

UECIDE's terminal is far superior.

I was using "Serial Tools" for Mac and the screen command inside the terminal. Both work and both have the annoying issue that somehow I can't upload changes as the IDE says that the serial port is currently in use. So far I only managed to solve that by disconnecting and reconnecting again. Any advice for that?

Just quit screen before uploading.

just get a $2 AVR that you don't care about "burning out". I often code new chunks in short JS first w/something like jsfiddle/codepen, using as close to C as possible (eg x.substring(0,x.indexOf(y)) instead of x.split(y)[0]. Once it works, i drop it into the sketch and add the types. Once it compiles, you've got a pretty good shot at it working as expected with minimal debugging. of course, you can run C w/o uploading too, but i've not found a decent "emulator", if that's the question.

As you've probably noticed, trying to run tests over the serial port is frustrating.  Worse, the relatively large delays associated with writing serial data can affect the accuracy of your measurements.
To cope with this, I wrote my own unit testing framework for Arduino, which lets you fully mock (simulate) the hardware so that you can verify the operation of the software.
There are some examples of how my library accomplishes that, in the project README.  Here is one for pins:
unittest(pin_history)
{
  GodmodeState* state = GODMODE();
  int myPin = 3;
  state->reset();            // pin will start LOW
  digitalWrite(myPin, HIGH);
  digitalWrite(myPin, LOW);
  digitalWrite(myPin, LOW);
  digitalWrite(myPin, HIGH);
  digitalWrite(myPin, HIGH);

  assertEqual(6, state->digitalPin[1].size());
  bool expected[6] = {LOW, HIGH, LOW, LOW, HIGH, HIGH};
  bool actual[6];

  // convert pin history to an array, and verify expected results
  int numMoved = state->digitalPin[myPin].toArray(actual, 6);
  assertEqual(6, numMoved);

  // verify each element
  for (int i = 0; i < 6; ++i) {
    assertEqual(expected[i], actual[i]);
  }
}

You may also like the example for mocking Serial port data, although I probably need to improve that documentation.
The beauty of all this is that I was able to develop this framework and all these tests without ever plugging an Arduino board into my computer.

You can unit test your code by creating stubs of the functions you are calling, like replacing a couple of includes with their dumb counterparts.
My friend Jan Beayens did something very valuable on that front and he is also the main author of a good replacement for the Arduino IDE when you start needing some more advanced capabilities: Sloeber is the product name and it also contains an improved version of the serial monitor with clear and scroll lock capabilities.
Go check it out.
Disclaimer : I'm a contributor of the project

Why are you issuing a warning? Do you believe there's anything wrong with Eclipse? It is OSS and works perfectly on Linux, which are two factors you should appreciate...
BTW, Sloeber also exists as a product, but that it is still dependent on Eclipse CDT.

I respect your opinion, but I completely disagree: Eclipse is my IDE of choice.


text:
Arduino Mega 2560 interrupt pins and port mapping with rotary encoder
I am trying to use port manipulation in interrupts to read a rotary encoder. I found code for a Uno, so the port call for pins 2 and 3 are different. I think on the Mega they are PORTH3 and PORTH4 respectively. My code is not working. Do I have my ports wrong? I've tried reading up on this and I'm not fully understanding the Bxxxxxxxx part. I think that might be what's incorrect. Here is part of my code with one of the interrupts.
static int pinA = 2;
// Our first hardware interrupt pin is digital pin 2
static int pinB = 3;
// Our second hardware interrupt pin is digital pin 3
volatile byte aFlag = 0;
// let us know when we're expecting a rising edge on pinA to signal that the encoder has arrived at a detent
volatile byte bFlag = 0;
// let us know when we're expecting a rising edge on pinB to signal that the encoder has arrived at a detent (opposite direction to when aFlag is set)
volatile byte encoderPos = 0;
//this variable stores our current value of encoder position. Change to int or uin16_t instead of byte if you want to record a larger range than 0-255
volatile byte oldEncPos = 0;
//stores the last encoder position value so we can compare to the current reading and see if it has changed (so we know when to print to the serial monitor)
volatile byte reading = 0;

void setup () {
  pinMode(pinA, INPUT);
  // set pinA as an input, pulled HIGH to the logic voltage (5V or 3.3V for most cases)
  pinMode(pinB, INPUT);
  attachInterrupt(0, PinA, RISING);
  // set an interrupt on PinA,
  //looking for a rising edge signal and executing the "PinA" Interrupt Service Routine (below)
  attachInterrupt(1, PinB, RISING);
  // set an interrupt on PinB,
  //looking for a rising edge signal and executing the "PinB" Interrupt Service Routine (below)
}

void PinA() {
  //CCW
  cli();
  //stop interrupts happening before we read pin values
  reading = PORTH & 0xC;
  // read all eight pin values then strip away all but pinA and pinB's values
  if (reading == B00001100 && aFlag) {
    //check that we have both pins at detent (HIGH) and that we are expecting detent on this pin's rising edge
    encoderPos --; //decrement the encoder's position count
    bFlag = 0; //reset flags for the next turn
    aFlag = 0; //reset flags for the next turn
  } else if (reading == B00000100) bFlag = 1;
  //signal that we're expecting pinB to signal the transition to detent from free rotation
  sei(); //restart interrupts
}

Did you ever get this working? I too have been wanting to use a Arduino Mega to track the angular position of a Omron Encoder with 3 interrupts. One of the interrupts for he Index to reset to 0 every time it completes one revolution. I want to use it to track a rotating mast for for direction finding. There are pieces of code but nothing complete.
Is yours complete?
bkukuk@cox.net

Re “pins 2 and 3 are different. I think on the Mega they are PORTH3 and PORTH4 respectively”, it's true that Arduino digital pins 2 and 3 belong to different ports on Uno vs Mega2560 boards.
Mega2560's have six INTx pins, vs two such on Uno's.  On the Mega, INT0...INT3 are PD0...PD3, and INT4,INT5 are PE4,PE5.  On the Uno, INT0,INT1 are PD2,PD3.  Note, in an answer at Can external interrupts be OR'd together on the '328 (Uno)? I show a couple of routines that will display appropriate masks for pins on different Arduinos.  See the sections “Using other pins for PCIs” and “ISR-framework-generating Sketch”.

Here are a few problems with the code shown in the question:

aFlag is initialized to zero, and is never set nonzero in the code shown.  So the first if condition in PinA() is never met.
PinA() is an interrupt handler, connected to interrupts by your attachInterrupt() calls.  Because hardware disables interrupts before it enters an interrupt handler, there is no need for the interrupt handler to turn off interrupts.  That is, delete cli() in PinA().  Similarly, delete the sei() at the end of PinA() because hardware restores interrupt status when a RETI instruction executes.
The Arduino software environment defines constants like B00001100 with binary values that match the name.  That is, in the Arduino software environment, constant B00001100 has the value 0B00001100.  In my opinion, that's a stupid and unnecessary feature; I suggest that in your code you use standard C notation like 0B00001100 when you want to use binary constant values.
I regard writing encoderPos -- instead of encoderPos-- as a perversion and suggest deleting that unnecessary space.
As you haven't shown the PinB() interrupt handler, I don't know how you were going to handle the encoderPos++ case.  Judging from the code shown, you are using a method that won't correctly handle bounce and intermittent errors.  I suggest using pin-change interrupts and a state-machine method, as illustrated in answers to:
• Reading from a KY-040 rotary encoder with Digispark
• How to read RPS for fast rotation with status change method in Arduino?
• Read RC receiver channels using Interrupt instead of PulseIn
• Can external interrupts be OR'd together on the '328 (Uno)?

On the mega, you'd read the pins with PINE.
So your code in PinA would change to:
reading = PINE & 0b00110000;

  if(reading == 0b00110000 && aFlag)

  {  encoderPos --;
    bFlag = 0;
    aFlag = 0;
  }
  else if (reading == 0b00010000) bFlag = 1;

I found a great discussion talking about the masking required here: https://forum.arduino.cc/index.php?topic=561741.0


text:
Esp32 and 74hc595 problem
I am using 74hc595 in several projects where I need more I/O and always worked fine using arduino pro mini or arduino mega. Now I connected same 2 of 74hc595 to an esp32 and does not work.
Is there any special things to do for esp32?
Wiring is exactly the same like here https://www.arduino.cc/en/tutorial/ShiftOut on chapter 2 (Connect the 2 registers.). If I use this with an arduino mega on pins 10,9,8 (see commented in code) is working perfect.
Then I replace arduino mega with esp32 and using pins 23,18,5 and does nothing. I get in serial monitor on/off prints but nothing changes to the relays.
Code
int SER_Pin = 23;//10; //pin 14 on 75hc595 //data pin
int RCLK_Pin = 18;//9; //pin 12  //latch
int SRCLK_Pin = 5;//8; //pin 11  //clock

#define number_of_74hc595s 2

#define numOfRegisterPins number_of_74hc595s * 8

boolean registers[numOfRegisterPins];

void setup() {
  Serial.begin(9600);
  pinMode(SER_Pin, OUTPUT);
  pinMode(RCLK_Pin, OUTPUT);
  pinMode(SRCLK_Pin, OUTPUT);

  clearRegisters();
  writeRegisters();
}

void clearRegisters() {

  for (int i = numOfRegisterPins -1; i >= 0; i--) {
    registers[i] =HIGH;
  }
}

//Set and display registers
//Only call after all values are set how you would like
void writeRegisters() {
   digitalWrite(RCLK_Pin, LOW);

   for (int i = numOfRegisterPins -1; i >= 0; i--) {
      digitalWrite(SRCLK_Pin, LOW);
      int val = registers[i];

      digitalWrite(SER_Pin, val);
      digitalWrite(SRCLK_Pin, HIGH);
}
  digitalWrite(RCLK_Pin, HIGH);

}

//set an individual pin high or low
void setRegisterPin (int index, int value) {
  registers[index] = value;
}

void c_on() {
  Serial.println("on");
  setRegisterPin(13,LOW);
  writeRegisters();
  delay(50);
}

void c_off() {
  Serial.println("off");
  setRegisterPin(13,HIGH);
  writeRegisters();
  delay(50);
}

void loop() {

c_on();
delay(1000);
c_off();
delay(1000);

}

Is there any special thing to do for using esp32?
Thank you very much

Are you powering the shift registers from 5V or 3.3V?

What relays are you using? Are you sure they work with the voltage you are powering your shift registers with? If you connect an LED+resistor to the shift register pin you are testing (#13 according to your code), does it light up?

the speed is different. maybe add some short delay in micros after setting the SRCLK

@Juraj, one single microsecond should be more than enough for the HC595.

The issue was from the power supply. Weird because same power supply worked with arduino mega

WiFi requires more current


text:
Web page using bluetooth?
I have a project where I read 2 sensors using an esp32 and also have an web server. I can connect using mobile phone and display the page where I see info about the sensors (using web sockets to update the info on the page very quickly ) and also send some commands back to esp32. Is working fine, just the issue that when I am connected to esp I don t have internet on my phone anymore (which is a normal thing:) ).
My question is if I can achieve same but using bluetooth instead wifi ? Is there any way to have a "web page" using bluetooth ?
Thank you

why not connect the esp32 to the same WiFi network you connect your phone?

Of course you can use bluetooth to comunicate with a webpage
here is an example
https://github.com/hewittwill/WebBluetooth-Terminal

No. There is no such facility in Bluetooth to provide such a feature.  That's not to say that technically it can't be done, there just isn't any software (a web browser) that would support it.
Instead you would need to use a Bluetooth-enabled app on the smartphone to communicate with the ESP32 over Bluetooth and display the data / provide control natively.  Such an app would probably have to be written by you since it would be specific to the way you are working, unless you can find a generic app that lets you design an interface for your project and then communicate using a documented protocol that you would then have to implement on the ESP32.

An alternative is to just reverse everything. Instead of having your phone connect to the ESP32 then connect to a webserver on it just have the ESp32 connect to your phone when your phone is set to WiFi Hotspot mode. You can still then get your phone to connect to the webserver on the ESP32, and your phone also has mobile internet. If course, if you are wanting internet through a WiFi connection for your phone then you can't do that. However, your ESP32 can then just also connect to your WiFi router so there is nothing to change on your phone. You just browse to the webserver on the ESP32 through your local WiFi network.

There is an experimental feature called the Web Bluetooth API. You could host a single file on a Webserver which then interacts via Bluetooth with your ESP. Keep in mind that aside from localhost you have to use https as protocol. Here is a Tutorial that shows how you can read and write to Bluetooth caracteristics using JavaScript.

Program your ESP32 to connect to your wifi - it then gets its own IP address on your LAN (e.g. 192.168.1.123 ) - then connect to your ESP from your phone (or anything else on your LAN).
Have you tried micropython? Works amazing on esp32 - makes everything super easy


text:
Get deceleration (negative acceleration when apply brake force)
I want to build a device to measure deceleration force when a car brakes. I am using a MPU6050 for get data and I read from it acceleration on X,Y,Z axes in m/s2 and also it gives me gyro in degrees/second.
My question is how can I use these gyro values to correct acceleration? Basically when apply brake the position of the axes are changing .
Also I guess I need to calculate the deviation as well if the car goes to the left or right during brake process.
Any ideas, hints will be very appreciated
Thank you very much

What exactly you want to calculate? Deceleration is indeed a negative number defined as deceleration = (velocity@begin - velocity@final)/time.

I accelerate to some speed for example. After that I will have a time without acceleration and when apply brake I start record values till the car is stopped. Then I want to get the speed that was when I started to brake and the distance till the car was stopped


text:
5 arrays or one matrix?
I am working on a project where i need to store as fast I can following :
1 - Acceleration on X
2 - Acceleration on Y
3 - Acceleration on Z
4 - timestamp
5 - A value from some other sensor
Because I need to get these as fast as I can I am thinking to not do any calculation while acquire values and just store them for 30 -60 seconds and then when the "test" is complete to compute calculations.
My question is if will be better to create 5 arrays and put these values there or create a matrix and store values there.
I need these values to be stored like they are "connected"
e.g. on reading 1 i get 5 values and put them on array[0] , then on reading 1 and so on
Also an important thing to mention, this will run on a esp32.
Thank you

The time needed to store these values in RAM will most likely be completely dwarfed by the time needed to read the values from the sensors.

Thanks a lot, I think you are right

I fully agree with Edgar Bonet.
My opinion is keeping a 'matrix' is better, or actually one array (of structs), where each array elements stores all information for one measurement (which is stored inside one struct). This has some benefits:

Data of one measurement is consecutive in memory, so you can easily transfer it (to some external memory or sending it). It's exact one struct (and you can use sizeof(struct_item) to know how many bytes you have to transfer.
It's good practice in general to keep information together, creating 5 always-equal length arrays seems strange.
If for some reason you want to make a single array dynamic or change it to a ring buffer for example, you can easily add/remove items (instead of dynamically changing 5 arrays).
Locality of change (see comments of Kwasmich/DuncanC)

There is also one benefit about having separate arrays (where each array stores one type of information, like an acceleration or timestamp: when you have a function (especially in another class) that only needs one of them, you can specifically send that array (or pointer/reference), so the other information is hidden from that function.

You are right but now rise another question: If i put all in one array then value[x] should contain all - probably i need concatenate them somehow accX,accY...so i will have a string array

You know there are religious fights going on abaout AoS vs. SoA (Arrays of Struct versus Structure of Arrays). It is mostly about data locality which does not apply to MCUs because of the lack of caches.

@David the idea is to make an array of structs where you put in the values.

@Kwasmich I didn't know those fights are so hard/religious. However, I can mention something about it in my answer (so I'm going to adapt).

For modern CPUs or GPU farms, locality of reference can make a huge improvement in cache coherence, and thus a huge speed improvement. That would suggest an array of structs, where all the values for a single calculation were grouped together. However, as Kwasmich says, that doesn't apply to MCUs like Arduinos.

@DuncanC  Ok, so another (good) reason to have an array of structs. On the other hand, suppose you need to perform an algorithm on a single type (let's say timestamp), than it would be opposite, but in most cases I assume the info of one measurements belongs more together than the information of one  type (axis, time stamp).


text:
Arduino Countdown without using delay()
I am working on a project which requires countdown from 30sec to 0sec. I can't use delay() function because I am taking input from keyboard during countdown. millis() function wont help because my board will be active for more than 50 days. I require something like counter which I can reset after or before completion of 30sec.

millis wrap around isn't a problem as long as you only use time difference. So timediff = endtime - starttime.

Background
The function millis () returns an unsigned long, which is the number of milliseconds since the processor was reset (until it overflows).
See: http://arduino.cc/en/Reference/Millis
Example:
unsigned long startTime = millis ();

Since there are 232 bits in an unsigned long it can count from 0 to 4294967295.
Computing this in terms of days we have:
2^32 / 1000 / 60 / 60 / 24 = 49.710 days

So, the number returned will overflow (go back to zero) after around 49 days (almost 50 days, as the reference page says).

Is this bad?
No. Is it bad your clock overflows (goes back to zero) at midnight? No it isn't.
Let's clear up some misconceptions:

The processor does not reset when the timer overflows.
The timer does not stop.
Nothing "bad" happens.

All that happens, on a timer overflow, is that it goes back to zero and starts counting up again. Just like your clock does.

How do I time an event?
There are two ways of timing something (eg. a minute from now). You can add or subtract. Because of the way that unsigned arithmetic works, subtracting is the correct way.

Example of adding - not recommended!
I want to detect a minute in the future...
unsigned long startTime = millis ();
unsigned long whenToStop = startTime + 60000;

...

if (millis () >= whenToStop)
  {
  // do something
  }

This will work most of the time, but not when the timer overflows. Let's see why:
Say the timer will overflow in 50 seconds, that is, it is currently:
2^32 - 50000 = 4294917296 (0xFFFF3CB0)

Now we add 60000, and get:
2^32 - 50000 + 60000 = 10000 (0x2710)

Our "whenToStop" variable has overflowed and is now quite small. And thus it is immediately less than the current time, and our check for when a minute is up fails, it appears to be up immediately.

Example of subtracting - recommended
I want to detect a minute in the future...
unsigned long startTime = millis ();
unsigned long interval = 60000;

...

if (millis () - startTime >= interval)
  {
  // do something
  }

This will work all the time. Let's see why:
Say the timer will overflow in 50 seconds, that is, it is currently:
2^32 - 50000 = 4294917296 (0xFFFF3CB0)

In 50 seconds the timer wraps around and goes to zero. Subtracting now gives us:
// millis () - startTime   = elapsed interval
    0        - 4294917296  = 50000 (0xC350)

The subtraction "wrapped around" and gave us a small number. If you use a scientific calculator and try the above you may get a result of 0xFF0000C350. The initial 0xFF is the "extended sign bit", in effect, however as the field is unsigned, and only four bytes long, the sign bits are dropped, giving a small positive number, not a large negative one.
Demo using the Mac Calculator app:

In 60 seconds the timer goes to 10000. Subtracting now gives us:
// millis () - startTime   = elapsed interval
    10000    - 4294917296  = 60000 (0xEA60)

So the elapsed interval (the difference) is now 60000, which is what we wanted.
Directly after we set up startTime and millis we will see a sequence like this:
millis ()   -  startTime    =  difference
                             (modulo 2^32)
4294917296     4294917296               0  <-- we start timing here
4294917297     4294917296               1
4294917298     4294917296               2
...
4294967295     4294917296           49999  <-- largest unsigned long value
         0     4294917296           50000  <-- wraps here back to zero
         1     4294917296           50001  <-- keeps counting up
...
      9999     4294917296           59999
     10000     4294917296           60000  <-- time's up!

Recommended method

Use unsigned long (not just long) for "time" variables.
Record the start time of some event (eg. a debounce, when you start feeding the fish, etc.)
Subtract the start time from the time now, giving a difference.
See if the difference exceeds the desired interval.

eg.
startedFeedingFish = millis ();

...

if (millis () - startedFeedingFish >= 20000)  // feed them for 20 seconds
  {
  // stop feeding the fish
  }

Can't I just reset millis?
You can, but you don't need to. Plus it may well throw out any library you are using that does not expect millis to be reset. Plus you have to decide exactly when to do it. It would need to be a time when you aren't using millis. For example if you happened to be feeding the fish in the above example, and your code reset millis, then the fish will get an awful lot of food!

What about micros?
The function micros() returns the number of microseconds since reset. This also wraps around, however since there are 1000 microseconds to a millisecond it will wrap around faster.
 2^32 / 1000 / 1000 / 60  = 71.58 minutes

http://arduino.cc/en/Reference/Micros
However you can use exactly the same technique to keep track of time to the microsecond interval. Be aware that you can't time more than 71.58 minutes this way though.
Also be aware that the resolution of micros() is four microseconds (because of the timer prescaler) so you won't ever be able to time a one or two microsecond interval.

Limitations
If you are using millis() you cannot time more than 49.71 days, and if you are using micros() you cannot time more than 71.58 minutes, without extra code to detect the wrap-around. For long intervals I suggest a real-time clock, since that would be more reliable during power failures, or when you replace batteries, etc.

Reference
This answer taken from my page http://www.gammon.com.au/millis


text:
Why am i getting "phantom" readings from a flowmeter?
I have 2 flowmeters hooked up to my arduino uno.  They're set to read beer volume as beer flows through them.  Everything is working great, except i'm getting phantom readings.  I have the arduino communicating w/ a raspberry pi over USB, and i set my python script on the pi to start logging when reads are taking place.  i'm getting reads of 1-3ml every 15-30 mins (with 1 fluke of 16ml).  i have 2 flowmeters connected, but only 1 is sending these pulses.
there is nothing coming out of the taps, and everything inside the kegerator is bone dry.  i don't know what to look for...

As is, this looks too vague to be answered.  Please edit your question to at least give  the model numbers of flowmeters.  Presumably they can jitter and/or lack hysteresis?  If the problem may be in code, then include a Minimal, Complete, and Verifiable example of code that exhibits the problem

Try swapping the meters, and see if the problem is with the meter (or keg), or the rest of the system.

It could be a dodgy earth connection.


text:
How To Read Serial Data With NodeMCU
I am trying to change leds status via serial port screen. Here is my code but it's not reading anything from serial port screen. I got leds on D1 and D2 pins.
void setup() {
pinMode(5,OUTPUT);
pinMode(4,OUTPUT);
Serial.begin(115200);

}

void loop() {
// put your main code here, to run repeatedly:
int point = Serial.read();
 if(point == 1)
{
digitalWrite(5,!5);
}
else if(point == 2)
{
 digitalWrite(4,!4);
}

}

!4 means 0 and so does !5

Your code isn't doing what you expect because of a few issues.  As echo_salik says you are only ever turning off the output pins.  If you want to toggle the values then its probably easiest to store the value in a bool and use that to control the LED.
I think - and I may be wrong - that you are pressing the one and two keys and expecting that to work.  When you press the 1 key Serial.read() will return 49 and 2 will return 50.  These are the ASCII values for the keys you are pressing.
Its advisable to test to see if there is any data available to read on the serial port.  read() will return -1 if there is no data.
void loop()
{
  if (Serial.available())
  {
    int point = Serial.read();
    switch (point)
    {
      case 1:
        digitalWrite(5,HIGH); // Not !5 use High and Low
        break;
      case 2:
        digitalWrite(4,HIGH);
        break;
      case 3:
        digitalWrite(5,LOW); // Not !5 use High and Low
        break;
      case 4:
        digitalWrite(5,LOW); // Not !5 use High and Low
        break;
    }  // End of switch
  }  // End of if
  delay(50);  // I have no idea why, but most programs of this sort have a delay in.  (Hope someone explains to me too)
}  // End of function

(A switch statement is a more efficient way of doing a number of if elses)
One thing you might want to consider is the values you are checking against.  Serial.read() is returning a value between -1 and 255.  It is not returning the key you pressed.  If you want to change it to work with keys then you can do it by changing the case statements that are checking integers case 1: to ones that are checking characters i.e. case '1':.

authors: ميثم الشهابي


text:
creating array using string name
I appreciate if someone can help me.
I have a function that counts the time and I would like to store values according to the day.
For example: day_7.11.2015 = [gain = 100.23, cost = 78.0 ...]
              day_8.11.2015 = ...
I do not know how can I create an array with these values taking as input the day, month and year. Does anyone have any idea?
String test = "day_" + String(day) + "." + String(month) + "." + String(year);
float String(test)[] = {11.2, 10, 20, 31.2};
 Serial.println(test);
Thanks a lot!

What is your end goal?  Is this an Arduino-related question?  Please edit question and state the general idea before obscure details.

What you're talking about is often called a Hash or a Map or sometimes both together as a HashMap.
Unfortunately it's a facility that isn't supported in the Arduino C++ language
There are map objects available in normal C++, but they are incredibly expensive to use with regards to memory and they just aren't practical for use on a small microcontroller with memory measured in the kilobytes.
The closest you can probably get is to "invert" the storage, so you have a list of values that happen to be in date order (because that's when you added them) but the "key", a simple sequential number, doesn't define the date.  Instead you store the date inside the array along with the data - assuming you really need to know the date.
A good concept to get to grips with for this is the struct.  This is a custom data type which you define and can store a number of other different data types within itself.  You can then make an array or linked list out of those new data types.
For instance, you may have:
typedef struct {
    int year;
    byte month;
    byte day;
    float gain;
    float cost;
} Data;

You can then create variables of type "Data" and assign values to the items within it:
Data myEntry;
myEntry.year = 2015;
myEntry.month = 11;
myEntry.day = 7;
myEntry.gain = 100.23;
myEntry.cost = 78.0;

Or assign them directly at creation time:
Data myEntry = {2015, 11, 7, 100.23, 78.0};

If you wanted to store 100 days' worth of data you could use an array:
Data myArray[100];

Then you access each slice:
myArray[0].year = 2015;
... etc ...

I mentioned above "assuming you really need to know the date".  Most of the time with this kind of method you really don't need to store the date.  If you have one entry per day and you know when you started gathering data then you know that each entry is one day more than the one before it - so you know that the tenth entry is ten days later than when you started gathering data.  Alternatively, if you have a 100 entry circular array (that is, when you reach the end of the array you start filling from the bottom again, so you keep the last 100 days' worth of data) and you know what the date is today you can count backwards from today to work out what date each entry is.

Hi Majenko,
I tried to solve the problem with structs, but I'm not sure how it works. I could not even run the examples I found on the internet.
Your example worked here. But I can not access the values that I want. How should I do if I want to access the value of the variable cost that I created? Is printing another value when I try   :|


text:
Arduino Due uploading error using Eclipse plugin "avrdude: stk500_recv(): programmer is not responding"
I have a Arduino Due that I'm trying to upload a sketch to. I follow the tutorial http://playground.arduino.cc/Code/Eclipse to get the board running with the Eclipse plugin.
However uploading the sketch gives me the error
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x03

If I use the Arduino IDE everthing works fine. I'm using Eclipse mars with Arduino 1.6.5
What could have gone wrong?

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

There's your clue.
1) programmer is not responding - This usually means the device isn't connected, or powered, or reachable by the IDE, make sure you have eclipse configured correctly for your device, and it's location.
2) not in sync - This is a redundant, or overlapping error, of course it's not going to sync if it can't connect.

The weird thing is if I press erase and reset on the Due before uploading the sketch it runs without any problems! I thought the Due has auto reset functionality?

I searched for a solution to this problem but it seems to be that I'm not the only one who struggles with that: https://forum.arduino.cc/index.php?topic=167492.0. They found some fix but these are a little bit ugly. I'm also worried about damaging my board if I press each time erase when uploading my sketch.

You are using the wrong upload tool.
The due is not using avr dude as upload tool.
You need to use bossac.
If you turn on verbose upload in the arduino ide preferences you will see
...arduino\tools\bossac\1.6.1-arduino/bossac.exe ...


text:
Uno pin 13 LED mysteriously always ON at 0.14V unless pinMode OUTPUT

I upload a blank sketch: pin 13 LED is on. Why?
I connect pin 13 to GND: it turns off until I remove the connection
I connect multimeter between pin 13 and GND: measures 0.14V and LED turns off until multimeter is removed
I press hard reset: LED blinks a few times, turns off for a second then turns on
I upload a sketch that on setup sets pinMode(13, INPUT): pin 13 LED is on
I upload a sketch that on setup sets pinMode(13, OUTPUT): pin 13 LED is off 0.01V
I upload a Blink example: Everything works fine, LED cycles from 4.84V to 0.01V

Why is the LED on unless I set pinMode to output? Have I broken my UNO or is this normal?
I swear it wasn't like this a few days ago.

The LED is driven by an op-amp (see the schematic). When the pin is configured as input the op-amp has an undefined input (floating input). Thus it may or may not turn on the LED. If you configure it to an output the op-amp is driven in a known way.

Why is the LED on unless I set pinMode to output? Have I broken my UNO or is this normal?

It's perfectly normal.

I think they did this to stop the LED "loading" the SCK pin (pin 13), particularly if you have it configured as an input and are trying to measure something, the 1k resistor and LED would throw out the measurement.
You could conceivably have a pull-down resistor from SCK to GND, but that would load the pin as well.

Nice answer - especially with the schematics

Apparently it's normal. Although random. Sometimes the default voltage of the pin is high enough to make the LED light up because of the op-amp. Sometimes it isn't.
Source: https://electronics.stackexchange.com/a/39707

If SCK is set as an input then pin 5 of the op amp goes high (pnp transistor input stage) and the op amp output goes high turning on the LED.


text:
Giving the impression of a dying device - making a vibrating motor slow down and stop
I'm trying to make a gag gift for a friend. The effect I'm trying to imitate is of a device that starts up for a moment and then putters out like something is wrong.
So I need it to:
1. Vibrate a motor for a second or two.
2. Make the vibration sputter out.
3. Light up an LED behind an error message on a paper screen.
I have very little hands on experience with anything electronic, but I have some programming and I took enough physics to know what a capacitor, etc is.
My questions are whether an Arduino is a good and cost effective way to accomplish this and is there any beginner friendly advice anyone can give me to get this accomplish

You can control the motor using PWM (Pulse Width Modulation) and make it run for full, then slowly decrease the speed till stop and after light up the led.
This tutorial from Adafruit could be a good start if you are not familiar with PWM and have also some good advices: https://learn.adafruit.com/adafruit-arduino-lesson-13-dc-motors/overview
Please be really careful about the supply source. Motors can easy draw more current then the limited available from the pins of arduino. Maybe a H-bridge could be helpfull here.(take a look at this for example of h-bridge: https://learn.adafruit.com/adafruit-raspberry-pi-lesson-9-controlling-a-dc-motor/lm293d )

If it's a smallish motor then the output pins should be able to handle it; I've driven a force feedback motor from a DualShock directly from an AVR before, with two PWM outputs acting as a H bridge.

@Personagem - Thank you for your response, particularly the warning. Based on what you've said, I think I need to figure out how large of a motor I need to vibrate a wooden box before I can determine if it would draw too much current...


text:
Can't read from DHT sensor when motor is running
I've been following this tutorial and I've run into some weird problems. When my motor starts running, I get "Failed to read from DHT sensor" on my serial window, meaning that readHumidity() and readTemperature() functions are returning NaNs.
This only happens while the motor is running. Once I stop the motor even momentarily, the DHT sensor starts working again.
Does anyone know why this is happening? I'm using a genuine UNO and a RHT03 sensor and some 5.9V motor (TD599839).
I've attached a diagram I made of my circuit in fritzing -

try to add a 100nF ceramic capacitor between the motor terminals.

And a flyback diode across the terminals, too - every little helps. On a different note, you are using a resistor with that LED, yes? I'll overlook the fact that it's the wrong way round in the schematic!

What is that capacitor doing there? Slow start?

First make sure that your motor has its own run back to ground - you must avoid motor current passing through the Arduino's ground.  Next, filtering your PWM is a bad idea - at a minimum it is inefficient.  You do not want to have your transistor "part way on" as that leads to conversion of power to heat in the transistor.  Instead, you want the transistor to only ever be fully on or off, applying full voltage to the motor at variable duty cycle. The inductance of the motor will cause some limitation of current, but the mechanical inertia of the rotor will accomplish the rest of the averaging.

Remove 10k resistor and use 1k instead. Or, just connect directly to Analog A0 pin. And modify your code. This may help you. Also consider GND to be 0V. Not below 1V instead while motor is working.

The problem may be electrical noise from the motor, or
you may have a wiring problem (an incorrect or intermittent connection).

Kira San’s comment “try to add a 100nF ceramic capacitor between the motor terminals” is directed toward suppressing electrical motor noise.  As brushes make or break connections on a motor's commutator, arcs and sparks can occur.  The capacitor will limit voltage rate of change thus suppressing some of that electrical noise.
CharlieHanson's comment (add a flyback diode across the motor terminals) is partly related to noise suppression but mostly to suppressing high voltage excursion that occurs when you shut off motor power.  While the motor is running, the magnetic field in it stores ½ L i² joules of power.  When current stops suddenly, those joules of power convert to a high voltage spike.  A flyback diode acts as a near-short to absorb that spike.  The cathode (cross-bar) of the flyback diode attaches to the high side of the motor voltage, as shown in the circuit diagram of the project you linked to on electroschematics.com.
Re “you are using a resistor with that LED, yes? I'll overlook the fact that it's the wrong way round in the schematic!”, if the LED is wired backwards as shown in your drawing, it won't turn on – which is a good thing, because without a resistor (say 300-3000 Ω) in series with the LED, enough current may flow to damage the Uno or the LED.  Turn the LED around on the schematic (and on your wiring setup if you didn't already), and add a series resistor.

Edit: A comment says, “Don't have a diode either :S Will an LED work instead?”.  LEDs typically have rather low reverse-voltage ratings – 4 to 5 volts.  You could put two or three in series and if they don't burn up you're ok for this experiment.  But in production, don't depend on LEDs as flyback diodes except where it doesn't matter what happens.

Gerben's comment, “What is that capacitor doing there? Slow start?” refers to the 100 μF capacitor shown between transistor base and emitter.  In conjunction with the 1KΩ resistor from D4, that gives RC=0.1 second, so the transistor will take an appreciable amount of time to turn on.  This has a couple of consequences:  PWM control may be less effective (at low duty cycles, PWM depends on short, high-current pulses, to overcome stiction etc) and the transistor will run hotter.  If it's a big power transistor, ok.  If it's a small switching transistor intended for full-on or full-off, no.

Edit: A comment refers to a fan speed controlled temperature page at electroschematics.com.  That page shows a BD139 power transistor, and says the 100 μF capacitor between transistor base and emitter eliminates some motor noise.  Thus it falls into the “big power transistor, ok” category.  Well, more or less ok.  A heat sink may be needed on the transistor and the capacitor probably doesn't need to be that big; eg try 10 μF instead of 100.

An ordinary 9V battery easily supplies a dozen milliamps, but current draw larger than that quickly depletes it.  See eg 9V Alkaline tests at powerstream.com and my answer to a previous question, Using Arduino Micro With 12V Buzzer that's somewhat related.  The motor shown (TD599839) is rated at 35 mA at 5.9 V no-load, so will draw say 50 mA no-load from a 9V battery and will try to draw several times that if loaded; ie it will overstress an ordinary 9V battery.  In brief: Use a wall-wart or equivalent, or a big battery, rather than a small 9V battery when running motors.

Sorry about that, didn't see that its backward in the schematic. I'm actually not using that LED in the actual project anyway, just playing around in fritzing. Thanks for pointing that out though.

I'm actually following another tutorial to control the motor speed -> http://www.electroschematics.com/9540/arduino-fan-speed-controlled-temperature/. Apparently its an RC filter to smooth out noise from the PWM.

Would it help if I changed the motor completely? Bought a less powerful one intended for hobbyists? Because the shop I bought the components from wasn't well stocked.

-> I'll try those out, but I don't have the necessary materials. 1. -> I only have 100uF capacitors, will those work? 2 -> Don't have a diode either :S Will an LED work instead? (or is that a totally crazy idea?)

@cybergla, see edits

In the long run if you are going to be in electronics I would suggest you learn how to draw schematics. KiCad is free and one of the better schematic capture programs available. It runs on most platforms. It will not be an overnight learning experience but there are lots of tutorials on line for it. If later you want to do simulation you will probably have to do a schematic anyway.


text:
Arduino OBD connection
I am using this code on a arduino nano and works fine.
#include <LiquidCrystal.h>

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);           // select the pins used on the LCD panel

#include <OBD2UART.h>

COBD obd;

void setup()
{

  // start communication with OBD-II UART adapter
  obd.begin();
  lcd.begin(16, 2);
  // initiate OBD-II connection until success
  while (!obd.init());
}

void loop()
{
  int value;
  obd.readPID(PID_RPM, value);
  int value2;
  obd.readPID(PID_COOLANT_TEMP, value2);
  lcd.setCursor(0,0);
  lcd.print("RPM = ");
  lcd.print(value);
  lcd.print("     ");
  lcd.setCursor(0,1);
  lcd.print("ECT = ");
  lcd.print(value2);
  lcd.print("     ");
    }

But if OBD is not connected, then it's get stuck in the setup.
What I want to do is to go over setup even if obd is not connected, and try connect to OBD meanwhile...something like display "Connecting..." on first row and count something on second...
Thank you in advance

The while() loop in setup() is what gets hung up. Instead of calling odb.init() until it returns true, just call it once just to get it initiated, then call/check in loop() and react accordingly:
void setup()
{
  // start communication with OBD-II UART adapter
  obd.begin();
  lcd.begin(16, 2);
  // initiate OBD-II connection once
  obd.init()
}

void loop()
{
  static int error_count;
  if (!obd.init()) {
    // Not connected
    lcd.setCursor(0,0);
    lcd.print("Connecting");
    lcd.setCursor(0,1);
    lcd.print("Count: ");
    lcd.print(error_count);
    error_count++;`
  } else {
    int value;
    int value2;

    obd.readPID(PID_RPM, value);
    obd.readPID(PID_COOLANT_TEMP, value2);
    lcd.setCursor(0,0);
    lcd.print("RPM = ");
    lcd.print(value);
    lcd.print("     ");
    lcd.setCursor(0,1);
    lcd.print("ECT = ");
    lcd.print(value2);
    lcd.print("     ");
  }
}

Thanks for the answer. Is working but seems there is a big timeout till it receive the status of the obd if is not init yet.


text:
Serial.print start prints unreadable character without any reason
I wrote the following code. The idea is to execute some AT command on my ESP-01 module. The problem is that first command is execute without problem, the second sometimes but the reply on AT+GMR is the following:
    AT
OK
AT+GMR

AT version:1.1/0.0(May 11 3016 18:09:57)
SDK version:1.5.ar.0
AR)�WS�TZ�j
C�j�L�AZCA�O�C�

FINE

The problem is that, after some thing that I don't understand, the formatting (maybe the baud change?) gone wrong. Then the reply of the following commands became unreadable. Any idea why it happens?
#include <SoftwareSerial.h>
#define DEBUG true
SoftwareSerial wifi(2,3);

void setup() {
   Serial.begin(115200);
   wifi.begin(115200);
   sendCommand("AT\r\n", 2000);
   sendCommand("AT+GMR\r\n",2000);
   sendCommand("AT+CWMODE=2\r\n", 2000);
   sendCommand("AT\r\n", 2000);
   Serial.print("\n\nFINE");
}

void loop() {}

String sendCommand(String cmd, int timeout){
   wifi.print(cmd);
   return readSerial(timeout);
 }

 String readSerial(int timeout){
   long int time = millis();
   String res = "";
   while( (time+timeout) > millis() ){
        while(wifi.available()){
          char c = wifi.read();
           res += c;
        }
    }
    if(DEBUG)
       Serial.print(res);

    return res;
 }

Looks like all that String usage is making mincemeat of your heap...

So I should do not use String? How can I manage string?

Arrays of char. Here is information on how: https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/

I tried to use a single array of char (http://pastebin.com/K6j5nzdD) but there is no effect on output that is always unreadable after some point.

The problem was about high baud for SoftwareSerial. Changing it to 9600 the problem disappears.

Take a look at the connections check the all the connections properly i also had the same problem


text:
how does a bluetooth on android works and what are the best alternative in saving data receive from bluetooth?
Can anyone confirm this for me although I have tested it myself but when I send a string of data from my android app and send it to arduino say for example data = bluetoothPort.read(); inside an if statement then when I try to use the data in another if statement for example Serial.print(data); inside another if statement it will only show a blank line which let me believe that none of the data are saved. also when a receiving a string of data for example a string of abcde and send it to arduino for example data = bluetoothport.read() and then Serial.print(data) the serial monitor shows abcde as expected but what really happens is data has the value of a then prints then replace by b then print then replace by c then print then replace by d then print then replace by e. Am I wrong or somehow right? are there any work around or parts I need that will make me store data as a whole so that I can use it for other thread or a better code to store string of data?
#include <IRremote.h>
#include <SoftwareSerial.h>

SoftwareSerial bluetoothPort(4,5);
const int RECV_PIN = 12;
const int SEND_PIN = 13;

IRsend irsend;
IRrecv irrecv(RECV_PIN);

decode_results results;
char data;

void setup()
{
   bluetoothPort.begin(9600);
   Serial.begin(9600);
   irrecv.enableIRIn();
}

void loop()
{
   if (bluetoothPort.available() > 0)
   {
       data = bluetoothPort.read(); //received bluetooth data from android
   }

   if(irrecv.decode(&results))
   {
       irreceived(); //received IR code from a remote then sends it to my android
       irsend.sendNEC(data, 32)
   }
 }

 void irreceived()
 {
     Serial.println(results.value, HEX);   //receive value of 489010
     bluetoothPort.println(results.value, HEX); //send value to android
     irrecv.resume();
 }

so the above is a simple sketch that receive data from a remote controller then send it to my android app then when I resend it back to my arduino I would like the data to be able to receive all the data instead of saving it per letter/number and also be able to store it for other statement to use.

Serial communications only consist of one character. That is what serial is - the sending of one character at a time.
How you then deal with those characters, combining them into strings, interpreting them as numbers, whatever, is completely up to you to program.
There is no such thing as a string in serial communications. There is only the character.
The Arduino API has a few (badly implemented IMHO) helper functions that can get a whole string (kinda), but it is much better (both from a learning perspective and an implementation perspective) to do it yourself.
I have a little tutorial here that may help you get to grips with it.

This works great for me at best even and I love it. I got one question though... I am developing a universal remote control Arduino paired with Android app and thanks to your help I was able to receive the code sent from a remote control and send to the android app and on a push of a button the Arduino received(thanks to your help) and sends using IR emitter... the usual way to send was irsend.sendNEC(0x40BFEA15, 32); but when I do this irsend.sendNEC(buffer, 32); the buffer has 0x40BFEA15 value it does not work? any idea or tips or work around on how to make it work?

You have a string, and you need a 32-bit unsigned integer. You need to parse the string and convert it to an integer. strtoul() may help you there.

Through trial and error I have manage to figure out that I need when I do this long number = 0x40BFEA15; then this irsend.sendNEC(number, 32) it works so the next question is... how do I convert the received Bluetooth data on a char bufferthat contains 0x40BFEA15 into a long that will retain the value ofbuffer`..? or is there other way to receive bluetooth data as a long instead of a char.? silly question but I know I am near to finish with this one.

I told you the function to use just now.

just did this long data = strtoul(buffer, NULL, 16); then Serial.print(val); and it gives me a combination of numbers so I did this Serial.print(val, HEX); and gives me 40BFEA15 and was expecting the result to be 0x40BFEA15, it omits the first two character :"0x" am I doing it wrong?

0x is an instruction to the compiler to say "The following numbers are hexadecimal". Internally everything is just binary. Even your 40BFEA15, which the Arduino Serial.print() function, when passed the HEX parameter, displays in a human readable format using hexadecimal notation.


text:
Control the ethernet shield with Chrome and Safari
I am trying to communicate with ethernet shield. When I enter the IP in Chrome the job is done (simply an LED turns off and on with IP/$1 and IP/$2) but with Safari it is not. Any idea what the difference is?

I had the same problem. I forgot to complete the client.println with a newline (\n).

Can you explain why this would happen? println should already insert two newlines—why do you need two?


text:
Building an adjustable low frequency PWM controller with Arduino
I am looking for a way to create an adjustable PWM controller capable of modulation frequency from 0-100 (more preferably 0-1000) Hz, duty cycle from 0-100%, and able to accept a voltage range of 5-30V DC. I have looked through Sparkfun and Adafruit for product or PWM shields capable of this and I have yet to find one. Some servo shields can be programmed down to 50Hz and arduino itself can be slowed to like 30Hz using timer0 and timer1 changes. However none of these options make it easy to vary frequency and none of them can accept much more than 6V.
I have searched far and wide and found a few interesting things:
1) http://www.instructables.com/id/The-ultimate-PWM-driver-for-many-applications/
 This instructable shows an analog un-sensored PWM driver. It would get the job done here however, I need a way to read my Frequency and Duty Cycle

2) https://www.electronicsblog.net/arduino-frequency-counterduty-cycle-meter/

Here there is a way using pulsein() and other arduino functions to read both frequency and duty cycle as seen above. But then this is also assuming you're PWM voltage is 5V. So maybe you use a 5V regulator on the signal into the arduino? Would something that simple work or would it skew the signal and prevent accurate measurements?
Obviously, if anyone has a better idea I'm open to it. I've been searching for a solution for some time. The trouble really seems to be the low frequency PWM request.

The ATmega328 in the Arduino Uno has a 16-bit timer (Timer/Counter 1) which can do PWM. It has a prescaler that can divide by 1024.  The lowest frequency that it can generate is about 0.12 Hz:
16MHz / 1024 / 65535 / 2 = 0.1192 Hz

We change the PWM frequency by changing the "top" value. For higher frequencies, lower the top value, and/or pick a smaller prescaler.
(And, really, what does 0 Hz PWM even mean?!? :-)
The duty cycle can vary from 0-100%, with the resolution changing with the specific frequency you generate.
As for the high-voltage... use a motor driver, or darlington, or hexfet, or whatever...
I'm confused as to why you're reading the frequency. With the 16MHz crystal, you set it and you get what you asked for (within the crystal tolerances, temperature, etc.)
At least, that's how I think it works.
Good luck!

So for 440Hz at 25% on pins 9&10, you might choose a fast PWM with Wave Generation Mode 14, 16e6 /1/440 = 36363 TOP with /1 prescaling, so: ICR1=36363 ; TCCR1A=0b10100010; TCCR1B=0b00011001; TCCR1C=0; OCR1A=36363/4

The PWM Waveform Generation Modes with a settable TOP value (e.g. set with the OCR1A or ICR1) are the ones that can achieve these low, adjustable frequencies. Set the Waveform Generation Mode mode and prescaler with the TCCR1* registers and then the duty cycles would be modified by adjusting OCR?B. For frequencies below the threshhold the timers can handle, one could switch over to toggling based on elapsed millis() and handle frequencies down to 1 cycle per 50 days.

@Mike I appreciate the help. However I truly intend on the PWM frequency to be variable. And yes 0Hz is improper but my point is to make it very low. Using prescale factor like shown in this link you can only reach 30Hz using prescale factors. If you also modulate your TOP values I suppose you get any 16-bit value from 1-65535 in resolution. The 2 indicate difference between the two outputs?? link

@Mike  Either way this looks like I'll be able to modulate frequency easy enough...Now just the high voltage. I'll have to think more about that. But I definitely think you solved my frequency problem.

Your question is so close to my own project, for a second I thought it was something I posted awhile back, go figure.   I don't expect you to gain from my answer, me coming along to find your question some 2 years, 5 months later. It may be of help to others who pass by this way in the future. I am currently working on the exact same variable duty cycle controller and will offer up my findings.
The following programming code is the result of apx. 5 months of study into the Arduino programming as well as a long failing attempt at getting control through a series of 555 timer chip builds. I shit canned the 555 timer chip & Darlington transistor method. I thought it was too crude, and all 'engineering' schematics never allowed me to have anything more than a 50% duty cycle control. I wanted control over all PWM variables. Today I will be purchasing a metal case, or making one that can hold apx. 5-6 potentiometers allowing me to adjust every possible variable within the PWM domain of parameters (there are more variables than what I have in this code below). I will give you some details in the code first, that will give you some idea of the obsessively precise control I'm demanding from my PWM project:
Getting into the heart of the variable HIGH/LOW control. Be sure to read everything you can to understand fully why these functions are needed. Also, know that with 10 bits the 1023 value allows a resolution of .0043 volt increments (really nice):
void loop()
{
Potentiometer1 = analogRead(PotHzHIGH);
Potentiometer1 = map(Potentiometer1, 0, 1023, 1023, 0);
Potentiometer1 = constrain(Potentiometer1, 500, 1023);

Potentiometer2 = analogRead(PotHzLOW);
Potentiometer2 = map(Potentiometer2, 0, 1023, 1023, 0);
Potentiometer2 = constrain(Potentiometer2, 500, 1023);

Potentiometer3 = analogRead(Pot5Volts);
Potentiometer3 = map(Potentiometer3, 0, 1023, 1023, 1023); //Hold at 12Volts
Potentiometer3 = constrain(Potentiometer3, 0, 1023);
//Potentiometer3 can either be locked at 12volts with the map function, or
//you can use a Potentiometer to varry the voltage. I illistrate the
//constant at 12 volts with the map function - low/high both set to
//1023 & 1023

digitalWrite(PotHzHIGH, HIGH);
//turn it ON delayMicroseconds(PotHzHIGH);
//Keep ON for Potentiometer1=PotHzHIGH Microseconds
//1000 microseconds = 1millisecond; 1000ms = 1second

digitalWrite(PotHzLOW, LOW);
//turn it OFF delayMicroseconds(PotHzLOW); //Keep OFF for
Potentiometer2=PotHzLOW Microseconds
//1000 microseconds = 1millisecond; 1000ms = 1second;
//Largest value within the delayMicroseconds function: 16383microseconds
//Largest value when converted to milliseconds is 16.383ms, or axp. 1/20th of
//...a second

}
//other things to understand about the above program. It is possible to
//have the LOW written with: delayMicroseconds(PotHzLOW+100);
//or delayMicroseconds(PotHzLOW*1.1);
//You can add an additional potentiometer to be the multiplier of the LOW.
//these added controls prevent the LOW from ever being less than the high.
//this can come in handy if you wish to work within duty cycles that are
//between 1% & 50%. It is of interest to me because I am dealing with
//high frequencies.

timkasey1@gmail.com


text:
how can I combine two 2 digit 7 segment display to a single arduino uno
One of the two digit 7segment display will read its values from a smoke sensor while the other will read its values from a temperature sensor. From what I have seen in textbooks recently;each segment display will make use of ten digital pins(7 segments, decimal point, display faces(correct me if I'm wrong Pls)).

You could connect the segments of the two displays to the same Arduino pins, so you only need two additional pins for the second display. You then multiplex over the four digits instead of the previous two.

You are correct about the 10 pins, shift register are probably the way to go for you. They are very cheap and pretty simple to use.
Try googling 74hc595. It basicly turns 3 pins into 8, and you can even Daisy chain the chips to get 16, 24, 32 and so on from the 3 pins on the arduino.
Good luck to you.

This is one way to do it, but you can do it without any extra hardware, as explained in the question/answer I linked to.

Well that's a brilliant solution! I suggest trying marks link before my solution.