How did I burn out this ESP8266 unit? ESP8266 -> FTDI -> USB Mac

I followed the wiring on this page: http://williamdurand.fr/2015/03/17/playing-with-a-esp8266-wifi-module/

I was communicating with it via Serial at 115200.  I issued a AT+UART_DEF=9600,8,1,0,0 and a few seconds later I looked over and it was smoking.

I bought 2 of these.  The previous one I had wired to an Arduino Nano running through a logic level converter.  That one only returns Exception (28) over and over again after issuing that same command.

On both units AT+GMR returned:

AT+GMR
AT version:0.40.0.0(Aug  8 2015 14:45:58)
SDK version:1.3.0

Are these units too hard to use? What did I do to burn it out?

[UPDATE]

Answer given was that I fed it 5v instead of 3.3v. Obvious. I didn't think I did but I checked the output of the FTDI and sure enough it was 5.1v.  So why does the output on it say 3V3 ?  I thought that meant that it was 3.3v...

Should have checked it first.

You supplied 5V to a device that only takes up to 3.6V. Heat generated by the excessive power did the rest.


2 sensors, add delay between each reading I have two temperature sensors, an MCP9808 and a DS18B20, connected to an arduino and I've read that it could be advantageous to set a small delay between temperature readings. What I wonder is where I should set the delay, in the setup function:

tempsensor.begin();                           //initialize communication with mcp9808
sensors.begin();                              //initialize communication with dc18b20
readSensors();

or the readSensors function?:

temp = tempsensor.readTempC();              //read current temperature and save value inside "temp"
sensors.requestTemperatures();              // Send the command to get temperatures
temp2 = sensors.getTempCByIndex(0);

As you can probably tell I am very new to all of this, intuition tells me that I should set the delay within the readSensors function.

Any alternative suggestions about how I should be readings temperature data from two different sensors connected to one arduino would be appreciated.

EDIT
after re-reading question and based on first answer I haven't made it unequivocally clear my intention; I want to delay the time between the mcp9808 and the ds18b20 temperature readings, so that it waits X seconds between each. I have read that this may help to reduce noise.

I've read that it could be advantageous to set a small delay between
  temperature readings

Although temperature is typically a measure that changes slowly in time, there is nothing in programming/device side preventing you from making readings in short intervals; unless this added time is necessary to prevent issues on other tasks, but so it should be not related to that.


Absolute encoder vs Accelerometer for calculating angles I've been toying with this idea for a while and after some thorough research I'm more than happy that the project is realistic. However I'm in need of some direction in terms of the sensors I should be using.

There will be 3 arms all connected together (Like a poor mans Microscribe). I want to read the angle between each arm and use that info to calculate the final X and Y coordinates of the final end point on the arm.

I've looked closely into forward kinematics in robot arms and understand the principles are very much the same.

I've narrowed it down to Absolute encoders or accelerometers. Unfortunately I just can't find enough documentation about how to use the encoder with Arduino. There's plenty on using an accelerometer but I can't imagine the accuracy would be as good as the encoder.

I'm hoping to get the X and Y coordinate accuracy within +/- 0.5mm. Is this accuracy feasible?

The diagram attached shows the basic principle and formula I will use.

------EDIT-----

Thanks for the info everyone! Seems like this is going to be a little trickier than I originally thought. I've found a project achieving something very similar, however there's no mention of it's accuracy. http://fablab.ruc.dk/diy-digitizer/

Any ideas as to what sort of accuracy he could be achieving? I understand the length of the arms are considerably shorter than mine which must help a huge deal.

I'm hoping to get the X and Y coordinate accuracy within +/- 0.5mm. Is this accuracy feasible?

I'm only going to consider the A1 in your diagram since the accuracy of that will have the greatest impact in the final position. For the other angles any errors will have a smaller impact on the final position accuracy.

Take the most simple case, the arm is in a straight line almost completely in the X direction.

You want a Y reading of +/- 0.5 mm with an arm length of 1400 mm. That will require an angular accuracy of +/- 0.02 degrees.

Assuming you have a maximum travel of 90 degrees and you scale things such that your full ADC range is used linearly over that range then you require log(90/0.02)/log(2) = 12.1 bits resolution on your readings. So after allowing for the noise in all sensor outputs you're looking at a minimum of a 14 bit data required to give that level of resolution.

It's been suggested you use a pot connected to the internal 10 bit ADC.
Assuming you used your full ADC range over 90 degrees and the 10 bit ADC reading had no noise on it you would be looking at around 2 mm accuracy. In the real world I'd be impressed if such a system could reach 5 mm accuracy.

Assuming you are working vertically accelerators could work, they typically have at least 16 bit resolution on the output but are noisy, you'd need to average for a long time in a very stable environment to get the levels of accuracy needed. Probably a non-starter.

A very quick google didn't find any easily available encoders with the required accuracy. I'm sure they exist but they are probably going to be expensive. You could possibly use gearing to improve the sensitivity of a more standard part but that's adding mechanical complexity.

In other words the accuracy you're aiming for isn't easy to achieve. You may want to look at relaxing your requirements a little.


Code flow execution between loop() and timer interrupts My platform is the Arduino DUE.
I know that the timer counts up to a certain value, then generates an interrupt.
In the Arduino DUE, you can specify the timer value. In other words, you can specify the frequency of the intterupts. You can do this via the TC_SetRC(tc, channel, rc) function.

My question is how code flows in general.
Obvisouly the arduino runs the setup function first.
After that it jumps to loop.
But when does tghe timer starts counting down? When you first jump to loop?
Can you figure out how many instructions will be executed in the loop function, before a call to a timer interrupt is performed, for the given frequency you have specified?

After the interrupt is fired, all the code in the interrupt is run.
Then code flow jumps back to loop()?
And when the timer starts counting again? At the same time the code jumps to loop?

If you set up the timer interrupt frequnecy too high, do you run the risk of having code in you loop functin not run at all? (If, for example, you have lots of code inside the loop()).

In that case, would it be wise to put code that you would generally put inside the loop(), inside a timer interrupt?

The timers starts when it is enabled. Either explicitly or via one of The calls to timer functionality.

Once the interrupt fires, current execution is preserved and the isr execution starts. Once you exit the isr, the loop execution resumes from where it pauses

Yes, if your use fires too frequently or takes too long to execute your loop may never gets executed.


Measuring li-ion that arduino is running from I am using a 5v Arduino pro mini (with regulator and power led removed).
I have been reading how to accurately measure Li-ion batteries when powering from the same battery you are trying to measure from. Using the 1.1V internal analog reference to measure a draining VCC source by using a voltage divider on it, and math to show that converted reading.
Reading the Arduino forums I came across this answer.
  long readVcc() {
  long result;
  // Read 1.1V reference against AVcc
  ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
  delay(2); // Wait for Vref to settle
  ADCSRA |= _BV(ADSC); // Convert
  while (bit_is_set(ADCSRA,ADSC));
  result = ADCL;
  result |= ADCH<<8;
  result = 1126400L / result; // Back-calculate AVcc in mV
  return result;
}

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

void loop() {
  Serial.println( readVcc(), DEC );
  delay(1000);
}

However, I cant see a analogRead anywhere in this sketch. (Is this a strictly internal reference?)
At the bottom of the thread someone is saying that you can do this without a voltage divider on the analog pin.
Can someone confirm or explain this? I don't want to fry my Arduino...

Using the 1.1V internal analog reference to measure a draining VCC
source by using a voltage divider on it

You could indeed use a voltage divider, and measure a scaled-down Vcc
against the internal 1.1 V reference. This is, however, not what
the code you posted is doing. It is instead measuring the internal
reference against Vcc, as stated in the comment within the code. The
REFS0 bit selects Vcc as the reference for the ADC. The bits MUX1...MUX3
select the internal reference as the input channel.

result = ADCL;
result |= ADCH<<8;

This idiom dates back from a time when the compiler did not know how to
read 16-bit I/O registers: you had to explicitly read one byte at a time
and then put these together into a 16-bit word. This time is long gone,
and you can now just access the 16-bit register as ADC directly. I
would even get rid of the result variable and just:
return 1126400L / ADC;  // Vcc in mV

Edit: As suggested by the busybee, here is the explanation of the
factor 1126400: The ADC meaures the ratio of its input voltage to its
reference voltage, and returns this ratio scaled by a factor 1024. In
this case,
ADC = 1024 × (Vbg ÷ Vcc)
where Vbg is the voltage of the 1.1 V bandgap reference. Thus,
Vcc = 1024 × Vbg ÷ ADC
If we want Vcc in millivolts, we plus the Vbg voltage in millivolts in
the above equation and get
Vcc (in mV) = 1024 × 1100 ÷ ADC = 1126400 ÷ ADC


Cannot correctly access element in array when given index I have the following strings which are stored in the program memory. They are basically just morse code definitions, with another array of characters where each character in the array has the same index as the morse code definitions:

const char a[] PROGMEM = ".-";
const char b[] PROGMEM = "-...";
const char c[] PROGMEM = "-.-.";
const char d[] PROGMEM = "-..";
const char e[] PROGMEM = ".";
const char f[] PROGMEM = "..-.";
const char g[] PROGMEM = "--.";
const char h[] PROGMEM = "....";
const char i[] PROGMEM = "..";
const char j[] PROGMEM = ".---";
const char k[] PROGMEM = "-.-";
const char l[] PROGMEM = ".-..";
const char m[] PROGMEM = "--";
const char n[] PROGMEM = "-.";
const char o[] PROGMEM = "---";
const char p[] PROGMEM = ".--.";
const char q[] PROGMEM = "--.-";
const char r[] PROGMEM = ".-.";
const char s[] PROGMEM = "...";
const char t[] PROGMEM = "-";
const char u[] PROGMEM = "..-";
const char v[] PROGMEM = "...-";
const char w[] PROGMEM = ".--";
const char x[] PROGMEM = "-..-";
const char y[] PROGMEM = "-.--";
const char z[] PROGMEM = "--..";
const char one[] PROGMEM = ".----";
const char two[] PROGMEM = "..---";
const char three[] PROGMEM = "...--";
const char four[] PROGMEM = "....-";
const char five[] PROGMEM = ".....";
const char six[] PROGMEM = "-....";
const char seven[] PROGMEM = "--...";
const char eight[] PROGMEM = "---..";
const char nine[] PROGMEM = "----.";
const char zero[] PROGMEM = "-----";

const char* const morse_table[] PROGMEM = {a, b, c, d, e, f, g, h, i, j, k, l, m,
    n, o, p, q, r, s, t, u, v, x, y, z, one, two, three, four, five, six,
    seven, eight, nine, zero};

const char alphabet[] PROGMEM = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','1','2','3','4','5','6','7','8','9','0'};

I am then creating a function which is supposed to be able to take in the morse code definition and spit out a character. This function is below:

void checkString(char * compare) {
  //Unwrap the pointer to the array into a "real" array
  char buf[7];
  for (int i = 0; i < 6; i++) {
    buf[i] = compare[i];
  }

  int correctIndex = -1;

  for (int iterator = 0; iterator < 35; iterator++) {

    char buf2[7];
    strcpy_P(buf2, (char*)pgm_read_word(&(morse_table[iterator])));

    if ((buf[0] == buf2[0]) && (buf[1] == buf2[1]) && (buf[2] == buf2[2]) && (buf[3] == buf2[3]) && (buf[4] == buf2[4])) {
      correctIndex = iterator;
    }
  }

  if (correctIndex == -1) {
    Serial.println("Failed!");
  }

  else {
    Serial.print("Success! Index: ");
    Serial.println(correctIndex);
  }

  char characterBuffer = alphabet[correctIndex];
  Serial.println(alphabet[correctIndex]);
}

