text:
PWM output voltage too high
I'm experimenting with PWM with the code below, but (according to my analog multimeter) the voltage on the output pins reach up to 5V whilst the largest analogRead(IN1) value is only around 700:
const int EN1 = 5;
const int EN2 = 6;
const int EN3 = 7;

const int IN1 = 9;
const int IN2 = 10;
const int IN3 = 11;

// SPWM (Sine Wave)
// const int pwmSin[] = {127, 138, 149, 160, 170, 181, 191, 200, 209, 217, 224, 231, 237, 242, 246, 250, 252, 254, 254, 254, 252, 250, 246, 242, 237, 231, 224, 217, 209, 200, 191, 181, 170, 160, 149, 138, 127, 116, 105, 94, 84, 73, 64, 54, 45, 37, 30, 23, 17, 12, 8, 4, 2, 0, 0, 0, 2, 4, 8, 12, 17, 23, 30, 37, 45, 54, 64, 73, 84, 94, 105, 116 };

/// SVPWM (Space Vector Wave)
//const int pwmSin[] = {128, 147, 166, 185, 203, 221, 238, 243, 248, 251, 253, 255, 255, 255, 253, 251, 248, 243, 238, 243, 248, 251, 253, 255, 255, 255, 253, 251, 248, 243, 238, 221, 203, 185, 166, 147, 128, 109, 90, 71, 53, 35, 18, 13, 8, 5, 3, 1, 1, 1, 3, 5, 8, 13, 18, 13, 8, 5, 3, 1, 1, 1, 3, 5, 8, 13, 18, 35, 53, 71, 90, 109};
const int pwmSin[] = {128, 132, 136, 140, 143, 147, 151, 155, 159, 162, 166, 170, 174, 178, 181, 185, 189, 192, 196, 200, 203, 207, 211, 214, 218, 221, 225, 228, 232, 235, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 248, 249, 250, 250, 251, 252, 252, 253, 253, 253, 254, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 254, 254, 253, 253, 253, 252, 252, 251, 250, 250, 249, 248, 248, 247, 246, 245, 244, 243, 242, 241, 240, 239, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 248, 249, 250, 250, 251, 252, 252, 253, 253, 253, 254, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 254, 254, 253, 253, 253, 252, 252, 251, 250, 250, 249, 248, 248, 247, 246, 245, 244, 243, 242, 241, 240, 239, 238, 235, 232, 228, 225, 221, 218, 214, 211, 207, 203, 200, 196, 192, 189, 185, 181, 178, 174, 170, 166, 162, 159, 155, 151, 147, 143, 140, 136, 132, 128, 124, 120, 116, 113, 109, 105, 101, 97, 94, 90, 86, 82, 78, 75, 71, 67, 64, 60, 56, 53, 49, 45, 42, 38, 35, 31, 28, 24, 21, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 8, 7, 6, 6, 5, 4, 4, 3, 3, 3, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 5, 6, 6, 7, 8, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 8, 7, 6, 6, 5, 4, 4, 3, 3, 3, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 5, 6, 6, 7, 8, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 21, 24, 28, 31, 35, 38, 42, 45, 49, 53, 56, 60, 64, 67, 71, 75, 78, 82, 86, 90, 94, 97, 101, 105, 109, 113, 116, 120, 124};

int currentStepA;
int currentStepB;
int currentStepC;
int sineArraySize;
int increment = 0;
boolean direct = 1; // direction true=forward, false=backward

//////////////////////////////////////////////////////////////////////////////

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

  setPwmFrequency(IN1); // Increase PWM frequency to 32 kHz  (make unaudible)
  setPwmFrequency(IN2);
  setPwmFrequency(IN3);

  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
  pinMode(IN3, OUTPUT);

  pinMode(EN1, OUTPUT);
  pinMode(EN2, OUTPUT);
  pinMode(EN3, OUTPUT);

  digitalWrite(EN1, HIGH);
  digitalWrite(EN2, HIGH);
  digitalWrite(EN3, HIGH);

  sineArraySize = sizeof(pwmSin)/sizeof(int); // Find lookup table size
  int phaseShift = sineArraySize / 3;         // Find phase shift and initial A, B C phase values
  currentStepA = 0;
  currentStepB = currentStepA + phaseShift;
  currentStepC = currentStepB + phaseShift;

  sineArraySize--; // Convert from array Size to last PWM array number
}

//////////////////////////////////////////////////////////////////////////////

void loop() {

  analogWrite(IN1, pwmSin[currentStepA]);
  analogWrite(IN2, pwmSin[currentStepB]);
  analogWrite(IN3, pwmSin[currentStepC]);

  if (direct==true) increment = 1;
  else increment = -1;

  currentStepA = currentStepA + increment;
  currentStepB = currentStepB + increment;
  currentStepC = currentStepC + increment;

  //Check for lookup table overflow and return to opposite end if necessary
  if(currentStepA > sineArraySize)  currentStepA = 0;
  if(currentStepA < 0)  currentStepA = sineArraySize;

  if(currentStepB > sineArraySize)  currentStepB = 0;
  if(currentStepB < 0)  currentStepB = sineArraySize;

  if(currentStepC > sineArraySize)  currentStepC = 0;
  if(currentStepC < 0) currentStepC = sineArraySize;

  /// Control speed by this delay
  delay(10);
  Serial.println(analogRead(IN1));
}

void setPwmFrequency(int pin) {
  if(pin == 5 || pin == 6 || pin == 9 || pin == 10) {
    if(pin == 5 || pin == 6) {
      TCCR0B = TCCR0B & 0b11111000 | 0x01;
    } else {
      TCCR1B = TCCR1B & 0b11111000 | 0x01;
    }
  }
  else if(pin == 3 || pin == 11) {
    TCCR2B = TCCR2B & 0b11111000 | 0x01;
  }
}

If analogRead(IN1) is just around 700 max, shouldn't the voltage be around 3.5V (700/1023 * 5V)? How come the output voltage is so high?
Any help would be appreciated.

What is your schematic? You have some pins connected to other pins, I gather?

It seems that you misunderstand how pwm works.
Pwm is the modulation of duty cycle, so the pin are outputting square waves 0-5v at the same frequency, but varying the time it's low and the time it's high. Your multimeter probably is only displaying high intervals, instead your analog read probably has filters and calculates the efficient voltage of the sine wave (divide max for sqr(2)).


text:
An audio jack modem
I'm looking at controlling Arduino by reading audio commands sent from a raspberry pi (through javascript). I've found the SoftModem code and wonder how it works. It claims that "It uses the phone's audio jack and Bell 202 modem-like FSK encoding", but I wonder how it's done. Doesn't it need to sample the ADC and apply some filtering like FFT? I can't seem to find where all this is done.
Any thought appreciated.

Which Arduino do you have?

@NickGammon It's a Nano. I could a Uno though.

Judging by the blog from the post you linked, he is calculating the frequency received by using the analog comparator built into the processor. That lets you detect a signal rising, falling or both, compared to a reference voltage.
With some interrupts and some timing, you could work out what frequency signal you were receiving, and thus deduce if you got a 0 or 1 bit incoming.
I have a page about the analog comparator if that helps.

Do you think there should be an opamp in that circuit? Shouldn't there be some kind of "signal conditioning" going on there?

Possibly. It depends on the voltage levels. The analog comparator is a high impedance input. Maybe a capacitor and/or diode should clamp the input to 0 to 5V.

source: Stack Exchange

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

sort: votes


text:
Use mobile charger as power suppy to ESP8266 wifi module with 3.3v converter
I am using this FTDI connector to power and flash code inside ESP8266 module.

Now I am done with adding code to ESP8266, now I just want to power it.
but when I connect the mobile charger(5v output) instead of FTDI connect it gives only "?????? ???? ????" this output.
can't I use this as VCC and GND ??

If you've replaced the FTDI with a mobile charger, where are you seeing this output?

I am only replacing vcc and GND, Rx and Tx are as it is connected to FTDI.

But not GND to the FTDI board...? Where is your circuit then? How can electrons flow...?

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


text:
Add string inputs into an array
I have been working on this a while and I cannot seem to figure it out. Essentially, I am using the app/server Blynk and their Terminal Widget to sent String inputs to my Arduino board. My code is below:

  String INFO;
  String fromTerminal = param.asStr();
  int indexstart = fromTerminal.indexOf(",");
  int indexend = fromTerminal.lastIndexOf(",");
  int counter = indexstart - indexend;
  INFO[counter] = fromTerminal;
My thoughts on the code was, based on the number of "," I enter in the string then that will assign my input to an index within the INFO array. However as I have tried several different things, I constantly get errors such as:
cannot convert 'String' to 'char' in assignment.
Oddly enough if I set: INFO[counter] = fromTerminal.toInt();
I dont get an error but I dont think that will allow me to print out my actual input. Any help is much appreciated, thanks!

INFO isn't an array - it's a String.

Yeah so I was looking into it further, dumb oversight on my part but I guess you cant dynamically create an array. So I am just going to over initialize the array ie. INFO[20}; even when I only ever input between 5-10 strings, and then just call the index up to how many I input

I think you should better read about the String Object and don't mix this up with string as char array.

That is not an answer!

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


text:
Arduino: Sending SD CSV file online at specific time of the day
I intend to perform data logging from sensors and store it on SD card as CSV format. The data is related to weather and I would like to send it at the end of the day/
Any available codes how to deploy the SD files from Arduino to the cloud/online at specific time of the day?
Thank you in advance.

