perform an action maximum x times per hour is it possible to perform an action maximum x times per hour on the arduino?

I made a automatic water sprinkler that sprays when the humidity is lower than 50%. but if the sprayer performs this "spray" more than 4 times an hour the humidity wil be to high and wil rise to fast.so is there a way to restrict the amount of times an action is performed per hour,and then if the next hour comes the sprayer can perform his "sprays" 4 times before it stops again

sorry for bad english, this is not the language I speak (and type) mutch

Sure it's possible. It would be better if you had a real time clock module. Then you could use time-of-day.

You need to define your problem a little better. Would it be ok to run the sprinkler every 5 minutes, then not again for 40 minutes, for a total of 4 sprays in an hour, but clustered together? Do you want to prevent 4 sprays in a clock hour, or not go over an average of 4 sprays per hour?

Without a realtime clock module, I guess here's what I would do:

After a spray, record the time (in millis). Then in your loop, don't spray again for 15 minutes (15*1000*3600 milliseconds.)

The code would look something like this: (not real code, more like pseudocode)

const unsigned long fifteenMinutes = 15*1000*3600;
unsigned long nextSprayTime = 0;

loop()
{
  if (millis() >= nextSprayTime)
  {
    if (humidity < 50)
    {
      spray();
      nextSprayTime = millis() + fifteenMinutes;
    }
  }
}

Edit: You said, in comments:

  i want it not to go over 4 sprays an hour,i have the ds1307 rtc
  module. situation: ist an automatic egg incubator and the humidity
  must be between 50% and 60%.i control the sprayer whit a dht11 sensor
  an a servo connected to an spray bottle. if the humidity is below 50 %
  the servo starts whit spraying.the servo keeps on spraying every
  second until that 60% mark is reached and then shuts of.so the amount
  of water in the box is way to much and so the humidity keeps on
  climbing until the 100% mark whit is deadly for the eggs

Ok, that gives your readers a clearer picture.

You're dealing with a process control problem, not just a hardware or software problem.

When you spray water, it will likely take several minutes for the change in humidity to stabilize and be detected by your sensor.

Your current approach sounds wrong because you dump far too much water into the system, and don't give it time to reach a new equilibrium before adding more water.

You need to collect some data.

There is going to be a significant lag between putting a spray into the incubator and sensing the increase in humidity, and when the increase reaches it's max.

You need to measure that lag.

You also need to know how much a single spray increases the humidity.

You should probably **ALSO* figure out how many sprays at a time you can spray before water droplets form on the walls of your incubator and on your eggs, since I assume that is very bad and to be avoided at all costs. Thus I would add a moisture detector to your system (A small piece of cloth with electrodes on it at 2 locations a couple of CM apart, and a sensitive conductivity sensor that detects the change from insulator to weak conductor that takes place when the cloth becomes saturated with water.)

You should also figure out how fast the humidity in your incubator drops if you don't add any water, for a variety of different conditions. (Likely affected by current humidity, outside temp and outside relative humidity, so you probably want 2 humidity sensors, one inside and one outside the incubator, and to record all the variables and graph them.)

I would suggest writing a data collection program. You might want to run it with the serial cable connected to a PC constantly, or install an SD card and save your data there.

In all your tests, you probably want to wait a significant time (15 minutes? 1/2 hour? 1 hour?) for the incubator to reach equilibrium before beginning your test.

You want the conditions of your incubator to be as close to your real-world conditions as possible. You might want to put eggs (dummy eggs, grocery store eggs at room temp, or something like that) in the incubator during the test to allow for the amount of water they absorb. You want the outside temp to be as close to your real-world temp as possible. If the incubator will be exposed to direct sunlight, air vents, wind, etc, then you want those same conditions.

At each step in every test you should record the current time, the current outside temp and humidity, and the current incubator temp and humidity, and the time of each spray you trigger.

Add your condensation detector at the beginning, and any time it detects condensation you should sound an alarm, record the time that it trips, and abort the current test. If you get liquid condensation you've done something wrong and need to adjust.

Write a program for your computer that graphs all your data points over time. Every time you run a test (other than the very first test) graph all the data and look at it. Patterns will probably jump out at you.

Test 1:

Record the time and the current humidity. Add one spray of water, and then record the humidity for 15 minutes. Look for an increase in humidity and when it peaks. The time from adding a spray to the peak increase in humidity is what you want.

Test 2:

Then modify your program to log the spray-to-peak-humidity-increase time, and each time it detects the humidity starting to drop again, spray once more, log the current outside temp and humidity, the inside humidity and outside time of the spray, and repeat.

This will give you spray-to-peak-humitity lag times over a range of humidity values. Graph that data with starting relative humidity on the x axis and the lag time on the y axis and look at it. Is it a constant value? A straight line? Is it a geometric curve? Exponential? Come up with a curve that fits the data fairly well.

Test 3:

A test that uses an increasing number of sprays, looking for how many sprays you can do at once before you cause condensation.

Start with 2 sprays.

Look for the peak increase in humidity, and once the humidity starts to drop, increment your spray counter to 3, spray that many times, and repeat. When the condensation alarm trips, stop the test.

Note that the number of consecutive sprays you can do before the moisture alarm trips will probably change for different starting humidity levels. My guess is that the max number of sprays you can add without triggering condensation will be highest at your lowest humidity level, and as the humidity increases, you'll get condensation with less and less sprays.

Test 4:

Figure out how to measure the max number of sprays that trigger condensation when you start at less than your minimum humidity, at your minimum humidity, at halfway between min and max, and at max. (This experiment will take some thought since it's not easy to get to a given humidity level, and once you trigger condensation you'll have to stop, dry everything out, and start again.)

Test 5:

Get your incubator as close to the maximum acceptable humidity (60%) as you can at the beginning of the test, or even a little above. Simply record the humidity every minute until it drops to the lowest acceptable level (50%). Graph the data. That will show you how fast the humidity drops if you do nothing.

Test 6:

Repeat test 5 for the range of outside conditions you might find in your production environment. (If you're in a climate-controlled space, do you have summer and winter thermostat settings? Test for those upper and lower ranges. How much does your indoor humidity level vary?)

Now what?

Now you have lots and lots of data.

More than likely you have an idea of how many sprays you can add at a time without triggering condensation over your humidity range. This should be fairly simple: (for example, at humidity < 50% to 52%, you can use 3 sprays.  AT 53-55%, 2 sprays. Above 55%, 1 spray.) You should also have a rough idea how much increase you'll get in humidity for a given number of sprays.

You have an idea of how fast the humidity drops if you don't add water.

You have an idea how long it takes for a spray set of sprays to cause a peak in the humidity level.

Write a program that strives to keep the incubator in the middle of your desired range. If 50% is your absolute minimum humidity level and 60% is your max, then trigger sprays at 52%, not 50%. Spray as many sprays as you can without causing condensation (or overshooting your max humidity), then lock out sprays for the time period you calculated as the time it takes for your sprays to cause the maximum increase in humidity.

If you've found that the max number of sprays you can do at a time is different for different humidity levels, use code that comes up with a number of sprays that stays below that limit. Also try to estimate how much increase in humidity you get per spray, and each time you trigger a series of sprays, stay below the number of sprays that reaches your max humidity.

If you've found that the conditions outside the incubator have a big effect on your system, adjust your code to compensate for those changing conditions.

You want a system that uses small adjustments over time to keep a system at near equilibrium. Big adjustments will likely cause wild variations in conditions that go outside of the acceptable range.

Other considerations:

Do you need to open the incubator at regular intervals to check on the eggs or turn them, or do you have an egg turner? If you do need to open the incubator, you will need to figure out the effect this has on your temp and humidity levels for the range of outside conditions you face. You can probably build your system with a door sensor that detects you opening the door, the outside temp and humidity, and how long the door is open. Once you close the door, it would note the new inside temp and humidity and make an educated guess as to how much the humidity will drop after being open, and add water accordingly.


AC Motor speed control using SSR? I want to control speed of an AC Motor using phase cutting..
Well, I already have zero cross detector and SSR but don't know how to program Arduino to phase cutting using SSR..
And to connect the motor to SSR, do I need some protective circuit or not? Thanks!

First of all no protective circuit is needed in order to connect an arduino with an SSR. SSR input is isolated from the load.
Now answering your question you better go with an inverter, forget the SSR, and let arduino control the inverter. Using DOs from an arduino you can command the inverter to start/stop the motor or change the motor direction. Using an AO e.g provided by a DAC like MCP4921 you can control the motor RPM, too. There are a lot of inverters available for different loads and also different controls (Manual, Digital/Analog, Serial)

As per Your question You must need a protective circuit to save the Arduino from Back Voltage.

Take reference from this Link AC Motor Speed Control


Best way to send I2C commands between Arduino and ESP32 I made a board with an Arduino nano and a ESP32 Dev kit. I connected them via I2C with voltage adaptation. I'm using arduino IDE and the related library Wire.h.

I send messages as ascii chars or native bytes from the ESP32 (master) to the Arduino (slave) and all work fine.

I have to take a decision now. I have to implement a simple protocol to send command to the Arduino, in order to ask it do some tasks or in order to ask it to send some data to the esp32 (e.g. the speed of a motor or the state of some sensors and so on).

What I would ask is your suggestion if the simple protocol has to be managed as native bytes (the natural way I2C work) or as string (managed by mean of an array).
I try to explain.

In case of bytes I could send for example FF 0E14 01 to ask arduino to start the motor=FF at the speed=0E14 and direction=01. So the specific command is coded in the first byte.

What I miss is the need or not for a delimiter like "<" and ">" as used in case of string. In case of exchange of native bytes the value of "<" is "busy" in an integer and couldn't be distinguish by the parser. So what delimiter could I use?

On the other hand in case of strings I don't like the necessity to convert number "213" or "1529" in the relative integer. In case of the previous command I could send the string

""

having in mind the first char as command and for this specific command "S" ("S" for example) parsing the following chars until the "," and convert it in a integer and last char as direction (as byte or as char the test is the same).

I don't know... what way do you suggest and in case of native bytes what delimiters?

Thanks.

First, using a byte-value based protocol is the standard with I2C. There is no real reason to go to ASCII encoded data (The reason for doing this with Serial (UART) is normally, that the message is human readable at the PC. This is normally not the case with I2C, since only computers like the Raspberry Pi even have I2C interfaces).

About delimiters: They are only really needed for asynchronous data transfers (as UART)(to frame a full packet/message) or maybe, if you have an unknown transmission size. Both is not the case for I2C (it is a synchronous interface, that already implements transmission packages/message). You can look at the datasheet of any I2C sensor. The standard communication protocol is a command send by the master, then sending/receiving a specific number of bytes with a specific protocol, that defines, which bytes contains which information. Here you don't need a delimiter, because you already know, in what format the data will be send.

Let's take an example from your question: You want the Arduino to report the speed of your motor to the ESP. You implement the first byte of every master write transmission as a command, for example the decimal value 10 as command to report the motor speed. Then you terminate the master write transmission and request 1 byte from the Arduino (since you already know, that the motor speed has 1 byte). The Arduino knows through the command, that it should send the motor speed byte, and the ESP knows, that the byte received will be the 1 byte motor speed.

Now we define the command 11 to report the motor speed and the 3 bytes sensor value. The ESP sends 11 and then requests 4 bytes, as it knows, that the message will be 4 bytes long. The Arduino sends the data and the ESP knows, that the first byte will be the motor speed and the following 3 bytes the sensor value. No delimiter is needed, since the structure of your data is already defined through the implementation of your protocol. Start or end markers for a message are not needed, since I2C already works with distinct message/packets of data (a transmission is started with a START condition on the bus and ended with a STOP condition).

This solution is used for most I2C devices, since it is easier to implement at a low level. At the first glance for us humans it seems easier to use ASCII encoded and thus human readable data. But as you already mentioned, this makes it more complex for microcontrollers (writing parsers for ASCII data is more complex than using binary data on a fixed protocol). Keep in mind, that I2C means "Inter Integrated Circuit", so communication between integrated circuits, not communication between an integrated circuit and a human.

But in the end it is up to you to decide, which protocol you want to use.

As you might not know the concept yet: A Finite State Machine (FSM) is a good way to implement such a communication protocol on both sides. You define a state variable and based on this variable only the corresponding code is executed. You can change the state by changing the state variable.

For example on the Arduino (receiver side): First state could be the command state, where the Arduino waits for an I2C transmission. If a transmission was received, it will read it's first byte. Depending on this byte it will go into a different state, for example into the "Send motor speed" state. There it will prepare everything to send the motor speed to the master, should the master request data from the Arduino.

How to implement a FSM in detail is covered in many tutorials on the web and also in many questions on this side. You can see my answer to this question, where I explained this in more detail.

Before giving pointers to your question; First I will start to recommend to avoid using i2C for these kind of things and recommend UART (Serial) which is much better for communication between multiple mcu's.
The UART) Serial Gives you a stack (memory of received data) meaning that you receive data when processing other functions and act on them in arduinos' own time. UART is more then fast enough for things like this and enables longer distances then few cm, its more resilient to interference
UART (Serial) uses fewer ports and most ports can be converted into Software Serial
You will find many libraries which deal with communication even encryption over Serial If you use write() rather then print you don't have to convert the data.if you use correct input on your arduino, you can even read the data as it comes from your PC and much more
Anyway, to your question Most of the data communications tend to have a starting byte and the ending byte to package the pocket among common ones is 00-Start and 0xFF as end.Now assuming that we only have one slave and single priority level etc we don't need to be too much of smartasess for package header... next I would define Process as it will let you chose the function that then can receive then next details as variables.
This option means that you will have to number the operations from 1 not 0Major benefit is that as different function may take different number of variables (for example one only states on off, while other states vector distance) you will not have to decide on a packet length, but simply deal with any number of variables (within reason)