The strcpy_p line of code was essentially copied from the PROGMEM reference for Arduino. I don't understand much about it, but from my tests it appears to work in getting an actual string object out of the pointer.

If I input any of the morse code definitions given, the correctIndex integer does contain the correct location of that definition in the morse_table 2d array. However, when I pass this integer into the alphabet array hoping to get out the character at that location I am given a seemingly random character. Is there something that I'm doing wrong with this code to produce such a result? Thanks for your help.

You can't access arrays that are in PROGMEM as if they were normal variables. The compiler can't tell the difference and just interprets it as a RAM address, which is wrong.

Instead you have to use pgm_read_byte to get the data:

char characterBuffer = pgm_read_byte(alphabet + correctIndex);


Arduino Due Digital Inputs without Response On two of my Arduino Due, when connecting the pin 3.3V to any digital inputs (37,36,35,34), no serial message nor LED_BUILTIN is thrown as output, only the Test message.

Digital Pins are set as INPUT by default. Blink works.

I have never connected any other thing on those pins, even 5V.

What I am missing?

void setup() {
    Serial.begin(115200);
    while(!Serial);
    pinMode(LED_BUILTIN,OUTPUT);
    Serial.print("Test");
}

void loop() {
    if (digitalRead(37))
        Serial.print("37");
    if (digitalRead(36))
        Serial.print("36");
    if (digitalRead(35))
        Serial.print("35");
    if (digitalRead(34))
        Serial.print("34");
    digitalWrite(LED_BUILTIN,digitalRead(37));
}

A good practice is to set the pin mode for all the pins used by the sketch.

void setup() {
    Serial.begin(115200);
    while(!Serial);
    pinMode(34, INPUT);
    pinMode(35, INPUT);
    pinMode(36, INPUT);
    pinMode(37, INPUT);
    pinMode(LED_BUILTIN, OUTPUT);
    Serial.print("Test");
}

The Arduino AVR core does set the pin mode to INPUT by default but the Arduino SAM core does not. The SAM MCU is much more advanced and allows turning on and off the ports, and a lot of other functionality.

Cheers!


Multiple boards blinking at same time I want to make two or more boards to blink an LED at the same time (within 1 ms difference) The boards cannot be connected with wires to each other and will be located in different rooms. How can I do this? What components do I need?

Have both sync to a master clock using GSM shields. These shields are getting very cheap (as low as $14 on ebay).

The shields receive the time wirelessly from the cellular network and this time base is extremely accurate. Here is some example code to read the current time from the shield...

http://forum.arduino.cc/index.php?topic=163155.msg2102141#msg2102141

Note that you will need a SIM card to get the time, but you should not need an active cellular account.


Does Serial.read() ever return a character? I'm trying to program my Arduino Mega to work with a TSL1401 line scan module and while looking over someone else code I came across this:

void loop()
{
    int b = Serial.read();      //Reads incoming serial data. Returns the first byte of
                                //incoming serial data available (or -1 if no data is available)

    if (b == 's')
    {
        getCamera();
        delay(2000);
    }
}

For the most part I understand what it's doing but I got confused when I saw that he was setting the return value of Serial.read() equal to a variable and then checking to see if that variable was a character. To my understanding Serial.read() returns an integer so why would you compare it to a character?

On an 8 bit arduino a character is a byte.  A byte can represent values between -128 and 127, or between 0 and 255, depending on how you "look" at them (signed or unsigned).

The whole concept of a character is a purely human thing. The Arduino only knows numbers.

For instance the character 'A' is actually the number 65. We, as humans, choose to represent it as an 'A' and call it "ASCII".

Again, the character 'a' is actually the number 97. You can also subtract characters from each other.  'a' - 'A' = 32


NodeMCU (ESP8266) board controlled over shared hosting database I have a NodeMCU (ESP8266) board that I want to control over the internet. I am trying to find a solution where I don't have to set up any configurations on my router like port forwarding. I came up with the following solution:

I have a website where the user changes the device status (with status I mean for example GPIO5 pin value HIGH or LOW) which is then saved to a database on a shared hosting server. The NodeMCU sends periodically (for example every 5 seconds) a HTTP GET request to the database. According to the value that is received from the database the NodeMCU board changes the pin value to HIGH or LOW. If NodeMCU changes it's status (for example a pin value from HIGH to LOW) the new device status is sent to the database with a HTTP POST request. The device also sends a HTTP POST request periodically (for example every 60 seconds) so the user can monitor the device status on the website.

There are a few problems with this configuration:

There is no real-time connection between NodeMCU and the user (there
is always a delay in the device response)
The device sends thousand of queries every day that are a load to
the shared hosting server. For example if the GET request is sent
every 5 seconds, that gives 17280 queries per day for one device.

So my question is how practical is this configuration on shared hosting or any kind of hosting, what are the alternatives or improvements to this configuration and how to establish a connection with the NodeMCU so that the device sends a GET request to the database only when the device status is changed in the database by the user.

Use MQTT.

You need:

The PubSubClient.h library
An MQTT server

For MQTT there are some free ones around on the internet (ask Google). Or if you have a Linux server available for use (e.g., a cheap VPS server from one of many many providers online) then you can run your own with mosquitto.

MQTT works kind of how you describe, but it's not making constant GET requests - it opens a single connection to the MQTT server and realtime requests are sent down it to the client, and back from the client to the server.

Near realtime communication.


Porting code from Arduino IDE to other IDEs - expected code size reduction Could I realistically be expecting some 25% - 50% code size reduction if I abandoned Arduino IDE's framework and moved to something more rudimentary such as AVR Studio ? I am using the EEPROM, Timer1 and Wire libraries whereas my own code is about 700 lines of code.

You don't need to abandon the Arduino IDE.

Let me quote from my forum post about sketch sizes.

Introduction

Every now and again this subject pops up on the Arduino forum. Why does it take 1000 bytes to blink an LED? Why, oh why? It is obviously very bloated, eh?

Example: blink

Let's check that claim first.

The "blink" sketch, as shipped with the IDE (and stripped of comments) is:

int led = 13;
void setup()
{
  pinMode(led, OUTPUT);
}

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

Compiled:

Binary sketch size: 1,084 bytes (of a 32,256 byte maximum)

OK, over 1000 bytes to "blink an LED".

Well first, as someone on the Arduino forum humorously pointed out, it doesn't take 2000 bytes to blink two LEDs!

int led1 = 13;
int led2 = 12;
void setup()
{
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
}

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

  digitalWrite(led2, HIGH);
  delay(1000);
  digitalWrite(led2, LOW);
  delay(1000);
}

That takes:

Binary sketch size: 1,140 bytes (of a 32,256 byte maximum)

So the overhead for the second LED is only:

1140 - 1084 = 56

So you could argue that it only takes 56 bytes to blink an LED (providing you are already blinking another one).

It does more than blink

The first relevant rejoinder here is that the example sketch does more than blink an LED. Rather importantly, it also waits for a second between turning the LED on and off (the "delay" function call).

If we remove that, the sketch is somewhat smaller:

int led = 13;
void setup()
{
  pinMode(led, OUTPUT);
}

void loop()
{
  digitalWrite(led, HIGH);
  digitalWrite(led, LOW);
}

Code size:

Binary sketch size: 882 bytes (of a 32,256 byte maximum)

So we saved 202 bytes by not doing a delay. This isn't totally unreasonable, as doing delays requires the library to configure a timer, and have code to check that timer.

The pins numbers are variables

The code in the Blink example uses (wrongly in my opinion) a variable to hold the pin number (13) when a constant would do. And if you use a constant there is a library called
digitalWriteFast that generates more efficient code.

#include <digitalWriteFast.h>

const int led = 13;
void setup()
{
  pinModeFast(led, OUTPUT);
}

void loop()
{
  digitalWriteFast(led, HIGH);
  digitalWriteFast(led, LOW);
}

Code size:

Binary sketch size: 470 bytes (of a 32,256 byte maximum)

Now we are down to 470 bytes to "blink an LED".

We can use port manipulation

If all we want to do is blink the LED, we can omit using setup and loop, and go straight into using the processor registers. For example:

int main ()
  {
  DDRB = bit (5);
  while (true)
    PINB = bit (5);
  }

That blinks pin 13, believe it or not*. And now it only takes 178 bytes:

Binary sketch size: 178 bytes (of a 32,256 byte maximum)

* very rapidly indeed

Interrupt vectors

Well, you may be thinking "Pfft! Still 178 bytes. Why not 10 bytes?"

The answer to that lies in the way the hardware works. The Atmega328P has 26 interrupt vectors, at the start of program memory. Each one is 4 bytes (it jumps to a handler for each interrupt). So 26 * 4 = 104 bytes.

