Finding and loading "libraries" I am 6 months into my Arduino Uno work and I would like a step by step way to find and download a "library". I work using WINDOWS and WORD and although I was eventually successful in getting a 7 segment display library to download and work, I must say I could not do it again since the path I followed was far from clear due to my lack of understanding about basic computer stores etc. I have enjoyed my work with the Uno but I have been very disappointed at lots of "help" offered on other sites since they assume I know far too much. It is a skill to be able to communicate with we lesser people so I am really hoping a step by step guide is possible.
Thanks

Start with the newest Arduino IDE. At this moment that is version 1.8.1.

Try to find the Library Manager. Via the menu: Sketch / Library...

In the Library Manager there is a input field in the upper-right corner where you can search for libraries.

If you can not find the library, then the next step is to download a zip file from Github. There is probably a green button "Clone or Download" on the right side with that project on Github. Use it to download that library and store it. Do not unzip it. In the Arduino IDE in the menu via: Sketch / Library... there is a option to install a .ZIP file. Use that to install the library from Github.

Your projects are probably at: Documents / Arduino

There is also a folder: Documents / Arduino / libraries

That is where the installed libraries will end up. That means you can also add libraries to that folder. Each library in its own sub-folder.


Arduino AT not working (Arduino UNO and HC-06) Recently had issues with HC-06 AND Arduino UNO. Turned out that the last module was not working, this module keeps flashing and it appeared in the Bluetooth list.
I'm trying to work with some AT commands but for some reason this doesn't work. This module is brand new (ZS-040).

#include <SoftwareSerial.h>

SoftwareSerial btSerial(2, 3); // RX, TX
/*
 * Connect pin 2 Arduino to pin TX HC-06
 * Connect pin 3 Arduino to pin RX HC-06
 */
void setup() {

Serial.begin(9600);

Serial.println("Enter AT commands:");

btSerial.begin(9600);

}

void loop()

{

if (btSerial.available())

Serial.write(btSerial.read());

if (Serial.available())

btSerial.write(Serial.read());

}

I uploaded the code, went into Serial Monitor. When I type a command, I get no reply. I opened "Arduino Bluetooth" app,connected to my phone and when I type something in the terminal on my phone I see the text on my PC's Serial Monitor screen.
Any ideas what I should do next? Could it be something to do with the RX pin? Should I use voltage divider? I have 1k and 2k Ohm resistors, how should I connect them if that's the solution?

Use a macro like this to send AT commands:
 #include <SoftwareSerial.h>

 SoftwareSerial btSerial(2, 3); // RX, TX
 /*
  * Connect pin 2 Arduino to pin TX HC-06
  * Connect pin 3 Arduino to pin RX HC-06
  */
 void setup() {

 Serial.begin(9600);

 Serial.println("Enter AT commands:");

 btSerial.begin(9600);

 }

 void loop()

 {

 if (btSerial.available())

 Serial.write(btSerial.read());

 if (Serial.available())

 btSerial.write(Serial.read());
 delay(1000);
 //btSerial.print("AT+PIN4321");
 //btSerial.print("AT+NAMEAlibaba");
 //btSerial.print("AT+BAUD4");

 }

You may have another port set on the HC 06 instead of 9600, like I had.
If so, try this code with all the possible port numbers and changing something like the password, and everytime you run the code - go check if it worked, this way you will find in wich port number you have your module.

good luck


How to communicate with ESP8266 ESP01 by sending data through softwareserial on Arduino Uno? I am able to send AT commands when connecting to the software through the TX/RX pins (1, 0) and the ESP01 communicates perfectly. However, as soon as I start doing that same thing with code I can't get the ESP01 to respond whatsoever. All I'm trying to do is get an OK back from the serial monitor. I changed the baudrate on the ESP01 as well as my serial monitor from 115200 to 9600, 19200 using this command:

AT+UART_DEF=9600,8,1,0,0

Troubleshooting steps taken:

Tried upping the voltage in case it wasn't getting enough current.
Tried different ESP01s.
Tried switching TX and RX pins.
Tried using different pins on the Uno (2 and 3, 10 and 11, 7 and 8).
tried changing myESP.println("AT"); to myESP.write("AT\n\r");.

Nothing works. I've done a ton of research and I haven't found anything wrong with what I'm doing, do you guys have any ideas?

#define TX 3
#define RX 2
String ssid = "*****";
String password = "******";

#include "SoftwareSerial.h"

SoftwareSerial myESP(RX,TX);

void setup() {
  pinMode(RX, INPUT);
  pinMode(TX, OUTPUT);
  myESP.begin(19200);
  Serial.begin(19200);
}

void loop() {
  myESP.println("AT");
  delay(5000);
}

Schematic is as follows:
TX -> pin 3
RX -> pin 2
Vcc -> 3.3v
GND -> Ground
CH_PD -> Vcc

How about this:

void loop() {
  while(Serial.available() > 0) {
     myESP.write(Serial.read());
  }
  while(myESP.available() > 0) {
     Serial.write(myESP.read());
  }
}

That code will continue to load data to and from the software serial not just one byte. You can also use string concatenation:

String data = "";
while(Serial.available() > 0) {
   data += Serial.read();
}

Or arrays:

int data_max = 4096;
int data_size = 0;
char data[data_max];
while(Serial.available() > 0) {
   if(data_size < data_max) data[data_size++] = Serial.read();
}


Using millis() in unsynchronized manner I am assuming millis() is a Timer ISR function.
If so :
When using millis() as mentioned in Arduino Reference :
unsigned long currentMillis = millis();
What would happen if the ISR asynchronously changes the value being read in a function. I mean if I have read one byte into currentMillis, but millis had changed the value before the remaining 7 bytes are read.
Cheers and TIA

I am assuming millis() is a Timer ISR function.

It is a function that retrieves a value that is updated by and ISR.

What would happen if the ISR asynchronously changes the value being
read in a function.

Cannot happen: the value is read with interrupts disabled.
See for example, in the AVR core:
// disable interrupts while we read timer0_millis or we might get an
// inconsistent value (e.g. in the middle of a write to timer0_millis)
cli();
m = timer0_millis;
SREG = oldSREG;

I mean if I have read one byte into currentMillis, but millis had
changed the value before the remaining 7 bytes are read.

An unsigned long is only 4 bytes. That is, until someone comes with a
64-bit Arduino platform.


LMT 84 temperature sensor measurement error I want to measure atomospheric temperature with arduino sensor i am using is LMT84.
 data sheet :http://www.ti.com/lit/ds/symlink/lmt84.pdf
 After uploading following code to arduino board i am getting very high temperature in serial window .I m new in electronics field so i am unable to understand what is error in my code .Ive connected0.1uf cap between vcc and ground,data pin is connected toA1 of arduino.

Plz check following code:

const int sensor = A1; // Assigning analog pin A1 to variable 'sensor'
float tempc;  //variable to store temperature in degree Celsius
float vout;  //temporary variable to hold sensor reading
float vout1;  //temporary variable to hold sensor reading

void setup()
{
  Serial.begin(9600);
  pinMode(sensor, INPUT); // Configuring pin A1 as input
}

void loop()
{
 vout = analogRead(sensor);
  vout1 = (vout * 500) / 1023;
  tempc = vout1; // Storing value in Degree Celsius
   Serial.print("LMT84 temp=");
  Serial.print(tempc);
  Serial.println();

delay(1000);
}

Serial window showing this values::

LMT84 temp=168.13
LMT84 temp=168.13
LMT84 temp=168.64
LMT84 temp=168.89
LMT84 temp=168.13

The Arduino uses an analog voltage as reference. It is default set to the Vcc of the microcontroller, which is about 5 V for an Arduino Uno. The function analogReference can be used to set something else as reference.

When that reference is not precisely 5.0 V, it is impossible to measure a voltage in a accurate way. It is almost never precisely 5.0 V. When using the USB connector to power the Arduino board, it might be somewhere between 4.5 and 5.0 V.

The Arduino Uno has an internal voltage reference of 1.1 V. That is better than using the default 5 V. The actual voltage can be 1.0 to 1.2 V, you have to put the actual value in your sketch.

The LMT84 has an output of 1034 mV at 0°C and 476 mV at 100°C. That means your calculation is not correct. In the datasheet are two ways to calculate the temperature, an accurate formula and a simple calculation.

You can avoid all these problems with a temperature sensor that has a digital interface to the Arduino board. For example the DS18B20. That is a cheap and accurate temperature sensor.


my arduino uno board is not working at once, when i connect arduino uno to my computer, my computer shuts down, after that i cannot upload programs to my computer,the board is not working but the led is ON. Before this, i upload programs 4 to 5 times continuously. i upload program with no physical connections in arduino except motor shield which is also not connected to anything.
i used three boards, all of them got damaged.

my computer's USB port and USB cable is in good codition.
i already updated my drivers.

computer spec: dell inspiron 15 3567
               windows10 x64 bit

Computer shutting down is often an indication that excess power is being drawn.
If you measure  between +5 and Gnd on the unpowered board with a meter set for resistance, do you get a reading in the 5Kohm range? Or something much lower? Much lower would be bad.


How can I use IRsend with a string or convert a char from serial to uint32_t? I'm trying to control my arduino with a raspberry pi with python instead of C++ (which I don't know). I've found code to take a string from serial and print it, but instead I'd like to use IRsend to use the code. Unfortunately I'm getting the error invalid conversion from 'char*' to 'uint32_t {aka long unsigned int}' [-fpermissive]. I know this must be an incredibly dumb question but is there a int() function for uint32_t for arduino C++? that I could set blah=uint32_t(buf) and then use my irsend.sendNEC(buf, 32)? If it's not painfully obvious, I don't know C++ and my python isn't great.
#include <IRremote.h>

char buf[80];

int readline(int readch, char *buffer, int len) {
  static int pos = 0;
  int rpos;

  if (readch > 0) {
    switch (readch) {
      case '\r': // Ignore CR
        break;
      case '\n': // Return on new-line
        rpos = pos;
        pos = 0; // Reset position index ready for next time
        return rpos;
      default:
        if (pos < len-1) {
          buffer[pos++] = readch;
          buffer[pos] = 0;
        }
    }
  }
  return 0;
}

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

IRsend irsend;

void loop() {
  if (readline(Serial.read(), buf, 80) > 0) {
    Serial.print("You entered: >");
    Serial.print(buf);
    Serial.println("<");
    irsend.sendNEC(buf, 32);

  }
}

Error:
/home/pi/Desktop/sendIRfromserial2addingir/sendIRfromserial2addingir.ino: 39:27: warning: invalid conversion from 'char*' to 'uint32_t {aka long unsigned int}' [-fpermissive]
             irsend.sendNEC(buf, 32);

                  ^