What is the difference between delay() and delaymicroseconds() Does delaymicroseconds() provide something more than the time accuracy

There is a more important difference between the two functions other than the unit of time the accept as parameters
the function delay() calculates time using the time interript of the arduino. However Delaymicroseconds() does not use the time interrupt
As you may know once an interrupt is called it stops all other interrupts
So the real difference is you can not use delay() in a program in which you are using an interrupt and instead, use delaymicroseconds() but be aware that it has a range where it is accurate and it is between 3 and 16383 micro seconds


Arduino and 2 MOSFETs I want to turn on 2 bulbs using 2 MOSFETs. The problem is that they both turn on when it should turn up just one light.

Code:

void setup() {
  pinMode(13, OUTPUT);
  pinMode(7, OUTPUT);
}

void loop() {
  digitalWrite(13,1);
  digitalWrite(13,0);
}

See circuit below:

Try adding a delay into your loop. In your code pin 13 will toggle very rapidly, much too fast to see it. For example:

void loop() {
  digitalWrite(13,HIGH);
  delay (1000);
  digitalWrite(13,LOW);
  delay (1000);
}

It doesn't look wired correctly. For an N-channel MOSFET the Source should go to ground, like this:

i prefer you to use relay to control any ac appliance with arduino it very much safe...

Just follow this circuit diagram and use 5v relay in your project it will always work fine.....


Switching 4.2V circuit with 3.3V Arduino GPIO I am trying to learn about MOSFETs and see this p channel MOSFET and this tutorial.  I am trying to use a 3.3V arduino GPIO pin to control a load that is powered from a 4.2V battery in much the same configuration as the circuit drawn in that tutorial.  Most other tutorials I see say the Gate Voltage needs to be equal or greater than the Source Voltage, but the tutorial I cited describes that actually the Voltage between the Gate and Source just needs to be more negative than the Threshold Voltage.  The P channel mosfet I cited is Vthreshold -2V to -4.  So my question is whether this P channel MOSFET would allow me to use a 3.3V arduino GPIO to control whether that 4.2V source is closed or open to the drain/load.  Looking at how that tutorial does the math, it seems in my case the GPIO being off would mean Vgs is 0 - 4.2 = -4.2 and therefore the MOSFET is in the ON state.  If GPIO is on at 3.3V then Vgs is 3.3 - 4.2 = -0.9 and therefore the MOSFET is OFF.  However, the tutorial doesn't say what happens when Vgate < Vsource but by an amount less than the Vthreshold so I don't know if my math is right.
In sum my questions are:

Is my math and prediction of the MOSFET states correct when that 3.3V GPIO is on or off?
If not, is it because of some other quality in this MOSFET and a different P MOSFET would work?
I presume that if I keep out of the Vgs upper and lower bounds then I avoid issues where the MOSFET is in a partially on and partially off state, is that correct?
Is it just impossible to use P MOSFETS in this way?

Note:  My questions only pertain to P MOSFETs.  For my project (switching a 1-2A disco light toy), it has to be a high side switch and that's even besides the point because I am more importantly trying to understand how the P channel mosfets work.

The MOSFET you chose will probably fail. Using a 30V device on a 24V system is asking for problems. Go to a minimum of a 60V MOSFET and use a UIS, Avalanche rated one. R4 is very week for what you need to do, I would suggest something in the 10K range to swamp out any leakage in the Arduino. If the MOSFET is properly rated the flyback diode is not needed but make a space for it incase you have to sub a MOSFET. Putting C2 in parallel with C1 will help. I do this a lot with electrolytics. I double up each one the needed size when one fails you don't notice it. I would suggest a couple of 220nF caps across the motor but that is application dependent.


How to transmit characters or just use xbee like serial monitor I have an arduino mega and an uno, mega has an xbee s2c as coordinator and uno an xbee s2c as router, both in AT ( transparent ) mode. When I send integers from uno with Serial.write() coordinator receives just fine, but when i try float, negative numbers and chars, i get still integers but as I found out sending chars it is in ASCII. I tried Serial.print() but no result. Is there a way to send a negative float from one xbee to the other in AT mode?

Coordinator code

void setup() {
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  Serial1.begin(9600);
  Serial.println("Comersing test!");
}