Thus there is an unavoidable overhead of 104 bytes in any piece of code. (Unless you know in advance you aren't going to use all those interrupt vectors, but this is rather specialized).

You can see these vectors if you add handlers for them:

EMPTY_INTERRUPT (INT0_vect)
EMPTY_INTERRUPT (INT1_vect)
EMPTY_INTERRUPT (PCINT0_vect)
EMPTY_INTERRUPT (PCINT1_vect)
EMPTY_INTERRUPT (PCINT2_vect)
EMPTY_INTERRUPT (WDT_vect)
EMPTY_INTERRUPT (TIMER2_COMPA_vect)
EMPTY_INTERRUPT (TIMER2_COMPB_vect)
EMPTY_INTERRUPT (TIMER2_OVF_vect)
EMPTY_INTERRUPT (TIMER1_CAPT_vect)
EMPTY_INTERRUPT (TIMER1_COMPA_vect)
EMPTY_INTERRUPT (TIMER1_COMPB_vect)
EMPTY_INTERRUPT (TIMER1_OVF_vect)
EMPTY_INTERRUPT (TIMER0_COMPA_vect)
EMPTY_INTERRUPT (TIMER0_COMPB_vect)
EMPTY_INTERRUPT (TIMER0_OVF_vect)
EMPTY_INTERRUPT (SPI_STC_vect)
EMPTY_INTERRUPT (USART_RX_vect)
EMPTY_INTERRUPT (USART_UDRE_vect)
EMPTY_INTERRUPT (USART_TX_vect)
EMPTY_INTERRUPT (ADC_vect)
EMPTY_INTERRUPT (EE_READY_vect)
EMPTY_INTERRUPT (ANALOG_COMP_vect)
EMPTY_INTERRUPT (TWI_vect)
EMPTY_INTERRUPT (SPM_READY_vect)

Now the start of the object code is:

00000000 <__vectors>:
   0:   0c 94 34 00     jmp 0x68    ; 0x68 <__ctors_end>
   4:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__vector_1>
   8:   0c 94 52 00     jmp 0xa4    ; 0xa4 <__vector_2>
   c:   0c 94 53 00     jmp 0xa6    ; 0xa6 <__vector_3>
  10:   0c 94 54 00     jmp 0xa8    ; 0xa8 <__vector_4>
  14:   0c 94 55 00     jmp 0xaa    ; 0xaa <__vector_5>
  18:   0c 94 56 00     jmp 0xac    ; 0xac <__vector_6>
  1c:   0c 94 57 00     jmp 0xae    ; 0xae <__vector_7>
  20:   0c 94 58 00     jmp 0xb0    ; 0xb0 <__vector_8>
  24:   0c 94 59 00     jmp 0xb2    ; 0xb2 <__vector_9>
  28:   0c 94 5a 00     jmp 0xb4    ; 0xb4 <__vector_10>
  2c:   0c 94 5b 00     jmp 0xb6    ; 0xb6 <__vector_11>
  30:   0c 94 5c 00     jmp 0xb8    ; 0xb8 <__vector_12>
  34:   0c 94 5d 00     jmp 0xba    ; 0xba <__vector_13>
  38:   0c 94 5e 00     jmp 0xbc    ; 0xbc <__vector_14>
  3c:   0c 94 5f 00     jmp 0xbe    ; 0xbe <__vector_15>
  40:   0c 94 60 00     jmp 0xc0    ; 0xc0 <__vector_16>
  44:   0c 94 61 00     jmp 0xc2    ; 0xc2 <__vector_17>
  48:   0c 94 62 00     jmp 0xc4    ; 0xc4 <__vector_18>
  4c:   0c 94 63 00     jmp 0xc6    ; 0xc6 <__vector_19>
  50:   0c 94 64 00     jmp 0xc8    ; 0xc8 <__vector_20>
  54:   0c 94 65 00     jmp 0xca    ; 0xca <__vector_21>
  58:   0c 94 66 00     jmp 0xcc    ; 0xcc <__vector_22>
  5c:   0c 94 67 00     jmp 0xce    ; 0xce <__vector_23>
  60:   0c 94 68 00     jmp 0xd0    ; 0xd0 <__vector_24>
  64:   0c 94 69 00     jmp 0xd2    ; 0xd2 <__vector_25>

The "real" code has to start at 0x68 (decimal 104) which is where the reset vector takes us (the first vector).

So now, our code is really 178 - 104 bytes of useful code. That's 74 bytes to blink an LED.

However even some (most) of that is overhead, generated by the C compiler to initialize global variables, call class constructors, etc. Let's test that by blinking two LEDs.

int main ()
  {
  DDRB = bit (5);  // pin 13
  DDRB |= bit (4);  // pin 12

  while (true)
    {
    PINB = bit (5); // pin 13
    PINB = bit (4); // pin 12
    }
  }

Code size:

Binary sketch size: 186 bytes (of a 32,256 byte maximum)

Eight bytes difference. So really, you can blink an LED in 8 bytes. That is the bottom line. And you can do it in the Arduino IDE.

The libraries are designed to make things easy

The fact is that the default behaviour of the Arduino libraries is to simplify things for beginners. Thus they do some things which take up a bit of memory;

You can pass variables to pinMode and digitalWrite. Not just constants. Thus, at runtime, code has to convert the variable value to an actual processor port.
You get an automatic set-up of Timer 0, so you can use millis(), micros(), and delay() function calls.
You get Timer 1 and Timer 2 set-up, so you can do PWM output easily.

So you are trading off program space, to an extent, for ease of use. But if you want to code around it, as I did above, you can trim that program space right down.

Tests on an Arduino Uno board type, IDE 1.0.5.


"Soft WDT reset" stack error: RFID-RC522 with NodeMCU I have been all over the internet to try and find a solution to this, but after one solid week of intense Google searching I have come up with nothing.

What I'm trying to accomplish:

I am simply trying to use the RFID-RC522 NFC reader on an NodeMCU development board (built in ESP8266) with the mfrc522 library.

Problem:

Upon initiating the mfrc522 library, reaching the line mfrc522.PCD_Init(); the Serial outputs the following "error":

Soft WDT reset

ctx: cont
sp: 3ffefa10 end: 3ffefc40 offset: 01b0

>>>stack>>>
3ffefbc0:  00241001 00000001 3ffeec20 40106895
3ffefbd0:  00000002 3ffee9d8 3ffee9f4 40202794
3ffefbe0:  402010b2 00000001 00000032 402010a7
3ffefbf0:  3fffdad0 00000010 3ffee9d8 4020290d
3ffefc00:  402010b2 3ffee9d8 3ffee9d8 40202a01
3ffefc10:  feefeffe 00000000 3ffeebec 40202080
3ffefc20:  feefeffe 00000000 3ffeec08 40203e08
3ffefc30:  feefeffe feefeffe 3ffeec20 40100108
<<<stack<<<
R+⸮⸮⸮

I found a tool that can translate the error EspExceptionDecoder, translated error:

Decoding 10 results
0x40106895: __digitalWrite at C:\Users\my_user\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266/core_esp8266_wiring_digital.c line 84
0x40202794: MFRC522::PCD_ReadRegister(MFRC522::PCD_Register) at C:\Users\my_user\Documents\Arduino\libraries\MFRC522\src/MFRC522.cpp line 1141
0x402010b2: delay at C:\Users\my_user\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266/core_esp8266_wiring.c line 54
0x402010a7: delay at C:\Users\my_user\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266/core_esp8266_wiring.c line 51
0x4020290d: MFRC522::PCD_Reset() at C:\Users\my_user\Documents\Arduino\libraries\MFRC522\src/MFRC522.cpp line 1141
0x402010b2: delay at C:\Users\my_user\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266/core_esp8266_wiring.c line 54
0x40202a01: MFRC522::PCD_Init() at C:\Users\my_user\Documents\Arduino\libraries\MFRC522\src/MFRC522.cpp line 1141
0x40202080: setup at C:\Users\my_user\OneDrive\Arduino\projekter\RFID_DumpInfo_test/RFID_DumpInfo_test.ino line 53
0x40203e08: loop_wrapper at C:\Users\my_user\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266/core_esp8266_main.cpp line 57
0x40100108: cont_norm at C:\Users\my_user\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266/cont.S line 109

When the mfrc522.PCD_init(); line is commented out the stack-error does not appear.
Reading the NFC tags has worked before on the NodeMCU unit, and I sometimes stubmled upon this error when adding one simple line like var1 = var2; somewhere in the loop, but now the error is there constantly, even with code that once worked - however I did change the pin-loadout, and I suspect that this is the problem.

What I have tried:

With the configurable pins I have tried most combinations I could
think of, trying both the SS and the RST in every available pin.
this Github
example suggets
this
instructables tutorial.
3 different RFID-RC522 modules (same model)
2 different NodeMCU units (same model)

Pin layout:

My pin layout for the RFID-RC522 module is as follows;

SDA (SS): D4
RST: D3
SCK: D5
MOSI: D7
MISO: D6
GND: GND
3v3: 3v3

Arduino project info:

Arduino IDE 1.8.5
Latest MFRC522 from the Library Manager
Board: NodeMCU 1.0 (ESP-12E Module)

Code:

#include <SPI.h>
#include <MFRC522.h>

#define SS_PIN          D4
#define RST_PIN         D3

MFRC522 mfrc522(SS_PIN, RST_PIN);

void setup() {
    Serial.begin(9600);
    delay(100);
    SPI.begin();
  delay(100);
    mfrc522.PCD_Init();
    mfrc522.PCD_DumpVersionToSerial();
    Serial.println(F("Scan PICC to see UID, SAK, type, and data blocks..."));
}

I've been on this issue for days now, and my Google searches tell me that I'm not the only one who has had this problem before. Any input is very welcome.

can you also try to increase the serial boud rate to fe. 115200 instead of 9600?
In some cases I had some issues with 9600, because some buffers were not cleared fast enough and forces some WDT resets.

Cheers,
Jorgen


How to learn enough C++ to program Arduino? I am an experienced web developer, but my C++ skills are very basic. I struggle with the concepts because it is so different from something like Javascript (which I already know). I do not have a lot of time to learn C++, and I only need to know enough to play with Arduinos.

Are there any good resources out there for learning C++ that is specifically geared towards Arduino programming, and is there anything interactive like Codecademy?

If I were you I'd take the high road.

I was in your shoes a while ago and I didn't know how to approach Arduino. I was very lucky that I came across a book written by the famous Jack Purdum, "Learn C programming for the Arduino". It is written by a retired Purdue University professor who is well known for his extremely easy to learn teaching method. He has another

I only knew MATLAB and Simulink before starting this book. This book is amazing. It was extremely easy to follow. I now have no difficulty programming Arduino in the correct way. This book trains you to optimize everything which is very crucial with the limited resources on Arduino boards.

I suggest C instead of C++. It is the language of choice for programming embedded system. It is said to be low level, but as a MATLAB user I should tell you that syntaxes are extremely easy and intuitive. I didn't find anything hard about them.

Remember:

There isn't any problem to use C in Arduino IDE.
You don't need to worry about libraries. You only need to load them in the beginning of the code. You do not need to know how was the code written in the library.
Check the comments about the book on Amazon if you are not convinced.

Good Luck


Inherent delay running EEPROM.read() I'm using EEPROM to store long term data for use in sketches (thanks to DarthRubik for the guidance).  I store stuff like a location ("Garden") and a device name ("Greenhouse Monitor 02") plus whatever else I'd need to store to help filter through data.

When this information is stored in the sketch itself it is recalled quickly and accurately, is passed via wifi to my PHP, that then posts the data to the relevant fields in my AWS db.  Piece o' cake!  When I store it in the EEPROM, the extra time required to find it in EEPROM, pull it through the sketch, and then push it through to the db corrupts the data sourced from EEPROM and posts a jumbled mess of characters...if it even makes it to the db at all.

My question is actually simple (I think):
Is it possible to "stage" strings from EEPROM in flash or SRAM vs. pulling cold from EEPROM?

I think PROGMEM plays a role here and I'm looking at examples oh how other sketched employ PROGMEM to better understand how to use it.

I am withholding the code for now because I want to try to implement concepts people may describe before I am just shown the solution...although that would be easier.  If I can't figure it out I'll post the code for more direct answers.

When I store it in the EEPROM, the extra time required to find it in EEPROM, pull it through the sketch, and then push it through to the db corrupts the data sourced from EEPROM and posts a jumbled mess of characters...if it even makes it to the db at all.

Are you certain of that? It is incredibly unlikely that mere time will corrupt characters and data as they are read and sent - especially the minuscule amounts of time we are talking here.

  Is it possible to "stage" strings from EEPROM in flash or SRAM vs. pulling cold from EEPROM?

Yes, and you are already doing so, since you can't send direct from EEPROM to WiFi - you have to go via SRAM. You read from EEPROM into SRAM then send from SRAM through WiFi. You just won't be doing it an entire string at once.

  I think PROGMEM plays a role here and I'm looking at examples oh how other sketched employ PROGMEM to better understand how to use it.

No, it doesn't. PROGMEM is for storing strings and other data within your sketch. It has nothing at all to do with EEPROM.

  I am withholding the code for now because I want to try to implement concepts people may describe before I am just shown the solution...although that would be easier. If I can't figure it out I'll post the code for more direct answers.

Without seeing your code no one is really going to be able to help you. I suspect (although I am stabbing wildly in the dark) that your EEPROM reading/writing code is completely wrong and you aren't actually storing the data you expect in the EEPROM, nor reading it back properly. Unless we see your code we can't know what is going on, and so we don't have a cat's hope in hell of diagnosing your problem.


Writing a new function: configMotor(speed, direction) How can I create a function that can control a DC motor's speed and direction?

configMotor(int speed, direction){
   pwmVal = speed;

   //need help with code for picking direction
}

//move FORWARD
void moveForward(){
  analogWrite(pwn, pwmVal);
  delay(sDelay);
  digitalWrite(ina, HIGH);
  digitalWrite(inb, LOW);
}

//move BACKWARD
void moveBackward(){
  analogWrite(pwn, pwmVal);
  delay(sDelay);
  digitalWrite(ina, LOW);
  digitalWrite(inb, HIGH);
}

I don't know what to write in the code for configMotor function so that it can choose going forward or backward.

All you need to do is pass a parameter to config that says forward or backwards (was direction).
This parameter then sets the values of that the pins INA/B will be set to, because they are opposite.

Does that make sense?  If not add a comment with you question and I'll try and clarify.

int inaDirection = LOW;
int inbDirection = LOW;

void configMotor( int speed, bool forwards = true)
{
   pwmVal = speed;
   inaDirection = forwards?HIGH:LOW;   // ? and : are the same as an if statement, just more compact.
   inbDirection = forwards?LOW:HIGH;
}

// move no need for forward and reverse anymore
void move()
{
    analogWrite(pwn, pwmVal);
    delay(sDelay);
    digitalWrite(ina, inaDirection);
    digitalWrite(inb, inbDirection);
}


Can not connect with Bluetooth hc-05 I connect my Bluetooth hc-05. But the blind led in the Bluetooth module is not stable when I connect with my Android phone. Help help me to solve this.

It is very simple really.

Initially the Bluetooth got paired automatically with my Android, but apparently the variable transmission was not complete.

If this is the case with your module,it will be blinking with high frequency.

So here is what I did:

Hit the RESET button on HC-05 once
Go to Android Bluetooth Settings and UNPAIR HC-05
Now Pair it again by clicking on it
You will be prompted to enter password- '1234'
Open your Bluetooth Terminal and you will find your data appearing
on Android

P.S.-A 2 Hz blinking frequency on HC-05 should signify proper connection


Arduino servo motor on pushbutton I'm working on my first arduino project and i have my first problem dealing with servo motor , i'm trying to control the servo from my pc with this code but it just spining :

  #include <Servo.h>

Servo servo1;
long num;

void setup()
{
   servo1.attach(7);
   Serial.begin(9600);
   Serial.print("Enter Position = ");
}

void loop()
{
  while(Serial.available()>0)
  {
    num= Serial.parseInt();
    Serial.print(num);
    Serial.println(" degree");
    Serial.print("Enter Position = ");
  }
  servo1.write(num);
  delay(15);
}

this is my setup

I have reformatted your code and the problem becomes very clear (to me).

void loop()
{
  while(Serial.available()>0)
  {
    num= Serial.parseInt();
    Serial.print(num);
    Serial.println(" degree");
    Serial.print("Enter Position = ");
  }
  servo1.write(num);
  delay(15);
}

You are getting some input from the user and then setting the servo to that point.

When there is no data in the Serial buffer you set the servo to the value of write and delay 15ms before checking the buffer again.
I think what you want to do is if there is no data then you don't want to change the Servo position.  In short move the servo1.write(num); line inside the } of the while loop.

Now much more importantly the first time you enter loop() you won't have any data there so the servo will be moved to the number held in num which is? Undefined, it could be anything at all from 0 to 4294967295 and if its the upper end of that it will take a while for the servo to get there, it might seem like all it does is spin.  ALWAYS INITIALIES VARIABLES BEFORE USE :)

A minor point, your while loop could be, probably should be an if statement.  That will prevent a cat sitting on the keyboard and blocking the servo movement.


Delay not working in function other than loop So I just got an Arduino and thought I would play around a bit.

However not five minutes in I already ran into a problem.

I tried programming a simple SOS blinking light sequence. To get rid of code duplication I refactored the on and off turning of the LED into functions and then again refactored a short blink and a long blink function which are expected to turn the LED on for a short time and then for a long time.

The problem is the delay in those functions is completely ignored.

int ledPin = 13;

void on()
{
 digitalWrite(ledPin,HIGH);
}

void off()
{
 digitalWrite(ledPin,LOW);
}

void shortB()
{
 on();
 delay(1000);
 off();
}

void longB()
{
 on();
 delay(2000);
 off();
}

void setup()
{
  pinMode(ledPin, OUTPUT);
}

void loop()
{
 shortB();
 shortB();
 shortB();
 shortB();
 longB();
 longB();
 longB();
 shortB();
 shortB();
 shortB();
 delay(5000);
}

My expected behavior would be that it does an SOS and then waits 5 seconds and repeats.

What really happens however is that it stay continuously lit for a second or so then turns off for 5 seconds.

Using

on();
delay(1000);
off();

In the main loop works so I guess it simply ignores the delays that are put into the other functions. My question would be why and ho do I fix it?

I know that I can use other timer function constructs however I really think this is something that should work by default.

You have no delay in between turning the LED off and turning it back on. Add one.


Anyone have the Maplin N97DG bluetooth shield working? I went & impulse-bought a Maplin Bluetooth shield yesterday.

It comes with a little tiny book containing examples, and uses the softwareserial library in these; I can load them, and get the Arduino <-> PC communication going OK, however there appears not to be a response from the bluetooth part of the device. The LED lights much as the booklet says it should. I did see it return some odd characters one time, just the once..

Given that the system appears to be alive, I don't want to give up & take it back; however the output from Google is not promising, and my trial to date isn't either - so I'm looking for positive news that this product does actually work for someone somewhere?

I'm using the built-in serial in the IDE to talk to it, not X-CTU as they suggest (as they don't do a Linux version).