In file included from
/home/pi/Desktop/sendIRfromserial2addingir/sendIRfromserial2addingir.ino:1:0:
/home/pi/Arduino/libraries/IRremote/src/IRremote.h:444:10: note:   initializing argument 1 of 'void IRsend::sendNEC(uint32_t, uint8_t, bool)'
     void sendNEC(uint32_t data, uint8_t nbits, bool repeat = false);
          ^~~~~~~`

Instead of
irsend.sendNEC(buf, 32);

cast it to an unsigned int32 type:
irsend.sendNEC((uint32_t) buf, 32);


Adafruit CC3000 WiFi Module working together with MFRC522 RFID Module Issues both SPI over Arduino I'm asking if how can I implement this one. I'm aware about multiple devices being connected over SPI, like having to select individual SS pin for each. Adafruit's CC3000 works fine alone along with the default Adafruit library. CC3000 uses SPI. MFRC522 RFID module by sonmicro (bought at Sparksfun) uses SPI too. It works fine too, independently. But whenever I connect them together, only WiFi works perfectly. I dont want to turn on and off the wifi to make way for the RFID to communicate since it takes some time for it to be connected in a wireless network. I want the two to work synchronously (or having to be scheduled but really fast that's unnoticeable by the user)

here's my code as of now. i cannot post it here as strange things happen i don't know why haha https://drive.google.com/file/d/0B0bZsYo0xMH8YV9uWXJaRFdPT3M/view?usp=sharing

I'm thinking of replacing the RFID with SonMicro's SM130 RFID Module w/ SparkFun Eval board with UART (convertible to I2c) or Adafruit's PN532 with I2c by default. Are these okay to be paired with SPIs like the CC3000? Or should I change CC3000 with the Official WiFi module (UART) or WiFly Module (SPI-to-UART)

I couldn't get your code to download so this might be wrong, but it sounds like the modules are running different SPI modes: http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus#Mode_numbers

I had this problem a few years ago. You'd expect SPI to be SPI, but it comes in four different flavours and they won't talk to each other on the same bus. Unfortunately there's no solution but to replace the modules; the Arduino can only run one SPI bus, so can only talk to one of these modules at a time.

However you can run UART and I2C or UART and SPI concurrently by using SoftwareSerial (don't use the native Tx/Rx pins, bad things happen).

So your best bet is to switch to modules that use I2C or UART. Personally I'd use UART, simply for the simplicity of having two separate connections and a higher data rate.


How to use printf with Arduino's serial ports without an intermediary buffer? How to use printf with Arduino's streams without an intermediary buffer? The following seems unnecessary:

char buf[256];
sprintf(buf, ...);
Serial.print(buf);

Is there a way to connect HardwareSerial or SoftwareSerial to a libc stream or is there a custom implementation of printf that does this?

Sure - here's a Hello, World program that uses printf(). Everything that mentions "uart" is what connects printf() to your output stream. uart_putchar() does the actual outputting to ... someplace. That's what you'd modify to direct the C standard output to a different device - SofwareSerial, for instance:

// Hello, World program using printf()

#include <Arduino.h>

static FILE uartout = { 0 };   // FILE struct
static int uart_putchar(char c, FILE *stream);

void setup() {
   // For printf: fills in the UART file descriptor with pointer to putchar func.
   fdev_setup_stream(&uartout, uart_putchar, NULL, _FDEV_SETUP_WRITE);
   stdout = &uartout;

   Serial.begin(9600);
   printf("Hello, World!\n");
}

void loop( void ){
   printf("Elapsed time: %ld\n", millis());
}

// uart_putchar - char output function for printf
static int uart_putchar (char c, FILE *stream)
{
   if( c == '\n' )
      Serial.write('\r');
   Serial.write(c) ;
   return 0 ;
}


From Arduino and breadboard to PCB After building a working prototype with a breadboard, I was wondering what's next.
So I read about integrating the arduino into a PCB layout.

But in my case, it's worth it?

My project will use a Arduino Mega, futhermore some wired piezo switches therefore I need pcb connectors, and a small amount of resistor and transistors.
I am considering to buy a Mega of the shelf and use the contactpins on a header to fix it on my PCB. Also probably fix it with some screws.

It will save me a lot of pcb design time (a maybe some mistakes) and it will save me buying all diferent components. The  ATMega2560 alone is already around 10,-

I think I only need 10 or 15 pcb's, definitly no massproduction.

Your opinions...

I agree with Majenko's proposal for a proto shield, or if you need a "flat" design beside the Mega get yourself a striped (one /two sided and in different sizes) vero board (its like a breadboard to solder)

You could even use Fritzing to design the most efficient layout for this option in regards to space/material saving or minimum solder points


how to make led fade on and blink while wav file plays To clarify I'm extremely new to this and I'm using an Arduino Uno with a wave shield. My circuit works as intended but I haven't learned enough of the code to know what to do to make it do exactly what I want.

Right now the following code makes the sound play on button press but the led sequence doesn't at all. If I move root.rewind(); play(root); to after the last digitalWrite then the led sequence runs but the audio doesn't play until the led sequence ends. I'm out to make the audio play while the led sequence runs. Any suggestions?

if (state == 1) {
    root.rewind();
    play(root);
    for (i = 0; i < 255; i++) { // loop from 0 to 254 (fade in)
        analogWrite(LED,i);     // set the LED brightness
        delay(15);              // wait 15ms because analogWrite
                                // is instantaneous and we would
                                // not see any change
    }
    analogWrite(LED, HIGH);     // turns the LED on
    delay(300);                 // waits for a second
    analogWrite(LED, LOW);      // turns the LED off
    delay(100);                 // waits for a second
    analogWrite(LED, HIGH);     // turns the LED on
    delay(300);                 // waits for a second
    analogWrite(LED, LOW);      // turns the LED off
    delay(100);                 // waits for a second

    digitalWrite(RESET, LOW);
}

As this can not be your entire sketch we can only guess that you are using some sort of SDCard music playing Arduino shield and library.

An application can not call the delay() function if the application is trying to accomplish more than one task.  Calls to delay() block the processor from doing anything other than waiting for the delay to time out.

In order to (appear to) do multiple tasks, run a loop with no calls to the delay() function.  Instead call the millis() function checking if enough time has elapsed to call the LED function or the sound function.  In neither function should you call the delay() function!  If you did not write the function (for example you are using a library) you may need to edit the code in the library to ensure it is following the no-calls-to-delay()-function rule!

In general terms, this is referred to as a state machine.  In this case, the state machine is driven by the amount of elapsed time as reported by the call to the millis() function.


Making HTTPS requests using ESP8266 AT commands I am trying to make HTTPS GET/POST requests to the following server using AT commands.
AT+CIPSTART="TCP","54.166.71.140 ",443

I get errors when i use port 443 but on port 80 the requests are successful.
How can i get around this issue ? what could be potential solutions ?

HTTPS requires that you make an SSL connection not a TCP connection.  To do that you need to use
AT+CIPSTART="SSL","54.166.71.140 ",443

You also need to configure SSL itself.
However the SSL support is not great and struggles with some sites (no SNI support by all accounts).
So you're better off programming the ESP8266 directly with your own sketch to make any HTTPS requests and process the data for you.


Nodemcu ESP12-E (ESP8266), Can I reprogramming when the UART pins are defined as GPIO? I wonder if there may be any problems using the pins that the UART are using as GPIOs, if now I want to be able to reprogram the circuit?
(Of course I will detach the ESP12-E from the mainboard before so)

Sure, you can use the UART pins as general purpose IO pins - however, it's far from ideal - for one simple reason:

The ROM issues messages on the UART at boot time.

This means that when you power the chip up whatever is connected to the UART TX pin will receive pulses of HIGH and LOW.

That may or may not be a problem, depending on what is connected. It's something you need to bear in mind though.


Ignoring the first high output from the sensor If the vibration sensor with Arduino detects two high inputs within 1 minute, I want the led to flash in one second.
My ability to write Arduino code is very low; I tried with millis() but I couldn't.
I want it to ignore the first high entrance.
Thank you for all the information you will give.
const byte sensor = 7;
const byte LED = 13;
unsigned long sensorMillis;
unsigned long ledTurnedOnAt;
unsigned long high_1 = 60000UL;
bool ledState = false;

void setup() {
  pinMode(sensor, INPUT);
  pinMode(13, OUTPUT);
}

void loop() {
  unsigned long currentMillis = millis();

  if (digitalRead(sensor) == HIGH) {
    sensorMillis = currentMillis;
    ledstate = true;
  }

  if (ledstate == HIGH) && ((unsigned long)(currentMillis - ledTurnedOnAt) <= high_1) {
    digitalWrite(8, HIGH);
    delay (1000);
    digitalWrite(8, LOW);
  }

  ledstate = false;
}

One simple solution could be:
Start by noticing the first time you get the HIGH input whit a simple if statement:
if (digitalRead(sensor) == HIGH) {
}

where sensor is the pin of the sensor according to your code.
When this statement is True, you are interested in remain here until one of two things happens:

either you interrupt some kind of loop with another HIGH input,
or the time you have set is passed.

One way of knowing elapsed times will be with the millis() function, that returns the milliseconds since the board began running.
We should get the elapsed time the first time we enter the loop:
if (digitalRead(sensor) == HIGH) {
  long startTime = millis();
}

Then, as I have said, we need to remain here for a specific amount of time. We could use the while loop, but, which condition needs to be true?
So we have a start time, lets said x and you need to stay in the loop for, let's say, y milliseconds. This is the same as saying that you want to stay in the loop until the time we enter the loop and a specific amount of milliseconds, x+y. When the millis() function gives us a greater number, we should exit the loop:
if (digitalRead(sensor) == HIGH) {
  long startTime = millis();
  while (millis() <= (startTime+1000))
//                              ^ The second you are interested, 1000 milliseconds.
}

Now, we have to check if there is another interrupt during this time, by using the same statement of the beginning:
if (digitalRead(sensor) == HIGH) {
  long startTime = millis();
  while (millis() <= (startTime+1000)) {
    if (digitalRead(sensor) == HIGH) {
      // 2 interrupts in less than 1000 millis!
    }
  }
}

Summarizing is nicer to declare a global with the specific time we want, instead of the 1000 value we are using now:
const long maxTimeInterval = 1000;

And changing it in our code (that is inside the loop())
if (digitalRead(sensor) == HIGH) {
  long startTime = millis();
  while (millis() <= (startTime+maxTimeInterval)) {
    if (digitalRead(sensor) == HIGH) {
      // 2 interrupts in less than 1000 millis!
      digitalWrite(LED, HIGH);
    }
  }
}

Hope this helps!


I had this same problem when I began experimenting with soil moisture readings. I noticed that the readings from the sensor can vary widely when not hooked up correctly, or when other nearby objects are somehow interfering.

For instance when I put a SparkFun breakout similar to yours in dry soil and continuously take readings every 50ms, the signal oscillates from 0 to 50, and simply touching the soil with my finger can affect the signal due to the electricity in my body. If you have a metal pot on a metal table, that could be affecting your readings. There's a lot to consider!

However, once I water the soil and let it soak in, the reading generally becomes much more stable. Below I included a real-time plot using a plant I watered about 24 hours ago. Here's how I set up my soil moisture sensor, including code. The readings are taken every 60s and the plotter repeats the old reading until a new one is taken. There's very little deviation when all connections are secure and the soil moisture is evenly distributed.

In general, the specs for the sensor will inform you on what kind of signal to expect. Based on your sample data I suspect yours is a 10-bit signal from 0-1023, so 800 range means the soil is quite moist. If you just watered the plant, then the water content around the sensor will change as it seeps through the soil, leading to fluctuations when measuring. Give the soil a few hours to absorb the moisture and try measuring again.


Atmel studio 7 vs Arduino IDE for register level coding? Which one is better to get started with register level embedded c coding?
Also which one is used professionally?

I actually wouldn’t recommend either for professionally developing for Atmel chips. Although Atmel Studio is a nice enough IDE (the simulator is amazing!), it does make it very difficult to unit test your code or to set up a build server. I would personally recommend you set up a Make (or possibly CMake) based setup directly on top of the avr-gcc tool chain and then simply use the text editor of your choice.

As for learning about programming against raw registers, I have to recommend Atmel Studio and one of their XPlained evaluation boards. Atmel Studio includes a simulator that actually shows you, bit by bit, the current state of the registers.


Arduino vs 12bit ADC 12bit ADC will give us about 1.2mV per step:

5 / 4096 = 0.00122

But if we give Arduino a 1.2V voltage reference we get 1.1mV per step:

1.2 / 1024 = 0.00117

Does that means Arduino can be more accurate than a 12 bit ADC?

In a word, no.

The Arduino uses a rather crude 10-bit ADC. If you feed it a small voltage reference, you can divide that small voltage into 1024 steps. (as you say, about 1.1mV/step)

If you feed the same small 1.2V reference voltage into a 12-bit ADC, you'll get 4 times as many steps for the same range. (about 293μV/step)

And, as mentioned before, the ADC's in Arduinos are not very good. They're slow, and not very accurate.

(To be technical, precision is how exactly you DESCRIBE your answer. A decimal reading using more decimal places is more precise than a reading with less decimal places. Accuracy is how close the measured value is to the actual value. If you're sloppy with your measurements but use lots of decimal places to write it down, and the answer is very far off, you have a precise but inaccurate answer. (e.g you measure something as 1.0000001 millimeters, but it's really 2.5 mm.

A 12-bit ADC is more precise than a 10-bit ADC, but it may or may not be more accurate. Given the crude nature of the ADCs in Arduinos, a dedicated 12-bit ADC is likely to be more accurate than built-in one.)


Capturing avrdude command in IDE With verbose upload selected the IDE provides the executed avrdude command at the top of the log.

I am interested in copy pasting that avrdude command. However at the end of the upload the command is not available anymore. The IDE only shows some last lines of the log and discard the top part.

Is that log saved anywhere? (I am on ubuntu). Any ideas how I can get that command?

If you run the IDE from a terminal you should get the output to STDOUT in your terminal to do with what you want.


Storing byte array from serial and converting to a floating point number I have tried getting my Arduino to communicate with another device, to no avail. The command A, when sent via serial to the device, triggers it to respond with 8 binary bytes with the first 4 representing a floating point number, and the final 4 representing a floating point number. The command only has to be sent once a second, and the aim is to store the 8 incoming bytes in an array, and convert them into their respective floats.

unsigned long previousMillis = 0;
const long interval = 1000;
char incomingByteA[8];

void setup() {
  Serial.begin(9600);
  while(!Serial);
  Serial1.begin(9600);
  while(!Serial1);
}

void loop() {
  unsigned long currentMillis = millis();
  if(currentMillis - previousMillis >= interval){
    //1 second timer
    previousMillis = currentMillis;
    Serial1.write('O');
    //Send command 'A' to device *noting Serial1 not Serial
    for(int n = 0; Serial1.available() < 8; n++) {
    incomingByteA[n] = Serial1.read();
    //Add each consecutive byte to an array until all 8 bytes have been added
  }
  float x;
  float y;
  ((byte*)&x)[3] = incomingByteA[0];
  //Convert first four bytes into a float
  ((byte*)&x)[2] = incomingByteA[1];
  ((byte*)&x)[1] = incomingByteA[2];
  ((byte*)&x)[0] = incomingByteA[3];
  ((byte*)&y)[3] = incomingByteA[4];
  //Convert final four bytes into a float
  ((byte*)&y)[2] = incomingByteA[5];
  ((byte*)&y)[1] = incomingByteA[6];
  ((byte*)&y)[0] = incomingByteA[7];
  Serial.println(x, 4);
}
}

However, when I do Serial.println(x);, it returns "nan". And if I try to do Serial.println(incomingByteA[2]);, it returns "?".

The following is the floating point format as per the device protocol:

31: sign of mantissa, 1=negative.
30-23: exponent, biased by 128.
22-0: mantissa, 24 bits, MSB hidden and always=1.

The mantissa is normalized, 24 bits with the MSB hidden. The MSB is always
assumed to be 1, therefore only 23 bits are needed to store the mantissa. The exponent is biased by 128; i.e. a 128 value represents an exponent of zero. A 129 value is an exponent of 1. Example: if the exponent has a 131 value (+3), the number is 2^3 * (mantissa). The mantissa is always less than one, and greater than or equal to 1/2. The number zero is stored as four zero bytes.

I am confident that it is not a fault with the hardware and for what it's worth, I am using a Leonardo. I would like to get the code down pat before I stress about hardware issues. What is this code not doing properly, if at all?

Thanks in advance.

Two things I see wrong:

  Serial1.write('O');                                            //Send command 'A' to device *noting Serial1 not Serial

No, you send O not A... ???

  for(int n = 0; Serial1.available() < 8; n++)

While there are less than 8 bytes available in the buffer read one.

Erm...  The buffer starts off empty - empty is less than 8. It remains empty (always less than 8) until a byte finally arrives. Then it's still less than 8. I can't really see this ever working, and your array will overflow instantly and clobber the entirety of the rest of your RAM. I guess it finally finished when the serial object itself gets clobbered and available() returns some garbage number. In the meantime your array is just full of nothingness.

You need to completely rewrite that whole section. The simplest way is to wait until there are 8 bytes in the buffer (which will take some time - serial is slooooow):

while (Serial1.available() < 8);

You now have 8 bytes available to read, so you can go ahead and read them.

A better way is to look to see if there is at least one byte available, then read it into the right place in your array - and keep count of how many bytes you have read:

int n = 0;
while (n < 8) {
    if (Serial1.available()) {
        incomingByteA[n++] = Serial1.read();
    }
}

Of course, it's better to add some form of timeout in there too - so if nothing arrives soon enough your program doesn't lock up - or if you miss a byte it doesn't get completely out of sync. Also purging your read buffer before sending the command can help to prevent sync issues:

// Purge any old data
while (Serial1.available()) {
    Serial1.read();
}

Serial1.write('A');

int n = 0;
uint32_t start = millis();
while (n < 8) {
    // 1 second timeout
    if (millis() - start > 1000) {
        break;
    }
    if (Serial1.available()) {
        incomingByteA[n++] = Serial1.read();
    }
}

if (n == 8) {
    // We got the data - do something with it
} else {
    // It timed out
}

Now when it comes to converting to a pair of floats there's better ways than your byte-wise manipulation.  For instance, you could use a union:

union FloatPair {
    struct {
        float a;
        float b;
    };
    char bytes[8];
} __attribute__((packed));

FloatPair data;

Now you can use:

data.bytes[n]

to access the memory directly, and

data.a;
data.b;

to access the float values.

You can also do something similar with casting:

struct FloatPair {
    float a;
    float b;
};

FloatPair data;

char *bytes = (char *)&data;

bytes is now a byte-wise view of the memory used by a pair of floats.

You can even work the other way around:

char data[8] __attribute__((aligned(4)));

The aligned attribute will force the address of the array to be on a 4-byte boundary. Not important for a little 8-bitter, but vital if you ever port to a 32-bit MCU since a float always has to be on a 4-byte boundary, so a good habit to get into.

Now you can map floats into that memory space:

float *a = (float *)(&data[0]);
float *b = (float *)(&data[4]);

and access the floats as *a and *b. The * dereferences the pointers back into real numbers.

One thing to note: these methods all depend on the endianness of your data matching the endianness of your MCU - if they differ then you will have no choice but to do it all with manual byte-wise mapping.


L298N beeps and malfunctions when receiving certain analogWrite values I created a simple circuit with an UNO, L298N and a single motor.
Wrote the following code to test controlling the speed of the motor.
Tested motor with digitalWrite() function and it works fine.
Tested motor with analogWrite() function and from 255 down to around 70 motor works at various speeds.

Q: But from around 70 and below, the L298N starts to beep and the motor stop spinning. Any thoughts?

int enr = 9;
int inr1 = 8;
int inr2 = 7;

void setup() {
 pinMode(enr, OUTPUT);
 pinMode(inr1, OUTPUT);
 pinMode(inr2, OUTPUT);
}

void loop() {
  analogWrite(enr, 71);
  digitalWrite(inr1, HIGH);
  digitalWrite(inr2, LOW);
}

Ok, here is my theory what's happening:

Every motor has an amount of friction at his rotor. You need to pass enough energy to overcome this friction, or the motor will not move. When you use analogWrite(enr, 71) or lower, you pass only a small amount of energy to the motor, so that it cannot overcome the friction.

Now you have to understand, what analogWrite() really does. It does not output an analog voltage. Instead it generates a PWM signal. The voltage changes between HIGH and LOW level (5V and 0V in case of the Uno) at a specific frequency. The relation between HIGH time and LOW time is called duty cycle. That is, what's controlling the motor speed. So instead of supplying different voltages, we turn the motor on and off very fast. Since the rotor has a relatively big inertia (because of it's mass), it cannot react fast enough to follow these pulses. We only give it small pushes very fast. Instead it integrates over all the pulses. If the duty cycle is low (more LOW than HIGH time) only a small amount of energy is passed to the motor.

So, what is the motor doing, when it's got not enough energy to overcome the friction? It will still get little pushes very fast, but cannot actually spin. Instead the passed energy will induce vibrations in the motor, which have the frequency of the PWM signal. These vibrations can then be heard as a continuous beep.

If enough energy is passed to overcome the friction, the rotor spins correctly and does not vibrate, thus you cannot hear a beep.

What to do now:

The described principle applies to every motor, so cannot do much about that. You can simply go the easy way and not drive the motor with such low duty cycles. Another cause might be, that your motor likes to get a higher current to give it's full power. The L298N is quite inefficient, so you could change that to a H-bridge driver, that uses MOSFETs instead of bipolar transistors. Also maybe you can increase the voltage, that you use to drive the motor (depending on the not specified motor).

You didn't describe, how you have connected everything, so 2 other points: You cannot drive a motor from a digital pins power (since a digital output pin can only provide 40mA at max, 20mA recommended) and you should also not power a motor through the Arduino, since you might fry the voltage regulator or the protection diode. You can get away with that, when using small motors without any load, but that doesn't scale well. You should always connect the motor circuit directly with the power supply, so that the motors current does not have to flow through the Arduino.


Arduino and RF24 library: communication stops after short amount of time I am using two Arduino Unos, NRF24L01+ transceivers, and a few components as per this site on which I am following the second tutorial on this page: Arduino Wireless Communication – NRF24L01 Tutorial.

I am using the exact code from the page as well - and have set everything up as per the diagrams, however everything stops working after a short amount of time. Usually between 15 and 30 seconds, everything stays powered but it seems like the transceivers stop communicating. A reset of the Transmitting board (the one with the potentiometer) will fix the problem until it again stops 15 or 30 seconds later.

Any idea what might be going on?

Your question does not provide much information to go on.  Setting up as given in the tutorial is a good start, but does not guarantee that there will be no problems.  It can still either be a problem due to hardware or firmware.

Firmware problems:

The radio data may be getting corrupted after some time, which shows up as a failed radio transaction
You inadvertently change the register settings of the radio

Hardware problems:

There is noise interference on the radio channel you are using due to the urban environment (wifi, etc).  Does the system work any better on a different channel?
The radio drains too much power and browns out, then will revert to default settings on the IC rather than the ones set by your Arduino sketch.


What is exactly MQ-2 sensor? What does the MQ-2 sensor detect?

I know it detects concentrations of flammable gas. But does it detect smoke from fires too?
What about smoke from cigarettes, and other things?

Simple answer is no.

There are about 10 similar sensors, each detect specific kind of chemicals


What can I do if I run out of Flash memory or SRAM? According to the Arduino documentation, the ATmega328 has 32KB of Flash memory for the bootloader + uploaded sketch, and only 2KB SRAM for runtime data. The ATmega2560 has quite a bit more, totalling 256KB and 8KB respectively.

In either case, those limits seem rather small, especially when compared to similarly sized consumer devices, such as smartphones.

What can you do if you run out? E.g. if your sketch is too big, or you need to process a lot of data (such as strings) at runtime? Is there any way to expand the Flash or SRAM?

Optimisation
Low-level programming for embedded systems is quite different from programming for general purpose devices, such as computers and cell phones. Efficiency (in terms of speed and space) is far more important because resources are at a premium. That means the very first thing to do if you run out of space is to look at what parts of your code you can optimise.

In terms of reducing program space (Flash) usage, the code size can be quite difficult to optimise if you're inexperienced, or if you're more used to programming for desktop computers which don't tend to need that skill. Unfortunately, there's no 'magic bullet' approach which will work for all situations, although it helps if you consider seriously what your sketch really needs to have. If a feature isn't needed, take it out.

Sometimes it's also helpful to identify where multiple parts of your code are the same (or very similar). You may be able to condense them into reusable functions which can be called from multiple places. However, be aware that sometimes trying to make code too reusable actually ends up making it more verbose. It's a tricky balance to strike that tends to come with practice. Spending some time looking at how code changes affect the compiler output can help.

Runtime data (SRAM) optimisation tends to be a bit easier when you're used to it. A very common pitfall for beginner programmers is using too much global data. Anything declared at global scope will exist for the entire lifetime of the sketch, and that isn't always necessary. If a variable is only used inside one function, and it doesn't need to persist between calls, then make it a local variable. If a value needs to be shared between functions, consider if you can pass it as a parameter instead of making it global. That way you'll only use SRAM for those variables when you actually need it.

Another killer for SRAM usage is text processing (e.g. using the String class). Generally speaking, you should avoid doing String operations if possible. They are massive memory hogs. For example, if you're outputting lots of text to serial, use multiple calls to Serial.print() instead of using string concatenation. Also try to reduce the number of string literals in your code if possible.

Avoid recursion if possible as well. Each time a recursive call is made, it takes the stack a level deeper. Refactor your recursive functions to be iterative instead.

Use EEPROM
EEPROM is used for long-term storage of things that only change occasionally. If you need to use large lists or look-up tables of fixed data, then consider storing it in EEPROM in advance, and only pulling out what you need when necessary.

Obviously EEPROM is quite limited in size and speed though, and has a limited number of write cycles. It's not a great solution to data limitations, but it might be enough to ease the burden on Flash or SRAM. It's also quite possible to interface with similar external storage, such as an SD card.

Expansion
If you've exhausted all other options, then expansion may be a possibility. Unfortunately, expanding Flash memory to increase program space isn't possible. However, it is possible to expand SRAM. This means you may be able to refactor your sketch to reduce code size at the expense of increasing data size.

Getting more SRAM is actually fairly straightforward. One option is to use one or more 23K256 chips. They are accessed via SPI, and there is the SpiRAM library to help you use them. Just beware that they operate at 3.3V not 5V!

If you're using the Mega, you could alternatively get SRAM expansion shields from Lagrangian Point or Rugged Circuits.


SN76489 - Ready pin not working? I'm testing the SN76489AN chip with Arduino and I'm able to play the 3 tones I want etc BUT I don't understand why the READY pin is not working? The datasheet says the pin goes high when the chip is ready and low when it's busy with processing a command. But the READY pin is always low! I've got 2 brand new pieces of the chip and they both act this way. I've even tried to pull-up this pin but it didn't help. I see everyone is just using delayMicroseconds in their examples, so I guess it is a common problem but it's just strange... Is it a bug in the chip or what? Does anyone know?

Thanks!

The READY signal is open-collector. It will therefore require a pullup-resistor. Test circuit in datasheet shows a 2 kohm resistor. You could try with that. Alternatively use the internal pullup resistor on the input pin but this may be too large (weak).

Cheers!


What is the best way to make a good but simple line follower? I am new in this site, and like you can see I want to do a line follower, not a clumsy and slow line follower, but a fast and "fancy".
I investigated about the PID method, but can someone explain me in simple words what is it.
Thanks for your answers.

Did you check wikipedia, for example?

I doubt it is possible to describe a PID controller in simpler words than those used by the article.

The pseudocode is quite simple and should be also very good for understanding the concept, when applied to a digital system.

See also the limitations of PID controllers.


Arduino play many piezo at once I need to play sound on 10 piezos at once. How to do that without delay() function.

Use the Timer library.

You can attach up to 10 events to each Timer object you declare. That will suit your use case.


VC0706 card failed, or not present I'm trying to follow this tutorial here:

https://learn.adafruit.com/ttl-serial-camera/using-the-camera

Here's what my serial log is printing-- I've added a few commands for logging:

Arduino version is: 10605
Chip Select is: 4
VC0706 Camera snapshot test
Card failed, or not present

I know my SD card works because when I use this program: https://www.arduino.cc/en/Tutorial/ReadWrite

it works just fine. What am I messing up?

I'm using an arduino uno with wifi shield.

Thanks!

Comparing and contrasting with the SD card file -- I've found that if you comment out the following -- it works. Maybe this will help someone.

//#if !defined(SOFTWARE_SPI)
//#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
//  if(chipSelect != 53) pinMode(53, OUTPUT); // SS on Mega
//#else
//  if(chipSelect != 10) pinMode(10, OUTPUT); // SS on Uno, etc.
//#endif
//#endif


A question about chars and Serial I have the following code:

int count = 0;
char serial_char;
char serial_message[96];

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

void loop(){
  while(Serial.available() > 0){

    serial_char = Serial.read();
    if (serial_char == '\n' || serial_char == '\r'){

      serial_message[count] = 0; // <<-- What does this line do?
      count = 0;
      Serial.println(serial_message);

    }
    else{
      serial_message[count++] = serial_char;
    }

  }

}

With this code, I can type a message into the serial monitor, and it will print the message back at me. So if I type 'Goodbye', it returns:

Goodbye

If I send it another message 'Word', it returns:

Word

However, my questions is when I comment out the line:

serial_message[count] = 0;

And then I repeat the same sequence of actions before, 'Goodbye' returns 'Goodbye', but when next I enter 'Word', it returns:

Wordbye

Could anyone explain this to me? I am really curious to know why this occurs. What does adding that 0 in the char array accomplish? Thank you.

The zero-value, the "null character", indicates the end of the string. For strings, you allocate some maximum space, in your case 96 bytes:

char serial_message[96];

When storing variable-length strings in that, you need to indicate where the string ends. That's what the zero value does in a null-terminated string. (Note that 0 is really binary 0x00 here; it's not the ASCII character 48, 0x30.) So, the 96 bytes allow for a string of at most 95 characters, followed by the terminator. When printing, it prints the memory contents until it finds that null character.


What is the point of a adafruit data logger In order to play an audio file, I was suggested to get an Adafruit data logger, yet right now I am stuck with the project and I realized that I'm not using the data logger to its full potential.

Yet I am unable to comprehend the purpose of a data logger ; all I'm using it for is to read SD Cards, and I can do that with a SD Card reader. I did read the whole documentation, data sheet, etc, and I can see that it has some cool functions, but my question is still, why data logger?

I know this  might be a stupid question, but I genuinely don't get what the data logger is supposed to be a huge help of. Please help me.

Are you referring to this?

That is a shield that has an SD card interface (with appropriate level-shifting for the SD card) plus a real-time clock.

The rest is "prototyping" area for you to install your own devices.

  In order to play an audio file, I was suggested to get an Adafruit data logger

I don't see how this helps play audio files, however you might read the audio file from the SD card. Then you need to send it to a DAC (digital-to-analog converter) to convert the digital information to analogue.

The Adafruit data logger is fine for recording data (for example, temperatures) but I don't see why someone would recommend it for playing audio files (apart from the SD card interface).

  my question is still, why data logger?

Better ask the person that recommended it, eh?


Why are MOSFETs only giving 8.1V for LEDs, not 12V? I'm using three PWM outputs from an Arduino Mini Pro to drive the R/G/B parts of some strips of LEDs. The circuit is basically this:

I've got a single 12V power supply, rated at 200W, to light the LEDs and to power the Arduino via the RAW pin, and there are 5 metres of 60LEDs/m RGB LEDs, i.e. a total of 300 LEDs, which should be drawing ~72W according to the spec sheet (14.4W/m).

The problem is that even when the sketch says digitalWrite(9, 255); digitalWrite(10, 255); digitalWrite(11,255), the LEDs are considerably dimmer than when connected directly to the 12V supply. My cheap, digital volt meter measures ~8.1V between GND and the PWM pins across the LEDs, not the 12V that the transformer is supplying.

Am I doing something wrong? Does the MOSFET really cause such a large drop in voltage? Is there anything I can do to mitigate it? (It's important to get as much brightness as possible from the LEDs for this project).

By my calculations you are sinking 6 amps:

72 W / 12 V = 6 A

I have some doubt that the Arduino board is designed to handle that amount of current through its ground plane. Try running a separate ground wire to the MOSFET sources.

I would also be concerned about the gauge of wire you are using, and whether the prototyping board can handle that amount of current.


Having Arduino read a video game screen I want to connect my Arduino to my tv screen while playing a playstation/XBox game. When a certain screen comes up (like say when you die the same screen pops up) then I want Arduino to catch that and then trigger another device on and off. How might I be able to trigger something by having arduino read the screen then trigger something on and off?

Most Arduino platforms contain a very low power embedded processor.  As such it is very unlikely such a device will decode an NTSC or PAL signal let alone modern digitally compressed video.

Instead consider using a light sensor attached to your monitor.  This is more in line with what, for instance, the Arduino Uno is capable of.  If you can identify a spot on the monitor that will only change to a certain brightness at the conclusion of a game, you could look for that brightness level using a light sensor attached to the monitor and connected to an Arduino.

Here is a tutorial about using a light sensor with an Arduino.  Most of the circuit is for the display of which you need not bother with.


Multiple LEDs & HC-SR04 I want to use a distance sensor like the HC-SR04 to power a stop light like parking sensor for my garage. I have seen a lot of tutorials on how to use the HC-SR04 to power a single LED and found the schematic below on how to control up to 14 LEDs by hooking them onto the 5v and using a transistor. I have added a box where I would hook the sensor in. My question is, would it work if I had the sensor hooked into the 5v as well. The plan is to have 3 sets of 14 LEDs and have one set on at any given time. I plan on using an Arduino Uno.

If I am understanding correctly, you have 3 LEDs ... call them A, B and C (the fact that they are a group of 14 LEDs is a red herring).  As a function of the distance measured, you want ONE of LED A, B or C lit.

Since you are using an Arduino, you have GPIO pins.  Connect a different GPIO to each of A, B and C.   You can then write an application that senses the distance (as measured by the HC-SR04) and depending on the distance returned, have a set of  "if" statements which will choose which of the GPIOs to set HIGH and the others LOW.  The GPIO set HIGH will switch on the corresponding LED.

In fact, its going to look a lot like this Instructable:

http://www.instructables.com/id/Simple-Arduino-and-HC-SR04-Example/


Why can I measure two pins simultaneously? I would like to do an action if both buttons on my arduino pro micro are depressed simultaneously. I'm getting some strange results:

// Buttons
Bounce button0 = Bounce();
Bounce button1 = Bounce();

void setup() {
  Serial.begin(115200);
  while (!Serial) {
    ;
  }

  pinMode(2, INPUT_PULLUP);
  button0.attach(2);
  button1.interval(1);

  pinMode(3, INPUT_PULLUP);
  button1.attach(3);
  button1.interval(1);

  Serial.println("Setup Complete");
}

void loop() {
  button0.update();
  button1.update();

  if (button0.fell()){
     Serial.println("button0 fell");
  } else if (button0.rose()) {
    Serial.println("button0 rose");
  }

  if (button1.fell()){
     Serial.println("button1 fell");
  } else if (button1.rose()) {
    Serial.println("button1 rose");
  }

  if (button0.fell() & button1.fell()){
    Serial.println("buttons fell");
  } else if (button0.rose() && button1.rose()) {
    Serial.println("buttons rose");
  }
}

Here is the output to the Serial console:

Setup Complete
button0 fell
button1 fell
button0 rose
button1 rose

Why isn't this branch being executed? button0.fell() & button1.fell() For the life of me I cannot figure this out. Thank you!

EDIT

This doesn't work either, which is crazy:

void loop() {
  button0.update();
  button1.update();

  if (button0.fell()) {
    if (button1.fell()) {
      Serial.println("buttons fell");
    }
  }

  if (button0.rose()) {
    if (button1.rose()) {
      Serial.println("buttons rose");
    }
  }
}

EDIT

Thank you for the answers! Unless the person was to push both buttons in the exact same iteration of the loop, my code would never work. Here is what I ended up using:

if ((button0.fell() && !button1.read()) || (button1.fell() && !button0.read())) {

You can test it easily by calling the function twice directly after each other. If the first time a true is returned and the second time a false, the state is internally reset.

But probably because after you call the fell function, the internal state is reset, so after the call not a new fell has been happened.

So store the return value of the fell and rose functions and use those instead.

Update:

I'm not sure if this is the actual implementation but I found for fell/rose and see this:

bool Bounce::rose()
{
    return ( state & _BV(DEBOUNCED_STATE) ) && ( state & _BV(STATE_CHANGED));
}

bool Bounce::fell()
{
    return !( state & _BV(DEBOUNCED_STATE) ) && ( state & _BV(STATE_CHANGED));
}

So as long as the state has not changed it returns false (which is similar/equal as 'resetting the internal state'. Except this reset is done at a different location (but checked in the fell and rose function).

Update:

See remarks from gre_gor below


Digispark ATtiny 85 erases flash after power loss I have some issues with my Digispark ATtiny85 board.
If I upload the blink sketch for example the LED starts blinking and everything looks fine. But as soon as I unplug the Digispark from the USB port and plug it back in nothing happens. I know that the programm starts with a delay of 5 seconds so programming via USB becomes possible, but still nothing. Its seems like the flash-memory (where the programm is stored) of the ATtiny 85 is empty.

Here is the example blink sketch:

// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(0, OUTPUT); //LED on Model B
  pinMode(1, OUTPUT); //LED on Model A
}

// the loop routine runs over and over again forever:
void loop() {
  digitalWrite(0, HIGH);   // turn the LED on (HIGH is the voltage level)
  digitalWrite(1, HIGH);
  delay(1000);               // wait for a second
  digitalWrite(0, LOW);    // turn the LED off by making the voltage LOW
  digitalWrite(1, LOW);
  delay(1000);               // wait for a second
}

I also tried uploading the sketch from a Laptop running on Windows but without success.

I am using Linux Mint and Arduino IDE 1.8.10.

Since I am new to Microcontrollers, I would be grateful for explainations, tipps or useful links.
Thank you!

I got the same issue, on two boards. Will probably try to burn the bootloader using usbasp, maybe they burned the wrong one back in china.

EDIT:

As expected flashing the micronucleus bootloader using USBasp solved the problem on both of the boards. I've used burn-o-mat as the arduino was not seeing my programmer.

Just download the firmware from github (I've used this: https://github.com/f4goh/micronucleus/archive/master.zip )

and connect like so (here the guy is using arduino uno, doesn't matter): https://hamprojects.wordpress.com/2018/12/27/digispark-microcontrollers-implementation/


arduino due-Python interfacing for high speed data rate Four our project, I want to send data mesured by an Arduino due to a computer via Pyton very vast. So I tried to make a simple benchmark by sending 10240 int datas to determine the time it take. In order to do this, I first try using the programming port and execute this simple script:

int i=1;
int maxv=10240;
int value[10240];
int deb, fin;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(250000); //serial initialisation
  for (i=0 ; i<maxv ; i++){
    value[i]=i;
  }
  delay(200);
}

void loop() {
  // put your main code here, to run repeatedly:
  Serial.println("starti"); //flag
  deb=micros();
  for (i=0 ; i<maxv ; i++) { // sending loop
      Serial.println(value[i]);
  }
  fin=micros();
  Serial.println("stopi");
  Serial.println((fin-deb)/1000000.0);
  delay(2000); //waiting
}

So with this I can mesure the time it take to send all the datas. And I receive it with this Python's script:

import numpy as np
import serial
ser = serial.Serial('/dev/ttyACM0', 250000)

value=np.empty(10240)

temp=ser.readline()

while temp!='starti\r\n': #search for the flag
    temp=ser.readline()

for j in range(10240):
    value[j]=int(ser.readline())

ser.readline()

time=float(ser.readline())
print time

with this beaudrate, it take nearly 2.4s which too slow for my purpose. If  try another baudrate, 500000 for example I read data like this : �Ë$Pd@s`¥š... I have this for all baudrate higher than 250000.

