text:
Xbee S2 API Data Packets dropping out
I made a setup which consists of 3 Zigbee's, 2 routers(Zigbee S2C's) and 1 coordinator(Zigbee S2). The routers are each connected to arduino nano which collects data from 2 FSR's and an IMU(frame type: zigbee transmit request and packet size 46 bytes) and sends it to the Coordinator attached to an arduino UNO. All the Xbees are in API mode 2 and working at a baud rate of 115200. I am using a library called "Simple Zigbee Library" to send all the collected data to the Coordinator. The collection and sending of data works fine except that there are packets lost in the way. The nano's sample data at a frequency of around 25Hz independently. The coordinator tries to read the data send from the zigbees(using the library of course) in every loop, but unfortunately, it seems to receive only around 40-45 samples.(Should have been 25*2=50 samples total from the 2 xbees). Can anybody suggest why this is happening. I need as less data loss as possible for my setup to achieve its motive. Any kind of help is appreciated.
P.S: It may be important to mention that the coordinator is reading the data only from one xbee in each loop.
[[As can be seen from the "Source" heading in this image of data received by the coordinator, "19" and "106" are addresses of the routers. Data drop is intermittent]]1
    void setup()
{
// Start the serial ports ...
Serial.begin( 9600 );
while( !Serial ){;}  // Wait for serial port (for Leonardo only).
xbeeSerial.begin( 9600 );
// ... and set the serial port for the XBee radio.
xbee.setSerial( xbeeSerial );
// Set a non-zero frame id to receive Status packets.
xbee.setAcknowledgement(true);
}

void loop()
{
// Each SimpleZigBeeRadio instance contains two
// SimpleZigBeePacket instances, one for storing incoming
// messages and one for preparing outgoing messages.
// This example will not send any messages to the network.
// Rather, the coordinator will receive messages and display
// the contents to the hardware serial port.

// While data is waiting in the XBee serial port ...
while( xbee.available() )
{
// ... read the data.
xbee.read();
// If a complete message is available, display the contents
if( xbee.isComplete() ){
Serial.print("\nIncoming Message: ");
printPacket( xbee.getIncomingPacketObject() );

}
}

delay(10); // Small delay for stability
// That's it! The coordinator is ready to go.
}

 // Function for printing the complete contents of a packet //

void printPacket(SimpleZigBeePacket & p)
{
Serial.print( START, HEX );
Serial.print(' ');
Serial.print( p.getLengthMSB(), HEX );
Serial.print(' ');
Serial.print( p.getLengthLSB(), HEX );
Serial.print(' ');
// Frame Type and Frame ID are stored in Frame Data
uint8_t checksum = 0;
for( int i=0; i<p.getFrameLength(); i++){
Serial.print( p.getFrameData(i), HEX );
Serial.print(' ');
checksum += p.getFrameData(i);
}
// Calculate checksum based on summation of frame bytes
checksum = 0xff - checksum;
Serial.print(checksum, HEX );
Serial.println();
}

If transmits aren't coordinated, perhaps CCA,  clear channel assessment, is wasting a bunch of time.  Perhaps have a transmit order, perhaps assign time slots?

I believe using the Xbee in API mode is supposed to take care of that. The routers are getting Acknowledgements from the Coordinator for most of the packets. The packets not acknowledged are getting dropped. I tried to decrease the frame size ,reduce the payload and remove all delays, still the data drop is present. Any kind of help is appreciated.

What happens if you turn off one router and let the other send as fast as it can?  Ie what throughput does it get, does it drop packets, etc

On working just with 1 router, I am not getting packets dropped. The nano is sending  25  packets and all of them are getting received by the UNO.

But try upping the rate of that one router (eg to 30, 40, 50, 60, 70... per second) and see how fast you can run without dropouts.  For example, if it runs ok at 60 or 70 samples/second through 1 router but only 40-45 with 2 then some interference between the two routers might be involved


text:
Arduino based SPI programming of LT1257 not working
I am trying to talk to an LT1257 using an Arduino Nano Atmega328. I am not using the default slave select pin. I am using pin 5 as chip select for the DAC. The LT1257 data sheet shows this timing diagram. What I inferred from this diagram is that SCLK can be used to clock in the data and it remains in the shift register and is loaded into the DAC register only when Load is pulled low.

I wrote this snippet to load a 0x0000 to the DAC. However, when I probe the output voltage it is ~1.02V. The DAC uses an internal reference of 2.048V. So I think this must be the default 1/2*FS output when the DAC powers on.
Please review my code and point the errors. (At the DAC output I have a 1k resistor connected to ground).
#include<SPI.h>
#define SCLK 13
#define MISO 12
#define MOSI 11
#define DAC_LOAD 5

#define DAC_SPI_CLOCK_SPEED 1000000 //Upto 1.4MHz

void setup()
{
Serial.begin(9600);
init();
SPI.begin();
dac_write();
}

void init()
{
pinMode(SCLK, OUTPUT);
pinMode(MOSI, OUTPUT);
pinMode(MISO, INPUT);
pinMode(DAC_LOAD, OUTPUT);
digitalWrite(SCLK, HIGH);
digitalWrite(MOSI, HIGH);
digitalWrite(DAC_LOAD, HIGH);
}

void dac_write()
{
SPI.beginTransaction(SPISettings(DAC_SPI_CLOCK_SPEED, MSBFIRST, SPI_MODE0));
delay(10);
SPI.transfer(0x0000);
delay(10);
digitalWrite(DAC_LOAD, LOW);
delay(10);
digitalWrite(DAC_LOAD, HIGH);
delay(10);
SPI.endTransaction();
}

void loop()
{
while(1)
{
Serial.println("Ping!");
delay(1000);
}
}

Notice that SPI.transfer() transfers one byte (8 bits) only, not 12 as you'd want.

I tried SPI.transfer16() too and that didn't work either.

Probably unrelated, but: From the diagram, the clock seems to be idle high => SPI mode 3. Also, what is MISO connected to? If nothing, use or enable a pull-up or -down on that input.

Plus: Apparently !LOAD must be asserted during the last falling edge of the clock line, see t6 and t7. You'll have a hard time trying that with the hardware SPI. You probably have to go with software bit-banging.

I read the LT1257 data-sheet more carefully. There is a pull down nmos at the output of the DAC. So when uninitialized, the output of LT1257 should be ~0V. So the output I was measuring (~1.02V) is spurious. I suspect I damaged the IC. I tried the same code on a different LT1257 and it worked. I can confirm now that this code is working.

For a master to select an SPI slave to transmit data to it [the slave], the Slave Select pin is held low.

Do you see any reference to the SS signal in the timing diagram?

OK. The OP refered to an SPI device with slave select pin and I assumed a standard 4 wire SPI device. The datasheet refers to the protocol as '3 wire cascadable serial'.  Anyway, here is description of an apparently successful attempt to interface an LT1257 to an Arduino link

source: Stack Exchange

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

sort: votes


text:
Input Capture Pin Atmel ATmega328P
I have some code that relies on the input capture timer value.
I assume the timer value (as defined by the pre-scaler etc) is not affected by other code running i.e. it is updated every nth clock regardless of what instruction is next?
If you want code or more detail ask in comments and I will post code.

The way IC typically works is completely independent from the CPU and what instructions you are running.
The timer runs freely between the start and end input capture events. At the moment of capture the timer value is frozen into another register. The interrupt is then triggered. You then read that frozen value. It doesn't matter how long after the end event the interrupt executes, or what you do in that interrupt, the captured time is still the same.

Hello @Majenko - thanksfor answer. A quick one though. What happens if during the interrupt the interrupt is fired again faster than the code can run i.e. still responding to the interrupt when interrupt is fired again? I assume it is over-written and we have a loss of data?

The interrupt cannot trigger while it is current triggered. The CPU disables interrupts when it enters an interrupt and enables them afterwards. Any events that occur while the interrupt is running will be ignored.

I assume the timer value (as defined by the pre-scaler etc) is not affected by other code running i.e. it is updated every nth clock regardless of what instruction is next?

yes, unless your code writes to the registers involved.

Aren't there any higher priority Interrupts?  They would certainly affect the timer register

@cyberponk No, registering input capture time works via dedicated hardware, idependent of what the CPU is doing.

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


text:
X and Y axis on Arduino Serial Plotter?
I am trying to plot my counter vs. time on the serial plotter, but the values on the y axis are so big there is no way that it's displaying the counter values.
I have printed both values:
  Serial.print("counter: ");
  Serial.println(counter);
  time = millis();
  Serial.print("Time: ");
  Serial.println(time);

I expected time to show up in the x-axis, but I think it's displaying on the y-axis and I'm not sure how to change this.
The plot should just be an increasing line as the counter and time get bigger...
what am I missing?
Thanks.
Slashing out the Serial.print("Time:") does not correct anything.

Inorder to plot multiple variables or waveforms simultaneously a 'space' is printed between the two print statements.
Serial.print(counter);
Serial.print(" ");
time = millis();
Serial.println(time);

OR
Serial.print(counter);
Serial.print("\t");
time = millis();
Serial.println(time);

Comment out the Serial.print("Time: "); line. The Arduino serial plotter wants only numbers.

The X-axis is fixed and nothing gets plotted on the X-axis. It has its own divisions and they are automatically set by the Arduino IDE. The Arduino IDE still has to do some improvements to its software so that the X- axis can be adjusted and plotted too! This is my experience so far and corrections are welcome!

To plot multiple values over time you need to output just the numbers on a single line per iteration, and delimit with a space or tab:
Serial.print(counter);
Serial.print("\t"); // delimit with tab
time = millis();
Serial.print(time);
Serial.println();

It's worth noting however, the time (x axis) is implied by each line. In essence each line of output advances "time" by 1 unit. So I suspect you'll want to remove the time variable output and just output the count variable by it self.

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


text:
Brownout with Arduino Nano

I'm making an RC car with the Arduino Nano. I'm using RF433 as  wireless communication with 2 motors and L293D as the motor driver. I use 4 1.5V batteries to power the Arduin and another 6V battery pack to power the motors, and a joystick with an Arduino Mega to send commands through the RF433 to the Arduino Nano.
I've written a program that sends specific digits when the joystick is in a certain position, i.e. when the joystick is "bent" to the front it sends a "1", a "2" is sent when the joystick is bent towards the back, and so on.
My problem is this:
When I bend the joystick towards a certain direction, the RC car moves accordingly without problem; However, when I bend the joystick towards another direction the RC car doesn't respond.
I took a look at what the RC car was receiving, and I've noticed that after the first command was sent (when I bend the joystick towards a certain direction), no more commands get to the RC car (in other words the Arduino Nano), and this occurs occasionally. I think this means the Arduino Nano "froze" after the first command.

Does the problem occur or not occur when you unhook power to the motors?

@jwpat7 Sorry, but what do you mean by "unhook power to the motors"? If I unhook the batteries powering the motors, It'll stop rotating in the first place, no?

You can run tests with an LED+resistor in place of each motor.  The idea is to have a low-current non-inductive load in place of the motors.  If problem still occurs, look for wiring or software errors.  If it doesn't, look for battery supply problem or electrical noise problem.

@jwpat7 Ok. I'll look into that and comment if things go awry again. Thanks for the help.

Nice drawing, bub.