I've just got mine working, in about 3 hours.

The first example I've never got working. The SAT+RESET worked first time... and I was then able to pair.

An easier module is the HC-05. That by default goes straight to discovery mode, and makes things alot easier.

I have more success with the serial monitor in Arduino studio, rather than X-CTU.

The point of the sheild is to prototype, or the shield you have to use in your production project. If you are doing the former, then there is little point in using the shield as you would have to change the code to fit the hardware.

It seems a thorough product, probably too involved.


Arduino Uno simple LED example with pointers I am new to Arduino and I have recently started off by trying to turn on an LED connected to pin 13 on my Arduino Uno using pointers.

I opted to do this with pointers because this would give me a better understanding on what really goes behind when I use predefined Arduino functions.

My simple code looks like this,

uint8_t *data = (uint8_t *) 0x05; //PortB data register ptr (Since pin 13 is PB6)
uint8_t *dir = (uint8_t *) 0x04;  //PortB dir register ptr (Since pin 13 is PB6)

void setup() {
    *dir = 0x40;  //PB6 direction set to O/P
    *data = 0x40; //PB6 data set to 1 to turn on the LED
}

void loop() {
  *data = 0x40;
}

I tried the same program using   pinMode(13, OUTPUT) and digitalWrite(13, LOW) functions and it works fine. But I do not understand what could be wrong with my pointers. If you find anything wrong, kindly let me know.

You made two small mistakes:

The addresses of the I/O registers are 0x24 for DDRB and 0x25
for PORTB. The numbers you used are I/O port numbers, but since
pointers are supposed to point to memory, you have to use the
memory-mapped addresses instead.
Pin 13 is PB5, not PB6.

With these two mistakes fixed, your code works as expected. There are
still two issues however:

Under some circumstances, the compiler can optimize away some writes
to these registers. You have to qualify the pointers as “pointer to
volatile data” in order to avoid this. Even if your simple example
does not show this problem, it is always safer to use the qualifier.
The compiler generates inefficient code. Not as inefficient as
digitalWrite(), but still... It knows how to optimize, but it is
prevented to do so by the fact that your pointers are modifiable. You
should qualify them as const if you want to benefit from compiler
optimizations.

With those fixes, your pointer definitions would look like:

volatile uint8_t * const data = (uint8_t *) 0x25;
volatile uint8_t * const dir  = (uint8_t *) 0x24;

and access to them gets compiled into efficient in ans out assembly
instructions.

That being said, if you want to do direct port access, I would recommend
doing it the avr-libc way:

void setup() {
    DDRB  = _BV(PB5);
    PORTB = _BV(PB5);
}

void loop() {
    PORTB = _BV(PB5);
}

The way the AVR-libc defines the I/O registers is roughly equivalent to

#define PORTB (* (volatile uint8_t *) 0x25)


Use an Arduino as a user interface for the computer I wanted to use either Arduino Mega or Uno as a form of an interface between me and the computer. I want to apply it to the following scenario; if I press a button on a circuit board I want it to trigger an action on my computer, like scroll down.

How can I achieve this? How would the code look like and what programs would I need to translate from Arduino to Windows?

For the sake of completeness, on the more traditional boards where the USB interface is not implemented from the main "sketch" processor, there are three other potential possibilities:

Use the (USB) serial data interface, and have software on the host computer which accepts commands over that.  Obviously, the downside is requiring installation of something on the host system - installation which may require admin privileges or even disabling code signing requirements in some cases (especially if it is to inject the data into the host operating system as if it came from a keyaboard)
On boards such as the Uno and comparable-generation Mega which use a secondary ATmega "u" series part as a USB-serial converter, this chip can be reprogrammed to act instead as a keyboard.  That could make loading sketches tricky - though it might be possible to come up with a dual-mode firmware that could switch roles under control of an external hardware or software signal.
The main ATmega "sketch" processor can generally implement a "not quite compliant, but workable" approximation of a low-speed USB interface in software on arbitrary I/O pins with some external matching/protection componenets.  A USB keyboard is a common demo application of that.


Controlling ESC with Arduino I want to control these motors: hexTronik DT750 Brushless Outrunner 750kv with this battery: Turnigy 2200mAh 3S 25C Lipo Pack and these ESCs: TURNIGY Plush 18amp Speed Controller.

I am new to this field of driving brush-less motors. Can someone tell me if I need anything else? Will this set-up work without anything getting destroyed?

I 've been working on an autonomous arduino quadcopter for about 7 months now and I have a few tips for you.

1) your setup seems fine as long as your motors aren't going to draw more amps than your ESC can supply, but It is always a good idea to buy ESCs with a higher "max amps" than your motors draws. I would choose 25 amp max ESCs or higher.

2) In order to control the motors via PWM, I use the Servo library because you get a resolution from 700-2000 as opposed to "analogWrite" which gives a default resolution of 0-255.

3) your ESC probably has a minimum pulse width value before it will start. I would recommend writing a program that gives you the ability to plug in values from 700-2000, and use the program to slowlly find that arming pulse width value. Mine is 1110 for reference.

If you have anymore questions, I will glady answer them.

May I ask, what is your project?


How to extract latitude and longitude from GPS I want to extract longitude and latitude from GSM/GPS module and then upload it to thingspeak. I am using sim808 GSM/GPS module and AT+CGPSINF=0 to get GPS location information sentence (CGPSINF: 0,6.823375,80.001038,36.300000,20170705124133.000,0,10,0.037040,47.410000
). I want to extract longitude and latitude from it. Does anyone know how to do it? I am not an expert in programming. someone told me to use strtok. But I don't know how to do it. Does anyone have any Arduino code to do this?

I tried DFRobot SIM808 library to collect GPS data. it works like charm. But the problem was, my upload code didn't work when i was using the library to collect longitude and latitude in the same code.

This is my web upload code.

#include <SoftwareSerial.h>
#include <String.h>

SoftwareSerial mySerial(10, 11);//(2,3)