So I tried the native port which normaly send the data as fast as he can, but we this it took nearly 1.3s, and it's again too slow for my purpose.

I checked that it is not python wich is too slow, by doing the same than in the last example:

import time
import numpy as np

value=np.empty(10240)

deb1 = time.clock()

for j in range(10240):
    value[j]=j

fin1= time.clock()
print fin1-deb1

and it took only 4ms. So is it clearly the arduino wich send the data to slowly.

So how can I increase the data flux? I have seen the serial.write(buf,len) function which seems does not convert the data into ascii caracters. Does this function will be faster by putting the correct arguments? And, if it's the cas, how can I read this with Python?

There's two things you need to know:

The Serial.write(buf, len) function sends the raw data - one byte for every "len" count.
On the Due integers are 32-bits, so each one takes 4 bytes.

So first you need to define how big the numbers are you'll be dealing with and use data types that are big enough without being wasteful - you have 3 choices: char, short and int - 8, 16 and 32 bits respectively.

Values between 0 and 255 use an unsigned char (uint8_t)
Values between -128 and 127 use a signed char (int8_t)
Values between 0 and 65535 use an unsigned short (uint16_t)
Values between -32768 and 32767 use a signed short (int16_t)
Values between 0 and 4,294,967,295 use an unsigned int (uint32_t)
Values between −2,147,483,648 and 2,147,483,647 a signed int (int32_t)