You have at least three problems here:
1) First and most critically, a nominal 6v pack does not meet the input voltage requirements of the regulator used an Arduino even before it gets loaded down by a motor, and it only gets worse under load
2) L293/L297 and similar bipolar bridges have absurdly high internal losses, so are unsuited to low voltage systems - effectively one of your cells goes just to feeding the wasteful driver chip.  Use a modern and efficient FET driver like a TB6612FNG, or else add another cell to the pack.
3) The 433 MHz RF modules are notoriously low fidelity, and in many places not permitted for the control of RC models anyway.  You'll have much better results with the sophisticated digital radio modules sold at comparable prices for 2.4 GHz, which are incidentally the functional equivelent of what most RC toys now use (and actually in many cases can be made interoperable with them).
Granted, you may well have other issues as well, such as errors in your software.


text:
Why does my code or Serial Monitor hang with analogRead?
I have the following code in loop() to collect values from an electret microphone
for(int i=0; i<sampleSize; i++){
  analogVal[i]= analogRead(ADC_Pin);
  sumOfSquares= sumOfSquares+sq(analogVal[i]);
}
Serial.print("Sum of squares: ");
Serial.print(sumOfSquares);

where sampleSize is an int variable, I've tried numbers from 3 to 1000, which is my desired value. ADC_Pin is an int variable set to be A1 and has been properly initialized through pinMode. analogVal is an int array of size sampleSize.
My circuit appears to be fine because the output produces a reasonable amount of voltage. I've tried eliminating the line with sumOfSquares and just having the first line in the for loop. However, the Serial Monitor hangs and does not display any values. The serial communication is at 9600 bps.

You claim  “the Serial Monitor hangs and does not display any values” even though the code doesn't have any references to Serial output!  Obviously that's the problem! ¶ Please edit your question to include a Minimal, Complete, and Verifiable example of code, not just snippets.

I've added the serial prints that immediately follow the for loop. It does not matter whether the Serial.print is inside or outside the for loop. The serial monitor does not show anything.

Now the obvious problem is that you didn't say Serial.begin(115200); [or whatever the data rate is that you have your serial monitor set at] ¶ Anyway, I don't know what the problem is, and if you don't edit your question to include a Minimal, Complete, and Verifiable example of code -- with visible definitions of every variable used, etc -- perhaps nobody else will be able to tell either.

Yes, MCVE please. There's nothing wrong with the code in your question which would result in this particular problem. (There's another problem but never mind that for now.) The problem is with code you haven't shown.

What is analogVal? What is sumOfSquares? What is the sq() function? In short: DO NOT POST SNIPPETS LIKE THIS - POST A COMPLETE PROGRAM SO WE CAN SEE THE ENTIRE PROGRAM AND VARIABLE DECLARATIONS.

Arduino UNO have 2K RAM (many other too). That is 2048 bytes of RAM.
I suppose, that analogVals[] is declared as int and having 1000 entries it takes 2000 bytes of RAM, leaving wholesome 48 bytes for all your others variables (including int i in the for cycle and Serial outside it) and stack for calling functions (like analogRead and sq) and all theirs variables and functions and arguments.
So int i = 2B, Serial = 2B, sumOfSquares = 2B, "Sum of squares: " = 17B of what I see takes anothe 23 bytes of those 48 bytes leaving us with only 25 bytes for all else.
I bet, that you try to use more REAM, than you have and so your stack overflows and

destroys some variable content on the vay
is overwriten by assigning to some variables, which then leads to all sort of problems.


text:
Power bank turns off spontaneously
I currently have a 50,000 mAH USB power bank powering my Arduino Uno and micro servomotor. Unfortunately, my power bank has an automatic shutoff and shuts off after 2 hrs of runtime (I need 16 hrs for my project). I can restart the power bank by hitting the on button and it will run just fine for another 1-2 hrs at which point it will shut off. In one instance, the power bank ran for the desired 16 hrs straight hours. I believe that my arduino/servo are very close to the current threshold of the bank which could explain some of the variability I am seeing in terms of turn-off time. Would hooking up a resistor in the circuit do the trick and if so where?
Not quite sure about the brand of power bank (just one I found off Ebay). I believe the arduino uno and servo consume about 60 mA for power.

This might be too vague to answer.  Perhaps  edit question to specify brand and model of  power bank and tell how much current is drawn on average by Uno and servo.

50,000 mAH for a USB power bank sounds extremely well specified. Some powerbanks shut off after detecting a period of low current consumption. There are tricks to periodically shunt a low value resistor across it, say with a timer, to create sufficient load to keep the powerbank 'alive'. A powerbank I have (much smaller than yours) requires a 47 Ohm resistor shunted across it every 2 seconds for 20 mS to suppress its auto shutoff.