void setup()
{
  mySerial.begin(2400);   // the GPRS baud rate 9600
  Serial.begin(2400);    // the GPRS baud rate 9600

  delay(1000);

  ShowSerialData();

}

void loop()
{
      Send2Pachube();
  if (mySerial.available())
    Serial.write(mySerial.read());
}
void Send2Pachube()
{
  mySerial.println("AT");//start with attention
  delay(1000);

  mySerial.println("AT+CPIN?");//check for the sim card
  delay(1000);

  mySerial.println("AT+CREG?");//check for registration and access technology of cell
  delay(1000);

  mySerial.println("AT+CGATT?");//check whether the device is attached to GPRS.0Detch,1Attch
  delay(1000);

  mySerial.println("AT+CIPSHUT");//shut packet data protocol context
  delay(1000);

  mySerial.println("AT+CIPSTATUS");// returns the current connection status
  delay(2000);

  mySerial.println("AT+CIPMUX=0"); //create multi-IP connection(0=single connection)
  delay(2000);

  ShowSerialData();

  mySerial.println("AT+CSTT=\"hutch3g\"");//start task and setting the APN,
  delay(1000);

  ShowSerialData();

  mySerial.println("AT+CIICR");//bring up wireless connection
  delay(3000);
  ShowSerialData();

  mySerial.println("AT+CIFSR");//get local IP adress
  delay(2000);
  ShowSerialData();

  mySerial.println("AT+CGPSINF=0");//get GPS
  delay(2000);
  ShowSerialData();

  mySerial.println("AT+CIPSPRT=0");//starts a TCP or UDP connection
  delay(3000);

  ShowSerialData();

  mySerial.println("AT+CIPSTART=\"TCP\",\"api.thingspeak.com\",\"80\"");//start up the connection
  delay(6000);

  ShowSerialData();

  mySerial.println("AT+CIPSEND");//begin send data to remote server
  delay(4000);
  ShowSerialData();

  String str="GET https://api.thingspeak.com/update?api_key=FF19NVWMPZEWX0XK&field1=100";
  mySerial.println(str);//begin send data to remote server
  delay(4000);
  ShowSerialData();

  mySerial.println((char)26);//sending
  delay(5000);//waitting for reply, important! the time is base on the condition of internet
  mySerial.println();

  ShowSerialData();

  mySerial.println("AT+CIPSHUT");//close the connection
  delay(100);
  ShowSerialData();
}
void ShowSerialData()
{
  while(mySerial.available()!=0)
    Serial.write(mySerial.read());
}

First rather than just dumping it to the screen store the data in a char array

char dataBuffer[64];
int dataCount=0;

while ( (mySerial.available()!=0) && (dataCount<63) ) {
    dataBuffer[dataCount] = mySerial.read());
    dataCount++;
}
dataBuffer[dataCount] = 0;

then use strtok to split the string on the : and , characters

char *output;
output = strtok(dataBuffer,":");
// output will now point to everything up to the first : so "CGPSINF" for gps
int field = 0;
while (output != null) {
  field++;
  output = strtok(null,",");
// output will now point to each value in turn
// for CGPSINF:0,6.823375,80.001038,36.300000,
// when field == 1 output=="0"
// when field == 2 output=="6.823375" etc...
}


How to detect an read buttons pressure on touchscreen I made simple 3 red buttons like this:

#include <SPI.h>

#include "Adafruit_GFX.h"
#include "Adafruit_ILI9341.h"
#include "URTouch.h"

#define TFT_DC 9
#define TFT_CS 10
#define TFT_RST 8
#define TFT_MOSI 11
#define TFT_CLK 13
#define TFT_IRQ  7

Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC, TFT_MOSI, TFT_CLK,

#define t_SCK 3
#define t_CS 4
#define t_MOSI 5
#define t_MISO 6
#define t_IRQ 7

URTouch ts(t_SCK, t_CS, t_MOSI, t_MISO, t_IRQ);

void setup() {

  tft.begin();
  tft.fillScreen(BLACK);

  tft.fillRoundRect (12,15,30,80,5,RED);//50,100,30,80,5,RED
  tft.fillRoundRect (50,15,30,80,5,RED);
  tft.fillRoundRect (88,15,30,80,5,RED);

  delay(500);
}

And this the part where I need help:

void loop()
{
  int x, y;

  while(ts.dataAvailable())
  {
    ts.read();                //-----------> this is the whole thing
    x = ts.getX();
    y = ts.getY();

  }

What I need is, to know how to detect and read the pressure of the button area, so that I can run different tasks.

The fillRoundRect function format is (initial_Xpoint,initial_Ypoint,length,width,corner_radius,color)

Therefore, you already have the information about the location of the button itself. Next, check if the x and y value is within the button area.

void setup() {

  tft.begin();
  tft.fillScreen(BLACK);

  tft.fillRoundRect (12,15,30,80,5,RED);  //button1
  tft.fillRoundRect (50,15,30,80,5,RED);  //button2
  tft.fillRoundRect (88,15,30,80,5,RED);  //button3

  delay(500);
}

void loop()
{
  int x, y, pressedbutton=0;

  if(ts.dataAvailable())
  {
    ts.read();                //-----------> this is the whole thing
    x = ts.getX();
    y = ts.getY();

    if ((x>=12) && (x<=12+30) && (y>=15) && (y<=15+80)) pressedbutton = 1; else
    if ((x>=50) && (x<=50+30) && (y>=15) && (y<=15+80)) pressedbutton = 2; else
    if ((x>=88) && (x<=88+30) && (y>=15) && (y<=15+80)) pressedbutton = 3;
  }

  ...
  ...
  ...
 }


Read status on SCART output I'm trying to get the status of my set top box (on/off).
It does have USB but it's always powered on.
It has optical out that is also always on.
It has an IP address that always responds to ping.

So my next idea is to read the signal in the SCART.
If I read the voltage across pin 8 and 14 I get 0-ish when off and 12 when on.
But when it powers on it spikes at 18 volt (at least what my multimeter can see).
 https://youtu.be/D2eVFe33MeM

What do I need to do to read this?
If I add a voltage divider with 1 and 4.7 Kohm I get a safe voltage if it does not go above 18 volt at any time.

But what can I do to be sure I don't burn a ESP chip?
Is there any way to make sure it's safe to read even if it spikes at say 25 volts?

I would use something like below. The optical isolator (PC817 or similar) protects your ESP.

Use a 1.0-1.5K resistor from the incoming SCART switch signal (SCART pin 8) to the anode of the Opto isolator (pin 1 in case of the PC817). This will limit the current through the PC817 internal LED to about 10mA with a 12V signal but the PC817 can survive up to 50mA, i.e. up to 60V on the SCART plug and even then will not damage your ESP processor.

Connect SCART ground (pin 14) to the cathode of the Opto isolator
(pin 2).

Connect a 3.3K - 4.7K resistor to the collector of the phototransistor of the PC817 (pin 4 of the PC817) and connect the other side of this resistor to Vcc of your ESP (+3.3V) as a pullup.

Connect pin 3 (emitter) of the PC817 to the Ground of your ESP.

Connect a digital input pin of your ESP to pin 4 (phototransistor collector) of your PC817 to create an active-low signal indicating your set top box is active.

This is the schematic you could use:

simulate this circuit – Schematic created using CircuitLab


Arduino Stepper Motor Standing Desk help! I currently have a standing desk at work, and I thought a fun way to learn Arduino would be to automate it, as it currently uses a hand crank.

I would love some help determining what I would need for this task.

What kind of motor should I use?
  -Stepper motor?
  -High/low rpm?
  -High/low torque?

What sort of power would I need?

Looking forward to hearing people's suggestions!

I think this might end up being more of a fun way to electrocute yourself, but let's find out...

Energy required to lift an object with mass "m" an upward distance of "h" in the Earth's gravitational field, on the surface...  E = mgh = m(9.8)h

So, to lift a 50kg desk one meter, we will need 50 x 9.8 x 1 = 490 Joules

How fast do you want to lift it? Let's say we want it to take 10 seconds - that will give us the power level we need. Power is in watts (Joules per second) - so if we want to lift the desk in 10 seconds we need 49 watts - let's call it 50.

Now, to produce 50 watts with a 12-volt battery, that would be 4.2 Amps. This is do-able, and it's not the high power level I expected for lifting a desk. Even if we throw in some efficiency losses, we're well within the safety zone and won't have to get out the high voltage equipment. So, I'm glad I did the math - my initial impression of this task was the joke at the beginning of the post.

So, you need a 50 watt motor... that's easy to find. Hell, why not go way over that and get a 100-watt motor... google that...

http://www.electricscooterparts.com/motors24volt.html - bang! Scooter motors! Nice!

So, that's an example of how you might figure out what parts to get - it all starts with basic physics and ends with Google (or Bing if you're one of those people). I simplified a lot, but you get the idea.

The other part of this task is to figure out the control system. I would probably not use Arduino to do this. I would have three switches - one "directional" switch to run the motor, and two sensor switches to disconnect the directions of the motor at each end of the track. I think that's how automatic power windows in cars used to work, which explains why if you didn't hold the button down long enough, it would immediately instead of continuing to the other end - it was still sitting on the sensor.

Sticking an Arduino in the mix and having it read the sensors would just waste power all day long, but you could do it that way. It's the same idea - just mount sensors on the track, which get tripped when the desk rolls up to that spot. Coding wouldn't be that tricky - when the user activates the "change button" or whatever, check which sensor is currently active, and move the desk the other way until the other sensor activates.

You're going to need a good power supply for that motor - a 24-volt 200-watt power supply if you like to over-engineer like I do. You'll need a relay to control the motor - it needs to handle 24 volts/200 watts. Then you'll need some kind of activation button, and two sensors. You want some kind of sensor that is definitely going to be activated when the desk is in position, or you risk over-running your target, binding the mechanics, and burning the motor, and possibly the office as well. So, I would choose some kind of mechanical sensor, not a light sensor or something like that.

This should get you started on finding those parts...
https://www.sparkfun.com/categories/145 - these are all kinds of buttons and switches - you should be able to find something that you can mount to the track which will activate when the desk runs into it. Search on this site for the other parts - they have the relays and stuff too.

Final warning though - this may be too complicated and dangerous for a first project. At 24 volts and 100 watts, we are getting into dangerous power levels. But, these are common power levels in consumer equipment. So, if you know what you're doing you should be safe. If you don't, I strongly suggest getting an experienced electrical engineer to look at your designs. Also, you probably can't install this device in an office - there is an insurance reason that it hand-cranks, your company isn't just being cheap.

What happens if someone bumps the desk and it becomes active when you're not around? What happens when the power goes out? What happens when the power comes back on? Do we have enough fuses in the right places to shut this system down before it catches fire? You need to consider all that.


Detecting grass, pavement, gravel I think about building my own robotic mower, therefore I would like to detect if the surface the mower in moving on is grass, pavement, gravel ... etc.

Which sensors would be the best choice in order to achieve this?

The benefits:

no parimeter wire to bury
possible lawn edge detection (here most mowers fail to do a good job)

You could try to use a force sensitive sensor to detect when grass blades touch it.


to measure the time between the ON signal and OFF signal int pin_state = LOW;
struct Channel {
    byte pin;
    byte state;
    byte count;
    unsigned long fell, rose;
};