One very tricky thing with this kind of binary data transfer is knowing where a value starts and ends.  You don't get that kind of issue with ASCII representations as you have a line feed and/or a carriage return after each full value and the range of valid characters that make up a value is very narrow and can never contain the delimiting character.  You don't have that luxury with binary transfers as there is no byte value that can't appear in a data stream.  However, there could be byte sequences that could never appear in the data stream - numbers you know you'll never be using that could form part of a synchronizing header (say, in hexadecimal, 0xFF 0xFF 0xFF 0xFF 0x00 0x00 0x00 0x00 - or in signed shorts that would be a sequence of 65535 65535 0 0) - once you see that sequence of bytes you know you're lined up with your data stream and can receive it byte by byte and build up the right sized values from that.

You can estimate your transfer time by working with the baud rate and knowing the data size.  For instance, to transfer 1000 short (16 bit) values at 250000 baud should take around:

1000 * 2 = 2000 bytes
250000 baud = 25000 bytes per second (8 bits for the byte, 2 bits for the start and stop bit)
2000 / 25000 = 0.08s


ATtiny167 Device not recognized I'm frustrated I feel like I am 90% there but my computer will not recognize the ATtiny167. Here i9s the list of things I have completed/tried using Windows 10 and Arduino 1.8.6;

                  1) Installed Driver USB Bootloader is complete
                  2) Device Management I see the device
                  3) Arduino Sketch select 16.5 MHz board in parameters
                  4) Led on the board flashes sound beeps and stops flashing
                  5) "Device not recognized"
                  6) I have rebooted many times. I deleted everything and started over again with same
                      results
                  7) Used a 3rd party software to look at my USB ports it see the device
                   I have tried more than one device as well

         I'm stuck at this point. I've tried running example programs however the device is not recognized.