I have a "50000mAh" power bank. By my estimation, and looking at what could actually physically fit in (I haven't torn it down yet), you can expect 8 18650 batteries at no more than 3600mAh each, totalling 28800mAh - probably less, since cheaper batteries used in cheap power banks have less capacity than the top of the range expensive ones.

once it shuts down automatically, how do you turn it back on? if it's by replugging, you can simulate that electronically with a relay or mosfet.

@Majenko. Big Clive (https://www.youtube.com/user/bigclivedotcom/videos) is guy devoted to tear down and review all kind of cheap chinese products like power banks, LED's and chargers. After watching his videos, I will never buy another chinese "consumer" products like those.

@LookAlterno Yes I know, I subscribe to the bear's channel already. Chinese stuff is fine if you know what to look out for and what pitfalls to expect. Rule 1: ignore the quoted specifications. Rule 2: Buy one and dismantle it to find out exactly what it is. Rule 3: tell others.

@LookAlterno Btw, the power bank to which I refer I actually find really good. It's about 6200mAh and works really nicely. I have had to reattach some of the USB sockets to the circuit board where I have broken them off, but apart from that it's really nice.

This is not a recommendation! This is just my own observation.
I found that this type of cheap power banks works great with low current applications like powering an Arduino UNO: https://www.aliexpress.com/item/32845722067.html

You have a couple of options, depending on how much you want to dive into electronics.

Find/buy a new powerbank that does not auto-shutoff
Find the current-sense resistor on the internal circuitry of your existing powerbank and change it out so that the device always thinks there is current flowing, or is more sensitive to your low-draw attachment. I was able to find a few websites describing this for specific powerbanks by searching.
Add a dummy load in parallel with your circuit, which wastes power, but does trick the powerbank into staying on.

It's also worth noting on the side, that you very likely do not have 50,000 mAh capacity in this powerbank, as others have noted. However, you ought to be able to get 16h of runtime with even a lower-rated powerbank if your claim of 60mA current draw is true.

Thank you jose! Yes, I am very skeptical about the "50,000 mAh" but suffice it to say I have never completely drained the power bank so it is likely in the five digit range.

Generally the mAh number they quote is the internal battery capacity. They have to step that up from 3.7 V (nominal) to 5V and will be using the cheapest possible supply to do that because they can without impacting the numbers on the spec. Which means you'll be looking at about 60-65% of the headline number in terms of mAh delivered to the USB output.

@Andrew: i would think a fixed-output boost converter would be more efficient than 60%; even adjustable ones (not optimized) are typically >80% worst-case. The fact that the case is not 35% as hot as the watts out says so too...

@dandavis I was assuming about 85% for the power supply. The rest is the inherent current capacity loss when converting voltages. 1000 mAh at 3.7 V = 740 mAh at 5 V assuming 100% efficiency.

@Andrew: true. you also can't get more than 80% or so out of the cell; buyer beware.

I can't see this helping.
It could only help if your power bank switched off its output when the current  drawn dropped too low - but unless your  circuit's current consumption drops after two hours, which you don't mention, that is unlikely to be the reason it's switching off.

Thanks Mark! I cannot say for certain whether or not my current consumption decreases with time. The powerbank sometimes will shut off 15 min after it has been turned. And in some lucky cases stays on for 16 hrs straight. I believe that whatever current threshold my powerbank has my servo/arduino are right at the tipping point.

Expanding @jose can u c first suggestion I did a little research and found that Voltaic Systems sells power banks with an option to disable auto-shutoff mode. There may be others. I found two of their power banks offered on Amazon. The blurb in the Amazon listing explicitly mentions using it with Arduino and Raspberry Pi.

As the company Voltaic has been mentioned I feel that it would be helpful if I warned you of that company. We are after all trying to offer solutions and if you follow the advice of the person who suggested Voltaic then I know from first hand experience that the thing turns itself off even when the auto shutdown mode is disabled. Though this may not be an end solution I know that by helping you to avoid useless information I can keep you on track and help you towards your solution. In detail : I'm a chauffeur and I bought a Voltaic for this specific reason and guess what? It switches off even when auto shutoff mode is disabled. I wanted my customers to be able to charge their devices as quick as poss and with as little complication as poss. I'm thinkin bout puttin a led fibre optic charging cable in so there is always a tiny power usage from the LED near the big USB jack. At least then also the cable wld be more 'look at me, look at me' I'm thinkin the problem comes either from an auto time out or from the completion of the charging of the power bank which is itself on a dribble charge from the car's electrics.

Look into the OmniCharge for that: https://www.omnicharge.co/ It won't let you down. You could even feed a SLA battery with this device if it's drained and can't start your car.

Could you please clarify a bit more how this would solve asker's problem?


text:
ADC with better performance
I need to sample voltage at a very high rate (say for like 10000 Hz) and with a very good precision(at least 10-12 bit ADC will do). So I am in need of an Analog-to-Digital Converter(ADC) which has a very high sampling rate (sampling rate has to be constant and known), can be interfaced with Arduino Mega or Raspberry Pi and noise should be neligible to minimum level of voltage magnitude that it can count. Can anyone suggests me with any ADC that follows these characteristics?

You mean like an external ADC chip?  What about a TeensyLC or Teensy3.6 instead?  About 100KHz 12-bit ADC, if that's accurate enough.  You could edit your question and say what "very good precision" actually means.

Define "very good precision". Define "high sampling rate". Define "negligible noise". What is the maximum voltage you need to measure? Your idea of "very good precision" and mine might vary by a considerable amount. You know that the chip vendors (like DigiKey) have search parameters that let you type in the things you want and it returns the chips that meet those requirements?

What are you planning to do with these figures? At 10000 samples per second, where are you going to store them? RAM? Disk? If in RAM you will soon run out of RAM on most microcontrollers after a second or so. If on disk, the speed of writing to disk will slow you down. So another question is: How many samples are you planning to capture?

I am trying to calculate total harmonic distortion of line voltage. I've already tried with Arduino Mega. I can store 3200 number of sample data into it's storage. The ADC captures data for like only 0.4 second but that's sufficient for me. The problem is, Arduinos ADC sampling rate can't be easlity determined and it adds some noise to obtained data I guess.Besides Arduino can't transmit data over serial port at a fast rate.

So now I'm thingking of using another ADC and interfacing it directly with Raspberry Pi and transmit sampled data directly to the Pi(if possible). Maximum volatge doesn't matter beacuse I'll have it stepped down and shifted within ADC voltage range.@NickGammon

If you change the prescaler you can get something like 76000 conversions per second on the AVR chip at (slightly less than) 10 bit resolution. See http://www.gammon.com.au/adc

The problem is,  using Ann external ADC solves none of those problems for you.

ADS7835 from Texas Instrument.

can be interfaced with Arduino Mega or Raspberry Pi

It is interfaced through SPI, 12 bit data, and up to 500kHz throughput rate.

I need to sample voltage at a very high rate (say for like 10000 Hz) and with a very good precision(at least 10-12 bit ADC will do).

10Ksps and 12bit-resolution adcs are fairly common for onboard ADC. you should be able to find lots of mcus that have adc modules that can do that.
even for an external adc, that's not difficult at all. because of the speed, you are likely looking at a spi adc module.
precision is another matter.


text:
SIM808 module restarting repeatedly
I have bought SIM808 module, everything working fine. All AT commands are giving expected response, i'm accessing it through hyperterminal. My problem is that whenever i make or receive a call or SMS , GSM gets restarting.(I can able to make/receive call, getting ring/alert for small period of time and then interrupt). But there is no Under or Lower voltage power down or warning.
I have tried with DC power supply of 5V/500mA , 5V/1A and 5V/2A.  What might be the reason ? Please help.
extra info : It has one LM2576S voltage regulator in-built.

Check the datasheet and I think you will find you need 3 amps peak.  It requires this peak current when you make a call or send a text/sms.
Use a 5A power supply and that should solve the problem.
I have never tried it but "super capacitors" might work, providing the extra power when its needed, it depends how long you need the 3A for.

Thanks Matt for reply. I dnt have datasheet for that module. Bt according to SIM808 datasheet, it's peak current is 2A and voltage is 3.4 to 4.4. so i dnt know for module, how much input should be given

does the module withstand with 5A current ? @Matt

I got the solution for my problem. With 12V-1.5A power supply, it works fine.

I too faced the same problem and solved it.
Just use a 3.3V logic converter or a 3.3V interface, as the 5V causes the device to restart.


text:
Need help with my project
Can anyone give me the full code of my project because my code is not working?
My aim is that when the Z axis of an accelerometer is below 370 and a pushbutton connected to a pin 2 becomes high, then pin 13 turns high and remains high.  When the Z axis is above 370 and pushbutton is high then the pin 13 goes low and remains low.
P.S I am also a noob to Arduino
Here is my code :
const int ledPin = 13;
const int threshold = 370;
const int pull_up_resistor = 12;
const int pull_down_resistor = 11;
const int groundpin = A1;
const int powerpin = A5;
const int xpin = A2;
const int ypin = A3;
const int zpin = A4;

int pushButton = 2;

void setup() {

  pinMode(ledPin, OUTPUT);

  Serial.begin(9600);

  Serial.begin(9600);

  pinMode(pushButton, INPUT);
  digitalWrite(pushButton, HIGH);
  Serial.begin(9600);

  pinMode(groundpin, OUTPUT);
  pinMode(powerpin, OUTPUT);
  digitalWrite(groundpin, LOW);
  digitalWrite(powerpin, HIGH);
}

void loop() {

  int buttonState = digitalRead(pushButton);

  Serial.println(buttonState);
  delay(100);        // delay in between reads for stability

  Serial.print(analogRead(xpin));

  Serial.print("\t");
  delay(100);
  Serial.print(analogRead(ypin));

  Serial.print("\t");
  delay(100);
  Serial.print(analogRead(zpin));
  Serial.println();

  delay(100);

  if (buttonState = 0) {
    digitalWrite( ledPin, HIGH);
  }
  if (buttonState = 1) {
    digitalWrite (pushButton, LOW);
  }

}

You can format your code nicely in the Arduino IDE before pasting it here. This is clearly wrong: if (buttonState = 1). You need a double equals.

I got bored after the 400th word of the first sentence OK ...

... and I think you forgot to take your Ritalin this morning ...

You also seem to be a noob at English. How about re-writting the question so that it makes more sense and doesn't stop mid sentence. Obvious errors - = in place of ==, you never set ledPin low, you are writing to your button input, you initalize the serial port 3 times. And seeing digital outputs called powerpin and goundpin make me worry that you've made some very bad mistakes wiring things up.

Use some formatter before posting it here. For example here is great one, written by KrzaQ edit: didn't noticed that was fixed by Mark
Next thing to do is keep your code clean. Three times you initialized Serial communcation. Why?
You should also first initalize Serial then set pinModes into state and then put digitalWrite. It helps reading the code.
Example:
Serial.begin(value);
pinMode(x,x);
pinMode(y,x);
pinMode(z,x);
digitalWrite(x,x);
digitalWrite(y,x);
digitalWrite(z,x);

More readable, isn't it?
Next step: Pull-up and pull-down resistors... It is not thing you need to set in your code. It is hardware connection of 1 resistor, sometimes capacitor and device. There is no use for it in your device.
Read about them here: Pull-up/pull-down
Next thing: You must not define your outputs as power pins and treat them like one. AVR's have limited power output from each pin and by doing so you can fry it very quickly.
If I understand your sentence correctly you need to save your angle values into variable like this (pseudo code, you have to adjust it to your case no one will write it for free):
int xvalue, yvalue, zvalue, button;
void setup(); // all setup should go here do not skip this like me here
void loop() {
  xvalue = analogRead(xpin);
  yvalue = analogRead(ypin);
  zvalue = analogRead(zpin);
  if (button == 1) {
    if (zvalue > 370)
      digitalWrite(ledPin, HIGH);
    else
      digitalWrite(ledPin, LOW);
  } else
    actionWhenPushButtonIsZero();
}

If you think about what I wrote and focus on your task I am sure that everything will work in your device. THINK first then ask next questions.


text:
Worldwide "Arduino in education" events
I'd like to know if there are events worldwide or in Latin America regarding how to introduce Arduino as an extra-curricular activity.
Thanks, Marcelo from Argentina.


text:
How can I connect an arduino to a raspberry pi via an HC 05 bluetooth module and transmit data?
I am currently undertaking a project where I am attempting to build a bluetooth thermometer using an arduino.
I have the temperature sensor working and returning temperature readings via a usb connection to the serial monitor in the Arduino IDE using the following code.
#include <OneWire.h>
#include <DallasTemperature.h>
#include "Timer.h"

Timer t;

// Data wire is plugged into pin 10 on the Arduino
#define ONE_WIRE_BUS 10

// Setup a oneWire instance to communicate with any OneWire devices
OneWire oneWire(ONE_WIRE_BUS);

DallasTemperature sensors(&oneWire);

DeviceAddress insideThermometer = { 0x28, 0x94, 0xE2, 0xDF, 0x02, 0x00, 0x00, 0xFE };

void setup(void)
{
  // start serial port
  Serial.begin(9600);
  // Start up the library
  sensors.begin();
  // set the resolution to 10 bit (good enough?)
  sensors.setResolution(insideThermometer, 10);
  int tickEvent = t.every(3000,doTempReading);

}

void loop()
{
    t.update();
}

void printTemperature(DeviceAddress deviceAddress)
{
  float tempC = sensors.getTempC(deviceAddress);
  if (tempC == -127.00) {
    Serial.print("Error getting temperature");
  } else {
    Serial.print("C: ");
    Serial.print(tempC);
  }
}

void doTempReading()
{
  delay(2000);
  Serial.print("Getting temperatures...\n\r");
  sensors.requestTemperatures();

  Serial.print("Inside temperature is: ");
  printTemperature(insideThermometer);
  Serial.print("\n\r");
}

I now want to try and transmit the readings via a bluetooth connection using the HC 05 module to a raspberry pi which will record the data.
I have done a lot of research and tried several different techniques and can't understand how to go about it.
What mode does the HC 05 need to be in? (Command AT/slave/data/etc.)
How should it be wired (I have found several different methods using various resistors and capacitors and unsure which to follow).
How should I pair it with the Raspberry pi?
Thanks in advance for any help.

have you tried searching "Arduino HC05" in google?

I know this is old but to help out newcomers:
Here's a place you can begin https://create.arduino.cc/projecthub/millerman4487/view-serial-monitor-over-bluetooth-fbb0e5
The wiring depends on which arduino board you are using and the model of your HC-05 BT module. mine uses 4 pins VCC (5v) GND (ground) TX --> TX and RX --> RX
You should be able to google the wiring for your module, and connect to the raspberry pi after you install bluetooth on raspberry pi
sudo apt-get install bluetooth bluez blueman

sudo reboot

Navigate to new bluetooth interface in menu bar through

preferences
bluetooth

Add new device, turn arduino on with BT module plugged in and make sure your HC-05 module is blinking red, and you should see a pair connection named HC-05 on raspberry pi. Password is 1234

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


text:
Issue regarding executing sketch code when not connected to USB
`I have an Arduino Uno A000066 Board R3 that has an Arduino A000079 Motor Shield Rev3 attached to it. Also I have connected two DC Servo Motors to the Motor Shield and wrote the following sequence:
 void setup()
    {
      //Setup Channel A
      pinMode(12, OUTPUT);     //Initiates Motor Channel A pin
      pinMode(9, OUTPUT);      //Initiates Brake Channel A pin

      //Setup Channel B
      pinMode(13, OUTPUT);     //Initiates Motor Channel A pin
      pinMode(8, OUTPUT);      //Initiates Brake Channel A pin
    }

    void loop()
    {
      //Phase 1 - going to the wall
      //Motor A forward - Max Speed
      digitalWrite(12, LOW);   //Establishes forward direction of Channel A
      digitalWrite(9, LOW);    //Disengage the Brake for Channel A
      analogWrite(3, 255);     //Spins the motor on Channel A at max speed

      //Motor B forward - Max Speed
      digitalWrite(13, HIGH);  //Establishes forward direction of Channel B
      digitalWrite(8, LOW);    //Disengage the Brake for Channel B
      analogWrite(11, 255);    //Spins the motor on Channel B at max speed

      delay(4000); // Adjust to correspond the distance

  //Phase 2 - getting back to initial point
  //Motor A backward - max speed
  digitalWrite(12, HIGH);  //Establishes backward direction of Channel A
  digitalWrite(9, LOW);    //Disengage the Brake for Channel A
  analogWrite(3, 255);     //Spins the motor on Channel A at max speed

  //Motor B backward - max speed
  digitalWrite(13, LOW);   //Establishes backward direction of Channel B
  digitalWrite(8, LOW);    //Disengage the Brake for Channel B
  analogWrite(11, 255);    //Spins the motor on Channel B at max speed

  delay(4000);

  //Phase 3 Stop for 7.5 seconds
  // Motor A stop
  digitalWrite(9, HIGH);   //Engage the Brake for Channel A
    //Motor B stop
  digitalWrite(8, HIGH);   //Engage the Brake for Channel B
  delay(7500);

  //Phase 4 Go to second point
  //Motor A forward - max speed
  digitalWrite(12, LOW);  //Establishes forward direction of Channel A
  digitalWrite(9, LOW);   //Disengage the Brake for Channel A
  analogWrite(3, 255);    //Spins the motor on Channel A at full speed

  //Motor B forward - max speed
  digitalWrite(13, HIGH);  //Establishes foward direction of Channel B
  digitalWrite(8, LOW);    //Disengage the Brake for Channel B
  analogWrite(11, 255);    //Spins the motor on Channel B at half speed

  delay(2000); // Adjust to correspond the distance

  //Phase 5 Final Stop
  //Motor A - stop
  digitalWrite(9, HIGH);   //Engage the brake for Channel A
  //Motor B - stop
  digitalWrite(8, HIGH);   //Engage the brake for Channel B

  delay(60000);        // 1 minute stop
}

While connected to USB, the device executes perfectly the sequence. As soon I run the sequence using the DC Source, the device does not respect any part of the coding. It started simply going forward while reversing the polarity randomly blocking the movement sometimes.
Looking forward to your suggestions.

What is your power source?

If that stuff in the question is code, mark it as such.  Click edit, and in the edit box, highlight the code and press ctrl-k. Or highlight the code and click the {} icon in the toolbar at the top of the editing box. To highlight text click-drag across it or use the arrow keys while holding the shift key.  ¶   While colorful, the phrase “the device does not respect any part of the coding” does not have a well-defined or specific meaning that imparts any information about what actually happened.  You could edit your question and tell what happens.

Is your "DC Source" a 9V battery, or what?  A stack of coin cells?  Some AAA batteries?  (Typically, none of those are good enough to keep the Arduino from resetting when the motors turn on.)


text:
Why does my ESP8266 making an HTTP request to an MDNS responder keep getting redirected to my ISP's search engine?
I have two ESP8266's trying to talk to each other, a 'host' and a 'client', if you will. I have the ESP8266mDNS.h responder running on the host at esp8266wifi.local. On sending an http GET request to  http://esp8266wifi.local/, I have the webserver send a simple "Success" message.
When I use my computer to access the host in a web browser, it responds just fine, "Success". But when I use the client ESP8266 to send the GET request, it appears to be redirected to my ISP's search engine. The raw html reads:
<meta http-equiv="refresh" content="0;url=http://search.frontier.com/search/?q=http://esp8266wifi.local/&t=0"/>

It appears to respond correctly when I connect to the IP address, http://192.168.0.10/ using ESP8266WebServer.h but when I use the mDNS request I get redirected. Is there any way to work around this?
EDIT:
I tested on my phone's internet browser and my Wii U console and I also get the same redirect to my ISP's search engine.

Those devices probably don't support mDNS, so they do a regular DNS lookup to the ISP's DNS servers. Because that domain name doesn't exist outside of your network, ISP points it to their search engine.


text:
Can an Arduino emulate a USB mass storage device?
Question:
Can I connect an Arduino's USB port to the USB port of another embedded device that is expecting a USB thumb/flash device?
Or, can I connect a USB module to this embedded device, with the other end connected to GPIO's of the Arduino?
This embedded USB thumb device requires a thumb drive to transfer a file. I need to emulate the connection, disconnection, and thumb drive with the folder and file with a Arduino.
Is it possible to emulate an USB thumb drive between an Arduino and an embedded device's USB port?
Research:
I saw a couple other questions that talk about USB being a master/slave configuration and that certain IC are required. Additionally, that there were some cables that can be used for two-way data transfer (mostly for PC to PC data transfers). If that is the case, could one of those cables be used for this configuration? Which cable would work?
Possible Solution:
The embedded device I need to emulate a thumb drive on will automatically search for the file in a specific folder of the thumb drive. Would I be able to partition a section of an SD card with the SD card module to appear as a thumb drive, and then connect that partition to the embedded device via USB-A to USB-A cable?
Diagram:
Arduino USB Port -> USB Cable -> Embedded Device USB Port
Arduino GPIO -> USB Module -> USB Cable -> Embedded Device USB Port
Requirements:
Connection via USB cable between Arduino and an embedded device's USB port.
Ability to emulate the connection and disconnection of a USB thumb drive on the embedded device.

Not with an UNO. Could you expand on what it is you want to achieve? What is the end goal here?

Sure. I want to be able to emulate a USB thumb drive for an embedded system that has a USB port. You usually plug in the USB thumb drive into the embedded system, and then it reboots when it reads a file from the USB thumb drive. I'd like to develop something where I can emulate the plugging in/unplugging the USB thumb drive with that file in it's folder.

Couldn't you just use a regular flash-drive, but have the Arduino disconnect and reconnect it. Using something like a MUX (multiplexer), or maybe even a few relays. Just get a usb extension cable, and cut it in the middle. Then connect the 4 wires inside via the MUX/relays.

On a side-note. The newer raspberry pis can act as a Mass Storage Device.

The Raspberry Pi sounds promising. I want to develop a program to upload/download the binary file on the mass storage device. Maybe the Pi is a better option?

The MUX or relays might be a good idea to emulate the insertion/removal of the USB thumb drive.

Anything else you want to know?

This is indeed not a fit for an Uno, though one of the ARM or 32u4 based boards (Arduino, Teensy, or other) could work up to the on-board storage size or with an SPI flash.  In the raspberry pi world only the boards without a hub in the way (such as the zero or model A) can do it, but pi's add a lot of delicate software state.

What are the Arduino 32u4 boards? I read about the AVR boards a little bit, but I'm not sure how they differ from the popular Arduino boards. Do you have a suggestion for an ARM board for this particular configuration?

The Arduino functions as a USB client device, not a USB host.
You can get a shield which claims to allow the Arduino to operate as a USB Host to allow it to control various USB devices including thumb drives: link

check out http://elasticsheep.com/2010/04/teensy2-usb-mass-storage-with-an-sd-card/

The description of this device from Sparkfun appears to match the OP's requirement for integrating an Arduino with other USB devices by enabling the Arduino to acts as a USB host. https://www.sparkfun.com/products/9947

This (Arduino is USB host so e.g. memory stick could be read by Arduino) is the opposite of what is being asked (Arduino acts as memory stick).


text:
Connecting to the Sparkfun Redboard on Mac OS X Sierra
I'm trying to connect to my Sparkfun Redboard (Arduino UNO compatible) on Mac OS X 10.12.3 (Sierra). The board comes with a USB mini to USB A FTDI cable. The board lights up and gets power over USB, but I don't see the right USB serial port in the Arduino IDE (I only see the Bluetooth port).
I've installed the VCP FTDI drivers v2.3 to no avail. When that didn't work, I also installed the CH340 CH341 drivers (but I doubt I need those). Rebooting the computer didn't help either.
I can only load the FTDI VCP v2.3 drivers using an explicit command sudo kextload /Library/Extensions/FTDIUSBSerialDriver.kext/. When I run kextstat | grep FTDI, I get:
 155    0 0xffffff7f83892000 0x7000     0x7000     com.FTDI.driver.FTDIUSBSerialDriver (2.3) ECC3AF36-431D-370D-86F2-5237785E9CF8 <127 41 5 4 3 1>

But it still doesn't show up in the Arduino IDE.
I've heard that Apple's own USB FTDI drivers (AppleUSBFTDI) could cause problems, but it seems these are never loaded. If I try to unload the Apple FTDI driver (sudo kextunload –b com.apple.driver.AppleUSBFTDI), I get the following:
(kernel) Kext com.apple.driver.AppleUSBFTDI not found for unload request.

Failed to unload com.apple.driver.AppleUSBFTDI - (libkern/kext) not found.
Any tips are welcome. Thanks!

I'm using MacOS Sierra and an Arduino Pro Mini (from Sparkfun) with a breakout USB-to-UART board that uses an FTDI FT232 chip. I'm using the default Apple FTDI drivers (the ones that are bundled with Sierra) and I'm having no problems whatsoever.
Some people have reported problems using the manufacturer (FTDI) drivers that they had already installed after upgrading to Sierra. Some of them solved it by uninstalling the conflicting drivers and relying on the default Apple FTDI drivers uninstalling the conflicting drivers and relying on the default Apple FTDI drivers instead. It's worth a try.
OTOH, the CG340 driver doesn't currently work under Mac OS Sierra. Fortunately, Adrian Mihalko patched the driver and made it available at GitHub, along with some troubleshooting instructions.


text:
Is it possible to burn a bootloader to an ATTiny85 with USB TTL and avrdude?
I have:

An Digispark clone (with no Arduino bootloader)
A USB -> TTL serial device
A development breadboard
Avrdude

I want to burn the micronucleus bootloader to the chip.
Is this possible, are there instructions?
ISP programmer is in the post but I'm not expecting it for 3 weeks.

AFAIK... No. The programming interface requires a, well, programmer. If you don't have any, you can't program. Since the microcontrollers usually used for arduinos can "self-program" (i.e. they can alter their programs), you can write a program to enable the serial interface and receive the new program, which then you can write and execute. This small program is called bootloader. But without bl you can't do these things, so at least the bl should be programmed with a programmer. If you manage to have someone lend you an arduino board, you can use it to program the ATTiny85 (search ArduinoISP)

Reading the attiny85 spec certainly has instructions for serial uploading but it's complicated.  I would have expected avrdude to have some bit bang setting to do this. I read some hacks for the ttl board that breaks out the reset pin but I have not tried this yet

Uhm, serial uploading means using the spi program interface, the one used by the programmer. You can use a USB-UART board (the TTL board you mentioned) even without hacks (you just have to "press" the reset button - or reset it in any other way - when the ide says "started uploading"). But you need the bootloader

Yeah i tried that with avrdude set to serial bitbanging

Tried hitting the reset button several times. Never seemed to get it right. Alway returned rc=1 No response from board. Everything seems to say you need a SCK (Sync Clock) but the TTL has only 5v+ GND RX TX and 3v3+
One of these
https://goo.gl/0IZAuH

Chips are these https://goo.gl/8nt2xY

Let me try again. SPI = programmer, TTL = UART. Both are "serial", but your TTL is th standard known as UART. No UART without bootloader

No bootloader. But we I should be able to burn the bootloader in spi mode using a serial bit bang as I understand. I wired up the auto reset to my pl2303 pin 2. (Tricky soldering) still not working. Response always low

Check this out.
http://nerdralph.blogspot.co.nz/2014/05/pl-2303hx-bit-bang-avr-programmer.html

Never knew this. Good to know. Anyway yes, he is using the serial interface as a generic I/O module, manually switching the pins. Ok. So, did you connect the pins as he suggested? I mean reset->txd sck->rts mosi->dtr miso->cts, then add the new programmer to the avrdude.conf file? Moreover what is the output voltage of the PL2303 you have? Is it a 5V or a 3.3V version? Depending on this, connect +5V or +3.3V to the attiny VCC and, of course, GND to GND. You will have six cables connecting the attiny to the programmer.

Well there i kinda got stuck. From what i understand by reading the manual was contrary to this configuration.
See table below from manual.
Notice data in and data out are MOSI and MISO
and TX = reset? this did not make sense to me.
    Table 20-10. Pin Mapping Serial Programming     Symbol Pins I/O Description     MOSI PB0 I Serial Data in     MISO PB1 O Serial Data out     SCK PB2 I Serial Clock
See. http://www.atmel.com/images/atmel-2586-avr-8-bit-microcontroller-attiny25-attiny45-attiny85_datasheet.pdf

Why? TXD, RTS, DTR, CTS are the pin names for the UART standard. But they are using them as general purpose IOs, so the name means nothing. Just connect them the way the blogger suggests you and do the modifications needed....

ok cool. will try.

No, you can't because a USB -> TTL serial device is not made for that. You CAN however use an Arduino Uno to burn a bootloader to another Atmel micro, including the Attiny85.
Now you may ask, can you use the Digispark in place of the Uno (and thus burn more Attiny chips). The answer is a qualified yes.  Another Arduino can do this -- search the web and find many examples.
You might (?) even adapt that sketch from the Uno to the Digispark (saving the cost of an Uno). I can't advise further and you're looking at a rabbit hole of possible issues.
Sparkfun does sell a chip which can perform boot-loading using minimal components:
https://learn.sparkfun.com/tutorials/how-to-install-an-attiny-bootloader-with-virtual-usb

Short answer, no. You can burn a bootloader onto the chip using a programmer, and then the bootloader does the serial communication magic so you can upload your sketches via serial or even low-speed USB (if your bootloader knows how to do USB bit-banging). But you can burn the bootloader only through SPI.

But SPI is what i am trying to achieve. USB to TTL is serial. Look
pic.twitter.com/JboHA3qq6d

Indeed TTL (well, UART in your case, that's a USB-UART chip) is a serial protocol but it's not the same as SPI. SPI is a synchronous serial protocol, which means it needs a clock line for timing, so it requires 3 lines for the communication to take place (SCK - clock line driven by the master, MOSI - for transmitting and MISO for receiving). UART is on the other hand an asynchronous serial protocol, so it requires only the 2 data lines (RX for receiving and TX for transmitting), the timing and synchronization is done by both the receiver and the transmitter.

Yes as i enquire i am seeing that i can do this. But i need to break out at least 2 more pins from the PL2303. Will do this tonight and see what happens.

From the datasheet of the chip you can't do it, it has an RS232 serial interface engine (that's UART) and 2 GPIO pins (you'd need 3 GPIO if you could even program the damn thing to do bit-bang SPI, which you probably can't). Why do you want to reinvent the lightbulb tho? Buy an ISP, it's 2 bucks or something like that. Or if you have an arduino laying around use it as an ISP.

With due respect i think you can do it if you breakout the extra pins of the PL2303. Well at least from what i have gathered so far. In the next few days i will attempt this and let you know how it goes.But yes. the ISP is in the post.

you can't program your hardware with just USB to tty converter you need a programmer for that now instead of buying expensive programmers you can buy an Arduino board and use it as ISP (In System Programmer) here is the link describing the whole process.
Adruino as a  ISP

In principle that is true; however a number of actual USB<>Serial chips have additional proprietary modes offering synchronous serial communication which with the right software on the host can be used for AVR ISP.

@ChrisStratton Care to list a few/all such chips and "right software", if it exists?


text:
How can I send integer from arduino to another arduino by FS1000A / XY-MK-5V 433Mhz TX/RX Module (WIFI)?
I'm trying to send and receive some data from arduino to another arduino and I'm using arduino UNO and FS1000A / XY-MK-5V 433Mhz TX/RX Modules.
For transmitting I use the library VirtualWire and It works very well for this code:
#include <VirtualWire.h>
void setup()
{
// Initialize the IO and ISR
vw_setup(2000); // Bits per sec
}
void loop()
{
  char msg[7] = {'h','e','l','l','o',' ','!'};
  vw_send((uint8_t *)msg, 7);
  vw_wait_tx(); // Wait until the whole message is gone
  delay(1000);
}

I was wondering if I want to send some string or int data how I can do that.
I tried to use it for string data but I couldn't because the Input of function vw_send(...) is char and I couldn't use int or string.
finally I run this code:
#include <VirtualWire.h>
void setup()
{
// Initialize the IO and ISR
vw_setup(2000); // Bits per sec
}
void loop()
{
  char msg[11]="Hello there";
  vw_send((uint8_t *)msg, 11);
  vw_wait_tx(); // Wait until the whole message is gone
delay(1000);
}

and I could send Hello there !, but I'm looking for the correct way for sending string and int.

Have a look at the Easy Transfer library.  I haven't used the particular modules you have, however I did successfully use the EasyTransfer library with Ciseco wireless modules.  In essence the EasyTransfer library transmits the data as a structure with the same format on each module.  The structure can contain any data type.

Would you please give me the link of this library?

How can I choose the library? there is a lot of library about one subject!

Hi, just Google Arduino EasyTransfer library that will provide links to the actual library and other various questions / comments / answers.  There is only one EasyTransfer library.  Study the available on line information and I am certain you will achieve your objectives.


text:
3.3v inductive proximity sensors
I'm using an ESP8266 so I'm limited to 3.3v.  I've found a number of inductive proximity sensors but they require 5v or more.  Does a 3.3v sensor exist?
I recently dropped some tiny screws on dark carpeting and would like to find them instead of just vacuuming them up.  Stupid project?  Maybe.  But a good excuse to buy another sensor.

Have you tried using a magnet?

i've not had many problems w/ 5v sensors w/ESPs. If its a digital output, that's easy enough to use a transistor or dropper diode on (or nada). w/analog output, it's easy enough to use a voltage divider...

Why use a magnet when I could build something?

if you want really cheap, try some of these ideas: https://www.newark.com/pdfs/techarticles/microchip/3_3vto5vAnalogTipsnTricksBrchr.pdf if none of the doezen or so ideas work, bite the bullet and get some 2-way level shifters on ebay like these: http://www.ebay.com/itm/132091293479

An inductive sensor may not see "tiny" screws very well, and if it does it may well also see things you don't care about, like nails in the underlying flooring.   In contrast a magnet will pick up the screws.  Then you can use them to make a more suitable project.

I don't know what voltages inductive proximity sensors use, but in general it's inexpensive to use  3.3V–5V logic level converter modules.  These typically are bi-directional interfaces that use an N-FET and pullups to the two supply voltages to interface different-voltage logics.
See the "Bi-directional level shifters" section of the TAKING IT TO ANOTHER LEVEL: MAKING 3.3V SPEAK WITH 5V article at hackaday.com for a circuit explanation.  See gearbest.com and sparkfun.com and Adafruit for inexpensive modules.
Note, for finding small screws in carpet, a search coil as used in a metal detector might be a better choice than a proximity sensor.  The coil is part of a tuned LC circuit; metal near the loop detunes the circuit slightly, producing a tone by heterodyning.

Those "inexpensive" devices cost more than an ESP8266 MCU...

@dandavis, can you give a link to an ESP8266 MCU that costs less than $1.21, the gearbest module cost delivered?

I wish! haha ;) tbh, I didn't see that one, just the paytafruit and the other...

You could probably just use a resistive divider to bring the 5V down to 3.3V.


text:
HTTP post request in JSON Format using SIM900 module
I tried to send HTTP post requests to a server in JSON Format using a SIM900 module. But the code is not posting the data. While posting the data I'm getting the error response while initializing the server using the command:
{("AT+HTTPPARA=\"URL\",\"http://test.server/insert-path")}

I don't know what the error is and how to fix it. Please help me to fix this.
#include<SoftwareSerial.h>

SoftwareSerial client(2,3);

String testReading="{  \"testID\" : 1,  \"testLevel\" : 1, }";

void setup() {
  Serial.begin(9600);
  client.begin(9600);
  delay(1000);
  if(client.available()) {
    Serial.print("Connected");
  } else {
    Serial.print("Not Connected");
  }
  checkSignal();
  connectGPRS();
  postData();
  delay(1000);
}

void loop() {
  if(client.available()) {
    checkSignal();
    connectGPRS();
    postData();
    delay(1000);
  }
}

void connectGPRS() {
  client.println("AT+CGATT?");
  delay(1000);
  ShowSerialData();
  client.println("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"");
  delay(1000);
  ShowSerialData();
  client.println("AT+SAPBR=3,1,\"APN\",\"www\"");
  //Using Indian Standard Vodafone Sim and so APN is www
  delay(1000);
  ShowSerialData();

  client.println("AT+SAPBR=1,1");
  delay(1000);
  ShowSerialData();

  client.println("AT+SAPBR=2,1");
  delay(1000);
  ShowSerialData();
}

void checkSignal() {
  client.println("AT+CSQ");
  delay(1000);
  ShowSerialData();
}

void ShowSerialData() {
  while(client.available()!=0)
    Serial.write(client.read());
}

void postData() {
  client.println("AT+HTTPINIT");
  delay(1000);
  ShowSerialData();

  client.println("AT+HTTPPARA=\"CID\",1");
  delay(1000);
  ShowSerialData();

  client.println("AT+HTTPPARA=\"URL\",\"http://test.server/insert-path");
  delay(1000);
  ShowSerialData();

  client.println("AT+HTTPPARA=\"CONTENT\",\"application/json");
  delay(1000);
  ShowSerialData();

  client.println("AT+HTTPDATA=99,10000");
  delay(1000);
  ShowSerialData;

  client.println(testReading);
  delay(1000);
  ShowSerialData;

  client.println("AT+HTTPACTION=1");
  delay(10000);
  while(!client.available());
  ShowSerialData();
}

Give us a clue - how far does it get? What does it do?

This code will post the manually given data in the Arduino to the server.It's just a sample code.I'm using SIM 900 to establish GPRS connection.

The connections are been establishing between the SIM and Arduino sometimes GPRS is been connected but the data is not been send to the server..

Can you post to the server using a PC (not on the server's local network)? Are you sure the server is working and accessible? Do the server's logs show the failing connections? Are we looking for a connectivity problem or a problem with the data it's sending?

It's worth mentioning that if you're relying on your ShowSerialData() function to know what's going on, it may not be reliable. Serial data does not all appear in one go.  Your code relies on a race - the data arriving fast enough for there always to be some in the buffer.  You can hack it by adding a delay(1000) right at the start of ShowSerialData().

Thanks.. I have delayed that.. The error is while initializing the URL.. When I send the command {("AT+HTTPPARA="URL","http://test.server/insert-path")}.. I'm receiving ERROR response.. I even delayed the time at posting the data and at initializing the HTTP.. But still I'm getting ERROR response..

Could you edit your question to include this information, please? I suspect I won't be able to solve it for you, but the clearer you make the question, the more likely someone else will.

Thanks Mark for your help.. If you got any idea of solving this please ping me..

Hi all use this code below for establishing HTTP connection with the server. And to neglect the 601 or 504 error use proper posting format. Here I'm using JSON format. I just gave manual data. Ignore those errors in HTTPINIT, AT+SAPBR=2,1. The data will be posted to the server
 #include<SoftwareSerial.h>

SoftwareSerial client(2,3);

String reading="{  \" : 1,  \"latitude\" : 12.983027,  \"longitude\" : 80.2594,  \"timestamp\" : 100,  }";

void setup()
{
  Serial.begin(9600);
  client.begin(9600);
  delay(500);

  if(client.available())
  {
    Serial.print("Connected");
  }
  else
  {
    Serial.print("NotConnected");
  }

  //initSIM();
  connectGPRS();
  connectHTTP();
}

void loop()
{

}

void connectGPRS()
{
  client.println("AT+SAPBR=3,1,\"Contype\",\"GPRS\"");
  delay(1000);
  ShowSerialData();

  client.println("AT+SAPBR=3,1,\"APN\",\"www\"");//APN
  delay(1000);
  ShowSerialData();

  client.println("AT+SAPBR=1,1");
  delay(1000);
  ShowSerialData();

  client.println("AT+SAPBR=2,1");
  delay(1000);
  ShowSerialData();
}

void connectHTTP()
{
  client.println("AT+HTTPINIT");
  delay(1000);
  ShowSerialData();

  client.println("AT+HTTPPARA=\"CID\",1");
  delay(1000);
  ShowSerialData();

  client.println("AT+HTTPPARA=\"URL\",\"http://xxx.xxx.xx/Listener/\"");//Public server IP address
  client.println("AT+HTTPPARA=\"URL\",\"http://testServer/Listener/\"");//Public server address
  delay(1000);
  ShowSerialData();

  client.println("AT+HTTPPARA=\"CONTENT\",\"application/json\"");
  delay(1000);
  ShowSerialData();

  client.println("AT+HTTPDATA=" + String(reading.length()) + ",100000");
  delay(1000);
  ShowSerialData();

  client.println(reading);
  delay(1000);
  ShowSerialData;

  client.println("AT+HTTPACTION=1");
  delay(1000);
  ShowSerialData();

  client.println("AT+HTTPREAD");
  delay(1000);
  ShowSerialData();

  client.println("AT+HTTPTERM");
  delay(1000);
  ShowSerialData;
}

void ShowSerialData()
{
  while(client.available()!=0)
  {
  Serial.write(client.read());
  delay(100);
  }
}

client.println(reading);
delay(1000);
ShowSerialData;

The above line of code would result in an error.


text:
DFROBOT I2C 16x2 Arduino LCD Display Module I2C communication interface
What is the proper connection to the I2C communication interface (e.g., JST Jumper 4 Wire Assembly) of the DFROBOT I2C 16x2 Arduino LCD Display Module (SKU:DFR0063)? I wish to connect 4 wires assembly directly to it.

Here is schema how to connect it and example how to use it, also link to needed library. Hope this helps.
https://www.dfrobot.com/wiki/index.php/I2C/TWI_LCD1602_Module_(SKU:_DFR0063)
Anyway - I2C is prettty standardized interface, so googling any I2C schema for your type of Arduino will work as for connection - just connect SDA (A4) to SDA, SCL (A5) to SCL, GND to GND and VCC to VCC as writen on the module interface.
There are also lots of correct results for googling the module name - just google SKU:DFR0063 and you get many of correct links. On first page every second link contains link for the library, those others just refers to the manufacturer in text.

While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference.  Link-only answers can become invalid if the linked page changes. - From Review

Esential part is connect I2C (connect the same name pins on module & Arduino), download library from manufacturer and use it usual way. The link ghoes to manufacturer wiki about the product, so it should not perish easy). Anyway I added this description to answer. Took me longer, then to google for the name of module and click the link for download library in every second google result.


text:
How to properly use interruptions with twi (I2C)
I would like to reprogram Wire.h, or a part, to use interruptions, in order to not waste time to wait. I'm using an Arduino Mega with an Adafruit motor shield v2.3.
In the datasheet, page 262, 24.9.2, bit 0, I can read that I have to set the TWIE flag to one to be able to catch the interruption.
So, I started to write this code :
//https://www.arduino.cc/en/uploads/Main/arduino-mega-schematic.pdf

#include <avr/interrupt.h>

#define ADDRSHIELD 0xC0//adresse sur 8 bits

#define TWI_FREQ 100000L
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |=  _BV(bit))

#define START       0x08  //TWI start
#define MT_SLA_ACK  0x18   //slave ACK has been received
#define MT_DATA_ACK 0x28   //master ACK has been received

#define LED0_ON_L 0x6

#define TWI_STATUS      (TWSR & 0xF8)

int etat = 0;
uint8_t currentstep = 0;
uint8_t _addr;
uint8_t _data;

ISR(TWI_vect)
{
  //I remove the TWINT flag
  TWCR |= (1<<TWINT);

  switch(etat)
  {
    case 0:
      //start has been send, let's check if it's ok
      if(TWI_STATUS == START)
      {
        //on charge l'adresse dans TWDR et on clear le bit TWINT dans TWCR pour demarrer la transmission
        TWDR = _addr;
        TWCR = _BV(TWIE) | _BV(TWEN);
        etat = 1;
        //Serial.println(etat);
      }
      else
      {
        etat = -1;
      }
      break;
    //addr has been send
    case 1:
      if(TWI_STATUS == MT_SLA_ACK)
      {
        TWDR = _data;
        TWCR = _BV(TWIE) | _BV(TWEN);
        etat = 2;
        //Serial.println(etat);
      }
      else
      {
        etat = -2;
      }
      break;
    //data have been send
    case 2:
      if(TWI_STATUS == MT_DATA_ACK)
      {
        // disable twi module, acks, and twi interrupt
        TWCR = (1<<TWIE)|(1<<TWEN)|(1<<TWSTO);
        etat = 3;
        //Serial.println(etat);
      }
      else
      {
        etat = -3;
      }
      break;
    //stop condition
    case 3:
      // desactivate internal pullups for twi.
      digitalWrite(SDA, 0);
      digitalWrite(SCL, 0);
      etat = 0;
      //Serial.println(etat);
      //Serial.println("Next");
      break;
  }
}

void sendData(uint8_t addr, uint8_t data)
{
  _addr = addr;
  _data = data;

  i2cSetup();
  //start condition
  TWCR = (1<<TWSTA)|(1<<TWEN)|(1<<TWIE);
}

void i2cSetup(void)
{
  // activate internal pull-ups for twi
  sbi(PORTD, 0);
  sbi(PORTD, 1);

  // initialize twi prescaler and bit rate
  cbi(TWSR, TWPS0);
  cbi(TWSR, TWPS1);

  TWBR = ((F_CPU / 100000) - 16) / 2;
}

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

void loop()
{
  if(etat == 0)
  {
    sendData(0xC0, 0b1010101);
  }
  if(etat == 3)
  {
      Serial.println("Next");
  }
  if(etat == -1)
  {
    Serial.println("Error from start");
    delay(100);
    exit(-1);
  }
  if(etat == -2)
  {
    Serial.println("NACK");
    delay(100);
    exit(-1);
  }
  if(etat == -3)
  {
    Serial.println("DATA NACK");
    delay(100);
    exit(-1);
  }
}

My problem is, once I reset TWIE to one on my interruption, the code looks like to freeze(in ISR(), case 0, TWCR =...). In my mind, the interruption is call only when TWIE is set to one and when the twi module says (when he sets TWINT to one I guess) that he finished the job. I don't understand how to properly use this interruption.
EDIT :
Thanks to @jfpoilpret, know I clearly know the problem, the slave doesn't reply by an acknowledge (in my switch, case 0, the status isn't equal to START (0x08)). In the datasheet, p246, they clearly explain how to use registers, but I'm not sure how to use the flag TWIE. I don't know if I have to set them both to one, or if i have to completely leave TWINT (I tried both, but nothing worked...).
Thanks for your help,
julien

First off, when using interruptions, you must make your ISR code as quick as possible. In particular, NEVER USE Serial.print... from an ISR.

I thought Serial.print wasn't too long. I'll modify my code.

Well, there is no more print in my ISR. Thanks you, so know I clearly know the problem, the slave doesn't reply by an acknowledge (in my switch, case 0, the status isn't equal to START (0x08)). I'll edit my question.

Well, after some tests, I achieved to make all of this working, thank you !

Great! Can you please post, as an answer, the modifications you made so that this can help other people with the same problem in the future?

Of course, I was doing it. Thank you a lot for your tips !

Perfect. Here is an additional hint to improve your program: make volatile your global variables when they are shared between your ISR and the rest of your code (i.e. etat, _addr and _data) otherwise the compiler might optimize access to these, thinking they never change.

One last point I think you should fix (I did not pay attention to it before, sorry): etat is currently an int (2 bytes), reading or writing it requires several assembly instructions and hence may be interrupted. You should rather declare it as int8_t (one byte only, access not interruptible) as it still fits values you need.

Done. Again, thanks ! If you have 3 minutes, you could post all of this as an answer, I would be glad to check it as the answer !

Well I believe there must be other general answers on this site about how to properly write ISR functions. I just wanted to quickly point you about some important hints for your code. One last point: you declared etat as uint8_t instead of int8_t: they are one byte each, but first one is unsigned, not suitable for negative values you assigned it, although it will probably work -maybe some compiler warnings- as long as you don't try if (etat < 0) which won't work.

Exactly, that's what append when I don't think... Thanks !

After some tests, it's working !
First off all, I used Serial.println in my ISR, that's made it freeze apparently.
Second, apparently, I can't send more than 6 bits, else I'll have an error (data NACK), I thought it was 8.
This is my code working :
//https://www.arduino.cc/en/uploads/Main/arduino-mega-schematic.pdf

#include <avr/interrupt.h>

#define ADDRSHIELD 0xC0//adresse sur 8 bits

#define TWI_FREQ 100000L
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |=  _BV(bit))

#define START       0x08  //TWI start
#define MT_SLA_ACK  0x18   //slave ACK has been received
#define MT_DATA_ACK 0x28   //master ACK has been received

#define LED0_ON_L 0x6

#define TWI_STATUS      (TWSR & 0xF8)

volatile int8_t etat = 0;
volatile uint8_t _addr;
volatile uint8_t _data;

ISR(TWI_vect)
{
  switch(etat)
  {
    case 0:
      //start has been send, let's check if it's ok
      if(TWI_STATUS == START)
      {
        //on charge l'adresse dans TWDR et on clear le bit TWINT dans TWCR pour demarrer la transmission
        TWDR = _addr;
        TWCR = _BV(TWIE) | _BV(TWEN);
        etat = 1;
      }
      else
        etat = -1;
      break;
    //addr has been send
    case 1:
      if(TWI_STATUS == MT_SLA_ACK)
      {
        TWDR = _data;
        TWCR = _BV(TWIE) | _BV(TWEN);
        etat = 2;
      }
      else
        etat = -2;
      break;
    //data have been send
    case 2:
      if(TWI_STATUS == MT_DATA_ACK)
      {
        // disable twi module, acks, and twi interrupt
        TWCR = (1<<TWIE)|(1<<TWEN)|(1<<TWSTO);
        etat = 3;
      }
      else
        etat = -3;
      break;
    //stop condition
    case 3:
      // desactivate internal pullups for twi.
      digitalWrite(SDA, 0);
      digitalWrite(SCL, 0);
      etat = 0;
      break;
  }
  //I remove the TWINT flag
  TWCR |= (1<<TWINT);
}

void sendData(uint8_t addr, uint8_t data)
{
  _addr = addr;
  _data = data;

  i2cSetup();
  //start condition
  TWCR = (1<<TWSTA)|(1<<TWEN)|(1<<TWIE)|(1<<TWINT);
}

void i2cSetup(void)
{
  // activate internal pull-ups for twi
  sbi(PORTD, 0);
  sbi(PORTD, 1);

  // initialize twi prescaler and bit rate
  cbi(TWSR, TWPS0);
  cbi(TWSR, TWPS1);

  TWBR = ((F_CPU / 100000) - 16) / 2;
}

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

void loop()
{
  if(etat == 0)
  {
    sendData(0xC0, 0b0010101);
  }
  if(etat == 3)
  {
      Serial.println("Next");
  }

  if(etat == -1)
  {
    Serial.println("Error from start");
    delay(100);
    exit(-1);
  }
  if(etat == -2)
  {
    Serial.println("NACK");
    delay(100);
    exit(-1);
  }
  if(etat == -3)
  {
    Serial.println("DATA NACK");
    delay(100);
    exit(-1);
  }
}

Thanks a lot to jfpoilpret !

Note that you can accept your own answer after some days by clicking on the tick beside it.

Two observations.

The datasheetss does a fairly good job of Laying out the states and required conditions to move forward. Your code simply needs to mimic that. A short cut is to take a look at lpc210x datasheetss as it has fairly simple c code for the state machine implementation in the Isr.
What I typically do for slow multi byte transmission, i2c or UART, is to point a pointer to a string to be transmission, load up the datasheetss register and enable the interrupt. In the Isr, test if all the data has been transmission. If yes, turn off the Isr. Otherwise, load up thee next char. The data received can be processed via a callback function.

This approach minimizes user involvement. On a SPI with buffer, it can transmit without interruption.

Why ?
The Arduino Mega 2560 is not very fast. The gain by using interrupts is not a lot.
The Wire.endTransmission and Wire.requestFrom wait until the I2C transaction has finished. That might seem a waste of time, but for the slow ATmega microcontrollers, not a lot of time is wasted.
The overhead by more code might even slow it down. A I2C library that is completely in software might even be faster than the original Arduino Wire library. Although the Arduino Wire library uses interrupts, the overhead by the Wire library creates a few extra delays during the I2C transaction.
It took years (it really did) to have a normal working Wire library for ATmega microcontrollers and it still is not very good. For example a hardware problem on the I2C bus could halt a sketch. I have seen a number of custom I2C libraries that run into problems one way or the other.
You can waste less time with:

Make a well designed sketch, using millis instead of delay.
Write a good interface to the sensor. I see a lot bad usage of the Wire library with unnecessary I2C transactions.
Increase the I2C speed to 200kHz or 400kHz with Wire.setClock.
Try to use the SPI bus if possible. For a 3.3V sensor with a SPI interface, a 3.3V Arduino board is the best choice. For example the Arduino Due with ARM M4 or a small board with ARM M0+ processor.
When using the SPI bus with a Ethernet shield, try setting the SPI bus faster.
When using a SD card, try full speed, instead of half speed.
Use the newest Arduino IDE, because the 'lto' optimization was enabled which helps a lot.

Really serious work for better I2C functions has been done for the Teensy. It is still compatible with the Arduino Wire functions, but extra functions have been added that do not wait.

I need it because I use interruptions (every 1ms) to call functions to read sensors, etc etc, and to send data in I2C. If I used wire.h, it tooks 3.6ms to send my data. Even if I wanted to use it  in 400kHz, and if it would took 0.9ms, it's always too loog, because I need additional time in the loop() to manage others things. So, with this, I can manage I2C with others things.

I only use delay() to let the time to Serial.println to print the error, before the exit(). I need I2C because my shield work with that.

Thank you for answering my "Why"-question. jfpoilpret has been a very good help (for example with the volatile single bytes). You use a complete I2C transaction for just one data byte for the motor shield every millisecond. Is that really needed ? For a software PWM signal ? I wonder what the other code is. Doing so many things every millisecond with a ATmega chip might be pushing the limit. You could try the MultiSpeed I2C scanner to test the I2C bus: http://forum.arduino.cc/index.php?topic=197360

Not only 1 byte, little bite more. Yes, it's for a PWM signal. The other code is to manage a Lora connection, logs, and maybe others futur things. I honeslty don't know if I need to send everytime the same data, I just mimic this library : https://github.com/adafruit/Adafruit_Motor_Shield_V2_Library Why would I push to the limit the ATmega ? If it isn't in my interruption, it would be in my loop(). Thank you for the scanner, I'll try it !

The PCA9685 on the motor shield creates the PWM signal. I tried to read the Adafruit library to understand why you need software PWM, but I don't understand it. Using software PWM via I2C at 1000 times per second can't be right. To set individual pins via I2C for a stepper motor is a bad idea, then you need a better motor shield. Either use the Arduino Stepper or the Mikem AccelStepper directly with Arduino pins, or a shield that can do that on its own. Perhaps someone else knows that Motor Shield, or you could try to ask on the Adafruit forum.

Thanks for you help :) Apparently, the library set only one time de PWM at the beginning, and then only manage which coil is feed or not.  Sorry if I wasn't clear, I make many mistakes in English.

It is only a PWM shield ? Then using the Arduino pins (with a 'dumb' motor driver module) would be better for a small and large stepper motor. Or maybe a complete module that drives the stepper motor and can do ramps, for a large stepper motor. Well, if you have it working now you can keep using it, but it is far from ideal.


text:
Is there a good Arduino enclosure for that works with the Olimex MIDI shield
I have a MIDI project I put together using an Arduino UNO R3 and the Olimex Shield-MIDI.

I want to install the project permanently in my Guitar rack so I want a decent enclosure, but there doesn't seem to be anything that would support the extra height that the MIDI ports have, relative to the Arduino + Ethernet enclosures.
Has anyone come up with a good solution for Arduino + MIDI projects?  A metal enclosure would be a plus.

You would need a custom enclosure, or some random enclosure with custom holes. How much do you balance cost against DIY competence? :)

By Guitar rack, do you mean something like this?

Your best bet is to 3D print the enclosure.
There are many places that will 3D print your enclosure for you and most will mail it to you as well. I would recommend Shapeways as they are fairly reasonable in price and ship worldwide.
If you are a handy DIY person you could use SketchUp or Tinkercad to design your enclosure. Also there are many Arduino enclosures on Thingiverse that you could use as a starting point.
Alternatively there are often places that will design (and then 3D print) the enclosure for you, you just have to supply your hardware. There are often a few places like this in each city.


text:
Do we really need to upload Arduino bootloader for new Atmega IC
I am using Atmega328p in my circuit. I will be programming this IC using Arduino. But because this is a PCB, so I will programming using USBasp programmer. So before uploading code as upload using programmer, I will select my arduino board in board select menu and then I will select USBasp as my programmer. But I want to know that is it really necessary to burn bootloader on a new Atmega328p IC. On some page, they say you do not require it. But some say, its necessary because you will be using Arduino functions like Serial.Begin() etc.
So I want to know what does this bootloader contains. Do I really need it. Can I directly upload my code using programmer. Can anyone please explain this to me.?

The bootloader is used to allow flash "self-programming" by the MCU, though USB. If you program the MCU through ISP, you don't need it. If you want to recover bootloader bytes though, you'll have to change some fuses (can't remember which ones, it also depends on the MCU, but you can google for it).

In fact, the bootloader is used to program a board through serial, not USB. So you may want to flash a bootloader on the 328p with an USBasp, then you just need to use the serial interface to download new sketches. On the other hand, you can gain a bit more space and faster boot times without a bootloader

You don't need to, but it has the side effect of setting the fuses. You you could just run it once. Then when you program your sketch, it will overwrite the bootloader, but keep the fuses. You could also manually set the fuses, which is preferable but a bit more complicated.

IIRC, at least the BOOTRST fuse should be programmed differently depending on whether you are using a bootloader or not.

No, you do not need the bootloader for your chip to function.  The bootloader is merely a convenience.
If you are programming through USBasp you don't even need it on a "normal" Arduino board.
All it does is allow you to program through the UART interface (or USB interface in the case of ATMega32U4 boards). If you don't want to do that then you don't need the bootloader.
If you do not provide a UART interface to the user that can be connected to then the bootloader would be pointless anyway since you cannot communicate with it.


text:
Problems creating 10Hz pulse wave
I'm trying to make a 10Hz pulse wave output at Arduino's pin 9 by using the following code I wrote:
#define F_CPU 16000000UL
#include <avr/io.h> //Defines pins, ports, etc.
#include <util/delay.h>

int main(void)
{

    DDRB |= (1<<DDD1); //Does this set port B pin 1 and is this pin 9 in UNO board?
    PORTB |= (1<<PORTB1);

    while(1){

        PORTB |= ~(1<<PORTB1);
        _delay_ms(100);
        PORTB |= (1<<PORTB1);

    }

}

I use Atmel Studio to uplaad the code and it works fine with other codes. But for some reason this code doesn't work. What can be the problem here?
Still doesnt work
edit:
#define F_CPU 16000000UL
#include <avr/io.h> //Defines pins, ports, etc.
#include <util/delay.h>

int main(void)
{

    DDRB |= (1<<DDD1);
    PORTB |= (1<<PORTB1);

    while(1){

        PORTB &= ~(1<<PORTB1);
        _delay_ms(100);
        PORTB |= (1<<PORTB1);

    }

}

You have your whole 100ms wait time while the pin is low.
You need half of it while low, half while high.
while(1){

    PORTB &= ~(1<<PORTB1);
    _delay_ms(50);
    PORTB |= (1<<PORTB1);
    _delay_ms(50); // You need a delay here too.
}

oh without the second delay it just jumps to low again. i see thanks. just curious is this a good way to obtain a very precise pulse frequency? i mean by using delay function as i did? or interrupts required? im trying to build a as precise as possible simple pulse generator.

@doncarlos no kidding, I was telling to you for a while!

@doncarlos and no, this is horrible way to do frequency generator. Use Timers and it's waveform generator modes instead.

Your code doesn't clear anything.

    PORTB |= ~(1<<PORTB1); // set everything except PORTB1 pin
    _delay_ms(100);
    PORTB |= (1<<PORTB1);  // set PORTB1 pin

And recommended tutorial: Bit manipulation (AKA "Programming 101") from the AVRFreaks.net
BTW: next issue might be "the pulse is way too fast so it seems there is none"
Try this:
while(1) {
    PINB = _BV(PINB1); // toggle pin
    _delay_ms(50);
}

Doesn't PORTB |= ~(1<<PORTB1); set PORTB1 pin to zero?

No, pipe | is logic OR, that means whenever is corresponding bit logic one, result is logic one

pulse is not fast and set to 10Hz _delay_ms(100). And I check with a scope. Theres nothing still

@doncarlos Well - there is clear bit, wait for 100ms, set bit ... and repeat..  that pause between setting and resetting bit might be even less than 200ns

   PORTB |= ~(1<<PORTB1);

change it to:
   PORTB &= ~(1<<PORTB1);

if you want to clear PB1.

I made that change but still doesnt work. Please see my edit.

@doncarlos see my "BTW" edit :D


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

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

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

No, you cannot set 6.4MHz on SPI with a default hardware arrangement.
On the ATMega series of chips the SPI clock is generated by dividing the system clock (8 or 16MHz depending on if you have a 3.3 or 5V board) by one of: 2, 4, 8, 16, 32, 64 or 128.
Looking at the datasheet (section 25) it may be possible to configure the USART to run in SPI mode which allows a flexible clock speed, though this is not supported by the Arduino API.

Just to be complete, the ATMegas can be clocked up to 20MHz

Yes, but the Ardiuno boards never are (or not that I have seen).

Yeah, thats right


text:
Does the reset button clean a programe that you programmed?
does the code clean from arduino if i touch reset button?

No, reset does not do that.

No, it only causes the microcontroller to start over the existing program/code.


text:
is it possible to power esp8266 with button cell
is it possible to power esp8266 wifi module with button cell for long period(1 year ) real time applications??
 Needs only wifi features (no need of gpio)
what will be voltage and current of the cell??

This is worth a watch.

No. It has to wake up to do something and turn on the wifi. At that moment it requires too much power for a button cell. It needs about 150mA, mostly for wifi.
The BLE (Bluetooth Low Energy) is specifically designed for low power usage. Also some RF modules (433MHz, 868MHz, 915MHz) can be used with a small battery.

can you suggest an alternative for this problem

I agree it won't have the best lifespan, certainly not a year, but  the math shown is likely pessimistic. 150ma is on the high-end of estimations, especially for modules with the newer antenna and not far from the router. Also, those hi-energy pulses only last a ms or two; the avg draw on a short run is closer to 50ma. OP: 2 parallel coin cells can provide twice as much current, which solves potential early-shut-down issues, but not the short-lifespan ones...


text:
Problem with TIMER in Arduino DUE
I'm writing a code to print/update the value of sensors for each 10 ms, and I decide to use Timer instead of delay function (I'm afraid it's not exactly 10ms with delay function).But when I watch the result on terminal, it stops running at about 0.5s. I guess there is a problem with my code in using Timer because when I remove timer, it prints normally. I debug all day but still cannot find any errors. I guess this is related to memory or pointer or print function.
Please help me :( !!
Here is the code. The code is very long but you can ignore all the unnecessary things:
  #include <DueTimer.h>

  int mod_11k = 12;
  int mod_17k = 13;

  int analog1 = 0;              //output pin of signal 1
  int analog2 = 1;              //output pin of signal 2
  int analog3 = 2;              //output pin of signal 3

  float xf; float yf;
  unsigned long t1;
  unsigned long t2;

void myHandler(){
    Serial.print(t2-t1);
    Serial.print(" ");
    Serial.print(xf,3);
    Serial.print(" ");
    Serial.println(yf,3);
}

void setup() {
  Serial.begin(38400);
  pinMode(mod_11k,OUTPUT);
  pinMode(mod_17k,OUTPUT);
  Timer1.attachInterrupt(myHandler).start(10000);
  digitalWrite(mod_17k,LOW);
  digitalWrite(mod_11k,HIGH);
}

void loop() {
    afficherSig(analog1,analog2,analog3);
}

void afficherSig(int pin1, int pin2, int pin3){
  unsigned int i;
  float mes[3];
  float mesflt[3];
  float x; float y;
  int  nb_ech = 10000;
  float res = 0.0049;
  float Te;
  float Tbeg;
  float QR1[2],QR2[2] ;
  float *sol1;float *sol2;float *sol3;
  float P1[4];float P2[4];float P3[4];
  float xprec1[2];float xprec2[2];float xprec3[2];
  float *s1_11k;
  float *s1f_11k;

  float H = 80;

                                       //------------------------------>>>
  QR1[0] = 1;
  QR1[1] = 10;
  QR2[0] = 1;
  QR2[1] = 100;
  P1[0] =QR1[0]; P1[1] =0; P1[2] =0; P1[3] =QR1[0];
  P2[0] =QR1[0]; P2[1] =0; P2[2] =0; P2[3] =QR1[0];
  P3[0] =QR1[0]; P3[1] =0; P3[2] =0; P3[3] =QR1[0];
  xprec1[0] =0; xprec1[1] =0;
  xprec2[0] =0; xprec2[1] =0;
  xprec3[0] =0; xprec3[1] =0;
                                      //------------------------------>>>
  t1 = millis();
  Tbeg= millis();
  mes[0]  = res*analogRead(analog1);
  mes[1]  = res*analogRead(analog2);
  mes[2]  = res*analogRead(analog3);

  xprec1[0] = mes[0];
  xprec2[0] = mes[1];
  xprec3[0] = mes[2];
  Te = (millis() - Tbeg)/1000;
  Tbeg = millis();
  sol1 = Fkalman(xprec1,mes[0],P1,QR1,Te);
  sol2 = Fkalman(xprec2,mes[1],P2,QR1,Te);
  sol3 = Fkalman(xprec3,mes[2],P3,QR1,Te);

                                      //------------------------------->>>
 for(i=1;i<nb_ech;i++) {

    P1[0] =sol1[2]; P1[1] =sol1[3]; P1[2] =sol1[4]; P1[3] =sol1[5];
    P2[0] =sol2[2]; P2[1] =sol2[3]; P2[2] =sol2[4]; P2[3] =sol2[5];
    P3[0] =sol3[2]; P3[1] =sol3[3]; P3[2] =sol3[4]; P3[3] =sol3[5];

    xprec1[0] =sol1[0]; xprec1[1] =sol1[1];
    xprec2[0] =sol2[0]; xprec2[1] =sol2[1];
    xprec3[0] =sol3[0]; xprec3[1] =sol3[1];

    free(sol1);
    free(sol2);
    free(sol3);

    mes[0]  = res*analogRead(analog1);
    mes[1]  = res*analogRead(analog2);
    mes[2]  = res*analogRead(analog3);

    Te = (millis() - Tbeg)/1000;
    Tbeg = millis();
    sol1 = Fkalman(xprec1,mes[0],P1,QR1,Te);
    sol2 = Fkalman(xprec2,mes[1],P2,QR1,Te);
    sol3 = Fkalman(xprec3,mes[2],P3,QR1,Te);

    mesflt[0] = sol1[0];
    mesflt[1] = sol2[0];
    mesflt[2] = sol3[0];                               // Envoie des résultats  à la sortie série

//Traitment du signal
    s1_11k = traitement1(mes[0],mes[1],mes[2]);
    s1f_11k = traitement1(mesflt[0],mesflt[1],mesflt[2]);

    x = H*s1_11k[0];
    xf = H*s1f_11k[0];
    y = -H*s1_11k[1];
    yf = -H*s1f_11k[1];
    t2 = millis();
  }
}

float *Fkalman(float xprec[2],float ymes,float P[4],float QR[2] ,float Te){
                     // Filtre proprement dit
    float *sol = NULL ;
    sol = (float*) malloc (sizeof(float) * 6);
    float xpred[2];
    float Ppred[4] ;
    float Kf[2] ;
    int q = QR[0];
    int r = QR[1];

    xpred[0] = xprec[0] + Te*xprec[1];
    xpred[1] = xprec[1];
    Ppred[0] = q*q + P[0]+ Te*(P[2] +P[1]+Te*P[3]);
    Ppred[1] = P[1] + Te*P[3];
    Ppred[2] = P[2] + Te*P[3] ;
    Ppred[3] = q*q+ P[3];
    Kf[0]  = (Ppred[0]/(r+Ppred[0]));
    Kf[1]  = (Ppred[2]/(r+Ppred[0]));

    sol[0] = xpred[0] + Kf[0]*(ymes-xpred[0]);
    sol[1] = xprec[1] + Kf[1]*(ymes-xprec[0]);
    sol[2] = Ppred[0]*(1-Kf[0]);
    sol[3] = Ppred[1]*(1-Kf[0]);
    sol[4] = -Kf[1]*Ppred[0]+Ppred[2];
    sol[5] = -Kf[1]*Ppred[1]+Ppred[3];
    return sol;
  }

  float *traitement1(float mes1,float mes2,float mes3)
  {
    float *sol11 = NULL ;
    sol11 = (float*) malloc (sizeof(float) * 2);
    sol11[0] = (mes1-mes2)/(mes1+mes2);
    sol11[1] = (((mes1+mes2)/2)-mes3)/(((mes1+mes2)/2)+mes3);
    return sol11;
  }

Here is the result using Timer (stop at about 0.5 second):

Using Serial.print inside the timer interrupt routine is not advised. It also doesn't look like it is doing what you actually want, and that is to measure every 10 ms. It just reports the last measurement every 10 ms (which might be stale). For now try increasing the baud-rate of the serial connection, and see if that helps.

I increased baud-rate, it still stops in the middle (but the program can print results longer). Can you suggest any modification of the code to achieve my objective? (I tried using millis() but it still stops in the middle).

As noted in the last part of Nick Gammon's answer to the question How does the Arduino handle serial buffer overflow?, if the serial output buffer fills up, serial output blocks, waiting for an interrupt telling it it's ok to send the next byte out the serial port.  When interrupts are turned off, that interrupt is never processed, so the program deadlocks. Don't do Serial prints in an ISR.
Looking at your code, it looks like a typical message has about 20 characters.  Sending at 38400 bps, or 384 characters per second, it seems to me the buffer shouldn't fill, even if it's small (16 bytes) instead of large (64 bytes).  However, I don't know of another explanation for the behavior you describe.
Summary:  In your ISR, just store the current time and other relevant data in volatile variables, set a flag in a volatile variable, and in your main loop print stuff and clear the flag (or clear the flag and print stuff) whenever you see that the flag has been set.

Edit 1: I've struck out some erroneous numbers above.  Here is a correction:  100 sends per second at 20 characters each is 2000
characters per second.  38400 bps of asynchronous data at 10 bits per transmitted byte is 3840 characters per second.  So the raw data rate should be fast enough that the buffer ordinarily doesn't overfill.

In the summary above, I suggested that the ISR store the current time and other relevant data in volatile variables and set a flag in a volatile variable.  That is, read millis() and store it, perhaps as follows:
// at file level ...
volatile unsigned long isrMillis;
volatile byte isrFlag;

// in ISR ...
  isrMillis = millis();
  isrFlag = true;

// in main loop ...
  unsigned long mlMillis;
  ...
  // when flag is true...
  cli();
  mlMillis = isrMillis;
  isrFlag = false;
  sei();
  // Now do stuff with mlMillis
  ...

However, looking at your ISR, perhaps it should go like the following instead:
// at file level ...
volatile float xf, yf, xfc, yfc;
volatile unsigned long t1, t2, tdelt;
volatile byte isrflag;

// in ISR ...
void myHandler(){
  tdelt = t2-t1;
  xfc = xf;
  yfc = yf;
  isrFlag = true;
}

// in main loop ...
  // when flag is true...
  isrFlag = false;
  // Now do stuff with tdelt, xfc, and yfc
  ...

Note that if an interrupt occurs while xf and yf are in the middle of being computed via your Kalman filter or whatever, the statements  xfc = xf; and   yfc = yf;   may pick up partially-stored results.  You can avoid that problem at least in part by protecting stores of t1, t2, xf, yf in the main loop:
  cli();
  xf = someXResult;
  yf = someYResult;
  t1 = someT1Result;
  t2 = someT2Result;
  sei();

In the above I've pointed out a few issues with races and concurrency and suggested technical solutions.  Those suggestions may be quite wide of the mark rather than appropriate.  In general I don't have a precise understanding of what you are trying to do with the software and don't know what redesign should be done to make it coherent.

As you said, I will set the timer for 10ms, and print stuff in loop() or another function. But my typical message is about 20 characters, which mean each time printing, it will take me ~5.2ms to print all. I'm wondering if I have to adjust the time setting for Timer or not? I want to be as close to 10ms as possible to match my sensor reading with another external reading.

@NguyễnThanhVũ, see edit


text:
Identification of IoT
For a school project I Have to make an IoT solution in the retail. We were thinking of a smart clothing hanger. We want to make the hanger smart enough to recognize what clothing is hanging on it. In order to do so the clothing has to be able to send some sort of ID to the hanger.
first thing we thought of was RFID but the hanger next to an one hanger would pick up the signal from the other hanger so that wouldn’t be an option.
Does anyone have any other ideas on what we could try to let the piece of clothing talk to the hanger?

if it's not too late, i would re-roll the dice on a topic (if it has to be practical)

What about manikins that move when a LDR detects movement nearby.

@sa_leinad Interesting idea but I think people will be scared if a manikin suddenly moves.

Well I guess the signal strength could be measured but clothes hanged in wardrobe are too close to each other to distinguish them. Maybe close range NFC?
I have other solution to be considered.
Maybe you look at the wrong touchpoint of that interaction. What if the desired action occurs not while it's already hanged but when user put the clothes on hanger? During that, it's not with other clothes (as you grab the hanger in your hand to put the clothes on it).
There are a few things to consider. I guess people put things only on one hanger at once while having clothes in second hand. How many % of users puts clothes on hanger by grabbing it outside of wardrobe (as mundane event/behavior)?
Why it's important?
During that interaction there is a moment when user tries to pair single cloth with single hanger separated from the rest.
The hanger could have additional sensor to know when it happens:

Magnetic field sensor and small magnet in collar?
Capacitive sensor?
Accelerometer?

...so the device will know when that interaction occurs and then activate the reading from single rfid tag.
I guess my answer is more about user experience and the aesthetics of interaction but it can give you some clues to finish your project.

Your answer is great. It opend my mind a little bit. Thank you!