Well for CSV, you might as well do dataFile.print(",");. It will log a comma and thus separating your values with a comma.
For logging your data at the end of the day, you have multiple ways.
1- Use a delay (worst idea EVER! Don't do this!). This will require you putting delay(86400000);. Yes that is indeed a 24h delay!
2- Use the millis() function. This function returns the number of milliseconds since the programmed started running. There is an example code called blinkWithOutDelay(or something like that). This method is somewhat "ok" but after 49 days there is a rollover which makes things complicated. To solve that rollover, see here.
3- Use a RTC. RTC stands for Real Time Clock. It is pretty much a module that keeps actual time even if the power to your project is disconnected. There are many popular models out there such as the DS3231. There are many libraries for it. You can do so that each day, at a specific time, it logs the data to your SD card.
Now to send the data. You have may options for this too.
1- Use an Arduino Ethernet shield. This will connect your Arduino to the Ethernet via an Ethernet cable. From there, you can either log your data to a Google Sheets file or a custom web server. Many tutorials out there for you.
2- Use an ESP8266. With this Wifi module, you can easily host your own web server with it. Note that This makes it somewhat harder for your code then simply using an Ethernet cable but it makes you project wireless. Note that if you do use an ESP8266, you can put the Arduino aside. The ESP has many GPIOs that can be used to do many things, but I'll still suggest keeping the Arduino for sake of simplicity. Again, many tutorials out there.
Note that there are many cloud services out there. A quick Arduino IOT search will bring out many result and interresting projects ideas for you.

You should use arduino as an ftp client, then stream the csv file to the site in binary mode. You should find examples on the web.


text:
XBee WiFi: Does it work on the Wireless Proto Shield?
I have been following this tutorial by sparkfun
https://learn.sparkfun.com/tutorials/internet-datalogging-with-arduino-and-xbee-wifi
and I have XBee Wifi but not the Shield of SparkFun. I have the Wireless ProtoShield which is provided by Arduino.cc
I wonder if both are compatible with each other?
Thank you in advance.


text:
Arduino for Weather and Air Monitoring: Casing and Power Source
I am intended to use Arduino to measure Temperature and Humidity (DTH11) and Gases Grove Sensor (Multichannel). Due to weather conditions in UK, I would to get your advice how to shield all of them in water proof box? Do you believe that using Polystyrene is useful?
Any recommended power source?

As this stands it is pretty opinion based and possibly broad. Aside, I wouldn't go with styrene stuff. Trying looking for weather station sensor enclosures(DIY route if need be)

The phrase you are looking for is "louvre box"

http://www.metoffice.gov.uk/guide/weather/observations-guide/how-we-measure-temperature

I'd say, use a IP-54 protection plastic case. The IP is a standard, that tells you, how big particles can(not) come into the case.
About powering, depends, how often can you go and switch batteries.
If you can, you can plug the cable in the case - drill the hole through and use watertight silicone plug to ensure, it is water resistant.
In case of batteries - use some LiPo batteries with DC-DC converter to minimum voltage.
Maybe you could even add a solar panel or two for addional life extension of batteries.


text:
Array variable name changes from readings1 to readings2
I've been using two MB1240 Ultrasonic Sensors with analogRead, and have found that after using bubble sort, the array is found in array readings2, and not readings1. This is important because I would like to find the distance from each sensor.
Below is the code I've put together that uses buttons to determine when each sensor should be triggered.
const int anPin1 = 1;
const int anPin2 = 2;

const int triggerPin = 2;
long anVolt1, anVolt2;

// button Pins
const int buttonPin1 = 11;
const int buttonPin2 = 13;

int buttonState1;
int buttonState2;
int lastButtonState1 = false;
int lastButtonState2 = false;

long lastDebounceTime1 = 0;
long lastDebounceTime2 = 0;
long debounceDelay = 50; //ms

// initialise averaging array
const int numberOfReadings = 10; // reasonable DOF
long readings1[numberOfReadings];
long readings2[numberOfReadings];
long median;

void setup() {
  Serial.begin(9600);
  pinMode(triggerPin,OUTPUT);
  pinMode(buttonPin1, INPUT);
  pinMode(buttonPin2, INPUT);
  delay(200); // Datasheet: Sensors require 175 ms to calibrate
}

void start_sensor(){
  digitalWrite(triggerPin,HIGH);
  delay(10);
  digitalWrite(triggerPin,LOW);
}

long read_sensor1(){
  //Used to read in the analog voltage output that is being sent by the XL-MaxSonar device.
  //Scale factor is (Vcc/1024) per centimeter. A 5V supply yields ~4.9mV/cm for standard range sensors
  anVolt1 = analogRead(anPin1);
  return anVolt1;
}

long read_sensor2(){
  anVolt2 = analogRead(anPin2);
  return anVolt2;
}

void printall(long readings[]) {
  int med = numberOfReadings/2;
  median = (readings[med-1] + readings[med])/2;

  Serial.print("Sensor: ");
  for (int i = 0; i < numberOfReadings; i++) {
    Serial.print(readings[i]);
    Serial.print("cm ");
  }
  Serial.println();

  Serial.print("Median: ");
  Serial.print(median);
  Serial.println(" cm");
}

void loop () {
  int reading1 = digitalRead(buttonPin1);
  int reading2 = digitalRead(buttonPin2);

  // for noise
  if (reading1 != lastButtonState1) {
    lastDebounceTime1 = millis();
  }

  // for noise
  if (reading2 != lastButtonState2) {
    lastDebounceTime2 = millis();
  }

  if ((millis() - lastDebounceTime1) > debounceDelay) {
    if (reading1 != buttonState1) {
      buttonState1 = reading1;
      if (buttonState1 == HIGH) {
        for (int i = 0; i < numberOfReadings; i++){
         start_sensor();
          readings1[i] = read_sensor1();
          delay(150); // From datasheet: Period = 99ms
        }

            **// bubble sort with flag
        for (int i = 0; i < sizeof(readings1)-1; i++) {
            bool flag = true;
            for (int j = 1; j < sizeof(readings1)-1; j++) {
                if (readings1[j-1] > readings1[j]) {
                    int t = readings1[j-1];
                    readings1[j-1] = readings1[j];
                    readings1[j] = t;
                    flag = false;
                }
            }
            if (flag) break;
        }
       printall(readings1);**
      }
    }
  }

  lastButtonState1 = reading1;

  if ((millis() - lastDebounceTime2) > debounceDelay) {
    if (reading2 != buttonState2) {
      buttonState2 = reading2;
      if (buttonState2 == HIGH) {
        for (int i = 0; i < numberOfReadings; i++) {
          start_sensor();
          readings2[i] = read_sensor2();
          delay(150);
        }
       printall(readings2);
      }
    }
  }
  lastButtonState2 = reading2;

  //clear previous readings
  memset(readings1, 0, sizeof(readings1));
  memset(readings2, 0, sizeof(readings2));
}

Scenario: I have clicked the first button to return a reading from the first sensor, and I am expecting the results to be stored then sorted in array readings1. After the bubble sort, if I enter printall(readings1), it returns an array of zeros, but if I use a printall(readings2), it returns the sorted array I expected.
I can't find where I'm going wrong with this one, any help would be greatly appreciated. Thank you!

Wouldn't using qsort be easier, faster, and more reliable?

qsort is brilliant. I switched from a bubble sort to a qsort algorithm for ordering triangles in a 3d mesh drawing library and it went from ~1fps for 8000 triangles to ~20fps.

for (int j = 1; j < sizeof(readings1)-1; j++) {

sizeof(readings1) is not the number of elements in the array, it is the size of the array in bytes (in your case, 40). You are exceeding the bounds of the array. You know the number of items (numberOfReadings) - why not use that?


text:
Arduino analog input protection
I've been trying to find a way to protect my analog input pins (for my Leonardo and Pro micro). I'm basically using them to read an amplified piezo sensor output. The output is amplified because I'm using it to measure very low signal (heartbeats). The normal level of the sensor's output doesn't exceed 5V when I'm measuring heartbeats or chest movement, yet when the sensor is moved rapidly or lifted, I can expect a 5v+ voltage. I know that Arduino has an internal protection circuit, will that be enough to combat those sudden movements?
If not, I've read so many posts on this topic including this one:
http://www.thebox.myzen.co.uk/Tutorial/Protection.html
If I wanted to add a series resistor by itself as a protection will it be okay? and also, my signal is already small, wouldn't adding a resistor attenuate it even more?
Most circuits seem to have a capacitor, my signal is DC shifted upward (to avoid -ve voltage), wouldn't the capacitor remove that offset?
Finally, if I wanted to use the diode clamping diodes, which diodes should I use (i.e 1n4148 or 1n4002)?
Thank you

If you amplified with an op-amp powered by 5V then it couldn't produce more than 5V output, so that could be your solution. Failing that, I think a resistor and a couple of clamping diodes would help. The resistor is to current-limit the clamping diodes. I don't think you need to worry about dropping the voltage through the resistor because the analog input is high impedance.
I think the 1n4148 would be OK, I don't see why not.

With an Opamp, the output swings between -4V and 4V (approximately) if my supply is 5V right?. I tried building a buffer with 5V (single supply) to have the output swinging from 0 to 5V but I seem to loose the signal below my DC offset point (1.8V). The buffer takes it's input from the original heartbeat amplifier (AD620) which I'm powering with -5V and +5V and it produces a DC offset of 1.8V (Vref is set by another Op Amp voltage divider.

I've built the clamping diodes circuit as in the following link: http://www.thebox.myzen.co.uk/Tutorial/Protection_files/shapeimage_10.png .... I used 22R, my diodes were 1N4148. I got better results! my signal now ranges from -840mV to 5V. Do you think the -840mV will burn my board?

Well ... you are exceeding the maximum (negative) ratings of -0.5V on an input pin by 380 mV.

I think you should be able to get an op-amp to do it by offsetting the input to the op-amp and powering by only 0 to 5V.

To be honest, you are taking me out of my area of expertise here. I Googled "op amp offset voltage" and found quite a few hits, some nearby on Electronics Stack Exchange. I think you should be able to configure your op-amp to give you a voltage range that won't exceed your processor specs. My advice is to not exceed the absolute maximum ratings of the processor, however you achieve that.

Actually, I remeasured the range again and it's between -840mV and 4.16V so this is around 5V range but shifted downward abit. I tried changing the diodes to 1n4002 and this didn't fix it. I also tried changing the supply and that -840mV is still there. How can I shift it upward a bit?

This is not really an Arduino question - it's an electronics question, so I suggest you ask on Electronics Stack Exchange.

Unless you supply the opamp with a negative voltage, it can't produce a negative voltage.

I know that Arduino has an internal protection circuit, will that be enough to combat those sudden movements?

it depends on the voltage your pin may see. the pins have clamp diodes - the reset pins may not have, so check the datasheet for sure.
those diodes can sustain some current - check the datasheet on that - absent of it, I wouldn't go more than 10ma on those little guys.
So if you think you may see 10v on the input, put a resistor of (10v-5v) / 10ma = 500ohm resistor there, where 5v is (assumed by me) the supply voltage of your mcu - use the real figure if yours has a different supply voltage.
the same calculation with the negative rail /ground.
and pick the larger of the two.
I typically put a 1k resistor there. I try to be careful if i need to go over 10k, especially for adc pins.
a safer route is to use a (dual directional) buffer. but it does add cost + board real estate.

The datasheet says nothing about the maximum current these diodes can sustain (yes, it's a shame), but application note AVR182 states “It is not recommended that the clamping diodes are conducting more than maximum 1mA”.

Use a voltage comparator to buffer the input to analog pin . E.g.  a cheap lm 393. If the signal is less than 5v in buffer circuit is stored and passed on- if its more than 5v voltage comparator blocks the , more than 5v, voltage to the arduino.


text:
Line not printing int in Serial Monitor
I'm trying to make a kernel for a macro-key maker, this is the starting page's code:
char m[] = "What do you want to do? Type the following commands in this "
      "terminal:\nnew  --> Creates a new Keybinding\ndelete  --> Deletes a "
      "previous Keybind\nlookup --> Find what is bound to a key\n\nTurn off the "
      "switch to go back to the normal mode.";
Serial.println(m);
Serial.println(String(takenKeybinds) + "/64 Keybinds taken.");

When I run it, the screen displays:
What do you want to do? Type the following commands in this terminal:
new  --> Creates a new Keybinding
delete  --> Deletes a previous Keybind
lookup --> Find what is bound to a key

Turn off the switch to go back to the normal mode.

The last line is missing.  Is this a problem with object casting? takenKeybind is an int.

does it happen in minimal sketch?

What board are you compiling for?

You should never do this:
Serial.println(String(takenKeybinds) + "/64 Keybinds taken.");

Yes, it should cope with it and append the strings, but that's really nasty even if it does work. And there is absolutely no call to ever do concatenation when printing to serial.
Instead just use:
Serial.print(takenKeybinds);
Serial.println(F("/64 Keybinds taken."));

Note also the use of the F() macro when printing a string literal. This keeps the string in flash and prevents it being copied to RAM, which is just wasteful.
The same with your big long string - it's wasting RAM, and if you never want to modify it, why have it in RAM? Better is:
Serial.println(F("What do you want to do? Type the following commands in this terminal:"));
Serial.println(F("new  --> Creates a new Keybinding"));
Serial.println(F("delete  --> Deletes a previous Keybind"));
Serial.println(F("lookup --> Find what is bound to a key"));
Serial.println();
Serial.println(F("Turn off the switch to go back to the normal mode."));

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


text:
Does Keyboard.begin() and Keyboard.end() make my code slower?
I'm making an IR Macro keyboard, and about 10% of the code is dedicated to the Keyboard commands, would having Keyboard.begin() and Keyboard.end() in the method responsible for typing make any difference to the speed or size?
My code:
void decodeCode(){ // send the macros.
  int pos = 0;
  for(int i = 0; i<output.length(); i++){
    if(output.charAt(i) == '$' && i!=output.length()-1){ //the $ is a symbol for "$pecial" characters
      i++;
      specialDecodeChar(output.charAt(i));
    }
    else if(output.charAt(i) == '%'){
      Keyboard.releaseAll();
    }
    else{
      Keyboard.press(output.charAt(i));
    }
  }
  Keyboard.releaseAll();
}

I currently have Keyboard.begin() in setup().

All code makes a difference to speed and size. Nothing is free.

keyboard.begin() is probably a constructor and .end is likely the destuctor.  We don't know for sure because not all your code is here.  Usually a constructor is run once during the life of a program. And, well, for an embedded program, the destuctor is sometimes just overlooked.  So, the question to be answered: Why would you need to make calls to these functions over and over?

@st2000 Keyboard.begin() and keyboard.end() are not constructors or destructors. They are normal functions typically called from setup, or wherever else you want to start or stop keyboard functionality. However they happen to be empty functions.

Thanks for clearing that up @Majenko.

The Keyboard::begin() and Keyboard::end() functions,  if you actually look at the code are empty functions. They do nothing.
In theory the compiler should just optimise them out.


text:
How do you make a Class variable array bigger?
I am making an infrared macro-keyboard, I want to store Unicode for the Keyboard class in an array inside a class I made called Keybindand to allow the user to program as many outputs as they want, I want the storage to be mutable.  I currently use the String class and decode within the program but it's cpu intensive and not very practical.
I want to use an array or list, but I haven't found any way to expand the size of an array inside a class.  Casting a temporary array didn't work:
  int intArray[] = {0,1,2,3,4,5};
  int* temp[7];

  for(int x = 0; x<sizeof(intArray)/sizeof(intArray[0]); x++){
    temp[x] = intArray[x];
  }
  temp[6] = 6;
  intArray = temp;

IDE spits out "incompatible types in assignment of 'int* [7]' to 'int [6]'"

The error is because ìnt* temp[7] gives you an array of 7 pointers to ints, not an array of 7 ints. Remove the *. Though I don't see, what this has to do with making the array bigger. That could be done via dynamic memory allocation (just like the String class does in the background), though that is not a good idea on Arduinos, especially on the ones with low memory, like the ones based on the Atmega328p (Uno, Nano, ...)

Please explain clearer, what you are trying to do and how.

I want to [...] allow the user to program as many outputs as they want

This may be problematic. The microcontroller has a limited amount of
RAM: it will not be able to store arbitrarily long macros. You should
consider a way of telling the user “sorry, no more memory”. Or you can
be optimistic and assume the user will never try to record macros long
enough to exhaust the memory... and let the firmware crash if this
assumption turns out to be invalid.

I currently use the String class and decode within the program but
  it's cpu intensive and not very practical.

CPU intensive? You mean the allocation? Reading the contents of a String
object is not CPU intensive. And what do you find impractical in the
String class? At it's core, it's just a dynamically sized container for
character data, which seems to be exactly what you are looking for.

I haven't found any way to expand the size of an array inside a class.

A class is a data structure of fixed size. There is no way you can
expand its contents. If you need something of variable size, you will
have to use dynamic allocation. You will then only store a pointer to
the allocated memory in your class. This is exactly what String does.
The only other option is to store an array of fixed size within the
class, and make that size large enough so that you never need more.


text:
Uploading a Library to the library manager from a Github branch
I am trying to upload a library to the Arduino Library Manager. I know the GitHub - arduino/library-registry: Arduino Library Manager list repository, and I have already read the instructions, but I have a question that I hope someone can explain to me.
The project I am working on is multiplatform, and to fulfill all the requirements for multiple platforms, many files are not required for the Arduino compilation process. I work around this because, with the help of GitHub actions, I have automated a workflow that publishes a branch within the project with an adequate file structure that complies with the Arduino library specification.
On the library-registry repo, step 7 says: " This should be the URL of the repository home page. For example: https://github.com/arduino-libraries/Servo" I am wondering if, in this section, I can put the link to the Arduino branch on the project.
This would mean to include :
https://github.com/myProfileName/myProjectName/tree/Arduino
Instead of :
https://github.com/myProfileName/myProjectName
With the reasoning that the second URL would contain many files that are not needed in an Arduino environment

What happens when you try it?

I mean, I did not try it because none of the URLs from the repositories.txt seems to have a branch in it, I did a ctrl+f with the keyword tree and found zero results, that's why I opened this question

No. As stated in the instructions for submitting a library to the Arduino Library Manager registry, the URL must be to the home page of the repository.
The way the Library Manager index generation system works:

Clone the repository from the URL that was registered URL.
Check out each Git tag in the repository.
Check to see whether the repository contains an Arduino library at that tag.
Check to see whether the library release at that tag is already in the index.
If it is a valid new library release, add the release to the index.

So there is no problem with having the Arduino library in a different branches in the repository because the indexer doesn't work from branches. It works from tags, which are independent from branches. You must only make sure to make a Git tag at the commit ref in the Arduino library branch of your repository at the point in the revision history where you make a release of the library.
In case you also want to tag other branches, that is fine. Even though tags are the unit of release for Library Manager, the versioning of the library releases is done exclusively using the value of the version field of the library.properties metadata file. So you can add something to the tag names to differentiate the Arduino library release tags from tags made in other branches (e.g., Arduino-1.2.3, 1.2.3).
The one consideration with the release strategy I mentioned above is that the submission validation system that checks for problems with the library when you submit it for inclusion in Library Manager checks out the most recent tag in the repository and does that initial validation on the contents of the repository at that specific tag. So you do need to make sure that the Arduino Library release tag is the most recent tag at the time you submit the library.
Once the submission is accepted, all tags in the repository will always be processed (ignoring those that don't pass Arduino Library validation), so it won't matter if tags from branches that don't contain an Arduino library are the most recent tags in the repository after the library has been registered.

Thanks for your answer. The process makes more sense now. I didn't know that the Library Manager index generation system checked out the git tags. I have to make some adjustments and create the first release for the project. Also, the name differentiation tags are an excellent idea to differentiate releases.


text:
Arduino: Reading PPM values from MQ-131 Ozone sensor
I have this sensor MQ131 by sainsmart: https://www.amazon.co.uk/gp/product/B00NL8XIQG/ref=ox_sc_act_title_1?ie=UTF8&psc=1&smid=A3DRI1TTHCTDIG
All I can read is the analog value which does not reflect the gas concentration. Any Arduino code for that to read the ppm concentration?
How long does the sensor needs to be preheated?

First you need t make it burn for 24hrs mini (48 advised). Just plug it and wait. Then for calibration you need a reference atmosphere free of NOx, CL2 and O3. In this reference atmosphere you should get an output value of 0.
I don't know this model you bought exactly, but most of these gas sensors mounted on a PCB have a mini eeprom so the output is the actual PPM concentration. Note that these sensors are not able to tell you how much of which gas is detected, but only a ppm concentration (you then have to guess which one is in the air). If you have several of these gas in the air, you will not be able to tell their concentration with such a sensor.

Can yuou suggest anyone that can give directly the ppm values instead of just struggling with the interfacing of this model I got from Amazon? @Vincent

this model is giving the ppm after calibration, but the ppm of all these gases together. For example if you have 100ppm CL2 and 200ppm O3, you'll read 300ppm on your arduino. If you want a sensor which will give you the ppm of only one gas, it will cost you much much more.

According to the picture, the sensor is a Winsen MQ131 low concentration (black bakelite version). You can have additional information on the sensor in the datasheet.
Your sensor is mounted on a PCB with some features like converting values (analog to digital), controlling the heater, maybe providing I2C bus... Without any additional information, it's difficult to give guidance on your module (the Amazon link doesn't mention any datasheet for the module).
In order to use your sensor, you can connect it directly on the sensor and pilot it by yourself. You can find some code on GitHub (for inspiration or fork).


text:
DHT22: Library and Data accuracy
I am using DHT22 temperature/humidity sensor and I noticed that there exist so many libraries. I wonder which one is the most accurate?
It is giving me readings that does not seem to be logic. High temperature and very low RH%. Is it because of the library or because I am not connecting 10k or 4.7k resistor?
Thank you so much in advance.
Regards,
Badr Eddine

Did you try other libraries?

Did you try connecting the resistor?

Yes, when I tried other libraries, similar results giving me low humidity level.
I did not try the resistor. Is it mandatory?

have the same problem <20% and in real its 68%

For the DHT units (11 and 22 and AM2302) you want the Adafruit_Sensor and DHT libraries.  Have you tried those?  Plus, it would be very helpful to see your code in a question like this.


text:
Deploy data online from SD Card on Arduino
I intend to design an air pollution monitoring station which will measure these data (CO, NO2, O3, Temperature, Humidity and Pressure). I want to store the data on the SD card during the whole day and deploy it online in CSV format.
I will have five stations in fixed locations and gather their daily data.

Any suggestions about specific types of sensors (references)?
How to store the data as CSV format?
How to send the data online at certain time on Arduino?
Is it better to use GSM or WiFi?

How to store the data as CSV format?

Write the values to the card with commas between them.
myFile.print(noxValue);
myFile.print(",");
myFile.print(coValue);
myFile.print(",");
myFile.println(ozValue);
... etc ...

How to send the data online at certain time on Arduino?

You need to make a suitable network request to whatever unknown thing it is you are sending it to. That may be a HTTP POST request, or it could be some completely different mechanism. Until you have decided where you are sending it we can't help you with the how of sending it.
As to the when, you really could do with a Real Time Clock module so you know what the time is. Then at a certain time you can run your code. Some RTC modules have an alarm that can alert you when it's time to send your code. Great for if your MCU has been placed in a sleep mode and needs waking up at the right time.

Is it better to use GSM or WiFi?

That depends if you have access to WiFi where the sensor is. If you do, then WiFi is (more often than not) cheaper. If you don't, then WiFi is impossible and GSM is the only option.


text:
Gas Sensors with Arduino + Interfacing Circuit
I am intended to use Gas Sensors (MQ series) on protoboard so I connect it to Arduino and perform analogue read.
I would like to request if possible to get the interfacing circuit (resistors, amplification.. etc.) or if there are schematics available.
Also, when I read the data digitized into 10bits ADC value, how can I convert it into units (ppm)?
Thank you so much in advance.

I would suggest checking out one of the gas sensors that comes with a breakout board. I've found the pins don't quite match the spacing of a protoboard and make it a little difficult to set up. Seeed Studio sells some of the sensors with a breakout board and has some nice examples of how to convert the values to PPM.
http://www.seeedstudio.com/wiki/Grove_-_Gas_Sensor(MQ5)

Thanks @kbuck3
Those SeedStudio sensors are ready to be connected but I believe they need special board as shield for the Arduino. or can we connect them directly if you used them before? Thank you.

The "special board" they have in the screenshots is just a shield that makes it easy to use the connector cable. You should be able to just use some female-to-male wires and connect the sensor to your protoboard or Arduino.

You can connect the directly to the Arduino +5, Gnd and Signal.
I don't know of any calibration data for the sensors that I have.  I suppose you could take the maximum concentration the sensor can measure and divide this by 1024, but I don't know if the value returned is linear or logarithmic.
The data sheet does have some info on, but this page may be more helpful
http://forum.arduino.cc/index.php?topic=230945.0
Oh and don't forget the warm up time on the sensors!


text:
I2C multi sensors reading on Arduino
I have several sensors (Grove multichannel gas sensor, Air Pressure Sensor MPX4115A, Temperature and Humidity Sensor DHT11) where most of them uses I2C communication.
I wonder if it is possible to read all of them using the I2C communication on a single Arduino board?

It is possible to use multiple I²C devices, all is needed is for each one to have a different address and the ability to set up the wiring(the other answer points to wriring info).
Of the sensors you listed only one is an I2C device(Grove sensor).
The DHT11 uses a single digital wire to communicate and the air pressure sensor is an analog device. Although you do mention having several devices, the only thing you need to be sure of is if there are no address conflicts, i.e. there being two devices with the same address on the I²C bus.
If address conflicts are an issue most devices provide a way of changing that address, often there are solder jumpers on the board. This allows you to change a devices address to a unique one.

Should be easy enough.  Do you already know how to connect and communicate with one I2C device?  If so, connecting multiple should be simply a case of connecting them in parallel.
If you don't know how to communicate with a single I2C device, then...
For the Arduino software you can use Wire to talk to devices over I2C.
For the hardware, connect the I2C clock and data lines from the Arduino to the I2C devices.  More on that here.


text:
Arduino Data to Cloud without shield []
I am performing basic analogue read like temperature and LDR, reading the data serially, but I would like to deploy it online to cloud platforms like (Plotly, Xively, ThingSpeak, or DataSparkFun). Is that feasible? Thank you in advance.

Without a shield? Yes, it's possible.
You send it serially to your computer as you are doing now. Then you write some software for your computer to read that data serially and send it on to your chosen web service.
Can the Arduino magically send data to the internet by itself without you investing in a network connection of some form (WiFi shield, Ethernet Shield, etc)? No, of course not. If it could there would be no market for the network shields, and so they wouldn't exist.

Thanks @Majenko, any recommended software to deploy the data online? like Python, Node.JS? C#..

@BadreddineZebbiche Whatever you feel most comfortable programming in.

Would it be okay to provide any links? I am more into hardware. Not familiar with both..

Links to what? Just choose a language already. I can't tell you what you are best at programming in. Just pick one and try it. If you don't like it, try another. If you're on Windows you're probably best off using one that is included with something like Visual Studio since that makes it "simple" to program. Personally I program mostly in C or C++ on Linux, but that takes more experience than programming in, say, Python (which I loathe, but some beginners really love).


text:
What will happen if I keep my arduino on for 24 hours?
Please tell me that if I keep my arduino uno on for 24 hours with a adapter, will it get harmed?

This is unanswerable without knowing the voltage supplied and the load on the regulator, especially from any add-on devices, or how the power adapter itself will react.  The ATmega itself should be suited to continuous operation at rated voltage and clock speed, at least in a reasonable thermal environment.

I have one of mine running 24/7.

I have several home-brUnos and a genuine Mega 2560 that are now, or have, run 24/7 for periods of weeks to months, powered by either a USB port or a USB-type wall charger. All of them supported (or still do) a string of 2 or 3 DS18b20 digital thermo sensors and a WiFi or Bluetooth radio. None of them slept during those jobs and they all still live and continue work as well as they always have.

I have a number of Arduinos running 24/7. Nothing bad has happened to them. I suggest if you are running them from a wall-wart style adapter that you choose one supplying voltage at the lower-end of the recommended range. That is, for a Uno for example, with a 7V adapter rather than a 12V one. The reason is that the extra voltage basically has to be thrown away by the voltage regulator as heat.
An adapter supplying 9V would be OK.
An alternative is to get one of those USB chargers that supply 5V (eg. for an iPhone), and use that by running a USB cable to the USB port of the Arduino. Then the voltage regulator doesn't have to do anything at all.

I also have a number of Arduinos running 24/7 and no problems what so ever so far. Just keep the input voltage < 14-15v. because higher voltage = higher temperature (in this case).
In case you need to reset your arduino in code due the long up time you can do that by connecting the reset pin to any output pin and supply logical 0 once every 24 hours for example.

It won't be harmed.
However, if the code crashes, it wont reset itself, so if the code crashes, the purpose of running you Arduino 24/7 will defeat itself.


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

Pull-up resistors are used to define the state of an otherwise "floating" input by pulling the voltage at the pin to a set voltage.
The most typical example is a switch - let's say you have some signal, which is connected to your input through a switch. If the switch is open, the state of your input is "floating". If you try to digitalRead or analogRead that input, the value will be pretty much just noise.
But, if you have a resistor connected from your input to ground (pull-down) or VCC (pull-up) your reading will be consistent (HIGH or LOW, depending on where the resistor goes) while the switch is open.
When the switch is closed, the voltage at the pin will be pulled to the voltage at the other end of the switch.  Because of the lower resistance of the switch relative to your pull-up resistor, this is the input level that will be read by the microcontroller. Pull-up resistors are usually pretty big value (5k-100k) in order to be much higher resistance than the switch and to decrease the current that is used by the switch to produce a signal.
If, for example, you have a pull-up resistor and a switch that connects your input to the ground, when the switch is open you will read HIGH and when it is closed you will read low.
Note that many components act similar to switches, for example transistors, open-drain / open-collector devices and many more, so the switch was just an example.
You can use external pull resistors (just add a resistor from your pin to ground or VCC) or use the internal pull resistors of your MCU.
The Arduino only has internal pull-up resistors (no internal pull-downs) - their value depends on the model, but usually is between 20K-150K.
To activate the internal pull-up resistor for a given pin on Arduino, use the following code:
pinMode(N, INPUT);
digitalWrite(N, HIGH):

where "N" is your pin number or with recent IDEs:
pinMode(N, INPUT_PULLUP);

ok, +1, also change intenral to internal

You can also activate them with: pinMode (N, INPUT_PULLUP); which is the preferred method these days. I think in the case of some other architectures (like ARM) that function call generates the correct code whereas doing a digitalWrite like you showed might not.

A short answer from Arduino Playground:

Pull-up resistors are used in electronic logic circuits to ensure that
  inputs to the arduino settle at expected logic levels if external
  devices are disconnected or high-impedance. 'Just because you have
  nothing at all connected to an input pin doesn't mean it is a logical
  zero.'


text:
Why is there a need to ground a circuit?
Please tell me why I have to connect one of the wires of arduino gnd to the gnd of a relay or a bluetooth module?

If you are constructing a complex circuits or connecting many boards and sensors together, you really need to provide a common ground for all the devices.
The main reason is here we are dealing voltage and different circuits operate at different voltages. It is important to understand that voltage is the potential difference between two points in the circuit. This value is relative to the circuit itself since every circuit has its own ground (GND) pin. What this means is there is no absolute potential difference for a complex circuits. Hence, it is important to establish a common ground such that all potential difference can be measured from a common GND pin.
For instance, consider you have an arduino (operates at 5V) connected to motor controllers or relays (operates at 12V) and there are no common ground established between them. This will mess up the signals from arduino to motor controllers or relays. The output signals coming from the arduino may not be 5V but lower. Therefore, it is not detected by the motor controllers/relays.
I hope this helps.

Electric circuits need to be closed. The hydraulic analogy might help you in this sense: suppose you have a garden fountain and want to recycle its water;  if you want water to circulate by means of a pump, you need a way to put the water back in the pump. That's what the ground connection is for.
Sometimes you have closed circuits using other wires, and a ground connection (or a shorter, direct ground connection) might be required to keep at bay the effect of EMI (electro-magnetic interference).
For example, this is the output of an Arduino Nano sensed by connecting only the tip of the oscillocope probe to pin 13.

And this is the same output when I connected the ground tip to Arduino's GND (actually to the USB frame):


text:
Is there a microcontroller that can output hdmi?
Pretty simple question. Is there a microcontroller that can output hdmi? If not, what microcontrollers can output any type of video?

A Raspberry Pi can output HDMI. A Arduino Uno can output some kind of minimal VGA.

It depends on what you are looking for. There are lots o chips made to control and process hdmi frames. However, as Jot said, the arduino is not suitable for this. The arduino can output basic VGA, but it does not have enough "horsepower" to play with HDMI. The best and cheapest solution is to use a Raspberry Pi.

Arduino does have a board that can do HDMI (the MKR Vidor 4000), though it's cheating a bit by doing it on a FPGA rather than on the microcontroller itself.

RP2040 can output DVI which HDMI monitors can render.


text:
Confusion receiving I2C data from magnetic sensor
So, I've found the address of my device using a I2C device scanner. I then looked up the datasheet for a magnetic sensor I am trying to grab data from.
I'm now trying to communicate with the device by following the 'Example Measurement' section in the data sheet.
Here is my code so far...
#include <Wire.h>
#define address 0b110000 // find the actual address, it is at 0x30, which is 0b00110000

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

void loop() {
  int x, y, z;

  Wire.requestFrom(0b00110000, 1); // START condition?, starts with a 0 to indicate a WRITE request
  if(Wire.available() > 0) {
    Serial.println("1");
    Wire.read();
  }
  Serial.println(Wire.read());
  Wire.write(0b00000111);
  if(Wire.available() > 0) {
    Serial.println("2");
    Wire.read();
  }
  Wire.write(0b00000001);
  if(Wire.available() > 0) {
    Serial.println("3");
    Wire.read();
  }
  Wire.requestFrom(0b00110000, 1); // write request
  if(Wire.available() > 0) {
    Serial.println("4");
    Wire.read();
  }
  Wire.write(0b00000110);
  if(Wire.available() > 0) {
    Serial.println("5");
    Wire.read();
  }
  Wire.requestFrom(0b10110000, 1); // READ request
  if(Wire.available() > 0) {
    Serial.println("6");
    Wire.read();
  }
  // not sure what to do for the 7th cycle???
  // am I even doing the previous correct?
  Wire.endTransmission(address);
  delay(1000);
}

The numbers in each of the if statements represent the cycle within the 'Example Measurement' section of the datasheet, I'm never able to read data from the device and I am sure that I am doing something wrong.
I appreciate any help! This is my first time ever trying to understand I2C, and I've just been staring at this datasheet for too long without getting anywhere.

The Wire.request does not need beginTransmission or endTransmission. Only the Wire.request is needed when data needs to be read. You can use one or more Wire.read or Wire.available if you like. To write data, you need Wire.beginTransmission, Wire.write (none, one, or more) and Wire.endTransmission. You request data from different i2c addresses. Please use: const int mmc3416Address = 0x30;

What is the difference between reading data and requesting data? It seems to me that the Wire.read() depends on which address was called to Wire.begin() whereas Wire.request() takes in an address of the device? Is this correct?

No, sorry, that is not correct. You need to learn about using the Wire library. Start here: https://www.arduino.cc/en/Reference/Wire I think you are confused with a serial port. The I2C functions are similar to the functions of a serial port, but it is not the same, since the I2C uses packets of data, and not a stream of data. The I2C can not read and write at the same time. Either a packet of data is transmitted to a sensor or a packet of data is requested from a sensor.

I have read the datasheet, and it is very confusing, even for me. The Wire library does all the start and stop and handles the acknowledge and set the read/write bit if needed. You don't have to worry about that. When communicating with the sensor, sometimes a delay is needed. The delay is the only odd thing, the sensor is just like any other I2C sensor.

I've never messed with any I2C protocols before, so if the Wire library takes care of all the start and stop and handling acknowledge for me, what exactly do I need to do? It seems like I would be in charge of writing particular bits, as described in the example measurement section. Also, which functions in the Wire library take care of the start and stop stuff for me? Thanks for your responses!

As I wrote before, start here: https://www.arduino.cc/en/Reference/Wire Read on the right what the functions do, and then have a look at a few examples.


text:
Arduino-RS232 converter baud rate problem
i have built a TTL/RS232 converter to send strings via RS232 using an Arduino nano, following the tutorial:Arduino-RS232. My problem concerns the transmission baud rate, because in the tutorial it is suggested a short script which manually generates the code which will become the RS232 signal. In this script some constant delays are used, i.e. "bit9600Delay 100 " and so on. These delays are set for a baud rate of 9600, but i need to double it to have a baud of 19200. Is it enough to divide by two those constant values or should i use a different method? Thank you very much

Do you notice anything when you look at the 4800 baud values?

Dividing by two may not be the best option since bit4800 delay is 188 and bit9600 delay is 100.  Seems like the delay is mainly used for reading the bits that were sent over the RS-232 port.  So this wait time may be good to run at 19200 bps.  After all, it looks to me like it is a simple delay to allow enough time to read back data without having it being distorted (nonsense).

It is never good to base code on delays instead of intervals.  This is especially true for faster intervals where the execution of the code its self consume a significant portion of the interval.  Also note, some protocols only occasionally resynchronize.  RS232 resynchronizes after each byte (about 8 bits of data).  So any accumulated delay errors may impact the integrity of the bits furthest from the resynchronization event.
Instead of delays use the Arduino's built in hardware to send and receive RS232 communications.  The hardware is designed to work independently of code execution and will out perform software implementations especially for the faster baud rates.

The waters might be a bit muddy here.  I think the Arduino's delays are based on the number of ms passed (intervals of time).  So they might be somewhat immune to interrupts.  (That is to say, they may not be simply dumb loop counters.)  Still, the built in processor HW is a much better choice for RS 232 communications.  But, if you need a SW implemented RS 232 port, there are libraries which have already lamented over these problems of balancing code execution time against the necessary delays needed to generate the proper baud rate.

Yes, the normal delay is based on time. delayMicroseconds is a tight loop. This is partly because of the granularity of the timer used for millis, micros and delay.

This Arduino sketch is a wonderful opportunity for you to learn the very basics of serial communication.
You should be very careful scaling the constants given in any baud rate program (whether using a hardware or software UART) as they are normally off by some small percentage, and without understanding the implications you may eventually introduce timing errors.
There is a great description of the timing sensitivities in this Picaxe note.
The table below shows the actual bit times for various baud rates:

Notice here that for 9600 baud the sketch uses a constant which will use a 100 uS delay function for the bit times. From the table above you can see that this is slightly inaccurate, and the more correct delay would be 104 uS. This is an error of about 4%.
Would this error prevent successful reception of characters in the sketch?    Single characters with inter character spaces more than 1 character time, no ....but if you sent a string of characters end to end with no gaps this sketch would fail on receive.
Scaling the constant for 19200 baud --> 100/2 gives 50 but the bit time for 19200 is actually 52 uS, so again an error, this time of about 1%.
If we scaled the constant (100) for 115200 --> 100/12 gives 8.3 uS while 104/12 gives 8.7 uS for an error 4.5% or close to 0%.
There is IMO an error in this sketch for the serial receive routine, since it's hard wired to expect 2 stop bits. Any concatenated characters separated by only one stop bit will fail (you miss the second character start bit).
int SWread()
{
  byte val = 0;
  while (digitalRead(rx));
  //wait for start bit
  if (digitalRead(rx) == LOW) {
    delayMicroseconds(halfBit9600Delay);
    for (int offset = 0; offset < 8; offset++) {
     delayMicroseconds(bit9600Delay);
     val |= digitalRead(rx) << offset;
    }
    //wait for stop bit + extra
    delayMicroseconds(bit9600Delay);     ....hard wired two stop bits
    delayMicroseconds(bit9600Delay);     ....or 1 stop and 1 bit time gap
    return val;
  }
}


text:
Port Manipulation and serial communication
i'm working on a laser timer using arduino and i saw that using direct port manipulation can have a really better time precision. My only concern is about serial communication, because i am using some pins for a software serial, and i don't know how to set them in the ports register. The pins are the 4 and 5, and the number 3 is the trigger output, unluckily this pinset cannot change. How should i set them in the DDRD? I'm using an Arduino Nano board

Don't. Just avoid touching them.

To manage a SoftwareSerial object different from the default Serial, take a look to the "Arduino - Software Serial Example". A possible setting could be SoftwareSerial mySerial(4, 5); // RX=4, TX=5.

A DIY attempt to revise the software serial libraries may not yield improvement - experienced programmers have already done that and published their versions, looking at those alternatives might be productive but reworking the implementation itself will require a fairly advanced understanding to end up with something functional, let alone better.  Also keep in mind that changing the direction of an I/O more efficiently is only a win if it happens often, which wouldn't be the case for an interface where RX and TX have distinct wires.

You can modify a single or multiple bits in a register by using a Read-Modify-Write approach. Essentially something like this:
byte temp = DDRD;
temp = (temp & ~(bitmask)) | bits_to_set;
DDRD = temp;

In the above code, bitmask is some value with the bit or bits you want to modify set - e.g. if you want to change bits 4 and 5, it would be (_BV(4) | _BV(5)) or just (0b00110000). bits_to_set is a value with all bits that you want to be one set - e.g. if you want bit 5 to be a 1, it would be (_BV(5)) or (0b00100000).
What the code does is to first get the current value of the register you want to manipulate. Then it will clear only the bits which you want to modify to 0 by using bitwise AND on the temp value. Next it will set only the bits you want to change to be set by using a bitwise OR. Finally it writes it back to the register.
If you are using interrupts which, you may wish to do this atomically (so that the register is not changed by an interrupt occurring before the new value is written back). You can do this by wrapping the above code in:
byte oldSREG = SREG;
cli();
...
SREG = oldSREG;

Which will clear the global interrupt flag to pause any interrupts, and then will restore the value of it afterwards.

If you just want to change a single bit in a register you can optimise this code down to one of the following examples:
DDRD |= _BV(4); //Set bit 4
DDRD &= ~_BV(5); //Clear bit 5

Again you may want to do this atomically as it may compile to a Read-Modify-Write access.


text:
Removing Robot IR Arduino Library on Macbook
I'm trying to use my IR receiver on my Arduino Uno Board.  First I need to remove my IR Robot library because it interferes with the IRremote library. On my Mac, I have gone into the Arduino/library folder, but the name of the library I have to remove is not there.
I cannot figure out how to remove this. Please help!!

The folder name is RobotIRremote.
It's actually not necessary to remove that folder, though that will solve your problem. A better solution is to change the folder name of the IRremote remote library so that the file named IRremote.h found in that library will be given include priority over the one found in the RobotIRremote library. This is better because you would need to remove the RobotIRremote library every time you update to a new version of the Arduino IDE. The Arduino IDE gives include priority to files that match the name of the library folder but unfortunately if you install the IRremote library manually it will tend to have the folder name Arduino-IRremote-master which causes the wrong file to have priority. So you just need to find that folder and rename it IRremote.
If you don't know where it is the library folder can be found by:

File > Examples > IRremote > AiwaRCT501SendDemo
Sketch > Show Sketch
Folder

So the library name for me is already IRremote, not Arduino-IRremote-master. Still not sure what to change. Also, I don't have a folder name called AiwaRCT501SendDemo under the IRremote --- instead its JVCPanasonicSendDemo.

You not having that example sketch name indicates you're using a different/outdated version of the Arduino-IRremote library. Please post a link to where you downloaded your IRremote library from. Also, please state which version of the Arduino IDE you're using. FYI, the steps to finding the library folder I posted above will work with any example from the library. I just used AiwaRCT501SendDemo because that was the first one shown on the menu for me.

Okay so I just downloaded the latest IRremote library, and it was named Arduino-IRremote-master. So all I have to do is change the name of that library to IRremote and it will work? Also, sorry for the confusion on my end, I'm just beginning with Arduino. Thank you!

Yes, change the name and replace your previous installation of the library with the new one and it should work.

It's not working. I changed the name from Arduino-IRremote-master to IRremote and removed the old IRremote, and it's not working still. Is there anything else I could be doing to make this work?

You still haven't said which version of the Arduino IDE you're using. My tests with the latest version show this should work but the behavior might be different on older IDE versions. You could always just delete the RobotIRremote library.


text:
Can Arduino be used as an FDTI Programmer?
I would like to program my ESP 8266 WiFi module. But I don't have an FDTI right now is there any way to use Arduino Uno as FDTI Programmer then use ESP without it.

Yes. Tie the reset pin on the ISP connector low to keep the ATmega328P in reset, then you can connect pins 0 and 1 to the ESP module to communicate using the Uno's USB-UART bridge. Since the pins are labelled from the perspective of the '328P, connect TX to TX and RX to RX.


text:
Burn new bootloader without crystal
I am considering purchasing these ATmega328 s from
3 pack ATmega328P.
The company says they come with the Arduino UNO bootloader.
I do NOT have any 16 MHz crystals, and I would like to make the chips run on the 8 MHz internal crystal.
I have an Arduino Duemilanove.
Is it possible to burn the minimal setup bootloader from here onto the bootloaded chips without using a crystal?

Have you looked at the datasheet yet?

I'm not sure how much that would help. In the minimal setup description they say the chip will not work when burned with the external crystal bootloader until a crystal (i do not have one) is connected. I was wondering if this applies to bootloader burning as well

Why do you consider buying ATmega with Arduino bootloader if you don't need Arduino bootloader? I'm sure you can finder cheaper sets without any bootloader at all.

I've done just that on a Arduino Pro Mini of mine.
You need to change the fuses to have the chip use the Internal Oscillator, instead of a crystal. After that you just program the 8-MHz version of the bootloader. Like the one used in the Arduino Pro Mini 3.3V.
The only problem is that you need to connect a crystal, to change the fuses to not use the crystal. Though it doesn't need to be 16Mhz. Anything between 1 and 16MHz will do.
But since you need to change both the fuses and the bootloader, there is no advantage to buy chips with the bootloader preinstalled.
I'd just buy some bare chips without the bootloader.
PS $4.66 is on the high side for an ATMega328P-PU.


text:
How to implement an alternating current using only two PWM pins on STM32 Nucleo L053R8?
I am an arduino rookie and definitely not an expert in electronics, even if I do know the physics that is behind it.
Before burning my object of experience, I prefer to ask my silly question to the community.
Context :

I do use a bare stm32 based Nucleo L053R8 board which is arduino compatible.
I want a 1 minute long loop during which I send a 1.5V@20mA impulsion during 1 second and a -1.5V@20mA impulsion 30 seconds later.

Question :

can I simply use and wire two arduino PWM-able pins only to implement that alternating polarity low current? Or will it fail because of unsinked current?

A Nucleo board is not considered an "Arduino" within the meaning of this site - some of them have a physically compatible shield connector, but unless you are running fairly unsupported 3rd party software that you have neglected to mention, they are not software compatible with Arduino, which means your question is not on topic here.  Typically the native development environment for a Nucleo is mbed.

I agree. My Nucleo board is not a real Arduino board, not even fully compatible. By the way, my board has a physically similar shield connector. And yes, I do use mbed.

It's quite hard to understand what you want from your question, it's quite "woolly".
However, I will note:

It's not possible to output a negative voltage from a normal microcontroller.
Getting a specific voltage (accurately) from PWM requires good filter design and a feedback system to keep the voltage within bounds.

I say it's not possible to output a negative voltage - that is with respect to ground. Depending on what you are feeding this voltage into you may not need to reference to ground. In this case it is possible to reference the voltage to another IO pin (steady state, output, not PWM). With it set HIGH the PWM pin's filtered voltage will be below that IO pin's voltage and thus appear, with respect to that IO pin, to be negative.  With the IO pin LOW it will appear, with respect to that IO pin, to be positive.
Once you have filtered your PWM signal you will need the output voltage from it to be monitored by an analog input. That can measure the voltage and make sure that your PWM is set to the right duty cycle. Note that the required duty cycle for any one specific voltage will depend largely on the filtering and the load on the output at the time. You will most likely need some form of PID algorithm to constantly adjust the PWM duty cycle. Also remember that your measured voltage will always be with respect to groud, so you will need to subtract your output reference voltage (the output state of your reference IO pin - high or low) from your measured voltage to get the voltage as seen with respect to the IO pin.

The last 2 sentences in the 2nd paragraph are unclear and incomplete, i think: "With the IO pin (LOW?), it will appear..."


text:
How do I turn off the blinking cursor/caret in the Arduino IDE?
I just purchased a RedBoard, knowing that it would work on Linux, and knowing that it could allow me to easily interface with some electronics project. I am aware of the ino command line tool but I wanted to try interfacing with my board using the Arduino IDE because the latter seems to be somewhat standard. However, when I open the IDE I see a blinking cursor and for whatever reason I can't deal with this. How do I turn off the blinking cursor in the IDE?
I've managed to fix the blinking cursor problem in Firefox, GNOME, KDE, and my terminal... just not sure what to do with Java applications like Arduino IDE.

Workaround; In the settings you can set the IDE to use a external editor. Then you can use an editor that doesn't blink the cursor.

@Gerben: Thank you. Just in case someone else reads this, it is "File > Preferences" and then I check the "Use external editor" box. You don't actually tell Arduino IDE what the external editor is, you just edit the file and the IDE will "see those changes automatically".

As suggested by Gerben, you can go into Preferences and check the box "Use external editor":

Now you can edit with your favourite editing program.
With this option active the IDE will show your sketch but in a non-editable way, and with a blue (cyan?) backwash:

Whenever you save the file in your external editor the IDE will detect the change and refresh the code shown in the internal editor.
Effectively you have replaced the IDE's editor with your own, but still use the IDE to compile and upload your sketches.

Note: does not work with version 1.6.11. Works with 1.0.6

Open the Arduino IDE
Go to File
Then go to Preferences
At the bottom of the page is the file location you can enter to set additional preferences
Exit the Arduino IDE
Go to the preferences file location then set editor.caret.blink=false
Then save
Then restart the IDE and the caret will not flash


text:
problems with Blue Pill (stm32f103c8t6) direct register manipulation
I'm trying to access registers but I keep getting the "was not declared in this scope" error message.
I'm currently using the STM32F1xx boards from http://dan.drown.org/stm32duino/package_STM32duino_index.json
The board package does not seam to recognize any of the registers from the reference manual, mostly trying to access the ADC registers such as 'ADC_CR2'. Does anyone know where I can find the register names which works in the Arduino IDE?

You probably have to include some special header. No idea what, as it's not anything related to Arduino.

@Majenko I'm using the "stm32duino" boards, I thought it was connected to Arduino? :S

stm32duino is a third party package made by Roger Clark. Nothing to do with Ardiuno. Roger's the guy you need to speak to about that core - maybe through github issues if it's hosted there, or find its own forum if there is one.

https://www.stm32duino.com/

you need to use something like this:
ADC1->CR2 = ... ;

note 2 things:

you need to use ADC1, ADC2 ... to access the registers. not just ADC.
you need to use arrow (->) operator to access the registers

and you may need to include the header file, something like this :
#include <stm32f030x6.h>

find the proper header file for your MCU. (it's not the same as stm32f1xx, but if proper definitions are made somewhere, it may also work)

For anyone else having this problem, the registers were called, surprise surprise, ”regs”, so ADC1->regs->CR2.       I still would want to know if theres any easy way to see what a struct contains though, for future problems :)


text:
When does the ADC take the reading?
I'm experimenting with the "2 pin capacitance meter" and trying to make it more accurate. Currently I've made the Arduino read 62.5 ns intervals but this means the time for the ADC to read is taking up a bigger part of the interval. I'm currently using a prescaler value of 8 on the ADC. Unfortunately reading continuously isn't really an option so I am limited to around 8us of read time instead of 6.5us. This isn't that much of a problem since I know that the read will take near 8us from experiments, however I do not know when during that 8us interval the actual reading takes place.
So that is my question, does the adc take the average value during those 8us, does it "lock" the bits at the beginning or when exactly does the reading occur?
Link to capacitance meter, specifically the third one: http://www.circuitbasics.com/how-to-make-an-arduino-capacitance-meter/#comment-363733)

The timing of analogRead() is not critical in the “2 pin capacitance meter” program. Only the time between pinMode(OUT_PIN, INPUT_PULLUP); and pinMode(OUT_PIN, INPUT); (variable t) needs to be known with high accuracy.

@EdgarBonet Why exactly is the timing to pinMode(OUT_PIN, INPUT); the important time, we do take a reading with the ADC after this, does changing the pin mode ”trap” the voltage or what’s going on here?

Yes. The INPUT_PULLUP pin mode charges the capacitor through the internal pullup resistor. The INPUT mode stop the process and, as you say, “traps” the charge in the capacitor. The time between the two mode changes is the charging time, which is the relevant time for solving for the capacitance.

@EdgarBonet Thank you! This knowledge greatly increased the accuracy I am able to achieve. I'm probably just chasing cars at this point, but you don't happen to know when the the voltage is "traped". I'm using PORTC to switch the pullup resistor on and off, and it appears it take only 1 clock cycle, however I am unsure if it's best to measure time before,after or in-between the switches. I'm currently measuring time after I switch.

Read the time either before or after switching PORTC. It doesn't matter as long as you do it consistently. If you took one reading before switching on the pullup and the other after switching it off (or vice-versa), you would have a small timing error. For maximum reliability, do this with interrupts disabled, e.g. cli(); PORTC |= _BV(PC2); start_time = TCNT1; sei();

@EdgarBonet Can switching off the interupts mess with the TCNT2 updating? I mean it’s not an interrupt which causes it to reset to 0 when it overflows in CTC mode, right?

No, TCNT2 doesn't rely on an interrupt for resetting.

The ADC is a "Successive Approximation" type ADC.  It works by:

Taking a snapshot of the incoming voltage in a small capacitor
Generating a reference voltage
Comparing the voltage in the capacitor to that reference voltage
Refining the reference voltage
Go back to 3 until you have the accuracy you desire.

There's lots of "time" involved there:

The capacitor can only store the voltage accurately for so long before the self-discharge (leakage current) causes the voltage to drop (this defines the maximum amount of time you can take to do a reading)
Each refining of the reference voltage and comparison thereof takes one ADC clock tick. There are a few "setup" clock ticks as well. This defines the minimum number of ADC clocks that you need to take a reading (13)
The DAC and comparator take a certain amount of time to operate each clock tick - this limits the maximum clock frequency the ADC can run at.

So you have a "sweet spot" of speed (like the "goldilocks zone" of the solar system). Set the ADC too slow or try and get too high a resolution out of it and you lose accuracy due to voltage droop on the capacitor. Set it too fast and the DAC can't keep up and you lose accuracy due to the comparison voltage not being right.
Well, that's the internals. Then on top of that you have the Arduino API. That adds an entire other layer of complication. analogRead() is a blocking operation.  It:

Congfigures the IO pin (if needed)
Turns on the ADC (if needed)
Configures the ADC MUX to the right channel
Starts a conversion
Sits there twiddling its thumbs for a while
Reads the conversion result
Returns it to you

And it does that (except maybe 1 and 2) every time you take a reading.  That's fine for reading a potentiometer, or an LDR, etc. But rubbish when you want to do fast, time-based, readings.
Instead you need to push the envelope a little and step away from the Arduino API.  Much of what the ADC does is done without intervention of the CPU. Manually configuring the ADC to read continuously and trigger an interrupt when the conversion is done, and then using that interrupt to grab the result of the comparison and start a new one (or use a timer interrupt to read the previous result and trigger a new reading) will give you much more control over the ADC and exactly when things happen.
So, now to answer your main question of "when during that 8us interval the actual reading takes place.", in the context of how the ADC works:
At the moment the SAH capacitor is detached from the MUX to start the comparison sequence.
When exactly is, though, is subjective.  If you use the Arduino API (analogRead()) then it's at some point near the start of the function call, but not at the start of it.
If you configure it manually and trigger it from within a timer interrupt, it's on the second (out of 13) falling edge of the ADC clock after ADSC has been set HIGH.
There are also "Free Running" and "Auto Trigger" modes whose timing is the same as for a single conversion.  Note that the first conversion performed in any mode imposes a "run-in" clock sequence where the ADC MUX and reference voltage DAC are initialised.
All this timing can be found in figures 23-4 and 23-5 on page 209 of the ATMega328P datasheet.  On page 210 there is a handy table that gives you how many ADC cycles from the start of a conversion the Sample And Hold occurs and how long the conversion takes in clock cycles.
For best throughput you want to use "Free Running" mode and read and store the ADC result in the interrupt the ADC triggers.  For most accurate and controllable timing you want to use Auto Triggered mode with a timer for the trigger source, and again read the result in the ADC interrupt.

Wow, this was an amazing answer :D Extremely detailed :D
I don't think Free running mode will work for me, since the analog pins will be used for output and analogRead. However, I did come across the low noise interupt mode which works very well. However, I cannot measure it's speed (since all timers go dead), do you happen to know how long it takes for the arduino to go to sleep and start the ADC? :s


text:
When does the ADC start reading again in interupt mode?
Simple question, I have set my ADC to read in "continuous"/interrupt mode and I take the reading the following way:
ISR(ADC_vect) {
   int val = ADCL;
   val += ADCH << 8;
   ... //Code to do stuff with reading here.
   }

My question is does the ADC start the new reading as soon as I have read the ADCH register or does it wait for the code inside the interrupt to finish? Basically I need to know if having more instructions in the interrupt will slow down my reading rate.
I don't have an oscilloscope or any good way to measure my reading rate accurately enough to know if a few extra lines of codes is affecting the rate or not.

Your answer is correct. The ADC does indeed keep going independently of
what the ISR does. There is, however, a point I would like to make
clearer. You asked:

My question is does the ADC start the new reading as soon as I have
  read the ADCH register or does it wait for the code inside the
  interrupt to finish?

The ADC starts a new reading as soon as it is done taking the previous
one, irrespective of whether you read ADCH or not. When your ISR
starts, the ADC is already busy making the following conversion. This
guarantees a steady conversion rate, at one A/D conversion every
13 ADC clock cycles exactly.
As a side note, you can read the result with
int val = ADC;

No need to read the bytes separately unless you are using a very ancient
version of gcc that does not know how to read a 16-bit register.

Thanks for the clarification :) Quick unrelated question (if you don’t know the answer I’ll delete this comment). In some debugging efforts I hooked up the A0 pin I was reading from to ground with a 300k resistor between them and got some rather significant ( up to 20 ) readings from it, fluctuating like a wave. I would expect it to be 0, what exactly is being measured when doing this? I thought the ADC did not recieve any voltage inside itself so where is the voltage comming from? :s guessing this is related to ”floating pin readings”, but I am still confused.

@BeaconofWierd that's probably your circuit catchinh some electromagbetic radiation and 300kOhm is simply too high to pull the analog pin to ground in that case. If you imagine you increase this resistance, at some point you would consider the pin floating (maybe at 1MOhm or at 100MOhm?).

@BeaconofWierd: I agree with Sim Son that the resistance is too high. According to the datasheet, the ADC should be fed the voltage to be measured from a source with no more than 10 kΩ of internal impedance.

Ok, I'm pretty sure I know the answer to this one now after some more testing. I played around with the number of instructions performed inside the ADC interrupt call and simply timed it using micros(). Though it did not give me super precise accuracy there was a clear and quick drop in read frequency when the number of CPU cycles needed inside the interrupt call exceeded the number of CPU cycles needed by the ADC while the frequency was hardly affected when the CPU cycles needed for the instructions were less than the cycles needed for the ADC. The only way I can make sense of this is if the ADC keeps going independently of the code that's inside the interrupt.
If someone wants to correct me/add some details here I would be very happy. But for my purposes this answer is enough :)


text:
Branchless programing on arduino?
So I've been looking into branchless programming to speed up code and I'm curious as to how exactly Arduino (or rather atmega328) actually reads machine instructions. Does it have a memory cache or does it read every instruction from the flash memory?
From my understanding of branchless programming it speeds up the computation because the CPU does not have to jump inside the instructions and can read it sequentially, hence does not need to load in new instructions in case it has to jump to a location that's not loaded.
My question is, does this apply to the atmega328? If it reads every instruction straight from flash without using a cache then it shouldn't matter much if it has to jump in the instructions, right?

no cache ... no loading of instructions during execution ... you would save a bit of time on each eliminated jump instruction ... so, if you are running an oscilloscope sketch, then run inline code from begining to end

Even inline is just a suggestion though right, and the compiler can do as it pleases? You should also compile with optimization level -O3 for speed instead of -Os for size.

@Beacon of Wierd, post this on https://www.avrfreaks.net/ too to see what they say, and give us a link here to it. I'd like to know, and they have a lot more low-level experts and advanced AVR users over there I imagine.

Branchless doesn't make a lot of sense to me for AVRs. I'd suggest learning to read the assembly code generated by the compiler (avr-objdump -S <filename>.elf). Then compare different versions of your algorithms to each other. I like to use wdt_reset() to add a marker before a certain section I'm interested in. Then in the assembly code look for the wdr instruction.

There is no cache, so you don't need to worry about that. All instructions are fetched direct from flash and executed straight away.
There is, though, a 2-stage pipeline. That means that in one clock cycle an instruction is fetched from flash, and in the next clock cycle it's executed - and while that is being executed the next instruction is being fetched ready.
That means that when a branch occurs, since the AVR uses a very very simplistic approach to branch prediction (i.e., it assumes the branch will not be taken and just loads the next instruction regardless), it has to discard the contents of the pipeline and start from scratch.
That's only a one clock penalty while it loads the newly-branched-to instruction, but it's still a penalty.
Cache is only needed when the CPU core runs faster than the memory can be accessed. Since the AVR only runs at up to 20MHz that is considerably slower than the flash can be accessed, so adding cache would be completely pointless. Other faster MCUs do use caching, such as the 200MHz PIC32MZ, since otherwise "wait states" would have to be introduced to slow the reading from flash down.


text:
Arduino not starting after 1.8.10 update
First off sorry if this is the wrong place.
Yesterday I updated the Arduino IDE to 1.8.10 and I was able to program a couple of hours.
Powering up my laptop today though the IDE is active, I can't switch to it and it shows a white screen if I hover over it in the taskbar below.
When I run the arduino_debug it literally says no error whatsoever it just loads the configuration and start the IDE (5 lines)
Already tried uninstalling and using another version of the IDE

Delete your Arduino data directory, wherever that happens to be on your operating system of choice...

Worked! Also made sure the new installation went into a different folder than it was and that solved it... Thank you :)


text:
How do I read from /dev/ttyACM0 in Linux without a terminal emulator?
I just bought an Arduino Due and I'm having trouble reading from a simple serial IO program.
I have a SparkFun RedBoard which is like an Uno. With that, I just ran a "stty" command to configure the baud rate and other terminal settings, and then I could do "cat /dev/ttyUSB0". Actually I have a C++ program which opens "/dev/ttyUSB01" and reads from it like a normal file.
Now, with the Due, the device is "/dev/ttyACM0" and there have been a few snags. One of them is that after programming the Due, and running stty, I have to open /dev/ttyACM0 using the screen program:
screen /dev/ttyACM0 115200

and then kill screen, before cat /dev/ttyACM0 will work. Otherwise, cat prints out one byte and exits; rarely it prints out 10 bytes or a line, or sometimes it prints nothing.
This is a bit annoying and I can't figure out what screen is doing to the device which I can't seem to accomplish using stty. My stty command is:
sudo stty -F /dev/ttyACM* 115200 -parenb -parodd -cmspar cs8 -hupcl -cstopb cread clocal -crtscts \
-ignbrk brkint ignpar -parmrk -inpck -istrip -inlcr -igncr -icrnl ixon -ixoff -iuclc \
-ixany -imaxbel -iutf8 \
-opost -olcuc -ocrnl -onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff0 \
-isig -icanon iexten -echo echoe echok -echonl -noflsh -xcase -tostop -echoprt echoctl \
echoke -flusho -extproc

I got this by running stty -a < /dev/ttyACM0 after using screen to initialize as above.
I thought it might have something to do with serial auto-reset, so I tried using a resistor between 3.3V and RESET, but this did not fix the problem.
I should note that cu from the uucp package is able to read continuously from /dev/ttyACM0, but unlike screen it does not leave the terminal set up in such a way that a subsequent cat command will work.
$ cu -l /dev/ttyACM0 -s 115200
<continuous stream of data>
$ killall cu             # (from another shell)
$ cat /dev/ttyACM0 | hexdump -c
<e.g. 7 bytes>
$

With screen, cat would have printed an infinite stream. Any ideas how to accomplish this setup without using screen?

You can have stty dump the settings established by screen for future use. See its man page for details.

I thought you'd missed my use of stty -a but then I saw that there's a stty -g ("print all current settings in a stty-readable form"). It doesn't really seem to be documented, but now I see that I can pass the output of stty -g as an argument to stty: stty "0:0:18b2:0:3:1c:7f:8:4:0:1:0:11:13:1a:0:12:f:17:16:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0" -F /dev/ttyACM0. This indeed works, where copy-pasting from stty -a didn't work because I missed the min 1 bit. However, I'm glad for @jantje's solution because now I understand what was going wrong and plus I have a readable command-line.

I have had very similar problems with my yun(shields) and I found the stty command to be very crucial for a good working.
I use following command and it works with mega and due on the yun
stty -F ${PortName}  ${SerialSpeed}  raw -clocal -echo icrnl

Since I call these I can redirect from and to /dev/ttyxxx without problems.
As far as I can see you mis the raw.

That seems to work for me. In fact I narrowed it down a bit: if I just stty -F /dev/ttyACM1 115200 min 1 then it works. The min 1 is part of the definition of stty raw. So I guess the Arduino IDE was putting the terminal into a mode where reads could be non-blocking. I guess I'll use your whole stty command in the future though - the other options look useful, although may I ask why you have icrnl?
Anyway, thank you!

To be honest.... I think you understand far more about this then I do. I started like you; with running a program (minicom in my case) and then querying stty. After 2 years of playing with the yun shield I ended up with these. I'm happy to see they work for you as well. But it is based on trial and error not on knowing. So I can't answer your question.

Well, I'm not sure, but I confess I had a recent issue with a mysterious glitch appearing in my software-oscilloscpe trace around X=13. It went away when I removed the icrnl setting :)


text:
How do I stop the Arduino TX/RX LEDs from flashing? How do I turn off the "ON" LED?
I actually have a SparkFun RedBoard, but I think this question applies to Arduino Uno and other boards as well.
I'm wondering how much control the programmer has over the various LEDs on the board. First there's the "ON" LED which is very bright. Can this be turned off or dimmed, or do I need to resort to electrical tape?
More annoying is the "TX" and "RX" LEDs. These blink rapidly when data is being communicated over the USB-serial connection. I'm guessing these are not configurable, but I couldn't find the answer anywhere online.
I know that the "Pin 13 LED" can be controlled (via Pin 13!).

I'm wondering how much control the programmer has over the various LEDs on the board. First there's the "ON" LED which is very bright. Can this be turned off or dimmed, or do I need to resort to electrical tape?

Remove it, remove the resistor inline with it, or cut the track powering it. Either that or resort to electrical tape (or blu-tack). You have absolutely no control over it.

More annoying is the "TX" and "RX" LEDs. These blink rapidly when data is being communicated over the USB-serial connection. I'm guessing these are not configurable, but I couldn't find the answer anywhere online.

If your board uses an ATMega16U2
As above, or compile a custom version of the ATMega16U2 firmware and flash it on to the ATMega16U2 chip.
If your board uses an FT232 chip
Download the FT232 EEPROM editing program from FTDI and use that to reconfigure the IO pins the LEDs are attached to so they do nothing. If you are on Linux you can use libftdi's ftdi_eeprom program.

According to Sparkfun the board does use an FT232


text:
No Response to AT commands
I'm unable to communicate with my nodemcu ESP8266 module using the AT commands. The module does not return 'ready'  on the serial monitor and entering AT commands has no effect at all. I am able to upload programs onto the module and even receive messages onto the serial monitor. But not for the AT commands.  Please help....

Does your nodemcu have a mini USB port? Then you can actually program it directly through the Arduino IDE. This way you don't even need an Arduino. You'll only need the board files for your nodemcu board.

Or you can choose to use it and flash a program that interprets AT commands itself.

It does have a micro USB port and yeah, I can upload arduino programs onto the board. But again, I'll be needing the AT commands to change stuff like passwords and all which I guess cannot be done through the arduino IDE.  And regarding flashing of a program, could you please elaborate how it can be done? Thank you.

The bare chip knows nothing, just as an Arduino would. The AT+ command set is provided by an interpreter running on the 8266 processor. The AI Thinker modules and others, come with that interpreter already loaded. Your module does not have it installed. And any time you load a program into it, the previous one is over-written.
You can find the AT+ interpreter available for download and upload it to the module, after which it will be able to execute AT+... commands.

AT commands require the installation of firmware that responds to AT commands.
A plain ESP module normally comes with that firmware installed. A nodemcu doesn't. A nodemcu comes with Lua installed instead.

I'm using the arduino IDE. I had downloaded the ESP8266 library within the IDE from the preferences.  So will I have to install the firmware separately again?

Yes. The AI Thinker AT firmware. It's a completely separate thing that is normally preinstalled.

Have you tried connecting the ESP8266 to 5 V?
Some Arduino Uno boards have 2 V output for 3.3 V pin and have 3.3 V output for 5 V pin. 5 V pin can provide more current than 3.3 V pin. I have tried 3.3 V pin and it doesn't work due to lack of current. When I connect it to 5 V pin, it works.

It is always best to check the voltages with a multimeter first, else you could end up frying the ESP8266, if the 5 V does actually supply 5 V.

Use the NodeMCU to process your logic, instead of the Arduino
When using the NodeMCU (or NodeMcLua) you (in a lot of cases) don't really need an Arduino. The ESP8266-12E based "dev boards" with mini-usb connector can be programmed just like an Arduino, using the Arduino IDE.
Why?

The ESP8266-12 is powerfull enough (32-bit 80mhz)
The ESP8266-12 has (usually) enough I/O pins (and you can use an I/O expander if needed)
Adding an Arduino to it is only making the system more expensive.
Adding an Arduino to it is only making the system more complex (and needs additional wiring).

This is especially true for the ESP8266-12 nodemcu boards with mini-USB, since they're "almost" as easy to program as the Arduino.
Configuring the board file
You'll need to be able to select the "ESP8266" as your target, the Arduino IDE has a possibility to use board files for other targets than Arduino. This is best explained on tutorials and other sources online:

Install Arduino 1.6.8 from the Arduino website.
Start Arduino and open Preferences window.
Enter http://arduino.esp8266.com/stable/package_esp8266com_index.json into Additional Board Manager URLs field. You can add multiple URLs, separating them with commas.
Open Boards Manager from Tools > Board menu and install esp8266 platform (and don't forget to select your ESP8266 board from Tools > Board menu after installation).

Sources:
https://github.com/esp8266/Arduino
https://learn.sparkfun.com/tutorials/esp8266-thing-hookup-guide/installing-the-esp8266-arduino-addon
Limitations
When using the ESP8266, you obviously can't use any of the specific hardware features that you could normally use with the Atmega based Arduino's. However, SPI, I2C, UART, analog and digital pins should be ported rather well, and can be used. You are not able to call Atmega328 registers directly (but you may, I believe, call registers of the ESP8266 directly).

Note on the boards.txt not listing your specific ESP8266
You may find that the boards.txt does not list your specific ESP8266 or that it simply doesn't upload (can cause various errors).
Note on Chinese boards with CH340G usb-serial chip
The Chinese boards often come with a CH340G chip, these usb<->uart chips are used to interface the MCU with the PC (over USB, while acting as an USB-COM device).
These drivers for these CH340x chips aren't installed in Windows/Mac on default, you'll have to instal the drivers manually. It can be a little frustrating since these drivers usually aren't signed.

authors: Андрей Тернити


text:
Arduino UNO Chinese Clone LEDs not lighting up

Hi all,
In the screenshot of a circuit I've included, I'm attempting to light up 4 LEDs off of pin 2. In circuits.io, everything works great. 3 blue LEDs and 1 red LED light up and blink as planned. When I create this same circuit on a Arduino Uno Chinese clone, IF the LEDs are all blue, they all light up and blink. If I change one of them to red, yellow, or green, ONLY the red, yellow, or green one lights up. The three blue LEDs no longer light up. It also doesn't seem to matter, where the off blue LED is put.
Not sure what's wrong.

Use one resistor per led, not one for all of them.
This is because different color leds have different forward voltages. Red requires a lower voltage to light up. So it will guzzle up all available current, while the blue leds are waiting for the voltage to go higher (which never happens).

I'd like to note that you may want to calculate the required resistor value. One pin can't supply a lot of current.

Good point @Paul. An Arduino pins shouldn't supply more than 20mA. That's 5mA per led, if you use 4 leds. If you use 1kOhm for each led, like in the diagram above, you should be fine.