Any suggestions?

If Digispark Pro clone is not recognized, you can try to use/upload .ino programs via ArduinoISP.

note use in File -> Preferences -> Additional Boards Manager URLs:
http://drazzy.com/package_drazzy.com_index.json
instead:
http://digistump.com/package_digistump_index.json

(The first is AttinyCore by Spence Konde, the second is the normal Digistump AVR Boards)

Then selected Tools -> Boards Manager, and Find AttinyCore -> (Wait and Install).

Now you can upload File -> Example -> ArduinoISP on your Arduino connected in ISP mode with your ATtiny167.

Now select ATtiny167 Board, 16Mhz (External) and write bootloader with your Arduino connected in same manner ISP mode with your ATtiny167.

And now upload any .ino file for ATtiny167 in the same manner with your Arduino connected in ISP mode with your ATtiny167.


Increase IR transmitter directivity and range I am working on a project to control different devices with arduino and IR LED so I am testing with this circuit:

So, everything is working fine but I want to increase range of my transmitter. For now its barely giving response at 1 meter distance. I want to increase this to at least 5 meters. I tried to increase receiver sensitivity by giving 5V to TSOP, when I do this the range is satisfactory but the directivity is too much its even responding when I point IR LED in opposite direction(inside a room, maybe the radiaton is bouncing off walls - this is not happening with 3.3V). I Know the transmitter range can be increased by increasing the current flowing through LED like this (please correct me if I am wrong):
The problem is with directivity of emitter, I do not want all the devices in my room to turn on when I try to turn on my TV. The devices are placed  up to 1 meter apart and the transmitting range should be at least 5 meters.