const int CHANNEL_COUNT = 3;
Channel channels[CHANNEL_COUNT] = {
    { 2, LOW, 0, 0 },
    { 3, LOW, 0, 0 },
    //{ 4, LOW, 0, 0 },
    //{ 5, LOW, 0, 0 },
    //{ 6, LOW, 0, 0 }
};

void setup()
{
    for (int i = 2; i <= CHANNEL_COUNT; ++i) {
        pinMode(channels[i].pin, INPUT);
    }
    Serial.begin(9600);
    //Serial.println("pin,fell,rose,low time");
    Serial.println("Minutes, Seconds, Count");
}

void loop()
{
    for (int i = 0; i < CHANNEL_COUNT; ++i)
    {
        Channel &c = channels[i];
        byte new_state = digitalRead(c.pin);
        if (c.state == LOW && new_state == HIGH)
        {
            c.rose = millis();
            c.count = c.count + 1;
        }
        else if (c.state == HIGH && new_state == LOW)
        {
            c.fell = millis();
            display_channel(c);
        }
        c.state = new_state;
    }
}

void display_channel(const Channel &c)
{
  int minutes, seconds;
  unsigned long difference;
  difference = c.fell - c.rose;
  seconds = int(difference/1000);
  if (seconds >= 60)
  {
       minutes = seconds / 60;
       seconds = seconds % 60;
  }
    //Serial.print(difference/1000);
    //Serial.print(",");
    Serial.print(minutes);
    Serial.print(",");
    Serial.print(seconds/1000);
    Serial.print(",");
    Serial.println(c.count-1);
    //Serial.print(",");
  }

When I try to run the program, I don't get any output.
Is there anything wrong with the code, that must be solved before any output can get displayed?

Here's the catalog of errors I see at first glance:

const int CHANNEL_COUNT = 3;
Channel channels[CHANNEL_COUNT] = {
    { 2, LOW, 0, 0 },
    { 3, LOW, 0, 0 },
    //{ 4, LOW, 0, 0 },
    //{ 5, LOW, 0, 0 },
    //{ 6, LOW, 0, 0 }
};

You set up space for 3 entries but only fill 2.  Also, the Channel structure has 5 entries, not 4. You don't initialize the 5th (rose) entry (although it will be initialized to 0 for you - best to be explicit though).

for (int i = 2; i <= CHANNEL_COUNT; ++i) {
    pinMode(channels[i].pin, INPUT);
}

You start from entry number 2 (the third entry) and iterate to the 4th (non-existent) entry to set the pin mode of either undefined or invalid pins.

for (int i = 0; i < CHANNEL_COUNT; ++i)

You have only filled in 2 of the three entries. Yet you use the third as if it were filled in.

Serial.print(minutes);

If seconds is less than 60 then minutes is undefined here.

I would suggest changing your code so that Channel is a class and embed the code to manage that class within it.

Bonus Time

Here's your program re-written using a class. As an added bonus I have added automatic allocation of a channel number to each object as it's created.  To add more channels just add the pin number into the initialization list.

class Channel {
    private:
        uint8_t _pin;
        uint8_t _state;
        uint32_t _rise;
        uint32_t _fall;
        uint8_t _count;
        uint8_t _channel;

        static uint8_t channelCount;

        void display() {
            uint32_t diff = (_fall - _rise) / 1000;
            uint32_t secs = diff % 60;
            uint32_t mins = diff / 60;
            Serial.print(_channel);
            Serial.print(",");
            Serial.print(mins);
            Serial.print(",");
            Serial.print(secs);
            Serial.print(",");
            Serial.println(_count);
        }

    public:
        Channel(int pin) : _pin(pin), _count(0) {
            _pin = pin;
            _count = 0;
            _channel = channelCount;
            channelCount++;
        }
        void process() {
            int s = digitalRead(_pin);
            if (s != _state) {
                _state = s;
                if (s == LOW) { // Fell
                    _fall = millis();
                    _count++;
                    display();
                } else {
                    _rise = millis();
                }
            }
        }
        void begin() {
            pinMode(_pin, INPUT);
        }
};

uint8_t Channel::channelCount = 0;

Channel channels[] = { 2, 3 };
#define NUM_CHANNELS (sizeof(channels) / sizeof(channels[0]))

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

    Serial.println("Channel,Minutes,Seconds,Count");

    for (unsigned int i = 0; i < NUM_CHANNELS; i++) {
        channels[i].begin();
    }
}

void loop() {
    for (unsigned int i = 0; i < NUM_CHANNELS; i++) {
        channels[i].process();
    }
}


Arduino Underwater Inertial Navigation I am working on prototyping an underwater navigation system with Arduino. It's going to be used to track movement underwater from a starting point and then be able to tell how to get back to that point or relatively close. The unit would only be going a few hundred feet underwater.

I am using an Arduino Nano, is this going to be sufficient? Also, what IMU would you recommend? I'm sure it will need to at least have a 3-axis gyroscope, 3-axes accelerometer, and possibly a 3-axis magnetometer.

This does need to be relatively affordable. Currently I'm building a unit that can go underwater and just record data onto an SD card so that I can take the data and map it out to check the IMUs accuracy, error margin, along with test various filters on the data. Any recommendations would be greatly appreciated.

The nano can run an IMU just fine, but unfortunately no accelerometer based IMU short of some fancy missile guidance tech is going to be able to track position as accurately as you seem to want.

Since the Gyro and Magnometer only help with rotational orientation, the accelerometer is the only source of info on linear motion, and it has to be integrated twice to get position or distance. This site has a great explanation:
http://www.chrobotics.com/library/accel-position-velocity

As their table shows, even with an angular error of only .1 degrees, after 1 minute your position could be off by 62 meters with a standard quality accelerometer.

As far as IMU's go, the MPU 6050 (accl, gyro) and MPU 9150 (Accl, gyro and mag) are pretty standard in the hobby area, and sparkfun has some breakouts. The AltiIMU from Pololu has similar features and comparable cost. If you don't want to do the sensor processing the UM7 from chrobotics works well, but is significantly more expensive.


How to arrange my code block to make it work smooth and correct I currently working on my system that automatically water the plant based on the water requirement of the plant for one day . I have a java application that let the user input the water requirement of the plant and then the java application send it to arduino the arduino will receive the data and put it inside the variable and it will be use .. I use the following sensor/module ..

SOIL MOISTURE 2 PCS.
WATER FLOW SENSOR 2 PCS.
SOLENOID VALVE 2PS
WATER LEVEL SENSOR 1 PCS.
HUMIDITY SENSOR 1 PCS.
REAL TIME CLOCK DS3231

The data that the java app will send is the water requirements for 1 day for example 400ml , the 400ml will be used by the water flow sensor if the sensor reads that its already 400ml has pass in the tube the solenoid will close the pipe . And my system has a water tank the water sensor is attach to it and will check if the water in the tank is not low if low the arduino will send that data into the java app .. All the sensors reading will be save into database using the java application ..

Here is My Whole code for arduino , its not finish yet because i'm stuck thinking on how to arrange my code blocks . Sorry for my English please bear with me ..

#include <DS3231.h>

//PINS
#define MOISTURE1 A15
#define MOISTURE2 A14
#define WATERFLOW1 A13
#define WATERFLOW2 A12
#define HUMIDITY A11
#define RELAY1 9
#define RELAY2 8
#define ALARM 2

DS3231  rtc(SDA, SCL);
int DELAYNI = 1000;
void setup() {
  // put your setup code here, to run once:
pinMode(MOISTURE1, INPUT);
pinMode(MOISTURE2, INPUT);
pinMode(WATERFLOW1, INPUT);
pinMode(WATERFLOW2, INPUT);
pinMode(HUMIDITY, INPUT);
pinMode(RELAY1, OUTPUT);
pinMode(RELAY2, OUTPUT);

rtc.begin();

Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:

  //Some Code here to get the data send by java app and then assign it to each variable

  readMoistureStatus();
  readWaterLevel();
}
void readWaterLevel(){
  ///Some code here
}

void readMoistureStatus(){

 int  moistureOneSensorValue = analogRead(MOISTURE1);
 int  moistureTwoSensorValue = analogRead(MOISTURE2);

   // checking the moisture range for the first soil moisture
  if(moistureOneSensorValue >= 700){
    // in case of dry soil:
    RelayOne();

     delay(DELAYNI);
  }
  if((moistureOneSensorValue < 700) && (moistureOneSensorValue >= 300)){
    // in case of moist soil:

    delay(DELAYNI);
  }
  if(moistureOneSensorValue < 300){
    // in case of soggy soil:

    delay(DELAYNI);
  }
   //
   //
   // Checking the moisture range for the second soil moisture

  if(moistureTwoSensorValue >= 700){
    // in case of dry soil:
    RelayTwo();

     delay(DELAYNI);
  }
  if((moistureTwoSensorValue < 700) && (moistureTwoSensorValue >= 300)){
    // in case of moist soil:

    delay(DELAYNI);
  }
  if(moistureTwoSensorValue < 300){
    // in case of soggy soil:

    delay(DELAYNI);
  }

}

void RelayOne(){
  //Close or Open the Solenoid

  //Read the water flow if the set point is reach it will close the solenoid using the relay
}

void RelayTwo(){
  //Close or Open the Solenoid

 //Read the water flow if the set point is reach it will close the solenoid using the relay
}

I think that overall your code looks good but I don't understand why you need to log data every 1 seconds (DELAYNI = 1000; is approx 1 sec).
Although there's nothing wrong in placing the

if(moistureOneSensorValue >= ...)
...
...

codeblock in your readstatus(), it's best to separate this out into a dosomething function. Alternatively, you can read the moisture status in the void loop() itself and then place a switch case in the doSomething() function.

You can also use the data from the RTC to check moisture and do something:

void setup(){
...
time = DS3231.time(); //Time at the beginning
}

void loop(){

timeElapsed = now() - DS3231.time();//seconds elapsed

if (timeElapsed >= DELAYNI){
    moisture1 = analogRead(MOISTURE1); // Read ADC value
    moisture2 = analogRead(MOISTURE2); // Read ADC value
    updateDatabase(time, moisture1, moisture2, relay1, relay2); //update the moisture values and statuses of the relays to the database
    switchRelays(moisture1,moisture2); // switch relay1 and relay2 depending on vals
time = DS3231.time(); // Update the time

    }

}


Servo speed in a Toggle Code I am new to Arduino and am trying to figure out servos. Right now I have a toggle button code for the servos. Although I want to know how to speed them up. Is there a way to do this?

Currently, this is my code:

#include <Servo.h>
int button = 5; //button pin, connect to ground to move servo
int press = 0;
Servo servo_7;
Servo servo_8;
Servo servo_9;
Servo servo_10;
boolean toggle = true;

void setup()
{

  pinMode(button, INPUT); //arduino monitor pin state
  servo_7.attach(7); //pin for servo control signal
  servo_8.attach(8);
  servo_9.attach(9);
  servo_10.attach(10);
  digitalWrite(5, HIGH); //enable pullups to make pin high
}

void loop()
{
  press = digitalRead(button);
  if (press == LOW)
  {
    if(toggle)
    {

      servo_7.write(180);
      servo_8.write(180);
      servo_9.write(180);
      servo_10.write(180);
      toggle = !toggle;
    }
    else
    {

      servo_7.write(0);
      servo_8.write(0);
      servo_9.write(0);
      servo_10.write(0);

      toggle = !toggle;
    }
  }
  delay(100);  //delay for debounce
}