void loop() {
  if(Serial1.available()>0){
         Serial.print(Serial1.read());
    }
}`

UNO code

#include <SoftwareSerial.h>
 SoftwareSerial xbSerial(8, 7); // RX, TX
void setup() {
  xbSerial.begin(9600);
  xbSerial.write("First data sent!");

}
int x=4;
void loop() {
  // put your main code here, to run repeatedly:
      xbSerial.write(x);
      x++;
      delay(1000);
      delay(1000);
      delay(1000);
}

if I change x in Uno to float, negative or char, I get weird values.

XBee cannot send negative integers, as it is working in hexadecimal and it has range between 0-255


ESP32 millis not working properly I have a program which measures temperatures every 30 minutes and sends them to a database. Immediately after running the program the first measurement is sent, however, the second (which should be sent after 30 min), is sent only after 1 hour. From then on the code works fine. The time is measured in millis. However, if I set the time difference to 28 minutes everything works fine from the beginning. What could be the reason for this? Is there a possibility that it goes to sleep mode? I don't understand why it works fine with 28 minutes and it stops working with 29 minutes?
Thanks in advance!
My code:
if (millis() - sendDataPrevMillis > 1740000)
  {
    sendDataPrevMillis = millis();

//other code

}

The only part I change, so it works is setting millis from 1740000 (29 minutes) to 1680000 (28 minutes).

Although not strictly required, maybe use parentheses around millis() - sendDataPrevMillis for readability;
I guess you will have initialised sendDataPrevMillis to 0 but
the first time you assign sendDataPrevMillis to millis() some time will have elapsed since you evaluated. So calling millis() twice will give different results. That makes it less easy to see what is going on.

Suggestion to try:
long HALFHOUR = 30 * 60 * 1000L;

if ( (millis() % HALFHOUR ) == 0L ) {
    //measure and send
    //....
}

Hope this helps.
NB: % is what is called the 'modulo operator' see: https://www.geeksforgeeks.org/modulo-operator-in-c-cpp-with-examples/


GPS: Not receiving any valid output from ATGM336H I have an Arduino Pro Mini along with a GPS Unit - ATGM336H. Below is the sketch I'm currently using:

#include <SoftwareSerial.h>
#include "Ublox.h"
SoftwareSerial GPS(4,5);
Ublox serial_gps;

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

void loop(){
  while(GPS.available()){
  char c = GPS.read();
  if(serial_gps.encode(c)){
  Serial.println(serial_gps.longitude);
    }
  }
}

I'm able to receive NMEA stream from the GPS Unit and parse (tried TinyGPS++, TinyGPS and Ublox) the stream but the data is not valid nor does it ever change. I've read that this GPS unit can take up to 32 seconds to get a fixed position and deliver valid co-ords but I cannot receive any.

Is there anything obviously wrong with my sketch or hardware setup?

Any and all help would be greatly appreciated!

while(GPS.available() > 0) {....

Also is the GPS unit outside?


Arduino tone frequency isn't always precise I'd like to play an asynch 'beep' sound (2.5kHz, pin 8) on an Arduino Mega with several other modules connected. I write them here, just for the record: SDCard reader and RFID reader through SPI bus, RTC through I2C, GSM module through hardware Serial 1. And I use PWM on two other pins (11,12) for controlling LEDs brightness.

It works well, however, sometimes (1 of 10) the beep frequency is about half-tone higher.

The code itself is good, because I use a constant in the tone() function call for specifying the frequency.

Does anybody have an idea what can influence the tone's PWM frequency such way, maybe on hardware level?

As far as I know, tone() implements pin toggling in software (using timer interrupt), so it's possible that the frequency is lower when there's a lot of activity and higher when the CPU is mostly idle.

Try calling your beeping code alone inside an otherwise empty sketch and with no external hardware, and check out whether the sound is higher than you expect.

Half-tone, that's a lot of change.  I would expect a lowering of frequency if anything from other resources being active.  An increase in frequency suggests perhaps something is changing the internal counter values that is used for the toggling.
2.5KHz is 400microseconds, toggling every 200us. You might consider using Arduino "blink without delay" to monitor the passing microseconds and toggling based on that. I've created up to 20KHz signal that way, but not with anything else running.


Connecting Nokia 106 to Arduino I was wondering if this can be done. I got a Nokia 106 and am trying to make it talk, but the audio jack doesn't seem to cooperate and the Fbus pins are right under the SIM slot, which is right under the battery. Any advice?

Added: It seems that it talks AT commands, since it is a GSM model, but I'm not 100% positive.

Here's the picture of the Nokia FBUS connector from your link:

And here's a (slightly dubious) method of connection from some random web page

which goes on to say

  The F-bus protocol uses 115,200bps so we can easily use the Arduino’s serial function to communication with the phone. All you need to is hook up the phones TX to the Arduino’s RX and then use a resistor divider (I choose 330 ohm resistors) to connect the Arduino’s TX to the phones RX as shown above.

That page goes on to show how to use an Arduino to get the phone to send SMS text messages.

Sources:

http://www.insidegadgets.com/2013/01/12/how-to-use-nokia-f-bus-to-send-an-sms-message/
http://forum.gsmhosting.com/vbb/f148/nokia-105-new-100-working-solution-1731398/

just trim the actual simcard, so its level with 'microsim insert' back edge. Its what i did on my Nokia 100/GPO 746 project, works fine, wont kill the phone


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

Here is a photo of a similar motor:

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


Is SPI a good way to connect two rfid modules on separate arduino boards? RFID access control

I have two separate rfid projects on separate arduino, the first project requires 2 minutes of contact between the tag and the reader after which it turns the LED on. the second project is a simple rfid access control, but on this access can only be granted if the conditions on the first tag were met. I am trying to use SPI for this but do not know if it would work, any suggestions on any other way of communication between two arduino boards?

Its very easy.

Set one PIN of ARDUINO as ouput pin. You will write that PIN HIGH when your conditions are matched in ARDUINO1 then SET LOW after 1 mS.
Connect that PIN of ARDUINO1 to external Interrupt PIN of ARDUINO2.
Write a CODE for ARDUINO2 such that when EXTERNAL INTERRUPT OCCURS it will set variable high indicating that Conditions is Matched in ARDUINO1.
While providing access to on ARDUNO2 check that variable status if it is HIGH grant access and SET it LOW.

This is the basic Structure you can follow using interrrupt.


How can program/arduino restarted by IDE? I wrote my custom sketch, where I am printing some greeting text inside setup() method.

I found, that each time I am restarting IDE, and opening serial monitor, a greeting text is printed there again, i.e. setup() method running again.

How can this happen? I was thinking setup() method run once, when Arduino is powered up by connecting to the USB socket?

If it is possible to restart it already connected, then how this can be done?

UPDATE

Code is follows:

#include <Wire.h>
#include <Adafruit_BMP085.h>

Adafruit_BMP085 bmp;

String command;

String awaitingMessage = "Temperature and pressure sensor awaiting commands\r\nCommand \'help\' is for help";

void awaiting() {
  Serial.println(awaitingMessage);
}

void help() {
  Serial.println("Temperature and pressure sensor commands:");
  Serial.println("temp\t- output temperature in degrees Celsius");
  Serial.println("press\t- output pressure in Pascals");
  Serial.println("wait\t- print awaiting message");
  Serial.println("help\t- output this text");
}

void temperature() {
  Serial.println(bmp.readTemperature());
}

void pressure() {
  Serial.println(bmp.readPressure());
}

void unknown() {
  if( command.length() > 0 ) {
      Serial.println("Unknown command was \'" + command + "'");
    }
}

void setup() {
   Serial.setTimeout(50000);
  Serial.begin(9600);
  if (!bmp.begin()) {
    Serial.println("Could not find a valid BMP085 sensor, check wiring!");
    while (1) {}
  }
  else {
    awaiting();
  }
}

void loop() {
  command = Serial.readStringUntil('\n');

  if( command.startsWith("temp") ) {
    temperature();
  }

  else if( command.startsWith("press") ) {
    pressure();
  }

  else if( command.startsWith("wait") ) {
    awaiting();
  }

  else if( command.startsWith("help") ) {
    help();
  }

  else {
    unknown();
    //awaiting();
  }

}

Video is here: https://youtu.be/-QBleGVxaus

When you open the serial monitor (or even just go to the serial port menu) the serial port is opened. When the serial port is opened the DTR line is asserted.  This is the method that the Arduino uses to reset so that you can access the bootloader and upload a new sketch.

Every time you open the serial port - through whatever means you choose - you reset the board, whether you like it or not.

There are a number of "fixes" for this - the simplest is to add a large (say 10µF) capacitor between the RESET and GND pins of the Arduino to filter out the reset pulse that would otherwise reboot the board.

There are also ways of disabling the reset within Windows, but that requires you to write your own software to interface with the board instead of using the serial monitor.

Some boards also come with a method of completely detaching the reset signal from the USB interface, but modifying the board itself isn't for beginners.

Just remember that once you have disabled reset through whatever means you will have to re-enable it (resolder the track you cut, remove the capacitor, whatever) before you can upload a new sketch.

This means your Arduino or ATmega328 is restarting due to another issue. Usually the Arduino will reboot when there is too much amperage draw which is called a brown-out.

It can also mean there is a bug in your code.

Please also note as you mentioned

  I found, that each time I am restarting IDE, and opening serial monitor, a greeting text is printed there again, i.e. setup() method running again

The Arduino will reboot when opening the serial monitor.


uint8_t * to integer and string Convert text array/buffer to integer and string.

hi! i'm sending text to an arduino and the output of that library is a
uint8_t array.

Atm the text send is a number between "0" and "1023"

void something(uint8_t * text){
 analogWrite(13,text);// does not work
}
/*
toInt() also not
int() not
atoi() not
invalid conversion from 'uint8_t* {aka unasigned char*}' to 'const char*'
*/

i need to convert it to an  integer or better to a uint16_t.

As i plan to send custom commands in near future it would also be good to know how to convert that array to a string, that i then split/manipulate/parse.. whatever.

i looked in various posts but i couldn't get it to work on that simple example above. i'm new to c++

if it's needed the length is also aviable inside the function.

Your problem is that you are storing your text in an unsigned pointer (uint8_t *)instead of a signed pointer (char *).

If you change all your text types to char * then you can directly use atoi().  If you have a lot to change, though, you can just cast the unsigned pointer into a signed one (and make it const at the same time):

analogWrite(13, atoi((const char *)text));

I've converted first four bytes to string, and then to int :

void something(uint8_t * payload){
String str="";
char c;
for(int i=0;i<4;i++)
    if (isDigit(c=(char)(*(payload+i))))
        str += c;

int Val =str.toInt();
Val=Val>1023?1023:Val;

analogWrite(14,Val);
}


Problem to upload code I tried to upload example code form arduino software and got error below. Two arduino attach with my computer running windows8.1. And These arduino using port 3 and port 4. The arduino using Port 3 is cordinator and arduino using port 4 is router.
I doesn't understand why error show COM1 is not available. I am not using COM1.

Arduino: 1.6.0 (Windows 8), Board: "Arduino Uno"

Sketch uses 1,030 bytes (3%) of program storage space. Maximum is 32,256 bytes.

Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes.

C:\Program Files (x86)\Arduino/hardware/tools/avr/bin/avrdude -CC:\Program Files (x86)\Arduino/hardware/tools/avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM1 -b115200 -D -Uflash:w:C:\Users\Jiya\AppData\Local\Temp\build1135139715306090793.tmp/Blink.cpp.hex:i

avrdude: Version 6.0.1, compiled on Apr  3 2014 at 23:12:16
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "C:\Program Files (x86)\Arduino/hardware/tools/avr/etc/avrdude.conf"

         Using Port                    : COM1
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: ser_open(): can't open device "\\.\COM1": The system cannot find the file specified.

avrdude done.  Thank you.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

Board at COM1 is not available
Board at COM1 is not available
Board at COM1 is not available
Board at COM1 is not available
Board at COM1 is not available

  This report would have more information with
  "Show verbose output during compilation"
  enabled in File > Preferences.

(I'm assuming you're using the official Arduino IDE here.)

Before uploading a sketch, you need to select which port you want to upload to. Within the Arduino IDE, click on the Tools menu and open the Port submenu. Click on the port your Arduino is connected to, such as COM3 or COM4.

You also need to ensure the appropriate board type is selected in Tools -> Board.

You should then be able to and upload the sketch.

your kernel need to provide support to USB ACM.

CONFIG_USB_ACM=y

you can look for it at:

$ zcat /proc/config.gz | grep CONFIG_USB_ACM
CONFIG_USB_ACM=y


avrdude: ser_open(): can't open device "\\.\COM3"? My computer cannot detect my Arduino Uno anymore,

Reset button- > L led light blinks and it turns on forever
Arduino 1.6.5: Tools->Port (greyed out) I remembered that previously it wasn't like this
Unable to upload any sketch codes into the Uno anymore
The existing code uploaded onto the Uno is FastLED(FirstLight) and it will work on my LEDs when I plugged them in

I have tried to .... but none fix my issue

Restart my computer
Press the reset button on the Uno
Using the device mananger to change COM ports
Device manager -> Other devices -> (nothing about Arduino Uno is found here)
Plugged Uno into another computer but still doesn't work
Reinstalled IDE

Problem shown in sketch,

avrdude: ser_open(): can't open device "\.\COM3": The system cannot find the file specified.
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

I have experienced a similar issue after plugging in another Arduino device. I didn't set up my environment for a long time and thus forgot he iterates the COM-Index. Maybe this is too easy, but you didn't provide much information.

This solved my problem:
Open Arduino application > Tools > Port > Change to the target Port

If you are unsure which port to choose from: (on Windows)
Open Device Manager > Connections (COM & LPT) > Usb Serial Port (COM[x])
where "[x]" is the index you are looking for.

Try a different arduino w/ your first computer, see if that will work.


Serial read in ESP8266-01 not working I am new to programming. kindly bear with me. I am trying to use ESP8266-01 device for serial read and write application. Before writing the full program for my application, i wanted to test how it functions. I programmed the ESP8266-01 device to read the data from its Rx pin and write it to Tx pin. I used a standard USB-TTL cable to send and receive data from PC using Hterm. The ESP device does not read the data available at the Rx pin. what am i missing ?. Also kindly help me in understanding the difference between serial.println and serial.write with respect to ESP8266-01 device. As per the program if i check the data from the Tx pin of the ESP8266 device, i get only "No data received". I am using arduino IDE 1.6.11. Kindly provide some guidance

regards

Sriniketh

#include <ESP8266WiFi.h>

void setup() {

Serial.begin(9600);
}

void loop()
{
  byte serin=0;
  if (Serial.available()>0)
  {
    serin=Serial.read();
    delay(100);
    Serial.println(serin);
    delay(100);
    Serial.write(serin);
  }
  else
  {
    Serial.println("No data received");
    delay(5000);
  }

}

A circuit diagram or photo would help, but I would guess you have taken the lead from the PC that is marked Rx and connected to the pin on the ESP marked Rx.  That's the wrong thing to do.  Firstly the PC will use 5V and the ESP uses 3.3V, so you need a little board called a level shifter something like this 2 channel level shifter.  This will let a 3.3v device talk to a 5V device.  Some ESP boards are 5V tolerant, but I don't know what you have so ...

Then when you "talk" over serial you need to cross the Tx and Rx between the two devices, so the can 'hear' each other

 PC - Tx  ---> Rx - ESP
 PC - Rx <---- Tx - ESP

(Lots of other level shifters are available and a lot are cheaper than the example shown, a lot cheaper!)


Take an Arduino or Teensy prototype to Mass production - Loading software onto microcontroller I am developing an educational product that I would like to mass produce. I am not sure of the quantity yet, but I imagine we will make a few hundred PCBs at least to begin

I spoke with an electrical engineering about how to take an Arduino prototype to mass production, and he warned me that the code written in the Arduino IDE cannot be fused onto the processor. (He used the term "fuse", although I don't see this elsewhere in the forum. is this the right term?)

He said that I would probably have to take each product, and load the Arduino code on manually, plugging in each one to a computer and upload like one would when prototyping. Also, he said the other option would be to recode my Arduino sketch from scratch using an AVR code.

Can someone shed some light on this for me? How can I take Arduino prototyping code and use it in mass production?

Arduino code and AVR code is essentially the same, at least once compiled it is. The only real difference is the existence of the bootloader, and that is not essential.

For quantities of a hundred or so it is probably most cost effective to manually program them via an ISP connector to the board. For larger quantities Atmel provide a mass programming service to pre-program the chips, but that costs money so the more you have done at once the cheaper it is per chip. I am not sure on Atmel's procedure off hand but others I have used just take either a .elf or .hex file which the Arduino IDE is perfectly capable of producing.

Either way you should design in an ISP connector on your board so the firmware can be upgraded in the future if needed.

For mass production, you really don't want to use your arduino code done with their IDE. There is several reasons for that, first would be optimization, then the portability (you may want to chose another MCU that fits closer your needs), and also robustness. The c++ like that arduino is using to ease the coding process is really not the best thing to use while programming MCU.

So to respond, definitely rewrite the whole thing in actual C and using AVR compiler.


Bootloader only works once with usb to serial module When programming the Pro Mini using this USB-to-serial adapter the boot loader only works once. After the first programming the programmer is out of sync or not responding.

To be able to program the Pro Mini again I have to burn the bootloader using my Uno as an ISP.

Programming the Pro Mini through an Uno does not present the same problem.

Are the lock bits not being set properly or somehow overridden?

The module I had does not have a DTR signal. I mistook the RTS for DTR. Ordering correct module.


Arduino ESP8266 direct/fast control of the digital pins How does one control a digital pin directly avoiding the slow digitalWrite or digitalRead?

After a weekend of searching and trying, here is what I was looking for:

It is slightly different than for the AVR chips. There is one register for setting the pins to HIGH and another one to set the pins to low.

Setting the pin HIGH:

GPOS = (1 << PIN_OUT);

Setting the pin LOW:

GPOC = (1 << PIN_OUT);

using this, I managed to speed up my code by a factor of three. It is not as dramatic as for the AVR chips, since the digitalWrite function is much more simple for the ESP8266.

the process outlined by ratchet freak is the correct one.

essentially, at the lowest level, you set or clear certain bits, as shown earlier in ratchet freak's post.

how exactly you do that, however, is a function of your approach or preference.

for example, if you want to access registers directly, use "eagle_soc.h" through "ets_sys.h".

if you want to use pre-defined routines, use "gpio.h".

if you want to use oem drivers, use "gpio16.h".

if you want to use other people's libraries, follow their instructions.

if you want to roll your own, well, sky is the limit.

essentially, you have to decide which route to take first and then follow the specific instructions.

but the gist is the same, as outlined by ratchet freak earlier.


Controlling Servo Motors with push button. Problem though I have this setup where I have and Arduino Uno, a mini servo motor, and a pushbutton. I use a single pushbutton to control the servo motor to go to one position, then push it again to go back. It first goes to 0 degrees, then if you push it it goes to 180 degrees then vice versa. The problem is that in its initial state (which is 0 degrees), the servo motor makes noise. Like it's running or something then it gets hot.

I've seen other servo motors that never do this. Here is my code by the way:

#include <Servo.h>

const int buttonPin = 8;
const int servoPin = 9;
int buttonState = 0;
int directionState = 0;
Servo servoOne;
int pos = 0;

void setup() {
  servoOne.attach(9);
  servoOne.write(directionState);
  pinMode(buttonPin, INPUT);
}

void loop() {
  buttonState = digitalRead(buttonPin);
  if (directionState == 0) {
    if (buttonState == HIGH) {
      directionState = 1;
      for (pos = 0; pos < 180; pos = pos + 1) {
        servoOne.write(pos);
        delay(5);
      }
    }
  } else if (directionState == 1) {
    if (buttonState == HIGH) {
      directionState = 0;
      for (pos = 180; pos > 1; pos = pos - 1) {
        servoOne.write(pos);
        delay(5);
      }
    }
  }
}

I really need all the help I can get.

You might need to add more time to the delay. Also, check how your powering the servo. If you're powering from the Arduino, it might be drawing to much current and causing issues. If it's a bigger servo, try to hook it up to an external power source and just connect the PWM line and it's ground.

I think you need to do some debouncing  on the button.

You can modify the code to suit your project:

/*
 Debounce

 Each time the input pin goes from LOW to HIGH (e.g. because of a push-button
 press), the output pin is toggled from LOW to HIGH or HIGH to LOW.  There's
 a minimum delay between toggles to debounce the circuit (i.e. to ignore
 noise).

 The circuit:
 * LED attached from pin 13 to ground
 * pushbutton attached from pin 2 to +5V
 * 10K resistor attached from pin 2 to ground

 * Note: On most Arduino boards, there is already an LED on the board
 connected to pin 13, so you don't need any extra components for this example.

 created 21 November 2006
 by David A. Mellis
 modified 30 Aug 2011
 by Limor Fried
 modified 28 Dec 2012
 by Mike Walters

 This example code is in the public domain.

 http://www.arduino.cc/en/Tutorial/Debounce
 */

// constants won't change. They're used here to
// set pin numbers:
const int buttonPin = 2;    // the number of the pushbutton pin
const int ledPin = 13;      // the number of the LED pin

// Variables will change:
int ledState = HIGH;         // the current state of the output pin
int buttonState;             // the current reading from the input pin
int lastButtonState = LOW;   // the previous reading from the input pin

// the following variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long lastDebounceTime = 0;  // the last time the output pin was toggled
long debounceDelay = 50;    // the debounce time; increase if the output flickers

void setup() {
  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);

  // set initial LED state
  digitalWrite(ledPin, ledState);
}

void loop() {
  // read the state of the switch into a local variable:
  int reading = digitalRead(buttonPin);

  // check to see if you just pressed the button
  // (i.e. the input went from LOW to HIGH),  and you've waited
  // long enough since the last press to ignore any noise:

  // If the switch changed, due to noise or pressing:
  if (reading != lastButtonState) {
    // reset the debouncing timer
    lastDebounceTime = millis();
  }

  if ((millis() - lastDebounceTime) > debounceDelay) {
    // whatever the reading is at, it's been there for longer
    // than the debounce delay, so take it as the actual current state:

    // if the button state has changed:
    if (reading != buttonState) {
      buttonState = reading;

      // only toggle the LED if the new button state is HIGH
      if (buttonState == HIGH) {
        ledState = !ledState;
      }
    }
  }

  // set the LED:
  digitalWrite(ledPin, ledState);

  // save the reading.  Next time through the loop,
  // it'll be the lastButtonState:
  lastButtonState = reading;
}


Arduino ultrasonic distance meter doesn't display correct distance The Arduino distance meter that I made doesn't display the correct distance. It just displays "0.0 inches".

Here's the code I used:

#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

int pingPin = 7;
int inPin = 6;
long duration, inches, cm;
int indec, cmdec;
int inchconv = 147;
int cmconv = 59;
String s1, s2;

void setup() {
  lcd.begin(16, 2);
  pinMode(pingPin, OUTPUT);
  pinMode(inPin, INPUT);
}

void loop()
{
  digitalWrite(pingPin, LOW);
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(pingPin, LOW);

  duration = pulseIn(inPin, HIGH);

  inches = microsecondsToInches(duration);
  indec = (duration - inches * inchconv) * 10 / inchconv;
  cm = microsecondsToCentimeters(duration);
  cmdec = (duration - cm * cmconv) * 10 / cmconv;
  s1 = String(inches) + "." + String(indec) + "in" + "     ";
  s2 = String(cm) + "." + String(cmdec) + "cm" + "     ";
  lcd.setCursor(0, 0);
  lcd.print(s1);
  lcd.setCursor(0,1);
  lcd.print(s2);

  delay(100);
}

long microsecondsToInches(long microseconds)
{
  return microseconds / inchconv;
}

long microsecondsToCentimeters(long microseconds)
{
  return microseconds / cmconv;
}

Here's the wiring diagram:

Might there be a problem in my code, or in my wiring?

To solve a problem like this you need to break it down into smaller pieces so that you can build up some confidence about what is working and what is not. When you share a problem like this as a question it helps if you can give us some idea of your experience level and of what you've already done to debug the problem – that helps with avoiding telling you what you already know and makes it easier to focus in on where the problem might be.

From what you've said it appears that you have things working well enough that you get a display on the LCD but it does not represent a meaningful distance.

Looking at your schematic the first thing that comes to my mind is that you have the ultrasonic sensor at the opposite end of the breadboard from the LCD. Many breadboards split their power rails at the middle. So start by confirming that you have power to the sensor.

After that, double-check the rest of your wiring.

The next step for me would be to confirm that I understood the sensor and to try and prove that it was working as I expected. Look for some sample code that is known to work (often the site you bought the sensor from will have links to beginning tutorials or code samples). Try that to see if the sensor works with the sample code.

If that doesn't work then check to see what you can do to prove the sensor is good (or bad). You might also contact the vendor to see if they can give you advice on proving that the sensor works.

Basically, break the problem down into "bite sized" chunks and work through it one step at a time, doing the simple stuff first. Try not to assume anything…

I think you should first check it in simulation and for that install Proteus software and get this Ultrasonic Sensor Library for Proteus and then test your code in simulation.

Once you confirmed that your code is working fine then you can come to the hardware debugging but I think its more probably because of programming issues.


Control Speed of DC FAN Using Arduino PID Library I want to make a circuit that control speed of DC fan Using Arduino PID Library to get thing at specific temperature.

The circuit looks like this but can be changed, The dc fan motor connected to PWM 3 and thermistor connected with pin A0.

The thermistor check the temperature of a device that heated by nearby heater so fan cools the device to get the specific temperature.

Case 1

When Heater not running, the thermistor value in Serial monitor 0-1023, When fan not running it gives 1023 and when fan runs at full speed it gives about 0.

Case 2

But when heater is running the values of thermistor has been changed and when fan not running it gives 1023 and when fan runs at full speed it gives about 500.

I want to set a point 650 from thermistor value(INPUT Value), and fan speed have to adjust using pid so temperature adjusted and the thermistor gives 650 value.

Sample PID code

 #include <PID_v1.h>
//Define Variables we'll be connecting to double Setpoint, Input, Output;
//Define the aggressive and conservative Tuning Parameters
double aggKp=4, aggKi=0.2, aggKd=1;
double consKp=1, consKi=0.05, consKd=0.25;
//Specify the links and initial tuning parameters
PID myPID(&Input, &Output, &Setpoint, consKp, consKi, consKd, DIRECT);
void setup()
{
  Serial.begin(115200);
  //initialize the variables we're linked to
  Input = map(analogRead(0), 0, 1023, 255, 0);
  Setpoint = 650;
  myPID.SetOutputLimits(0, 255);
  //turn the PID on
  myPID.SetMode(AUTOMATIC);
}
void loop()
{
  int sensorValue = analogRead(0);
  Input = map(analogRead(0), 0, 1023, 255, 0);
    double gap = abs(Setpoint-Input); //distance away from setpoint
  if(gap<10)
  {  //we're close to setpoint, use conservative tuning parameters
    myPID.SetTunings(consKp, consKi, consKd);
  }
  else
  {
     //we're far from setpoint, use aggressive tuning parameters
     myPID.SetTunings(aggKp, aggKi, aggKd);
  }
  myPID.Compute();
  analogWrite(3,Output);
  Serial.println(sensorValue);
}

What changes have to done in code so we can set point from input values?
And
Please help me so this code works for me.

Two thing that may be helpful.
First make sure you have a common ground. For instance for you transistor you are using separate power from the arduino and 12 volt source. Connecting the two ground of the arduino and the power supply may resolve this for you.
The other thing is it is often times helpful to put a capacitor across the DC motor to help with voltage fluctuations.

It may be better to not use map(), as it will give trouble between float and int variable usage - do it manually in the code.


TFT and SD don't work together I use a 2.8" TFT Touch Shield v1 and I want to read some data that were stred in sd and plot them with the tft.

When the following code is ordered, to access the data. TFT freezes.... but the code's execution is continued...

    pinMode(SS, OUTPUT);
    // see if the card is present and can be initialized:
    if (!SD.begin(chipSelect)) {
       Serial.println("Card failed, or not present");
    // don't do anything more:
       while (1) ;
    }

    Tempfile = SD.open("DATALOG.TXT",FILE_READ);
    if (! Tempfile) {
       Serial.println("error opening datalog.txt");
    // Wait forever since we cant write data
       while (1) ;}

I tested the code on the example of the tft graphics test... and the result was a freezed tft...

I tried also to run the example: tftbmp but the tft remains black. Once again the code is executed in the loop as i receive results from the Serial monitor but tft is black...

I use an Arduino Uno R3.

Any tip is welcomed

old topic, but since I'm having the same issues I'll share what I found.

chipSelect is usually 10 for arduino uno, some exemples have other pin setted.

also I found a guy claiming he fixed his issues setting after

pinMode(SS, OUTPUT);
digitalWrite(SS, HIGH);


Is Arduino Ethernet shield compatible with arduino due? Arduino Due's operating voltage is 3.3 volt and Ethernet shield operates on 5 volt supply. So my question is that this Ethernet shield will work on an Arduino Due and also if it will not harm the Arduino Due board due exceeding the operating voltage?

The Arduino Ethernet shield (or at least V2 of it) is based on a W5500 chip which itself features "3.3V operation with 5V I/O signal tolerance".  In other words, the core of it already is a 3.3v device, just one that can tolerate connection to a 5v Arduino.

Of course the shield is more than just the chip.  A very quick look isn't showing any glaringly obvious uses of 5v levels on the board in a place where a 3.3v Arduino derivative wouldn't expect them.

However, you should review the the full schematics and make your own determination that these are applicable to the specific board you plan to use and do not place 5v level on any signal the Due could not accommodate.

It's unfortunate that the shield documentation doesn't seem to say anything about compatibility, but worth noting the the Ethernet Library has some specifics for the SAM family of chips one of which is used on the Due.

The Ethernet Shield V1 was based on the W5100 chip.  This may not have 5v tolerant inputs, as it appears to use level translation on the input side.  But it is also powered from 3.3v, so likely the outputs would be fine for a Due.  An interesting question is if the V1 shield would be damaged if connected to a 5v Arduino with a sketch that erroneously drove MISO high as an output.

Of course it will harm your due. Now for that problem you could use a 3.3v to 5v and vice versa level converter.


avrdude: stk500_recv(): programmer is not responding Arduino IDE is throwing this error when uploading sketches - avrdude: stk500_recv(): programmer is not responding

The problem arose just after I uploaded a blink sketch to my Arduino Mini, which worked absolutely fine. After the successful upload I tried to upload a different sketch and got the error.

I thought I had destroyed the boot loader somehow and was about to get out the Bus Pirate for ICSP but I decided to try another Arduino Mini I had lying around (albeit from another manufacturer) and got the same error.

So I'm convinced it's a driver issue as I successfully uploaded a sketch (it still runs as we speak!) then just magically without changing ANYTHING I can no longer upload.

In a futile attempt to get back to work I've done the following:
Switched the RX-TX lines (clearly not the issue as the first upload worked)
Used a different FTDI cable
used a  different programmer
(FTDI 5V/3.3V USB to TTL Basic FT232 FIO Programmer)
(USB to TTL Serial UART RS232 Adaptor (PL2303HX)
I'm fairly certain these use different drivers - FTDI and Prolific

Please help me I'm about to murder something :'(

Screencaps of error and device manager - Imgur

Is it this?

"To upload a new sketch to the Arduino Mini, you need to press the reset button on the board immediately before pressing the upload button in the Arduino environment."

https://www.arduino.cc/en/Guide/ArduinoMini

avrdude: stk500_recv(): programmer is not responding

I have the same problem (Arduino uno)
I reset the Arduino several times, but finally i fixed the problem.
so you must change the pic of the arduino and make sure it was instilled correctly on the arduino board.

hope it work...


WiFi.begin doesn't work with ArduinoJson's const char* output I'm using ArduinoJson to parse a file full of JSON strings that contain the SSID and password for the registered networks. I have a little web interface that runs in soft AP mode so you can scan for networks and add them to the file. Adding networks to the file works fine, but reading them back and using them as input for WiFi.begin doesn't work. It moves to status code 1, which means it failed to find a network with that SSID.

I have compared the value of the result of const char* ssid = networks[network]["ssid"]; with const char* _ssid = "MySSID"; using strcmp and it returns 0, so I can't figure out why it's not working. It works if I replace networks[network]["ssid] with my SSID (though I need to replace the password with the string literal as well, otherwise it stays on status code 6, disconnected).

I can't figure out what it is about ArduinoJson, but it seems that the result of grabbing a string doesn't return a string that is formatted correctly for WiFi.begin, but it satisfies strcmp?

Edit:
I modified the code quite a bit in an effort to get it to work. I am no longer passing the ArduinoJson object, I'm now passing a struct with the data, and it still doesn't work. Is this the work of some advanced c++ constants/pointers stuff that I don't seem to understand?

main.cpp:

#include <ArduinoJson.h>
#include <ESPAsyncWebServer.h>
#include <ESPmDNS.h>
#include <SPIFFS.h>
#include <vector>
#include <elapsedMillis.h>

#include "config.h"
#include "restserver.h"
#include "scanwifiserver.h"

AsyncWebServer *Server = new AsyncWebServer(80);

ScanWifiServer *scanWifi;
RestServer *restServer;

struct Network {
    const char* ssid;
    const char* password;
};

std::vector<Network> readAP(fs::FS &fs) {
    //fs.remove("/ap.txt");
    File file = fs.open("/ap.txt");
    std::vector<Network> networks;
    if (!file) {
#ifdef DEBUG
        Serial.println("Failed to open file for reading");
#endif
        return networks;
    }

    while (file.available()) {
        DynamicJsonDocument n(JSON_CAPACITY);
        auto s = file.readStringUntil('\n');
        deserializeJson(n, s);
        struct Network network = {n["ssid"], n["password"]};
        networks.push_back(network);
        Serial.println(networks.back().ssid);
    }

    file.close();
    return networks;
}

void setup() {
#ifdef DEBUG
    Serial.begin(BAUDRATE);
    delay(2000);
#endif

    SPIFFS.begin();
    auto networks = readAP(SPIFFS);
    if (networks.size() > 0) {
        Serial.println("Networks:");
        int network = 0;
        Serial.println(networks.size());
        while (WiFi.status() != WL_CONNECTED && network < networks.size()) {
            const char* ssid = networks[network].ssid;
            const char* password = networks[network].password;
            Serial.printf("%s, %s\n", ssid, password);

            WiFi.begin(ssid, password);

            while (WiFi.status() != WL_CONNECTED) {
                if (WiFi.status() == WL_CONNECT_FAILED || WiFi.status() == WL_NO_SSID_AVAIL)
                    break;
                delay(500);
                Serial.print(WiFi.status());
            }
            Serial.println("");
            network++;
        }
        if (WiFi.status() == WL_CONNECTED) Serial.println("Connected");
        else networks.clear();
    }
    if (networks.size() == 0) {
        Serial.println("Starting ScanWifiServer");
        WiFi.mode(WIFI_AP);

        scanWifi = new ScanWifiServer(Server);

        Server->begin();

        MDNS.begin("grow");
        MDNS.addService("http", "tcp", 80);
    }
}

void loop() {}

I found the solution myself. I switched from using struct Network network = {n["ssid"], n["password"]}; to declare the struct and const char pointers to using char arrays and strcpy

struct Network network;
strcpy(network.ssid, n["ssid"]);
strcpy(network.password, n["password"]);

Seems like the pointers were getting freed or something right at the same time that I tried to use the value to connect to the network?

std::vector<JsonDocument> doesn't store a copy of the complete document, but just a copy of the internal pointers of JsonDocument. Therefore, at the time you use the value, it points to an invalid location.

This is clearly a bug, that's why I removed the copy constructor of JsonDocument, but the change hasn't been published yet.

You can fix your program by replacing the std::vector<JsonDocument> with std::vector<DynamicJsonDocument>.


Seeking to measure back EMF of an electric motor via Arduino Is it possible to measure the back EMF of a motor, using just the Arduino and no sensors?

Or what type of sensor do I need? One that measures current?

There is no need to measure the windings of the motor... please see the great write up for full details using an Arduino to sense the back EMF on a PWM driven motor to control the speed. This can be applied to a 3 phase motor as well, see Back EMF.

This person uses the analog input and a voltage divider to sense when the EMF happened, basically he gets the motor running, then periodically grounds one side of the motor through the H-Bridge he is using to drive it, and the other side of the  motor goes to a voltage divider into the Arduino... and it is also an open circuit at this time so the voltage generated is from the collapsing of the coil field so if it is 12V it becomes a safe 4V at the Arduino Analog input.

Now your question says "measure the back EMF", what I provided senses the back EMF... to measure it you just need to sample the Analog pin a bunch of times, and that will give you a reference of the max amplitude.

Take a look at this website:
http://www.vwlowen.co.uk/arduino/current/current.html

It shows how to make a create a simple current sensor with just a few resistors.


Burning a Uno bootloader into a Nano I bought some cheap Arduino Nanos from ebay, but the watchdog does not work in them.

So I removed their old bootloader and burnt a new Nano bootloader from the Arduino IDE. Same problem, the watchdog didn't work.

Then, I burned a Uno bootloader to the Arduino Nano and now the watchdog works properly. The only issue here is that in Arduino IDE I now have to tell it that I am programming an Arduino Uno instead of a Nano. So far everything seems to work just fine.

Are there other problems that may arise from using a Uno bootloader in a Nano? I notice that there are some extra analog pins in Arduino Nano, but I will still be able to use them with the Arduino Uno bootloader right?

Assuming they're based on the more recent Arduino Nano 3.x series or later, the microcontroller in your Nanos is probably an ATmega328 running at 16 MHz. That's the same as the Uno, so there should be no major problems hopefully.

It might be worth checking that you've got the latest version of the Arduino IDE though. I seem to remember there was a problem in some older bootloaders which prevented the watchdog from working properly.

In boards.txt in the Uno section, you change one line for the pinout type from uno.standard to all_pins or something like that to make the analog inputs A6 & A7 available. Compare the standard Nano line against the Uno line and you can see the difference.  I can't access the Arduino files from here to say what they are specifically, sorry.

Ok, here we go:

Uno
uno.build.variant=standard

Nano
nano.build.variant=eightanaloginputs

So change the Uno line to
uno.build.variant=eightanaloginputs

Then you can bootlood the Nano board with Uno bootloader and should have A6, A7 available without issue.


Arduino Fio and BC127 communication I am using an ArduinoFio and a BC127 (datasheet). I'm having troubles getting the serial connection working properly from the Arduino to the BC127 and viceversa. I wasn't able to communicate with the BC127 and I don't know if is because isn't correctly powered on or something else.

I've connected pin 0 of the BC127 to GND, pin 33 to 3V3 and pin 41,42 (RX, TX) to the TX, RX arduino's pins.

I've tested with the tester that all wires are connected, but the BC127 seems dead.

Any help is appreciated :|

There's a couple of things I would try.

First: Don't use the native Arduino TX/RX pins, they should be left alone to talk to the computer. Use SoftwareSerial instead in start a separate serial connection.

Second: Check that Arduino TX pin (that you declared in softwareSerial) is connected to the BC127 RX and vice versa. Unlike just about every other connection in electronics, serial connections need to have their pins reversed so that TX talks to RX. It's an easy mistake to make and one I've made when not paying attention to what I was doing.

Third: Flow control.

If the BC127 sends data when the Arduino isn't listening the data could be lost, to prevent this the BC127 won't send until the Arduino signals it is ready through flow control.
See the BC127 datasheet page 8, pins 40 and 43. Trying tying UART_CTS to 3V3 and UART_RTS to Ground. That should cause the BC127 to be in a constant 'send' state.

Lastly I'd hook up a couple of LEDs to pins 37 and 38. They should give you some sort of status indication that could be useful in debugging future problems.

Use voltage level translator. 5v to 3.3V. Dont just connect directly 5v tx to a 3.3v tx...!!


If I put a shield on an Arduino, can I use the Arduino for anything else? I did some basic Arduino examples in the recent past, but I have never actually seen a shield for Arduino firsthand.

So I wonder: If I put a shield on an Arduino (for example, the Adafruit Motor Shield), does it "block" the entire Arduino, including all input and output pins?

Is it possible to use a shield, and still connect additional components that would usually connect directly to the Arduino (say, a potentiometer, or anything similar)? Does this depend on the type of Arduino, or on the type of the shield, or is it not possible at all?

Normally, yes, you may plug other components to your setup after you plug your shield, but it depends on the shield exposing the unused Arduino pins through additional female headers.

Some shields even provide a little protoboard or perfboard to make it convenient for plugging or soldering additional components. Below are some examples:

Arduino shields are normally designed to be stackable, so you can plug one on top of the other. See more on Arduino shields from this WikiPedia article. See below one example of stacked shields, shamefully stolen from this great answer by RedGrittyBrick.

Photo by John Boxall

But note that you need to study carefully what pins each of the shields use to avoid conflicts between the boards. Such conflicts may lead to damages.

Yes, you can stack shields up to 4, because of power limitations. Only one this to be consider is the Pin configuration. You should make sure that the pins does not overlaps.

Example,

If I am using a gsm shield, It uses Pins 2 & 3 for Rx and Tx. I cannot mount on another shield with uses the same pin. Then we need to go for jumpers and other stuffs. A simpler way is to check the pin configuration and make sure that it does not overlaps.


Activate a DC motor for a fixed amount of time I have a single simple DC motor that upon a condition I wish to let it run for 3 minute. How can I do it in Arduino? a simple addition to the code will be great help.

As I use Adafruit motor shield this is my current code:

#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_PWMServoDriver.h"

Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_DCMotor *myMotor = AFMS.getMotor(1);

void setup() {
   Serial.begin(9600);           // set up Serial library at 9600 bps
   AFMS.begin();  // create with the default frequency 1.6KHz
}

void loop() {
IOvalue = 1000

if (IOvalue = 1000) {

 //this is the motor I wish to run for 3 min
   myMotor->setSpeed(25);
   myMotor->run(FORWARD);
   delay(100);
 }
}

Thanks a lot

#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_PWMServoDriver.h"

Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_DCMotor *myMotor = AFMS.getMotor(1);
boolean motorRunning = false;
unsigned long motorStartMillis;
unsigned long motorRunMillis = 180000;

void setup() {
   Serial.begin(9600);           // set up Serial library at 9600 bps
   AFMS.begin();  // create with the default frequency 1.6KHz
}

void loop() {
  IOvalue = 1000

  if (IOvalue = 1000) {
    //this is the motor I wish to run for 3 min
    myMotor->setSpeed(25);
    myMotor->run(FORWARD);
    motorStartMillis = millis();
    motorRunning = true;
  }

  // check if motor is running and time-to-run has elapsed
  if( motorRunning && (millis()-motorStartMillis > motorRunMillis) )
  {
    myMotor->setSpeed(0);
    myMotor->run(RELEASE);
    motorRunning = false;
  }
}

long int currentMillis;
void setup() {
    pinMode(motorPin, OUTPUT);
    digitalWrite(motorPin, LOW);
}
void loop() {
    if(condition is met){
        startOfMotor = millis();
        while(millis() != (startOfMotor+180000)){
            digitalWrite(motorPin, HIGH);
        }
    digitalWrite(motorPin, LOW);
    }
}

This motorPin is the pin to which the motor is connected. millis() gets the milliseconds after the board is started. 3 min = 180 seconds = 180000 ms.


Burn bootloader into Arduino UNO from Arduino Duemilanove I have been working with my Arduino UNO for 2-3 hours and after that it was not possible to load sketchs into the board since it returns a

  "avrdude: stk500_recv(): programmer is not responding" error.

The internal led "L" of the board is permanently on.

After a little research I guess that the bootloader was corrupted at some point (I still don't understand when and how).

Q: Apart from this board I have an Arduino Duemilanove board and I would like to know if it is possible to use this Duemilanove board to burn the bootloader in the broken board, is this possible? in afirmative case, how?

Since all the examples over there shows how to do it with the same board and not with a different one.

Yes, Nick Gammon has a page on doing that here  https://www.gammon.com.au/bootloader


Can I measure velocity from an accelerometer? How accurately? I've bought this module

Kootek GY-521 MPU-6050 MPU6050 Module 3 Axis analog gyro sensors+ 3 Axis Accelerometer Module

My project will involve affixing this to a moving object, moving at velocities varying from 0.1 to 1.0 meters per second.

From what I understand, this module will allow me to infer rotation and acceleration, will I be able to derive velocity?

How much accuracy can I expect?

The sensor in itself can't provide you the velocity. I have used it accelerometers in a couple of projects the easiest way to get the velocity is to constantly monitor acceleration changes and calculate velocity instantaneaously.

In order to do so follow these instruction. Pleas note that this is only 1 axis reading in actual case you will have to perform this for all three axis i.e. x,y and z.

I hope you are aware of the equation of motion (V = Vo + at)... The sensor will provide you value of acceleration at any given time. But acceleration can vary quite significantly during a huge time intervals so keep the time intervals 't' small. Lets say t = 10ms (depends on you). So calculate V after every 10ms intervale and this will give you current velocity at any given time. But what about Vo? As you know it is refered to as initial velocity so in the beginning it will be 0. Immediately after first reading when you are about to take second reading the Vo will change to the previous V calculated and hence forth.

This means Vo at any given interval is actually the V calculated in the previous interval.

I tried this method in my project when using accelerometer. hope it helps you as well.

Use to compass + accelerometer
Use compass to eliminate g from the readings


Can not upload to Arduino Nano BLE 33 I am new so please be nice :)
I am trying to upload the Blinky example to my Arduino Nano BLE 33 but I get this error message from the Arduino IDE:
No device found on ttyACM0
Set binary mode
Send auto-baud
An error occurred while uploading the sketch
Set binary mode

Any idea what I could try?
I am running the Arduino IDE as superuser in Manjaro (latest versions of everything). If you need any more information please feel free to ask.
Full IDE output:
Sketch uses 77820 bytes (7%) of program storage space. Maximum is 983040 bytes.
Global variables use 42192 bytes (16%) of dynamic memory, leaving 219952 bytes for local variables. Maximum is 262144 bytes.
Forcing reset using 1200bps open/close on port /dev/ttyACM0
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
Uploading using selected port: /dev/ttyACM0
/root/.arduino15/packages/arduino/tools/bossac/1.9.1-arduino1/bossac -d --port=ttyACM0 -U -i -e -w /tmp/arduino_build_408944/Blink.ino.bin -R
No device found on ttyACM0
Set binary mode
Send auto-baud
An error occurred while uploading the sketch
Set binary mode

It appears you are using Linux. In order to communicate you must establish yourself as being allowed to use it, that is the dial out function. "sudo usermod -a -G dialout " should work but you need to log out then back in before it takes effect. After that you are all set.


Arduino - Button to start / stop loop So basically I'm trying to create a device where when I push a button it starts a loop. When I push this button again, it stops the loop. Right now I have it logged to serial. It starts up correctly with no output. When I press the button the loop begins and it spits out "toggled on" continuously. When I press the button again... nothing happens. What should happen ideally is that it should stop spitting out "toggled on" and just go back to doing nothing.

#include <Bounce2.h>

Bounce bouncer = Bounce();
const int W = 10;
bool wOn = false;

void setup() {
  Serial.begin(9600);
  pinMode(W, INPUT_PULLUP);
  bouncer.attach(W);
  bouncer.interval(5);
}

void loop() {
  bouncer.update();
  if (bouncer.read() == LOW) {
    wOn = !wOn;
  }

  if (wOn > 0) {
    Serial.println("toggled on");
  }
}

If you change your sketch to this one, you'll see the issue:

const int W = 10;
bool wOn = false;

void setup() {
  Serial.begin(9600);
  pinMode(W, INPUT_PULLUP);
}

void loop() {
  if (digitalRead(W) == LOW) {
    wOn = !wOn;
  }

  if (wOn) {
    //Serial.println("toggled on");
  }
  Serial.println(wOn);
}

The button's contacts "bounce" (Google "contact bounce"), sending multiple low to high signals. There are several software solutions that will eliminate this issue. Have a look at: arduino.cc/en/Tutorial/Debounce. There are a couple of libraries that simplify de-bouncing buttons: playground.arduino.cc/Code/Debounce and playground.arduino.cc/Code/Bounce

Fixed. The solution I used was to add state change checking using .fell() which you'll see reflected below. I added state change verification using Bounce2.fell(), like so:

  if (bouncer.read() == LOW && bouncer.fell()) {


'serialWrite' was not declared in this scope Please help me! Once I click the upload button.
I get the following error:

  'serialWrite' was not declared in this scope

Here is my code:

int buttonPin
void setup ()
{
beginSerial(9600);
pinMode (buttonPin, INPUT);
}
void loop ()
{
if (digitalRead(buttonPin) == HIGH)
serialWrite('H');
else
serialwrite('L');
delay(1000);
}

It should be Serial.write to notice the period.

Which would make your code:

int buttonPin
void setup ()
{
    Serial.begin(9600);  # There was an error on this line as well
    pinMode (buttonPin, INPUT);
}
void loop ()
{
    if (digitalRead(buttonPin) == HIGH)
    Serial.write('H');
    else
    Serial.write('L');
    delay(1000);
}

Have a look at https://www.arduino.cc/en/Serial/Write for a complete example


Can I change Arduino program on-the-fly? I have Arduino which is programmed to do something. Is it possible that I could allow it to change behaviour by changing program on-the-fly without the need to reprogram Arduino via the computer.

What I need is to send the message via MQTT which will Arduino receive and change its behaviour by it. I managed to change the frequency of messages published or to add some new data, but what if I want to change how decisions are made. What if I want to change some Arduino code, to add some if or another state, can that be done on the fly?

Update: Changing device behaviour on the fly or after restart is acceptable. I am not strict with using arduino, nodemcu is and option. I just need a way to add new functionality to device if I need.

Replacing or modifying the existing code during run-time will require some form of uploading and over-writing the old code. This is deliberately not made straightforward or easy for these kinds of micro-controllers.

But you can change the program's strategy on the fly, if you anticipate the potential changes and include the code for each of the possibilities.

For example, write a set of functions that each embody one of the various ways of operating, and, at run-time, select which function the program should use. You can change the selection by setting a value from the keyboard or the program could sense some external trigger such as a button-press, or a temperature reading and respond by changing the selection - the value of an int, perhaps. A switch statement can use that value to call the appropriate function at the appropriate time:

uint8_t strategy = 0;           // init to the default strategy

switch( selector ){
case(1):                // has event 1 happened?
   func1();
   break;

case(2):                // has event 2 happened?
   func2();
   break;

case(3):                // has event 3 happened?
   func3();
   break;

default:                // none of the above or undefined selector value
   funcDefault();
   break;
}

This does mean that all of the code for the possible operating strategies must be included at upload-time and share the program-memory space, but unless your job is very complex, even an Uno should be capable enough.

Update:

  I need to be able to update the device with some new functionality.

There is another approach which may or may not fit in an Uno but would be doable with a Mega 2560 or other larger-RAMmed machine: interpreted code.

Define a set of operations that includes whatever you'll need to operate your external device(s): the necessary I/O operations to read your sensors and control your hardware; to make logical and/or arithmetic tests and conditionally branch or call a function based on the test result; to listen for a user-signal from the terminal (for example) and return to the arduino program. This will be the "language" in which you write your control program.
Define a concise coding scheme to specify each operation and whatever data it needs, such as reading a temperature sensor and storing the result in a named place. If your control programs won't be too complex, you can get away with pre-defining A, B, ..., Z to be data registers of some appropriate type.
In C++, write an interpreter for this new language. It's program will consist of the codes you just defined. But this code will be seen as data by the interpreter. This is the key - this pseudo-code will live in RAM, where your interpreter - a collection of C++ functions - can read and execute it, and the Arduino program can download a new one, over-write the old one, and run the interpreter again.

Caveat: Like the Greek mythological Hydra, this is a job that can grow new challenges as you address the current ones, but it is doable if you keep it simple as possible and include only what you must have to make it work.

Run-time-interpreted code can take 10 - 50 times as long to execute as a natively coded application, so anything that can be pre-coded in C++ should be. The finer and more flexible your interpreted instructions, the more expressive you can be when writing the control program, but the interpreter will be more complex to write, slower to execute, and harder to debug. Design your language to be only as flexible as it must be to allow you to write new control algorithms.

If you try to invent an entire pseudo-computer, completely flexible and capable of being programmed for any and all purposes, you'll drive yourself crazy. Whole businesses have folded after sinking money and time into inventing a new and better computer and got so bogged down they couldn't recover. Don't go that route.

Start with the grossest, least flexible operations you can live with and get that much working. Discover its limitations and address those, and only those, one at a time, until you have a sufficiently flexible system in which to control your device.

Is it possible that I could allow it to change behaviour by changing program on-the-fly without the need to reprogram Arduino via the computer.

Absolutely yes. As a matter of fact that's how many encrypted code works.


Can I use this pinhole camera with arduino? The pinhole camera is a 420TVL, 3.7mm Passive Infrared Detector Color Covert Security Camera. Can I use this camera with an arduino creation?

Things I don't know to answer the question:

Does the power need something special arduino can't offer?
Is the arduino powerful enough to push the video feed/photos to a computer or any other method to video/photos.

Here are some specs from the site:

  Sensor   1/3" Sony Super HAD II CCD
  Picture Elements  NTSC 768x494
  PAL 752x582
  Horizontal Resolution 420 TVL
  Minimum Illumination  0.001 Lux
  S/N Ratio more than 50dB
  Scanning System   2:1 interlace
  Synchronous System    Internal, Negative sync
  Auto Electronic Shutter   NTSC 1/60s ~ 1/100,000s
  PAL 1/50s ~ 1/100,000s
  Gamma Characteristics 0.45
  Video Output  1 Vpp, 75 ohms
  Auto Gain Control Auto
  Power / Current   DC 12V (±10%) / 150mA
  Lens  3.7mm Taper Pinhole Lens

Is it possible? They're on sale but I don't want to throw money away and find out that they don't work with any arduino. Also, I don't have any setup for this to be plugged into. Therefore, I'm not tied down to previous creations the cameras need to fit in.

No, you cannot use this with an Arduino without additional hardware in between, and even with it, not as more than a still camera (or maybe low quality video for one of the ARM- rather than ATmega-based boards).

The first problem is that this camera has a high speed analog output called composite video.  It is basically what would be fed into a modulator to produce an old-style analog TV signal.  Capturing this digitally requires an Analog to Digital converter (ADC) capable of several million measurements per second, while that on the classic ATmega-based Arduino tops out at around ten thousand.

But let's say you had an additional Analog-to-digital converter to put in between this and your arduino.  The next problem is that the data rate out of the camera will be too high, and the Arduino won't have enough RAM memory to buffer it.

In theory, you could get a "frame grabber" consisting of an ADC and its own buffer memory, which would take a still snapshot of the video and allow the arduino to read it out more slowly.  But you can buy cameras which already do that with their onboard electronics, and allowing something like an Arduino to read the still image data out over a moderate speed serial interface.

Even the ARM-based arduino boards would be taxed to keep up with the output of a video ADC and do much of anything useful with the results - typical digital cameras do not record raw images to SD card, but do JPEG compression within a frame.  When cheap digital cameras operate in video mode, they compress each frame of the video before storing it (just as with stills - they do not compress between frames in the manner of real video recorders), and are able to get that processing done in time because the actual computing hardware is optimized for it in a way that none of the Arduinos are.

If you want to experiment with a camera on a development platform, there is one with a high speed digital interface sold as an add-on for the Raspberry Pi board.  Or you can use a more inexpensive USB webcam with that.

As the question stands right now, YES you can use it.

NO, the Arduino should never act as a power supply for devices like this, so there's no power problems. You're going to power the camera separately, possibly from the same source as the Arduino, but power will not go from the source through the Arduino to the camera - NEVER do that! It doesn't even matter what the power requirements are for the device, but it needs 150mA at 12V which is more than the Arduino can supply anyway.
Yes. There are shields specifically for this purpose, but they usually include a camera. I'm not aware of one that has the camera separate, but you could easily copy the ADC section from something like this - http://blog.radioshack.com/2013/01/radioshack-camera-shield-for-arduino-boards/

See this too: http://www.arducam.com/


How time intensive or how long can an ISR be? I would like to code my ISR to be time intensive or interrupt the main program for atleast 1 or more seconds. My goal is to verify that if I am reading a sensor in the main loop, would it stop reading the sensor when the code is interrupted and for how long. I have trying to call various functions from the ISR like to turn on the motor but everything is instantaneous.

How long can an interrupt be?

If you don't want anything else to happen, then as long as the time between successive interrupts.

  would it stop reading the sensor when the code is interrupted and for how long.

While the interrupt is running nothing else can happen in software. Absolutely nothing. Only one thing ever happens at once - either your main loop or the interrupt. For the entire duration of your interrupt everything else is put on hold.

That includes things that rely on other interrupts to function, such as serial communications, millis() and delay(), etc. That means using such functions from within your interrupt handler is a big no-go.

It is generally very very bad practice to have an interrupt blocking for more time than absolutely necessary (a few milliseconds or even less). If you need to have things taking a long time then you should consider breaking them down into smaller operations and doing different sections at different times through different means.

Does the delay() function not work for you? It should halt all other processing, whether in ISR or not; so if you call it inside your ISR, your ISR would remain active for as long as the delay.

Of course, ISR should not be long like this. Perhaps there is a better way to code your test. Perhaps a variable that the sensor-reading code checks; if it's set to 1, don't read the sensor, and if it's 0, it's okay to read the sensor, etc.


How safe is it to use my body as part of a circuit? I have two polystyrene balls wrapped in copper tape. When the balls touch, the tape completes a circuit from a digital pin on an Arduino inside one of the balls to an Arduino inside the other (both powered by 9v batteries). This allows them to send information to each other via the copper tape path.

I was testing the balls out, and they were working too well. Even when the balls weren't quite touching, the signal was getting through! Turns out that's because the signals were travelling via my body. Even if I held one ball in one hand and the other ball in the other hand, digital reads on one Arduino were correctly reading the digital writes from the other.

This is actually great for my project!... unless it's not safe. So I'm looking for two things:

A reliable reference on what is and isn't safe in terms of voltage/wattage/amperage travelling from hand to hand.
A second opinion on the voltage/wattage/amperage that two Arduinos will actually pump through me (from digital pin to digital pin).

If you are talking about running at 5V, then I doubt there is any safety issue. After all, 9V batteries (the sort you put in your smoke detector) just have bare terminals and no-one tells you not to touch them.

There is quite a bit of related information at How much voltage is “dangerous”?. That link seems to have enough information that there isn't a lot of point of repeating it all here.

There is a reference on that page to someone holding a metal pole connected to a 12V battery wading through water which completed the circuit and he was unable to let go of the pole. But that is 12V (more than twice 5V) and in circumstances where there was good conduction (his body was wet).

In the interests of science I set up a small test. I connected myself to a 5V lab supply via an ammeter. I grasped the terminals firmly (with dry hands) and measured about 3 µA of current. From the page I referenced above there seems to be a consensus that 1 mA would be just noticeable, so this is about 300 times less.

I found if I wet my fingers I got up to about 20 µA of current, still a lot less than 1 mA.

That page mentions that 60V is getting into the range where you might get a shock.

Hopefully it goes without saying that if you are going to touch metal balls then you need to be certain that 5V is the maximum, and that some sort of failure in a power supply might not deliver a lot more. But if the balls are battery powered you should be pretty safe.

You've added that they are powered by 9V batteries. That doesn't change my answer much. The most that could "escape" due to some malfunction is then 9V. Under normal operation you would have 5V from a digital output pin.

I measured my body resistance as being around 1.5 MΩ, which is consistent with getting 3 µA of current through it.

I = V / R
I = 5 / 1500000 = 0.000003 A

i believe starting at one amp can kill you!


PWM generation using Arduino uno How to obtain four PWM outputs at 100 kHz using an arduino uno board? The requirement is that all four PWM outputs should have controllable duty ratios individually.

You can't squeeze 100kHz out of an Arduino without a major software rewrite (at which point you will be using an AtMega chip rather than Arduino). analogWrite defaults to ~500Hz and can be boosted to 62.5kHz on some Arduino models, and only for 2 pins. Other PWM pins are capped at 31.4kHz.

You can achieve 100kHz PWM by toggling pins manually and busy-waiting, but you won't be able to do anything else during this. Or you can make use of interrupts, which is a big leap from Arduino ecosystem as I already said.

use analogwrite() that's the arduino interface to the chips internal PWM capabalities.


Is it possible to power up Arduino upon serial transmission without dropping data? I have radiator valves that send readings about the temperature and valve opening to the serial output: Honeywell HR-25.

I want to collect those readings in a central server at home without flashing the thermostat with a custom firmware.

To do that, I need an Arduino (very bare one) that can receive the serial data, but at the same time I need it to be powered down most of the time, or it would kill the battery life of the thermostat.

Can I wake up an Arduino from power down using the serial transmission, and immediately capture the serial data without dropping bits? how?

I never tried myself, but afaik you can define an wake up/interrupt from USART, meaning that if you get a receiving byte from the UART it will wakeup the Arduino.

When powered up, you can read continuous data. I would be surprised if they make an UART wakeup signal, that bytes would be lost (i.e. that powering up would take too long to miss more UART bytes).

I don't think you can use the HW peripheral, so IF you really want/need low power you will need something like this (note: this may be very overkill for your application)

simulate this circuit – Schematic created using CircuitLab

NOTE: I assume the "serial" is a UART and its "rest" voltage is 5V. Choose the PMOS so that it is turned on with about 3V.

In this case, the circuit is normally powered off. When you receive a START, the PMOS start conducting. The ATMEL will then pull pin B to 5V, thus keeping the circuit powered. Through pin A it can sense the UART.

In this case, since you miss the start bit, you won't be able to use the usual libraries or peripherals. You can, however, implement a software uart which can avoid the first start bit to overcome this.

Just a suggestion, however. If your thermostat is transmitting frequently, maybe a more useful approach can be to listen to one transmission, then put everything to sleep for let's say 30 seconds, then turn on again and wait for the first serial transmission. This can be simpler than this solution and more effective


What do these operators do? Going through the "timeouts" example of the elapsedMillis library (https://github.com/pfeerick/elapsedMillis) I found the following statement:

digitalWrite(LEDPIN, flashPattern[ledIndex++] ? ledBrightness : !ledBrightness);

flashpattern is an array of boolean variables  (boolean flashPattern[] = { 1,1,1,1,1,1,1,0,1,1,0 };)
ledBrightness is a boolean as well.

What does the "?" and the ":" do there? are these boolean operators?

They are the conditional operator. If the expression before the ? is true then the result is the expression before the :, otherwise it is the expression after.

A ? B : C;

is shorthand for

if(A) {
    B;
} else {
    C;
}