Also it would be helpful if someone clarifies which part is actually sensitive (the part which looks like LED or the flat backside part - image below) for TSOP i.e. which part receives the pulses, so that I can cover it with tape (so that it receives signal from only one direction) if nothing else works.

Any help is appreciated, thank you.

The IR sensors are usually build that way, that they get signal from as wide range as possible, also using walls, ceiling etc. to reflect the signal to receiver - the bussiness logic is simple - user want press buttton and have TV reacting - no trying to hit some particular spot on TV wiht invisible light - it is not shooting game, it is meant as remote switch and if it works regardless actual direction, then the best. To select different devices the transmiter sends different codes - every device in room ideally gets the same input, just the TV "knows" it should react say to range 0xFF0000..0xFF00FF and the radio knows it should react to 0xFF1100..0xFF11FF instead (it is more conplicated and the ranges are not continuous and possibly ovelaps, but it is the principle).

So the best way to difference between your devices is using longer numbers and let the device react just to some selected (specific to that device) and ignore all others.

But if you insist on "shooting it directly to head", then the way is putting both the transmitter diode and the receiver to some kind of tubes (like bore of riffle), so the data could be only send to /get from some small cone of space and communication occures only when those cones are aligned. Anyway it would probabelly react on the reflection from the wall on your back (shooting cone opposite way) as then the cone will get way larger by distance (and so hit more receivers) and also from difraction from particles in the wall (so the wall would light to all directions, not just reflect the cone, as mirror would). And there is nearly nothing to prevent this. (Yes, you can cover the wall with some nonreflective black textile or so, but would you do it?)

As for active part of the receiver, the datasheet say the center of sensiteve area is in the centre of the "diode-like" part, with angle around 80 of sensitivity to both sides vercically and horisontally (with the best sensitivity vaguely straight forward) http://html.alldatasheet.com/html-pdf/26589/VISHAY/TSOP1738/1117/6/TSOP1738.html - but basically it can  somehow receive nearly from anywhere on the "diode-like" side.

The back side (flat one) should not be sensitive.

Also you can (and should) use resistor between the pin and transistor base, to limit current from the pin. (transistors have gain like 100 or more, so you need a little current to fully open it).

LEDs are current consumers, not voltage consumers, so you restrict current (not voltage) thru your LED to not burn it and to make it shine more or less. LEDS should use current sources (like providing 20mA, no more or less for normal LED), not voltage sources (which would provide something like 9V, 5V, 3.3V or any other value, no more or less).

But as there are much more easily obtained voltage sources, the resistors are use to limit current thru the LEDs as easy "cheat".

You take the voltage of source (say 9V), substract all known voltages around the path (typically 0.7V for transistors, 1.2V for LEDS and so) and suppose the rest is wasted on the resistor. Knowing maximum alloved current for your LED (typically 20mA for "normal one") you compute value of resistor by dividing voltage (in V) by current (in A) to get resitance (in Ohm).

In your picture: 9V-0.7V-1.2V=7.1V on resistor, 7.1V/0.02A=355 Ohm. You take any resistor equal or larger than that and it would be safe to shine for infinity.

First cheap IR LED I found have typical continuous current 20mA, Absolute Maximum Ratings at Ta=25℃ (room temperature) is current 100mA and  Peak Forward Current (1/10 Duty Cycle, 0.1ms Pulse Width) 1A. But those Absolute values are values, where you probabelly will destroy the LED soon, as any temperatue higher (as in summer) moves them down fast. You should read "Absolute Maximum Ratings Values"  as "values, which can destroy it randomly any moment, if I get near to them" rather than "manufacturer recomed it for extreme usage". (you cannot make perfect laboratory conditions for any device in normal use).

But if you want to make extra power on the risk of destroying the LED, you can set the resistor as low as 7.1V/0.1A = 71 Ohm or even for short pulses 7.1V/1A=7.1 Ohm, but I would bet, that the LED will burn soon anyway. I myself would risk like 80 Ohm in short pulses, but it does not get as much more light as it get in heat. Consult you datasheet and try only on your own risk.

TLDR: I suggest using unique codes by your Arduino sender for diferent receivers, because you cannot reach you goal other way with good certainlity.

Use your receiver to scan all usual remote controllers you have, then select something totally different for your Arduino receivers.


nRF2401 communication (extended vs normal) Communicating to the antenna-less version from an extended range nRF2401 seems to produce some strange results...

At a distance, the receiver seems to receive a number of values instead of one. For example, if I send a 1, I will receive a 1, but 30 times.

Has anyone had experience communicating across the two models, or is it just best practice to stick to communicating across same models? (Short range <-> short range, long range <-> long range)?

I've run both version fine together

Your symptom of receiving the same value 30 times would be related to a failed ACK, so the sender thinks it hasn't been received and resends it.

I've had potentially similar problems with the power amplified version running at full power causing interference in nearby circuity, try dialling down the power setting on it.


How to loop a specific tone? I am building a security system, and found the following code

#define NOOT_B0  31
#define NOOT_C1  33
#define NOOT_D1  37
#define NOOT_E1  41
#define NOOT_F1  44
#define NOOT_G1  49
#define NOOT_A1  55
#define NOOT_B1  62
#define NOOT_C2  65
#define NOOT_D2  73
#define NOOT_E2  82
#define NOOT_F2  87
#define NOOT_G2  98
#define NOOT_A2  110
#define NOOT_B2  123
#define NOOT_C3  131
#define NOOT_D3  147
#define NOOT_E3  165
#define NOOT_F3  175
#define NOOT_G3  196
#define NOOT_A3  220
#define NOOT_B3  247
#define NOOT_C4  262
#define NOOT_D4  294
#define NOOT_E4  330
#define NOOT_F4  349
#define NOOT_G4  392
#define NOOT_A4  440
#define NOOT_B4  494
#define NOOT_C5  523
#define NOOT_D5  587
#define NOOT_E5  659
#define NOOT_F5  698
#define NOOT_G5  784
#define NOOT_A5  880
#define NOOT_B5  988
#define NOOT_C6  1047
#define NOOT_D6  1175
#define NOOT_E6  1319
#define NOOT_F6  1397
#define NOOT_G6  1568
#define NOOT_A6  1760
#define NOOT_B6  1976
#define NOOT_C7  2093
#define NOOT_D7  2349
#define NOOT_E7  2637
#define NOOT_F7  2794
#define NOOT_G7  3136
#define NOOT_A7  3520
#define NOOT_B7  3951
#define NOOT_C8  4186
#define NOOT_D8  4699

 int melody[] = {
// NOOT_C4, NOOT_G3, NOOT_G3, NOOT_A3, NOOT_G3, 0, NOOT_B3, NOOT_C4
NOOT_D8, NOOT_D8, NOOT_D8, NOOT_D8, NOOT_D8, NOOT_D8
};
int NOOTDurations[] = {
 4, 4, 4, 4, 4, 4, 4, 4
 };
 void setup() {
    // iterate over the NOOTs of the melody:
  for (int thisNOOT = 0; thisNOOT < 8; thisNOOT++) {

// to calculate the NOOT duration, take one second divided by the NOOT type.
//e.g. quarter NOOT = 1000 / 4, eighth NOOT = 1000/8, etc.
int NOOTDuration = 1000 / NOOTDurations[thisNOOT];
tone(8, melody[thisNOOT], NOOTDuration);

// to distinguish the NOOTs, set a minimum time between them.
// the NOOT's duration + 30% seems to work well:
int pauseBetweenNOOTs = NOOTDuration * 1.50;
delay(pauseBetweenNOOTs);
// stop the tone playing:
noTone(8);
  }
 }

void loop() {
int melody[] = {
 // NOOT_C4, NOOT_G3, NOOT_G3, NOOT_A3, NOOT_G3, 0, NOOT_B3, NOOT_C4
 NOOT_D8, NOOT_D8, NOOT_D8, NOOT_D8, NOOT_D8, NOOT_D8
  };
 int NOOTDurations[] = {
  4, 4, 4, 4, 4, 4, 4, 4
  };

  }

How can i let the specific tone loop? Right now it's not within the loop and i am struggling to make it work in the loop. Thanks in advance!

#include "Arduino.h"

const byte TONE_PIN = 4;
const int ALARM_BEEP_1 = 4186;
const int ALARM_BEEP_2 = 4699;

const int ALARM_TONE_LENGTH = 200;
const int ALARM_TONE_PAUSE = 800;
const int ALARM_TONE_REPEAT = 6;

boolean alarm = false;

void setup()
{
  alarm = true;
}

void loop()
{
  if (alarm) {
    alarmSound();
  }
}

void alarmSound() {
  static unsigned long next = millis();
  static byte count = 0;
  if (millis() > next) {
    next += ALARM_TONE_LENGTH;
    count++;
    if (count == ALARM_TONE_REPEAT) {
      next += ALARM_TONE_PAUSE;
      count = 0;
    }
    tone(TONE_PIN, (count % 2) ? ALARM_BEEP_1 : ALARM_BEEP_2, ALARM_TONE_LENGTH);
  }
}


Error taking address of temporary array when passing compound literal array I have an Arduino sketch that passes an array into a method as a compound literal, but for some reason I keep getting the following error:

void setup() { }
void printConcatLine(char chunks[][20]) { }

void loop() {
  printConcatLine((char[][20]){ "{", "255", "}" });
}

I've also tried passing the number of the pointers/length of the array, and explicitly terminating it:

void setup() { }
void printConcatLine(char *chunks[]) { }

void loop() {
  printConcatLine((char*[]){ "{", "255", "}", NULL });
}