Normal servos have a speed. It's their speed, and you can't change it. You can make it appear slower by moving in small increments, but you can't actually change the speed it moves.

With constant rotation servos the "angle" dictates the rotation speed, but even with those there is nothing you can do to change the relationship between "angle" and rotational speed.

Other than buying a different servo with a different degrees-per-second rating.


i2c high speed and pull-up resistors hello guys i want to ask about 2 things
first one is i'm connecting and arduino uno attached to a usb host sheild and transferring data of a mouse coordinates to 10 arduino leonardo
i'm using the standard speed 100
normal mode
my wires is all about 10 cm long

i need to speed up the comm to fast mode
how to make this ? and the line of code where to put it in the code and in the master or slave ?

what about the pull-up resistors ? does arduino uno includes built in pull-up resistors ? does it needs to disable it and put my own pull up resistors ?
i’m using wire library

i need to speed up the comm to fast mode how to make this

Wire.setClock(400000);

and the line of code where to put it in the code

Just after Wire.begin() in setup().  Wire.begin() sets the speed to 100,000 and you need to then override that afterwards to set it to 400,000 (or whatever speed you want to run at).

and in the master or slave ?

In the master, since it's the master that generates the clock.

what about the pull-up resistors ? does arduino uno includes built in pull-up resistors ?

Yes, but they're too high for reliable I2C operation. You should add your own resistors in the region of 1kΩ.

does it needs to disable it and put my own pull up resistors ?

No, yours will just be in parallel with them, with the net result of a small reduction of overall resistance.


Get the uploaded code from arduino by using arduino IDE 1.0.6 Recently bought a arduino device which already have program,

it is model AR-293D and I have already connect it with my PC(windows 7) through usb

when I open the IDE , It seems there is no function that read the uploaded program?

And after searching a while , like some beginner tutorial , it only tell you how to upload the program but not how to get the uploadded program

http://www.forefront.io/a/beginners-guide-to-arduino

So, I wonder how to get the code? Thanks a lot for helping, I worried erase the uploadded program so I need to take caution about this


Why are pull-up resistors needed? Please tell me why is it necessary to access pull-up resistors and how can we access them in arduino?

Pull-up resistors are used to define the state of an otherwise "floating" input by pulling the voltage at the pin to a set voltage.
The most typical example is a switch - let's say you have some signal, which is connected to your input through a switch. If the switch is open, the state of your input is "floating". If you try to digitalRead or analogRead that input, the value will be pretty much just noise.
But, if you have a resistor connected from your input to ground (pull-down) or VCC (pull-up) your reading will be consistent (HIGH or LOW, depending on where the resistor goes) while the switch is open.
When the switch is closed, the voltage at the pin will be pulled to the voltage at the other end of the switch.  Because of the lower resistance of the switch relative to your pull-up resistor, this is the input level that will be read by the microcontroller. Pull-up resistors are usually pretty big value (5k-100k) in order to be much higher resistance than the switch and to decrease the current that is used by the switch to produce a signal.
If, for example, you have a pull-up resistor and a switch that connects your input to the ground, when the switch is open you will read HIGH and when it is closed you will read low.
Note that many components act similar to switches, for example transistors, open-drain / open-collector devices and many more, so the switch was just an example.

You can use external pull resistors (just add a resistor from your pin to ground or VCC) or use the internal pull resistors of your MCU.
The Arduino only has internal pull-up resistors (no internal pull-downs) - their value depends on the model, but usually is between 20K-150K.
To activate the internal pull-up resistor for a given pin on Arduino, use the following code:

pinMode(N, INPUT);
digitalWrite(N, HIGH):

where "N" is your pin number or with recent IDEs:

pinMode(N, INPUT_PULLUP);


How to send data from arduino to Temp Controller for setting temp? I send data from arduino by method following.
Configure the value : byte message[ ];

#include <SoftwareSerial.h>
#define RX 2
#define TX 3
int incomingByte = 0;

SoftwareSerial mySerial(RX, TX);

void setup()
{
  pinMode(5, OUTPUT);

  Serial.begin(9600);
  mySerial.begin(9600);
}

void loop()
{
  incomingByte = Serial.read();

  if (incomingByte == 's')
  {
    digitalWrite(5, HIGH);
    byte message[] = {0x01, 0x06, 0x00, 0x01, 0x02, 0x58, 0xD8, 0x90} ;
    mySerial.write(message1, sizeof(message1));
  }
}

It works. But I want to input from "Serial monitor" to set the temperature.
It does not work when input from "Serial monitor".

You're not writing any data to incomingByte and you're not detecting if data is sent towards the Arduino over serial.

You should change your void loop() into this:

void loop(){

  //Detects if something is sent over serial.
  if(Serial.available() > 0){

    //reads the byte and puts it into the incomingByte variable
    incomingByte = Serial.read();

    //below is your old code
    if (incomingByte == 's') {
      digitalWrite(5, HIGH);
      byte message[] = {0x01, 0x06, 0x00, 0x01, 0x02, 0x58, 0xD8, 0x90} ;
      mySerial.write(message1, sizeof(message1));
    }
  }
}

When you're using the serial monitor to send data towards the Arduino, also make sure the baudrate you use is the same as the Arduino's. In this case you set your baudrate to 9600 Serial.begin(9600).


for loop reads pots, passes value to PWM pins, can this be in the same for loop? In the code below I am using a for loop to iterate over analog pins (potentiometers) and pass their value, after being mapped, to PWM enabled analog output pins (currently controlling LED brightness). While this works as is, I am curious about the following: would it be better to split the analogRead and analogWrite lines into separate for loops, or would that simply be redundant from a code standpoint? My concern is accidentally mixing up the pot values due to difficult-to-perceive timing issues.

The code:

static const uint8_t analog_pins[] = {A0, A1, A2, A3};
static const uint8_t digital_pins[] = {3, 5, 6, 9};
int pot_vals[] = {0, 0, 0, 0};
int val[] = {0, 0, 0, 0};

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

  // setup inputs, outputs
  for ( int i = 0; i < 4; i++ ) {
    pinMode( analog_pins[i], INPUT );
    pinMode( digital_pins[i], OUTPUT );
  }
}

void loop() {
  for (int i = 0; i < 4; i++) {
    val[i] = analogRead(analog_pins[i]);
    analogWrite(digital_pins[i], map( val[i], 0, 1023, 0, 255 ));
  }
  delay(2);
}

Having both the analogRead() and analogWrite() in the same loop is
perfectly fine. That would be be my preferred choice if only for one
reason: less RAM consumption. If you split them in two loops, you have
to store somewhere the readings of the four channels, either before or
after mapping. If you keep them in the same loop, you don't need the
pot_vals[] nor val[] arrays. You would use a local variable instead,
which consumes no RAM:

void loop() {
  for (int i = 0; i < 4; i++) {
    int val = analogRead(analog_pins[i]);
    analogWrite(digital_pins[i], map(val, 0, 1023, 0, 255));
  }
  delay(2);
}

  My concern is accidentally mixing up the pot values due to
  difficult-to-perceive timing issues.

“Difficult to perceive”? I would call these issues “imaginary” instead.
You have no risk of “mixing” any values here. Maybe, if you can
elaborate on the kind of issues you imagine you could have, we could
help you clear some misunderstanding about how the microcontroller
executes your code.

Edit: To expand on Andrew's comment, the for loop can be optimized
as

for (int i = 0; i < 4; i++) {
  unsigned int val = analogRead(analog_pins[i]);
  analogWrite(digital_pins[i], val / 4);
}

Dividing the value by 4 is the best way to map the input range to the
output range. It gives a more uniform mapping than the map() call
above, as every output value is mapped to exactly 4 input values. It
could be noted, though, that map(val, 0, 1024, 0, 256) gives the same
uniform mapping.

The division by 4, however, is optimized by the compiler into a bit
shift, which is orders of magnitude faster than map(), and likely to
consume less stack space. There is one caveat to be aware of: this
optimization is only possible if val is unsigned. If it is signed,
then it is compiled into a call to a division routine, which is quite
expensive.

One could be tempted to go even further and get rid of the temporary
val variable, like:

for (int i = 0; i < 4; i++) {
  analogWrite(digital_pins[i], (unsigned int) analogRead(analog_pins[i]) / 4);
}

However, there is zero benefit from doing so: from the point of view of
an optimizing compiler, this form is exactly equivalent to the previous
one. I prefer the former which I deem more readable.


ATMega1284 and Relative Humidity libraries I am trying to use some Relative Humidity sensors (DHT11 and DHT22) with the ATMega1284 processor on a breadboard. I use libraries from Arduino playground (dht.h), Adafruit (DHT.h) and others. Even though both sensors and libraries work fine with Arduino Uno and Mega, they fail with ATMega1284, which produces an INVALID_VALUE error.

Connections are double checked, and other libraries such as Wire, OneWire etc work fine.

Does anyone have any experience with the ATMega1284 processor, or any suggestions?

Per the library instructions, you will receive INVALID_VALUE in the following situations:

The readXX() functions return:

DHTLIB_OK (0) : if the sensor sample and its checksum is OK.
DHTLIB_ERROR_CHECKSUM (-1) : if the checksum test failed. This means that data was received but may be incorrect.
DHTLIB_ERROR_TIMEOUT (-2) : if a timeout occured, communication failed.

In case of a DHTLIB_ERROR_TIMEOUT, humidity and temperature will both get the value DHTLIB_INVALID_VALUE. In case of DHTLIB_ERROR_CHECKSUM the values of humidity and temperature are left unchanged as it is impossible to determine which byte failed in the checksum. It is up to the programmer to decide what to do. One can compare with previous value, but better reread the sensor.

So read the value returned by the read11() or read22() functions to verify that it's an DHTLIB_ERROR_TIMEOUT condition, and if so try to figure out why the library is having trouble talking to the device.


Creating a product with arduino bootloader If you have a prototype with arduino and you wish to create a real product can you do it or the fact that it contains the arduino bootloader prevents you?

BTW, i dont have a product ready. I am thinking options though. Or maybe i will have to go find a job

A quick google search found this info on the Arduino Forum which a user kindly shows the rules relating to this stuff.