...and

void setup() { }
void printConcatLine(char chunks[][20]) { }

void loop() {
  printConcatLine((char[][20]){ "{", "255", "}", "" });
}

But they both produce the same error.

What is the correct method of passing the compound literal array as a method parameter?

You can't with the Arduino. I am not quite sure why, but I think it may be because it's a Modified Harvard architecture machine.

You can better achieve what you want with variadic arguments, however:

void printConcatLine(int num, ...) {
    va_list ap;
    const char *s;

    va_start(ap, num);
    for (int i = 0; i < num; i++) {
        s = va_arg(ap, const char *);
        Serial.print(s);
    }
    va_end(ap);
    Serial.println();
}

void setup() {
    Serial.begin(115200);
    printConcatLine(3, "{", "255", "}");
}

void loop() {

}

The first argument is the number of arguments that follow, and all the rest are string constants.


Could an `analogWrite` command and its variable output values be used to power multiple leds with same intensity? I seem to be getting the right response on single LED but with multiple LEDS or a relay connected LED strip the voltage outputs seem to be insuffiecient.
What kind of analogWrite values does an LED respond to?

Single LEDs like the standard 5mm leds work from low voltages such as 1.7 - 2.1v, so can be directly driven via an Arduino pin (through a resistor to prevent excess current draw which would damage the pin).

LED strips such as automotive LED strips (12v) require the use of a relay if you are simply switching the LEDs on and off. You can't run the relay directly from an Arduino pin, you will need to use a transistor to act as a buffer between the relay and the Arduino to prevent damaging the Arduino. Instead of the motor and diode in the below diagram, you connect your 12v led strip.

If you want to control intensity, you will need to use a transistor, or a mosfet (mosfets are easier). You can then use AnalogWrite to control the intensity of the LEDs via the MOSFET. You will need to connect the control pin for the MOSFET to one of the PWM-capable pins on the Arduino (the pins which have the ~ mark next to them), otherwise you will only be able to switch the MOSFET on and off, similar to the Relay. This site has a good guide on how to do this with a MOSFET. It also has a guide on how to use a transistor, but I can't include the link yet due to not enough reputation points. It shows both the code needed, and how to connect the components to the Arduino.


What is the pinout of the Arduino MKR motor carrier when using external power supply, not the Li-Po battery I see there is a blue terminal connector an the tags below the PCB Vin, 5V, 3,3V and GND, but I am unsure where should I supply voltage to power up the board.
Also, in the product page it says the power can range from 6.5 to 11v, so what is those 5V and 3.3V all about?
Thanks

Vin means "Voltage Input". That's where you provide your power. That is the input to the voltage regulator.
5V and 3.3V are what the board uses internally and are provided for you to also use should you want to. These are outputs from the voltage regulators.
It's exactly the same (though more efficient and higher current) as almost every other Arduino.


avrdude: stk500_recv(): programmer is not responding after serial I have searched but have not found any solution to my problem so I am asking it here.  I make a program in python that makes serial communication with the Arduino. I started to upload my Arduino code but I forgot that my python program was open in the terminal (I use Ubuntu). So, I think the Arduino code and python output went to the same port which the Arduino is on. After that I couldn't upload any code into the Arduino.

Every time it prints the following error:

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

and then makes more 9 attempts.
Any help?

Likely all you really need to do is exit/kill every process trying to use the Arduino, un-plug it from the USB port, and plug it back in.

This is in part because Linux doesn't really block multiple programs from trying to use the serial device at the same time, unless they take particularly efforts to claim it exclusively, but the attempted sharing may result in serial traffic that doesn't make any sense.

Another issue can be that if a still-running program was using a device that vanished, when that device is reconnected it will not be assigned to the in-use port number, but to a free one.


Using different variables in a function I have a function SetTFgr(float T, int FGr) to set the time and filtergrade of my LED enlarger.
It works without a problem and changes the values of T or Fgr according to the buttons I press. Both T and FGr are global variables.
Now I want to use the same funtion with different variables.
When I call the function with SetTFgr(TExp[i], FGrExp[i]) I would expect the function to work with the values of TExp[i] or FGrExp[i] and increase/decrease these values. It does not, it appears to use the value of T or Fgr instead.
How can I get what I am after?

To be clear, you want to read the values of buttons (meaning unspecified) and use those values to set a float and an int variable. Further, you want to write a function that takes a couple of parameters that specify where you want to store those button values?

That is an unusual way to use function parameters. Usually function parameters specify an input value, and then you use that value to do something. Instead, you want to have the inputs be globally available readings (button values) and have the function parameters specify where to store those values.

C and C++ function parameters are usually passed "by value". That means that what gets sent to the function is a value, not a pointer to the variable that contains that variable. Thus the called function can't change the original variable.

If you want to pass a pointer to the variable, you have to use the & "address of" operator to pass the variable "by reference".

Your function might look like this using C++ pass by reference syntax:

void SetTFgr(float &T, int &FGr) {
    float input_T = //figure out button value for T
    T = input_T;
    int input_FGr = //figure out button value for Far
    FGr = input_FGr;
}

Then you'd invoke it like this:

SeTFgr(T, FGr);

You could also accomplish the same thing using C pointer syntax.


Multiple client server over wifi Trying to setup a server on Arduino to support multiple clients,
I am able to support one but I don't want to flush that client to make another connection.

#include <ESP8266WiFi.h>
const char* ssid = "your-ssid";
const char* password = "your-password";
// Create an instance of the server
// specify the port to listen on as an argument
WiFiServer server(80);

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

  // prepare GPIO2
  pinMode(2, OUTPUT);
  digitalWrite(2, 0);

  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

  // Start the server
  server.begin();
  Serial.println("Server started");

  // Print the IP address
  Serial.println(WiFi.localIP());
}

void loop() {
  // Check if a client has connected
  WiFiClient client = server.available();
  if (!client) {
    return;
  }

  // Wait until the client sends some data
  Serial.println("new client");
  while(!client.available()){
    delay(1);
  }

  // Read the first line of the request
  String req = client.readStringUntil('\r');
  Serial.println(req);
  client.flush();

  // Match the request
  int val;
  if (req.indexOf("/gpio/0") != -1)
    val = 0;
  else if (req.indexOf("/gpio/1") != -1)
    val = 1;
  else {
    Serial.println("invalid request");
    client.stop();
    return;
  }

  // Set GPIO2 according to the request
  digitalWrite(2, val);

  client.flush();

  // Prepare the response
  String s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>\r\nGPIO is now ";
  s += (val)?"high":"low";
  s += "</html>\n";

  // Send the response to the client
  client.print(s);
  delay(1);
  Serial.println("Client disonnected");

  // The client will actually be disconnected
  // when the function returns and 'client' object is detroyed
}

Using this code, the server handles only one client at a time, but I need to connect multiple clents simultaneously.

You need to keep track of multiple WiFiClients - declare an array of them, for example, and each time server.available() gives you a new one, store it in the array.

Then you need to make sure your code doesn't stick waiting for data from each item.  You could service each WifiClient in turn: if it has data waiting (client[i].available() is true), read the data (client[i].read()) and store it. When you get a \r from a client, you know you have a whole line, and you can process it.

Here's a nearly-complete (but untested) example so you can see what I'm talking about.  Naturally it's not the only way to do it.

#include <ESP8266WiFi.h>
const char* ssid = "your-ssid";
const char* password = "your-password";
#define MAX_CLIENTS 10
#define MAX_LINE_LENGTH 50
// Create an instance of the server
// specify the port to listen on as an argument
WiFiServer server(80);
WiFiClient *clients[MAX_CLIENTS] = { NULL };
char inputs[MAX_CLIENTS][MAX_LINE_LENGTH] = { 0 };

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

  // prepare GPIO2
  pinMode(2, OUTPUT);
  digitalWrite(2, 0);

  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

  // Start the server
  server.begin();
  Serial.println("Server started");

  // Print the IP address
  Serial.println(WiFi.localIP());
}

void loop() {
  // Check if a new client has connected
  WiFiClient newClient = server.available();
  if (client) {
    Serial.println("new client");
    // Find the first unused space
    for (int i=0 ; i<MAX_CLIENTS ; ++i) {
        if (NULL == clients[i]) {
            clients[i] = new WiFiClient(newClient);
            break;
        }
     }
  }

  // Check whether each client has some data
  for (int i=0 ; i<MAX_CLIENTS ; ++i) {
    // If the client is in use, and has some data...
    if (NULL != clients[i] && clients[i]->available() ) {
      // Read the data
      char newChar = clients[i]->read();

      // If we have the end of a string
      // (Using the test your code uses)
      if ('\r' == newChar) {
        // Blah blah, do whatever you want with inputs[i]

        // Empty the string for next time
        inputs[i][0] = NULL;

        // The flush that you had in your code - I'm not sure
        // why you want this, but here it is
        clients[i]->flush();

        // If you want to disconnect the client here, then do this:
        clients[i]->stop();
        delete clients[i];
        clients[i] = NULL;

      } else {
        // Add it to the string
        strcat(inputs[i], newChar);
        // IMPORTANT: Nothing stops this from overrunning the string and
        //            trashing your memory. You SHOULD guard against this.
        //            But I'm not going to do all your work for you :-)
      }
    }
  }

}


LM35 and Character LCD I have an arduino pro mini and I have attached a 16x2 character LCD and an LM35 analog temperature sensor. When I upload a sketch using only the sensor and send the readings to serial monitor, the readings are OK. When I upload a sketch that displays the readings to the LCD the readings are about 130°C in room temperature. Where is the problem and how can I solve it. Thanks in advance

Code with lcd:

#include <LiquidCrystal.h>
byte smiley[8] = {
  B00000,
  B01110,
  B01010,
  B01110,
  B00000,
  B00000,
  B00000,
};
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
  // set up the LCD's number of columns and rows:
  lcd.createChar(0, smiley);
  lcd.begin(16, 2);
  analogReference(INTERNAL);
  // Print a message to the LCD.
  lcd.print(analogRead(0)/1024.0 * 500);
  lcd.write(byte(0));
  lcd.print("C");
  lcd.setCursor(0, 2);
  lcd.print("21");
  lcd.write(byte(0));
  lcd.print("C");

}

void loop() {
  // Turn off the cursor:
  lcd.print((analogRead(0)/1024.0)*500);
  lcd.write(byte(0));
  lcd.print("C");
  lcd.setCursor(0, 2);
  delay(5000);
  lcd.clear();
}

Only sensor code:

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  Serial.println(analogRead(0)/1024.0*500);
  delay(500);
}

Firstly you do not keep your code consistent between you temperature test and your LCD test code. The problem lies in your use of the internal analog reference, that reference is 1.1V and that is giving you 130°C.

Temp = 260*0.5= 130

The 260 is the ADC reading worked back from the 130°C you gave

To use Internal reference-

Internal ref = 1.1÷1024=0.001074219
That multiplied by one hundred to account for the mV reading of the lm35 gives 0.107 that will give you the correct temp when using the internal reference