The Optiboot bootloader is not actually an Arduino 'product'. Boards you design and software you write using Arduino IDE and libraries does not need to be disclosed to anybody, other than having the objects available (probably in a hidden part of your product's support website, in a "firmware" sub section) for some reason relating to being able to build the source against newer versions of Arduino.

I am currently making a product which I intend to use Arduino libraries and IDE and bootloader for fast development, but the board, schematics, and essentially the application code except for the libraries from Arduino will be mine. If you copy or build stuff specifically for/from Arduino hardware, you must(?) release certain source/schematics etc.


Can an Arduino (Leonardo) be recognized via Bluetooth as a mouse/keyboard? I'm new to wireless communication on Arduinos and doing research for a project. I'm looking at the Arduino Leonardo (which is like the Uno) which via its micro USB port can be automatically recognized as a mouse/keyboard. But also looking at a regular Uno wiFi Rev2.

I want to achieve the same result, but wirelessly via Bluetooth. Because I need to connect it to a device that only recognizes Bluetooth mice/keyboards and nothing else. If I buy something like the HC-05 how would the chip report itself?

How is the Bluetooth stack handled with regards to identification and authentication? Does it somehow copy the USB mouse/keyboard setup?

PS: Can anyone tell me if the Wifi Arduinos (Uno WiFi rev2) also have Bluetooth embedded?

If I buy something like the HC-05 how would the chip report itself?

As an SPP. I.e., a serial port.

  How is the bluetooth stack handled with regards to identification and authentication?

By the firmware on the HC-05

  Does it somehow copy the usb mouse/keyboard setup?

No.

You need a USB device that can emulate a keyboard. That's not the HC-05. The host microcontroller has absolutely nothing to do with what capabilities the bluetooth interface has.


Why connect the source pin on a mosfet to the pull down resistor? I'm trying to power stuff controlled by an arduino, and I'm looking at this tutorial: http://bildr.org/2012/03/rfp30n06le-arduino/ and it almost all makes sense, send a signal to the gate, but it's like a capacitor or something so provide a path for that signal to go to ground when the arduino isn't supplying current, but when it is supplying current then the source and drain are connected so current can flow from some external source through them... but why even connect that part of the circuit back to the board? I'll paste a pic with a question mark on the wire I'm frowning at:

I am not sure if I understood right, but I will try to answer:

Why there is ground line going back to the Arduino board?

Because all grounds in DC circuit must be connected together. Simple as that.

Why is there a pull-down resistor on MOSFET?

The MOSFET you are using is N-channel MOSFET. It is "activated" or "open" where voltage on the gate is larger than "Gate threshold voltage", the value you will find in MOSFET datasheet. You want your MOSFET to be off in all times unless you apply voltage to the gate.

In this case it is actually a pull-down resistor from gate to the ground(hence the pull-down resistor). It is coincidence that in N-channel MOSFET you connect source to the ground so it looks like there is a MOSFET on source line, but it is actually just a pull-down resistor on gate to keep MOSFET off.


best way to protect a digital or analog input from 12volts At work, I have connected an Arduino to a security key (which has a 12v power supply) in order to give us a more versatile door lock.  Unfortunately, people keep removing the key pad, disconnecting the wires and re-connecting them (defective keypad I guess.)  In the process, I am afraid that they will accidentally send 12v into the Vcc, ground, digital in, and/or analog in pins.  What is the best way to protect my Arduino from the 12 volts?  I really need a component or two that I can to my pins.

Edit: it is difficult for me to describe this problem without mentioning the danger to all components.  Please describe ways to protect digital outputs HERE

There are some suggestions at Protecting Inputs in Digital Electronics .

Amended answer

Testing of my earlier answer involving clamping diodes gave unsatisfactory results. Due to the small current flow the diodes allowed a considerable voltage to reach the input pin (like, 9 V).

The amended circuit below, tested with 12V input, satisfactorily keeps the Arduino input pin to 4.9 V, even with 12 V from the device. The current through R1 is around 7 mA which is what you would expect:

I = V / R
I = 7 / 1000
I = 7 mA

The 1N4733A is a 5.1 V, 1 W zener diode which can therefore handle dropping 5 V at 7 mA.

In case you are wondering where the number 7 comes from in the calculations above:

The input voltage is 12 volts
The desired output is 5 volts
Therefore we need to drop (12 - 5) volts over the resistor
Thus 7 volts are dropped over the resistor

Further reference material:

10 Ways to Destroy An Arduino
Protection
Microcontroller Input Protection Techniques


MD5 Password in Sketch I'm playing with Over The Air (OTA) updates in my LoLin. I can make connections to my router and OTA updates seem to work well.

I'm uncomfortable storing my WiFi router SSID and password unencrypted in every sketch. Can I store an encrypted password instead for use in WiFi.begin()?

For example, Linux has wpa_pasphrase, which generates a 32-byte number which is an encrypted version of the password which can safely be stored in plaintext configuration files.

Can I store an MD5 password hash instead

No. MD5 is a "trapdoor" algorithm. It's one-way. You can make a hash from a password but you cannot make a password from a hash.

You could AES encrypt it, but you would need to have the AES key in your sketch to decrypt the password, which just moves the problem elsewhere.

Typically in a real-world situation you wouldn't have either the SSID or the password in the sketch. Instead you'd create a configuration system which would allow you to set (and of course change) both the SSID and password at runtime, and have the data stored somewhere (either EEPROM or in a file in SPIFFS, for example).

You might want to take a look at WiFiManager which automates that process for you.


Connecting MicroSd Reader with arduino uno I am working on a Project with
(a) Arduino Uno Clone (6 PWM Pins i.e, 3,5,6,9,10,11)
(b) 6 Servos
(c) MicroSD Reader Module
(d) Speaker

As We Know that MicroSD reader modules uses pins 10, 11, 12 of an Arduino board, but my pin 11 is already being used by a servo motor.
1. Then how can I connect the MicroSD reader in my project ?
2. Which pin can I use for the speaker in this case ?

Please help me plus Provide me some additional information if needed.

The best answer is: don't use pin 11 for your servo motor - move it to another pin.

The SD card needs SPI.  SPI is pins 10/11/12/13.  You can't change that.  You can much more easily move the servo to a different pin, since there are multiple PWM pins that can support the servo in hardware. If they are all taken then software PWM is easy and there are libraries available to do it for you, so you can use any IO pin you like for that.  Much simpler than re-writing the SD card software to use bit-banged SPI on other pins (which would also be incredibly slow).


is there any possibility of connecting ACCELEROMETER + ARDUINO UNO + GSM module together? I am lakshman a mechanical engineer,i have a question that is there any possibility of connecting ACCELEROMETER + ARDUINO UNO + GSM module together???

so that i can take the output value from Accelerometer so that to make a call to a preprogrammed number???

Plz help me.

Thank you.

Yes, that is perfectly possible.  Typically:

Accelerometer is either an analog, SPI or I2C interface.
GSM is usually a UART interface
The Arduino UNO has all four interfaces (analog, SPI, I2C and UART) available on separate pins.

The rest is just a SMOP.


Set board manager as ATmega16 I tried to download the ATmega16 board in my Arduino. I have set below URL under File->Preference->Additional board manager URL

https://mcudude.github.io/MightyCore/package_MCUdude_MightyCore_index.json

I am getting below attach images. How can we resolve this error and install atmega16 board manager?

I am using Arduino version 1.6.9. I don't have any issue in opening MightyCare and Arudino URL from my chrome browser.

Thanks for everyone help here.

I have resolved by few steps.

1) File -> preference -> Board manager URL as like below. Basically URL are seperated by commas.
http://arduino.esp8266.com/stable/package_esp8266com_index.json,https://mcudude.github.io/MightyCore/package_MCUdude_MightyCore_index.json

2) Deleted the tmp file (package_index.json.tmp) which is in the path C:\Users\SIMBU\AppData\Local\Arduino15\

This helped me to resolve the issue.


Particle-like wifi configuration Can anybody tell me how the Particle (Photon/Core) WiFi setup works?

I am looking to mimic this WiFi configuration format for my own device.

The basic steps are as follows:

Power device on; put in "listening mode" if not already active;
Connect smartphone to the wireless network that you want to connect your device to;
Open the Tinker/Spark/whatever-it's-called App on your smartphone; choose "Add New Device";
Enter wireless password;
Wait for device to be discovered by the App; device is now connected to WiFi.

How is the information (SSID, password) transferred from the smartphone to the device?

Thanks in advance.

The Particle Photon is a replacement for the Spark Core module. This module was exploiting the Texas Instrument CC3000 chip. It was this chip that handle the very simple and convenient Wi-Fi configuration of the Spark Core. Texas Instrument named this method : SimpleLink.

The Particle Photon is now using a different module than the Core : a Broadcom BCM43362 instead of the CC3000. It's seems to work in a similar manner even if I was not able to find any information on it.

I've found on the George Howkins Depletion Region blog  multiple articles that explain how the CC3000 SimpleLink works.

CC3000 Smart Config - transmitting SSID and keyphrase
CC3000 advertises presence on network via DNS-SD

All the posts : http://depletionregion.blogspot.fr/search?q=smart+config


Arduino program to scan two different rfid cards in same program ? Im using nodemcu- esp8266 , rc522 reader and Firebase /*My project is a Library management system using rfid cards. Im trying to generate a code wherein User first scan a book and then the record will be pushed in Issued_Books table in Firebase . Then the user scans his id to ensure that the book will be issued on his/her id.
But in my program is scanning only books id. It fails to scan users Id after that. Im a beginner so can anyone guide me? */

//My loop code is as following:

void loop() {

  if ( !mfrc522.PICC_IsNewCardPresent() ) {
    delay(50);
    return;
  }

  if ( !mfrc522.PICC_ReadCardSerial() ) {
    delay(50);
    return;
  }
String book;

  for ( byte i = 0; i< mfrc522.uid.size; i++ ) {
    Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
    Serial.print(mfrc522.uid.uidByte[i], HEX);
    book.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
    book.concat(String(mfrc522.uid.uidByte[i], HEX));}
    book.toUpperCase();

    Firebase.pushString("Issued_Books/Book_rfid",book);

      Serial.println();

  if ( !mfrc522.PICC_IsNewCardPresent() ) {
    delay(50);
    return;
  }

  if ( !mfrc522.PICC_ReadCardSerial() ) {
    delay(50);
    return;
  }
  String user;

  //Serial.print("Scan your id: ");
    for ( byte i = 0; i< mfrc522.uid.size; i++ ) {
    Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
    Serial.print(mfrc522.uid.uidByte[i], HEX);
    user.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
    user.concat(String(mfrc522.uid.uidByte[i], HEX));}
    user.toUpperCase();
    //Serial.print(F("Card UID: "));
    Firebase.setString("Issued_Books/Book_rfid/user_rfid",user);

    delay(3000);
}

also look into sprintf to get hex formatting
(I dont have these libraries so I cannot test, this is all written in stackexchange editor, so I might have a typo somewhere)

unsigned long startScanTime;
bool GotBookId = false, GotUserId = false;
void loop() {
GotBookId = false;
GotUserId = false;

  if ( !mfrc522.PICC_IsNewCardPresent() ) {
    delay(50);
    return;
  }

  if ( !mfrc522.PICC_ReadCardSerial() ) {
    delay(50);
    return;
  }
String book;

  for ( byte i = 0; i< mfrc522.uid.size; i++ ) {
    Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
    Serial.print(mfrc522.uid.uidByte[i], HEX);
    book.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
    book.concat(String(mfrc522.uid.uidByte[i], HEX));
  }
    book.toUpperCase();
    if(book != "")
       GotBookId = true;

    Serial.println("Got Book");

startScanTime = millis(); //timeout look to get user card
  while( !mfrc522.PICC_IsNewCardPresent() && (millis() - startScanTime < SCAN_TIMEOUT) ) {
   //do nothing but wait
  }

  if(!mfrc522.PICC_IsNewCardPresent())
  { //did not get the user id, return from loop
      return;
  }
  if ( !mfrc522.PICC_ReadCardSerial() ) {
    return; //should never hit this if library works correctly
  }
  String user;

  Serial.print("Scan your id: ");
    for ( byte i = 0; i< mfrc522.uid.size; i++ ) {
    Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
    Serial.print(mfrc522.uid.uidByte[i], HEX);
    user.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
    user.concat(String(mfrc522.uid.uidByte[i], HEX));}
    user.toUpperCase();
    //Serial.print(F("Card UID: "));
    GotUserId = true;

   if(GotBookId && GotUserId){
       Firebase.pushString("Issued_Books/Book_rfid",book);
       Firebase.setString("Issued_Books/Book_rfid/user_rfid",user);
   }
}