Analog reference from the arduino site.

If you want to use the analog reading *0.5 comment out the analogReference()


Arduino Uno - Analog Circuit Simulator I control an analog circuit with Arduino Uno. I want to simulate an Arduino Uno with operational amplifiers (741). Can I simulate Arduino with SPICE?

You could use https://en.wikipedia.org/wiki/Ngspice.
From what is written there, the Xspice part could be used for creating a simple model of the Arduino, for checking how the analog part of your circuit interacts with the uC.
Unfortunately the main site () is down, atm, as many other projects hosted on SourceForge. But it might be worth having a look, once it's back online.


Getting a truly random number in Arduino What is the best method to get a truly (as opposed to pseudo) random number in Arduino, or at least the best possible approximation? From my understanding, the function randomSeed(analogRead(x)) it's not random enough.

If possible the method should leverage the basic Arduino setup alone (no additional sensors). Solutions with external sensors are welcome if they improve significantly the randomness over the basic setup.

The Entropy library uses:

  the watchdog timer's natural jitter to produce a reliable stream of true random numbers

I like this solution because it doesn't use up any pins of your microcontroller and doesn't require any external circuitry. This also makes it less subject to external failures.

In addition to a library, they also provide a sketch that demonstrates the use of the same technique used to generate a random seed for the microcontroller's PRNG without the library:
https://sites.google.com/site/astudyofentropy/project-definition/timer-jitter-entropy-sources/entropy-library/arduino-random-seed


How to interface with generic IR RGB LED controller? I want to hook up an arduino to one of those generic RGB LED controllers, you see them everywhere, they are these little white boxes with power input and RGB strip plug and an IR LED lead. Is there a way to take to the IR + and - and connect them the arduino? Then spoof an IR signal to control the control module? I want to do it this way because I already own both the arduino and control module and that module handles the power for the LEDs. All I am hoping I have to do is send the controller the hex value for the IR command through the the arduino in order to control it. Here's a link to what the module looks like and the remote it comes

https://www.amazon.com/dp/B00ASHQQKI/ref=cm_sw_r_cp_awd_htMywb1W85962

The IRRemote Library is a good starting point, but you'll probably need a RAW mode.   I've got a couple IR controllers from different companies, and they use different codes for the same things.


Connecting a servo via HC05 and HC06 I want to drive a servo via a HCO6 and HC05 link as a stand alone, using no android or PC.
The question is how to send a 1.5 ms signal (generated with a pulse command on a Nano) from one HC to another HC (to which my servo will be connected) ?
I do not need to care about passwords in my linking. No text to be sent, just the 1ms to 2 ms signal, at a refresh rate of 50 Hz.
I will use the HC with a OOK modulation (on - off on the data pin)?
How to achieve this ?
Thanks !

You cannot. You will need an Arduino at the servo end to generate the PWM signal from serial instructions sent over Bluetooth.

Since PWM is (typically) 8-bit and serial is (typically) 8-bit you could simply have each byte as a 1:1 mapping to a PWM value.

One the transmit end:

bluetoothSerial.write(pwmValue);

On the receive end:

if (bluetoothSerial.available()) {
    analogWrite(9, bluetoothSerial.read());
}


F() messes with program I'm working on command-handler library and I have a big problem with F() function.
Example sketch for library uses quite a lot of RAM, because it has to print a lot of text over UART. As before, I've used F() to lower RAM usage. It worked on first!

Lib works with help of strtok function. Command fomar is:

  cmd1,..,paramN;..;cmdN,..,paramN

Commands are separated with ; while command parameters(params) are separated with ,
Library works without any problems, it returns memory address(char*) of any command and every param.

When I try to compare parameter/command with strcmp it works only if all commands are in uppercase.
Let's take LED command for example:
It works only with Led, LED or any case where is letter d in uppercase. led won't work, and it will say that command le doesn't exist. Yes, le, it won't print led. But, after DURATION command, it somehow start working.

Memory for serial buffer is dynamicly allocaed in object constructor, in global scope.
Why? All those problems are because F(). Can someone explain why? Here's the code and screenshot of serial monitor.

void execCmd(const char *set)
{
char *cmdParam = CMDHandler.find(set, CMD_PARAM);

if (!strcmp(cmdParam, "LED"))
{
    // ONE WAY TO CHECK IF COMMAND HAS PARAM(S) - BEFORE GETTING PARAM(S) == BETTER WAY
    if (!CMDHandler.count(CMDHandler.getNext(CMD_PARAM), CMD_PARAM))
    {
        Serial.print(F("->> Command LED: Current LED status is "));
        Serial.println(digitalRead(LED_PIN));
        return;
    }

    cmdParam = CMDHandler.find(nullptr, CMD_PARAM);
    LEDStatus = 0;
    uint8_t status = atoi(cmdParam);

    digitalWrite(LED_PIN, status);
    Serial.print(F("->> Command led: LED Status is "));
    Serial.println(status, DEC);
}
else if (!strcmp(cmdParam, "LOOP"))
{
    cmdParam = CMDHandler.find(nullptr, CMD_PARAM);

    // SECOND WAY TO CHECK IF COMMAND HAS PARAM(S) - AFTER GETTING EVERY PARAM
    if (cmdParam == nullptr)
    {
        Serial.println(F("->> Command LOOP: Expected one parameter!"));
        return;
    }

    uint8_t status = atoi(cmdParam);
    if (status)
    {
        LEDStatus = 2;
        digitalWrite(LED_PIN, HIGH);
        Serial.println(F("->> Command LOOP: LED Blink Loop is on!"));
        delay(blinkDuration);
    }
    else
    {
        LEDStatus = 0;
        digitalWrite(LED_PIN, LOW);
        Serial.println(F("->> Command LOOP: LED Blink Loop is off!"));
    }
}
else if (!strcmp(cmdParam, "DURATION"))
{
    if (!CMDHandler.count(CMDHandler.getNext(CMD_PARAM), CMD_PARAM))
    {
        Serial.print(F("->> Command DURATION: Current blink duration is "));
        Serial.print(blinkDuration, DEC);
        Serial.println("ms");
        return;
    }

    cmdParam = CMDHandler.find(nullptr, CMD_PARAM);
    blinkDuration = atoi(cmdParam);

    Serial.print(F("->> Command DURATION: New blink duration is "));
    Serial.print(blinkDuration, DEC);
    Serial.println("ms!");
}
else if (!strcmp(cmdParam, "HELP"))
{
    Serial.println(F("------ HELP ------\n-> LED [0/1] - Turns off/on LED on pin 13\n-> LOOP [0/1] - Stops/starts blink loop with LED on pin 13\n-> DURATION [X] - Changes duration of LED loop blink. Recommended values is 50-500ms\n"));
}
else
{
    Serial.print(F("->> Command "));
    Serial.print(cmdParam);
    Serial.println(F(" does not exist!"));
}

}

char *CMDHand::find(const char *input, uint8_t const type)
{
    char *found = nullptr;
    char separator = delimiter[type];

    if (input != nullptr) // FIRST CALL
    {
        constrain[type] = input + strlen(input) - 1;
        next[type] = input;
    }
    else if (next[type] > constrain[type]) return (nullptr);

    found = strtok(next[type], &separator); // FOR SOME REASON IT DOES NOT WORK IF I PUT &delimiter[type] INSTEAD OF &separator
    last[type] = next[type];
    next[type] += strlen(found) + 1;

    return (found);
}

To compare with F() macro encased strings you have to use special forms of the string functions that are suffixed with _P.  You also need to cast the string literals to the right type (PGM_P).

To do a case-insensitive comparison you should use strcasecmp instead of strcmp.

To put those together you end up with:

if (strcasecmp_P(cmdParam, (PGM_P)F("help")) == 0) {
    ...
}

There is a problem here:

found = strtok(next[type], &separator)

strtok takes a C string as a list of separators (must be NULL terminated). You're passing it the address of a single character. There may or may not (probably not) be a NULL in the next byte in memory, but everything else up to the first NULL found in memory will be taken as delimiter characters.


ATtiny85 communication with computer through USB I am trying to receive and send some data from a computer to an ATtiny through USB. Can an ATtiny85 IC communicate with a computer through USB? If yes, how should it be connected?

Digispark made a lot of these as part of a "cheap Arduino USB interface" project a while back.

This is my Digispark, it's pretty cute:

They have a web page here.

I got them for about $2 each. The board has the ATtiny85, a voltage regulator, and a handful of other parts.

Schematic (courtesy of Digistump Wiki):

More information about the Virtual USB idea at USB-Keyboard with Arduino and V-USB library, an example.


LED and Switch Compolation Error Arduino 101 I'm getting an error on line 9 for some reason, (digitalWrite(Sender, HIGH);), and I just cant figure out why. My goal is to have two sets of flashing patterns, one for each switch state. I don't know how important this is but I'm using an Arduino 101. This is also my first day programming so the answer could be staring me right in the nose, (in fact, I would prefer that haha). Thank you for your time!

// Starting this by declairing intigers
int Sender = 2; // Switch Out on pin two
int LedG = 10; // LED Green out on pin ten
int LedR = 11; // LED Red out on pin eleven
int Reader = 12;  // Switch Input on pin twelve
//configuring I/O
pinMode(Sender = OUTPUT); // Setting pin two to output
pinMode(Reader = INPUT); // Making pin 12 set to read switch data
digitalWrite(Sender, HIGH); //Making pin two hot
//main loop
void loop() {
  if (digitalRead (Reader) == HIGH) { // if Switch input is reading on than do pattern A
    digitalWrite(LedG, HIGH); //turning on green led
    delay(50); //delay next instruction
    digitalWrite(LedG, LOW); //turn green led off
    digitalWrite(LedR, HIGH); //turn red led on
    delay(50); //delay next instruction
    digitalWrite(LedR, LOW); //turn red led off
  }
  else { //if switch input is readion off than play pattern b
    digitalWrite(LedR, HIGH); //turn red led on
    delay(1000); //delay next instruction
    digitalWrite(LedR, LOW); //turn red led off
    digitalWrite(LedG, HIGH); //turning on green led
    delay(1000); //delay next instruction
    digitalWrite(LedG, LOW); //turn green led off
  }
}

I notice that your pinMode function calls are not quite correct:

pinMode(Sender = OUTPUT); // Setting pin two to output
pinMode(Reader = INPUT); // Making pin 12 set to read switch data

Should be:

pinMode(Sender, OUTPUT); // Setting pin two to output
pinMode(Reader, INPUT); // Making pin 12 set to read switch data

Refer to https://www.arduino.cc/en/Reference/PinMode for more information.

And the whole section where you configure your I/O should be wrapped inside the setup() function.

//configuring I/O
void setup()
{
    pinMode(Sender, OUTPUT); // Setting pin two to output
    pinMode(Reader, INPUT); // Making pin 12 set to read switch data
    digitalWrite(Sender, HIGH); //Making pin two hot
}