text:
Why are there two sets of tools and bootloaders in the Arduino IDE?
After digging around on a separate problem, I found that avrdude, avr-gcc and some more tools can be found in two different locations:
(1): C:\Program Files\Arduino\hardware

(2): C:\Users\<user>\AppData\Local\Arduino15\packages\arduino

These two folders also both contain similar copies of the hardware directory where all the bootloader hex-files and source code is stored:
(3): C:\Program Files\Arduino\hardware\arduino\avr

(4): C:\Users\<user>\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.6.17

I say similar because the bootloaders\caterina folder in (4) contains quite a few hex-files that are missing in (3).
When burning a bootloader, looking at verbose output from the Arduino IDE reveals that hex-file and executable of avrdude from (2) are used, not (1).
What is the reason for this? My guess would be that location (1) is deprecated, but why choose to put stuff like this into Appdata in the first place?

My guess if that 1) if from a previous version. Did you ever update Arduino?

@Gerben I just checked by uninstalling Arduino completely and then reinstalling it. The files in (1) are still there.

Arduino IDE comes with a "platform" (the arduino AVR) in the Arduino\hardware folder.
Then you can add/upgrade platforms with the boards manager.
These will be installed in C:\Users\\AppData\Local\Arduino15\packages.
The reason for this is that Arduino IDE wants to be able to "work out of the box".
If they did not deliver the platform inside the installation/zip a "installation finishing" job needs to run after opening the Arduino IDE.

If that was the case, that would mean that location (4) only contained files of additional board packages. But that's not the case. I just reinstalled and it seems like all arduino files are already in (4) as they were before. The additional boards I had installed are missing now.

Removing the Arduino IDE does not remove the content of C:\Users\AppData\Local\Arduino15\packages.
When you upgrade the avr board they will be in C:\Users\AppData\Local\Arduino15\packages. and those will be used (arduino IDE only supports 1 version of each platform)


text:
Arduino Uno "WiFi Developer Edition" - How to disable WiFi?
I'm using Arduino Uno "Wifi Developer Edition". I made my Arduino to get connected with my local network based on http://www.arduino.org/learning/getting-started/getting-started-with-arduino-uno-wifi
Now I would like to disable it and work with USB serial communication to upload sketches. But now I'm unable to upload sketches even if I select the serial port. I'm getting an AVRDUDE : seropen() Access is disabled error. I could perfectly do uploading if I select the networked port of the same Arduino.
Can I know why ?

The serial should work regardless of the network. You could check the webinterface, but the problem seems to be on the serial side. Though I've never worked with the Arduino wifi

Have you installed al serial drivers and does it show in device manager? And try restarting your PC and running the Arduino IDE as administrator

You don't need to disable the Wi-Fi. The serial works with the Wi-Fi enabled.
You need to first install the driver and then select the Serial port on the Arduino IDE.

did you ever work with Arduino Uno WiFi Developer Edition?

The reason why "Arduino WiFi Dev Ed" USB upload sometimes doesn't work, is the esp8266 connected to UART of Atmega for the OTA upload. If esp8266 doesn't boot, it doesn't set pin 4 to disconnect from Atmega UART and the connection to UART stays and disturbs the upload from IDE.
The esp8266 hangs sometimes, because it has pin 2 floating on this board, but there is a trace and a soldering point on the bottom of the board for pin 2. If it is touched or otherwise grounded the esp8266 doesn't boot until the potential on the pin rises.
More about Uno WiFi Dev Ed hardware here.

source: Stack Exchange

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

sort: votes


text:
Read one(2) hex-adresses from a string
On a 2560 MEGA I use serial(0) and serial1.
Serial1 is connected to an AT-328P   (not an UNO but a single AT controller)
The 2560 use Interrupt (serialevent) and Serial1Event.
Serial(0) is connected to the PC(USB) and is used to get commands that are planned to control both microcontrollers. And RX1 /TX1 (Serial1Event) is connected to the AT-328P .
I plan to use single letter Commands (eg. 'A' , 'B' .... 'Z') followed by a
delimiter (space or comma) again followed by 1 to 4 hexadecimals arguments.
EG:  "A 00,FFFF,AA,00"  or  "B,00,FFFF,33,00"  or "C 00,FF,FFFF,11"  or
"D 01,0000,FFFF,01" or "E,00,0910,1"
Valid delimiters are space, comma and Carriage Return
First argument is the number of the controller (00 = 2560 / 01 = AT328P, second to 4'th is the actual command to the controller.
The problem is parsing the command line from the PC. The one I use is far to slow (I scan the inputBuffer char by char and take my desiscion from that) - much to slow.
Now I want to parse the inputBuffer BEFORE I check the command letter (saving time and get the param's before I go into the specific subroutine) but here I  am i trouble.  I dont' know how to convert the 4 (2) Ascii chars into a valid HEX (or INT) -value.
I have seen some code somewhere ( and naturally forgotten where) doing it, but the methods I have used till now is oldfashioned and (far) out of date, and I am not very good to C++ (but I wanna learn it), so  I will be ashamed showing it.
Can any one give me an idea how to proceed .
Thanks
Kris AKA Snestrup2016

You wrote “The [parser] I use is far to slow”. It's actually pretty hard to make a parser slower than the serial stream that feeds it.

@Edgar Bonet Sorry, what I mean, I use the Serial0event Interrupt and after receiving the CR I parsed the input line. I did that in a most unconvienient way as described in the question. So now I an searching for a new (smarter) way to do it.

DARN, I have just found out, that SERIAL_EVENT IS NOT the same as Interrupt , so I have to rewrite all my code.  (#¤&%¤%&¤%#¤)..  So I will redraw this question  (if possible) and come back later.   Anyway Thanks for any thoughs and help so far.

Yeah, I was about to tell you that. SerialXEvent is just a function that gets called between each iteration of loop(). If you want to make it properly interrupt driven you will have to scrap the HardwareSerial class crutch and write your own UART code.

One thing I added to the chipKIT version of the Arduino-esque API was to have Serial.attachInterrupt(...) so you can intercept the normal ISR for character reception. Maybe something Arduino should think about adding too...

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


text:
Fast I2C communication between ESP8266 & PCF8591
I need faster communication between the ESP and the ADC, so I found this
https://github.com/pasko-zh/brzo_i2c.
Original wire Example
#include "Wire.h"
#define PCF8591 0x48
byte a0;

void setup() {
  Wire.begin(13, 14);
  Serial.begin(115200);
}

void loop() {
  Wire.beginTransmission(PCF8591);
  Wire.write(0x04);
  Wire.endTransmission();
  Wire.requestFrom(PCF8591, 5);

  a0 = Wire.read();
  a0 = Wire.read();

  Serial.println(a0);
  delay(1000);
}

Brzo I2C example
#include "brzo_i2c.h"

uint8_t buffer[10];
uint8_t error = 0;
float temp = 0.0;

uint8_t ICACHE_RAM_ATTR get_temp(float *t) {
  uint8_t bcode = 0;
  brzo_i2c_start_transaction(0x48, 400);
  buffer[0] = 0x04;
  brzo_i2c_write(buffer, 1, false);
  brzo_i2c_read(buffer, 2, false);
  bcode = brzo_i2c_end_transaction();
  *t = ((buffer[0] << 8) | buffer[1]);
  return bcode;
}

void setup() {
  delay(500);
  Serial.begin(115200);
  brzo_i2c_setup(13, 14, 2000);
}

void loop() {
  error = get_temp(&temp);
  if (error == 0) {
    Serial.print("Temp = ");
    Serial.println(temp, 8);
  } else {
    Serial.print("Brzo error : ");
    Serial.println(error);
  }
  delay(500);
}

But I get always the same error.

1 : Bus not free

I rewrote it in different ways, changing the frequency, pins and doing multiple transactions. The main reason I don't get it to work is the difference in the API.
There is no Wire.requestFrom(); in the brzo_i2c lib. So I need to read the value with brzo_i2c_read(buffer,2,false);.

This line
brzo_i2c_start_transaction(0x48,400);

Sets the SCL frequency to 400kHz.
According to the Datasheet for the PCF8591 the maximum SCL clock frequency is 100kHz.
The other issue may be the "repeated_start" flag on brzo_i2c_write.
If you look at the examples, and "apply" that to your code, your would do something like:
uint8_t ICACHE_RAM_ATTR get_temp(float *t){
  uint8_t bcode=0;
  brzo_i2c_start_transaction(0x48,100); // changed 400 to 100
  buffer[0]=0x04;
  brzo_i2c_write(buffer,1,true); // changed to true because
  brzo_i2c_read(buffer,2,false);
  bcode=brzo_i2c_end_transaction();
  *t=((buffer[0]<<8)|buffer[1]);
  return bcode;
}

My understanding of the code is that you would set repeated_start to true in the write if you want to then immediately read - which in your case you want to.

I have no idea about Brzo but this looks wrong:
 brzo_i2c_start_transaction(0x48,400);
 buffer[0]=0x04;
 brzo_i2c_write(buffer,1,false);       // Write
 brzo_i2c_read(buffer,2,false);        // Then a read ??
 bcode=brzo_i2c_end_transaction();

I think you end and read are the wrong way round, but like I say I've never done anything with this so I'm probably wrong.

buffer[0]=0x04;
brzo_i2c_write(buffer,1,false); sets the chip to return the analog values. after that i need to read the chip the first byte is analog input0 2nd = AIN1...

Wire.write(0x04); // control byte - read ADC0 then auto-increment

Like I said, I thought I might be wrong, I thought you had to end the transaction between writing and reading.

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


text:
WiFiEsp not working on Software Serial, working fine on Hardware Serial
What I want to achieve
I want to connect to my wifi network using Arduino UNO and ESP8266 using WiFiEsp.h library over `SofwareSerial, since UNO doesn't have additional H/W serial.
What I am able to do already
I have a Mega, which I am able to connect to my wifi network(using ESP8266) using its hardware serial (RX1 and TX1), I've been following up this code example. Though it has code to deal with both cases( when H/W serial is present and when it's not) It doesn't seems to work on Software Serial on UNO, works perfectly on MEGA's H/W serial. I have made a little change in code as to set the Serial1 baudrate to 115200 as this seems to be supported by my ESP's firmware (1.54)
ERROR
[WiFiEsp] Initializing ESP module
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] Cannot initialize ESP module

What I've tried

Tried running Software Serial on MEGA on pins 10,11 and 6,7 (Rx,Tx) (Same Error).
Swapping Rx,Tx :P
Changing pins to 10,11 instead of 6,7 on UNO
Switching Baudrate to 9600 on UNO (no help)

Yeah, Not much, but it seems so straight forward I can't figure out what could go wrong. It seems like it can't communicate to ESP, but why?

Yes it looks like you can't talk to the ESP over Software Serial.  I have seen that sort of think mentioned on here a few times.  Have you tried hooking the ESP direct to your PC and see if you can read what it is saying.  You baud rate of the ESP looks like 9600, even though the default is 115200.

115200 is too fast for the uno/mega software serial. 9600 can be a problem. 57600 is usually stable. Make sure both ends use the same baud, It has to be rx>tx, tx>rx. Post the code from each.

If you're going to talk to your ESP at 9600 baud - and that's about the upper limit for SoftwareSerial - you need to first change the ESP board's baud rate to 9600 baud. It is probably at 115200 right now.
You can do that with either kind of serial. Even though SoftwareSerial can't receive at 115200, it can usually transmit (Uno -> ESP) that fast. You need to send it the command:
AT+UART_DEF=9600,8,1,0,0

If you do it with SoftwareSerial, the reply coming back from the ESP after changing its baud will be garbled because your serial terminal will still be listening at the faster speed. So at this point, change the speed of your terminal and send the command:
AT

The ESP should respond with
OK

If it does - and it probably will - you're all set and can continue using it at 9600 baud. If not, go back to 115200 baud on your serial terminal and try it again. (I've never had to do it twice).
Update:

I tried sending AT commands @ 115200, Its actually sending and receiving back well at 115200. Is this normal ?

With hardware serial, yes. The Uno's hardware UART can probably go at up to 4x that! But I've never had any luck receiving with SoftwareSerial at 115200; the most I could count on was 9600.

I liked your solution very much, before applying it I tried sending AT commands @ 115200, Its actually sending and receiving back well at 115200. Is this normal ?

i had a similar problem, followed the solution mention, changed the pin to 10,11 did the trick :)


text:
Performing multiple Wire.writes() - does endtransmission slow things down?
Here's a question for anyone knowledgeable of the ways of I2C.
I'm curious about sending multiple writes to a device and was looking at the code for a MPU9250 module.
There is a nice library that compiled straight off the shelf by Kris Winer here.
In one of his code examples he makes multiple calls to a function called writeByte():
// Wire.h read and write protocols
void writeByte(uint8_t address, uint8_t subAddress, uint8_t data)
{
    Wire.beginTransmission(address);  // Initialize the Tx buffer
    Wire.write(subAddress);           // Put slave register address in Tx buffer
    Wire.write(data);                 // Put data in Tx buffer
    Wire.endTransmission();           // Send the Tx buffer
}

here is a (truncated) example of the code calling writeByte():
void initMPU9250()
{
  writeByte(MPU9250_ADDRESS, PWR_MGMT_1, 0x00);
  delay(100);

  writeByte(MPU9250_ADDRESS, PWR_MGMT_1, 0x01);
  delay(200);
  writeByte(MPU9250_ADDRESS, CONFIG, 0x03);
  writeByte(MPU9250_ADDRESS, SMPLRT_DIV, 0x04);
  .
  .
  .
  etc
}

My question is why call Wire.endtransmission() each time your sending I2C to the same device? I can see one reason straight off the bat which is you may need to call delay after your write() - but in cases where you do not need to call delay, wouldnt it be faster to do something like:
Wire.beginTransmission(address);
Wire.write(data1);
Wire.write(data2);
Wire.write(data3);
Wire.write(data4);
Wire.endTransmission();

at least when it's possible?

Nothing happens with Wire until you do call endTransmission(). If you don't call it then nothing will happen - bytes will just get buffered until the buffer overflows.

that makes sense, but how much over head is associated with the endtransmission between bytes versus running them all in and then calling endtransmission? In my case I'll send a block of six bytes total.

100% of the work is in endTransmission. There is no "overhead", it's where the transmission takes place. If what you are sending to can cope with you sending lots of bytes together then you could batch them up and do an endTransmission afterwards, but it's not the endTransmission that you are then optimizing, it's the sending of the address (beginTransmission) that you are optimizing. But it all depends on if the device you are sending to understands what you are doing in that case - most I suspect will not.

Its a reasonable question, but no (as others will explain).

No, Wire.endTransmission() doesn't "slow things down". It is, however, critical to the operation of the Wire library.
When you do a Wire transaction all the data you send is first buffered in an internal array. Only when you call Wire.endTransmission() does that data actually get sent out. The actual Wire.endTransmission() doesn't add anything extra to the transmission though.
In your example you are sending a total of 5 bytes (address + 4 data bytes) plus start/ACK/stop bits. In general most devices require you to send specific numbers of bytes in a specific order - the most common being a register address followed by the content of that register. That means 3 bytes. Any more bytes after that in the same transaction will either be ignored or would overwrite the first bytes.
Some devices though would allow <address><value><address><value> to be sent, thus removing the need for the repeated I2C address byte for the device each time. Many won't though.
Other devices (most notably flash memory or SRAM chips) would allow you to do page mode accesses, which would be <address><data1><data2>...<dataN> where the address would automatically increment for each data byte. Again, some may, some won't.
It is entirely down to the device you are sending data to as to whether you are able to batch together multiple blocks of data, and the form that batching has to be in if it is supported at all. So you should look in the datasheet for the device to see just what it can support.

Might need to mention the internal buffer in Wiring. The size of that buffer will limit the interaction.

Thank you Majenko - the other device in question is a atmega328p running the wire library. I'll try to work out how well it deals with serial Wire.write()s. Thanks.

@OwenWhite Then it is up to you how you create the protocol. If you program it to cope with multiple batched writes then it can cope with multiple batched writes.

I have just dug out the source to Wire to find the maximum buffer size: 32 bytes. That doesn't include the I2C device address, which is stored separately.

Thanks very much for your help. Actually I use the i2c_t3 which looks like the tx buffer length 258. Thanks very much for your comments.


text:
Using an Arduino on a motorcycle
I want to use the Arduino to control various electronics on my motorcycle. I would need to power the Arduino with the motorcycle battery. So the question is, when the motorcycle is running the alternator will be putting out something like 13v to the battery. So can I still just connect the battery directly to the vIn and ground to power it?

Automotive power has a lot of noise and high transients in them. The Arduino a power circuitry has no protection against this. I'd suggest getting the circuitboard out of a cheap car-sigaret to USB power supply and using that.

an LM7808 would take a lot of pressure and heat off the internal LDO while regulating noisy 12v

Accordly to Arduino Technical Specs:
-Input Voltage (recommended)    7-12V
-Input Voltage (limit)  6-20V
https://www.arduino.cc/en/main/arduinoBoardUno
Another Arduino thread:
https://forum.arduino.cc/index.php?topic=22676.0
I would say a better choice is to use another battery power supply just for Arduino. Is is easy to install, easier to handle and more verstile unless you really needs to use your motorcycle battery. And if you want or need to read your motorcycle battery just use a portable voltage meter plugged onto Arduino with no need to use your vehicle battery to power it.

“Arduino need an DC input of 5 volts”: the Vin input is spec'd to take from 7 to 12 V.

For sure, I misundestood. Vin not USB. Im going to fix my answer

Just add a rectifier diode or two before the vin input. This gives you a 0.7V drop per diode for large currents, for small currents the LDO won't overheat anyway...


text:
HC-06 Bluethoot communication
During this week i purchased two hc-06 bluethoot module for arduino with the purpose of maintain a stable bluethoot connection between two arduino devices. Most people use hc-05 and hc-06 togheter so my question is if i can make a connection without hc-05 module.

No.
What you have is two slave devices and you need a master in order to initiate the Bluetooth communication with the slave. So, either you need two HC-05 Or 1* HC-05 and 1* HC-06.

Sorry its not the answer you wanted.

You have purchased two slave modules (HC-06). Actually, you have to use a master module (HC-05) in order to initiate the Bluetooth communication.
Therefore, the answer to your question is NO ,  can not make a connection without HC-05 module, unless you provide any other master module.

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


text:
Use registers as parameter?
I'm writing a helper class to manage timers, and I'm writing a lot of code like
if (timer == 1)
        ICR1 = icr;
    else if (timer == 3)
        ICR3 = icr;
    else if (timer == 4)
        ICR4 = icr;
    else if (timer == 5)
        ICR5 = icr;

Is there a better way to store these registers?
e.g. an array
timers {
{ ICR1, TCCR1A, OCR1A, OCR1B },
{ ICR2, TCCR2A, OCR2A, OCR2B }

etc.
to be accessed like
timers[1][0]

for ICR1.
And ultimately, how would I assign a value? e.g.
*timers[1][0] = 100;

UPDATE:
I solved the problem with
volatile uint16_t* ICRs[5];
ICRs[1] = &ICR1;
ICRs[3] = &ICR3;
ICRs[4] = &ICR4;
ICRs[5] = &ICR5;

*ICRs[1] = x;

afaik, since you assign to a different place each leaf, you can't use a look-up array, you need flow.

registers are nothing but pointers to memory addresses. so the best way to "parameterize" them is to do so via pointers.
assuming that ICRi is of 8-bit types - they are NOT to be sure:
uint8_t *ICRs[4];  //isr pointers

//initialize the icrs
ICRs[0]=(uint8_t *)&ICR0;
ICRs[1]=(uint8_t *)&ICR1;
...

*ICRs[i]=icr; //assign value to ICRi

note: that piece of code isn't operable in reality. The way to go is to use a pointer to void. But I'm sure you can figure that out.

i would suggest creating macro definitions for the timers you want
Something along the lines of:
#define OCR_BY_INDEX(i) OCR##i
//...other code...
OCR_BY_INDEX(1) = value;

and then have the indices in an array

That's wonderful, I didn't know about the token-pasting operator, https://msdn.microsoft.com/en-us/library/09dwwt6y.aspx

Note that this does not work with variables, so OCR_BY_INDEX(timer) does not work. This is a good solution if you don't need that.

You can better use a switch statement:
switch (timer)
{
case 1:
    ICR1 = icr;
    break;

case 3:
    ICR3 = icr;
    break;

case 4:
    ICR4 = icr;
    break;

case 5:
    ICR5 = icr;
    break;

default:
    // Handle other cases
    break;
}

About the variables:
You can make a 2 dimensional array:
typedef enum
{
   TYPE_ICR,   // Value 0
   TYPE_TCCRA, // Value 1
   TYPE_OCRA,  // Value 2
   TYPE_OCRB,  // Value 3
   TYPE_LAST,  // Value 4
} EType;

EType timers[TYPE_LAST][2];

You can access it by
timers[(int) TYPE_OCRB][0] = 3;
timers[(int) TYPE_OCRA][1] = 0;

Maybe the (int) cast is not needed.
You also can just iterate over the type:
for (int type = 0; type < (int) TYPE_LAST; type++)
{
    timers[type][0] = -1;
    timers[type][1] = -1;
}

Note 1: if a cast is needed probably static_cast(...) is better to use.
Note 2: I haven't tested the code above


text:
if condition does not work
I'm trying to connect two Arduinos according to the example in Example
I added a bit of debug prints so the code looks like:
#include <Wire.h>

// Include the required Wire library for I2C<br>#include <Wire.h>
int LED = 13;
int x = 0;
void setup() {
  // Define the LED pin as Output
  pinMode (LED, OUTPUT);
  // Start the I2C Bus as Slave on address 9
  Wire.begin(9);
  // Attach a function to trigger when something is received.
  Wire.onReceive(receiveEvent);
  Serial.begin(9600);
}
void receiveEvent(int bytes) {
  x = Wire.read();    // read one character from the I2C
  Serial.println(x);
}

void loop() {
  //If value received is 0 blink LED for 200 ms
  Serial.print("x = '");
  Serial.print(x);
  Serial.println("'");
  if (x == '0') {
    Serial.println("Do 0");
    digitalWrite(LED, HIGH);
    delay(200);
    digitalWrite(LED, LOW);
    delay(200);
  }
  //If value received is 3 blink LED for 400 ms
  if (x == '3') {
    Serial.println("Do 3");
    digitalWrite(LED, HIGH);
    delay(400);
    digitalWrite(LED, LOW);
    delay(400);
  }
}

The strange thing is, the terminal gives the following information:
...
x = '2'
x = '2'
x = '2'
x = '2'
x = '2'
x3= '3'
x = '3'
x = '3'
x = '3'
x = '3'
...

However, I never see the expected "Do 3" lines. Why is that? I assume if (x == '3) would return true when x = '3'?
Also I see the x3 = '3'instead of x = '3'... now I print x also while an event is received, but are those in two different threads since the expected text would be "3x = '3'")  or "x = '3'3"

Have you tried if (x == 3)?

@KIIV No ... however it works (that was the main problem)... Ah now I see, it's an integer ... strange the website itself contains an error. I would expect initially strings/characters to be sent but it seems everything can be sent. Thanks!

Maybe the author of that instructable never tested it.

Following code is printing value of integer as string.
int x = 0;
...
Serial.print("x = '");
Serial.print(x);
Serial.println("'");

It prints x = '3' for numeric value 3. But ASCII value for character '3' is actually 51.
And about the second issue - reveiveEvent is called from receive ISR asynchronously, so it's completely random when the main code gets interrupted. Btw printing anything inside of ISR is quite tricky. If the output buffer is full or will be filled up inside of ISR, everything gets deadlocked as it needs ISRs enabled.

I really missed the 'int' indeed.
And thanks about the comment about the ISR ... it was just for testing purposes. I know it's not good to process much things in an ISR (from my regular job).


text:
Differences between a real and clone Arduino uno?
Today I got my clone Arduino and connected it to my real Arduino and they both work. (UPDATE: The Arduino noted as real Arduino probably also is not a real Arduino; however both work fine).
However, I see some differences and wonder if these are good or bad:

My questions
1) At number 1 there is on the clone arduino a 12 MHz oscillator? What does it do? And since there is also the regular 16 MHz oscillator I wonder why there are two.
2) At number 2 are 4 holes without any explanation. What is the function?
3) At 3 there are 12 holes (sorry that only 9 are visible, under the blue/black cable are 4 more holes with silver square around them.
4) At 4 there is a SCL and SDA which are used for SPI I think, but these are not on the original Arduino. But the original Arduino has 6 pins at the same location and 4 holes (where 2 of them are marked as JP2).

Might need to check if your original arduino uno is not a counterfeit; https://www.arduino.cc/en/products/counterfeit

@MikaelPatel Probably the other one is not original either, since the text 'designed in Italy' is shown instead of 'made in italy'. But they both work :-)

What is the number on the main chip on the black one?

@Majenko first line: Delta-symbol (triangle) ATMEL, 2nd line: MEGA328P and 3th line: AU 1646

Ah right. I was wondering if it was one of the new B ones with the second UART. Shame.

By the way, the blue the blue one is counterfeit. The silk is wrong for a real one.

For 3 euro I expected something that might not even work :-)

@Majenko: what means 'silk' in this context?

Silk Screen. The white lettering and drawing on the board. The big giveaway is that they used a serif font for the URL. Serif fonts are common on Chinese boards. Arduino, and most "western" designers use a sans-serif font.

ok :-) since I probably will order mostly from Aliexpress, if there will be more Arduino's they might be clones too.

to me it just looks like your new one is an R3, nothing special.

I'm happy with the new R3 (it's my second Arduino anyway).

The best help is the schematics for the clone.

1) At number 1 there is on the clone arduino a 12 MHz oscillator? What does it do? And since there is also the regular 16 MHz oscillator I wonder why there are two.

Lower left on the schematics is the 12 MHz crystal. It is for the CH340G (USB-UART chip).

2) At number 2 are 4 holes without any explanation. What is the function?

Lower middle is the pins X1. They are extra signals from the USB-UART chip (CTS, DSR, R and DCD).

3) At 3 there are 12 holes (sorry that only 9 are visible, under the blue/black cable are 4 more holes with silver square around them.

Upper right on the schematics are the extra pins. This might be handy.

4) At 4 there is a SCL and SDA which are used for SPI I think, but these are not on the original Arduino. But the original Arduino has 6 pins at the same location and 4 holes (where 2 of them are marked as JP2).

The original has an extra ISP pins (ICSP1) for the ATmega16U2. See the schematics. The clone has the new layout I2C signals extending beyond pin 13.

Thank you very much (just for my curiosity), how did you find the schematics? I don't see any clear ID.
Guess it's not bad at all (and it was less than 3 euros).

Web-search "arduino uno ch340 schematics" :) It all about the "magical" index word. In this case the USB-UART ch340 chip.

I didn't know the USB/UART chip would be that important to find the schematics

The trick when constructing a web-search query is to consider the unique and distinguishing attribute, in this case the CH340G chip. This helps the search engine reduce the search space. Using for instance the 12 MHz crystal is not as distinguished as the Arduino itself could use that.

Thanks ... I am new to electronics so I was not aware that the CH340G was the 'unique'  factor. But it will help me in future to find datasheets/schematics as well to know such information.


text:
Why does this sketch give MPU FIFO overflows?
I'm transmitting this program over an NRF24l01, data from mpu, and I'm getting a FIFO overflow. Im not sure what the problem is but it gives me a lag when I put it on processing so I know the problem is in the code. I posted the code the below. Pleas help find the issue.
// Include libraries necessary for the radios
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

RF24 radio(7, 8);

#include "I2Cdev.h"
#include "MPU6050_6Axis_MotionApps20.h"

    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        #include "Wire.h"
    #endif

    MPU6050 mpu;

    #define OUTPUT_TEAPOT

    #define LED_PIN 13 // (Arduino is 13, Teensy is 11, Teensy++ is 6)
    bool blinkState = false;
    // MPU control/status vars
    bool dmpReady = false;  // set true if DMP init was successful
    uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
    uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
    uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
    uint16_t fifoCount;     // count of all bytes currently in FIFO
    uint8_t fifoBuffer[64]; // FIFO storage buffer
    // orientation/motion vars
    Quaternion q;           // [w, x, y, z]         quaternion container
    VectorFloat gravity;    // [x, y, z]            gravity vector
    float euler[3];         // [psi, theta, phi]    Euler angle container
    float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector
    // packet structure for InvenSense teapot demo
    uint8_t teapotPacket[14] = { '$', 0x02, 0,0, 0,0, 0,0, 0,0, 0x00, 0x00, '\r', '\n' };

    // ================================================================
    // ===               INTERRUPT DETECTION ROUTINE                ===
    // ================================================================
    volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
    void dmpDataReady() {
        mpuInterrupt = true;
    }
    // ================================================================
    // ===                      INITIAL SETUP                       ===
    // ================================================================
    void setup() {
        // join I2C bus (I2Cdev library doesn't do this automatically)
        #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
            Wire.begin();
          //TWBR = 8; // 400kHz I2C clock (200kHz if CPU is 8MHz). Comment this line if having compilation difficulties with TWBR.

        #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
            Fastwire::setup(400, true);
        #endif

        radio.begin();

        radio.setRetries(15, 15);
        radio.openWritingPipe(0xF0F0F0F0A1LL);

        radio.stopListening();
        Serial.begin(115200);

        // load and configure the DMP
        Serial.println(F("Initializing DMP..."));
        devStatus = mpu.dmpInitialize();

        mpu.setXGyroOffset(54);
        mpu.setYGyroOffset(15);
        mpu.setZGyroOffset(33);
        mpu.setZAccelOffset(1613); // 1688 factory default for my test chip
        mpu.setXAccelOffset(-4009);
        mpu.setYAccelOffset(332);

        // make sure it worked (returns 0 if so)
        if (devStatus == 0) {
            // turn on the DMP, now that it's ready
            Serial.println(F("Enabling DMP..."));
            mpu.setDMPEnabled(true);

            Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
            attachInterrupt(0, dmpDataReady, RISING);
            mpuIntStatus = mpu.getIntStatus();

            Serial.println(F("DMP ready! Waiting for first interrupt..."));
            dmpReady = true;
            // get expected DMP packet size for later comparison
            packetSize = mpu.dmpGetFIFOPacketSize();
        } else {

            Serial.print(F("DMP Initialization failed (code "));
            Serial.print(devStatus);
            Serial.println(F(")"));
        }
        // configure LED for output
        pinMode(LED_PIN, OUTPUT);
    }
    // ================================================================
    // ===                    MAIN PROGRAM LOOP                     ===
    // ================================================================
    void loop() {
        // if programming failed, don't try to do anything
        if (!dmpReady) return;
        // wait for MPU interrupt or extra packet(s) available
        while (!mpuInterrupt && fifoCount < packetSize) {

          /*Do some computational stuff here*/

        }

        // reset interrupt flag and get INT_STATUS byte
        mpuInterrupt = false;
        mpuIntStatus = mpu.getIntStatus();
        // get current FIFO count
        fifoCount = mpu.getFIFOCount();
        // check for overflow (this should never happen unless our code is too inefficient)
        if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
            // reset so we can continue cleanly
            mpu.resetFIFO();

            Serial.println(F("FIFO overflow!"));
        // otherwise, check for DMP data ready interrupt (this should happen frequently)
        } else if (mpuIntStatus & 0x02) {

            // wait for correct available data length, should be a VERY short wait
            while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();
            // read a packet from FIFO
            mpu.getFIFOBytes(fifoBuffer, packetSize);

            fifoCount -= packetSize;

                /*Object to Transmit Yaw, Pitch, and Roll*/
                typedef struct YPR_TX {
                  int y;
                  int p;
                  int r;

                } YPR_TX;

                YPR_TX ypr_tx;

             //   ypr_tx = calcYPR(ypr_tx.y, ypr_tx.p, ypr_tx.r);

                ypr_tx.y = ypr[0] * 180/M_PI;
                ypr_tx.p = ypr[1] * 180/M_PI;
                ypr_tx.r = ypr[2] * 180/M_PI;

            #ifdef OUTPUT_TEAPOT
                // display quaternion values in InvenSense Teapot demo format:
                teapotPacket[2] = fifoBuffer[0];
                teapotPacket[3] = fifoBuffer[1];
                teapotPacket[4] = fifoBuffer[4];
                teapotPacket[5] = fifoBuffer[5];
                teapotPacket[6] = fifoBuffer[8];
                teapotPacket[7] = fifoBuffer[9];
                teapotPacket[8] = fifoBuffer[12];
                teapotPacket[9] = fifoBuffer[13];

                Serial.print("teapotPacket/t");
                Serial.print("\t");
                Serial.print(teapotPacket[2]);
                Serial.print("\t");
                Serial.print(teapotPacket[3]);
                Serial.print("\t");
                Serial.print(teapotPacket[4]);
                Serial.print("\t");
                Serial.print(teapotPacket[5]);
                Serial.print("\t");
                Serial.print(teapotPacket[6]);
                Serial.print("\t");
                Serial.print(teapotPacket[7]);
                Serial.print("\t");
                Serial.print(teapotPacket[8]);
                Serial.print("\t");
                Serial.println(teapotPacket[9]);
               // radio.getDataRate();

                radio.write(&teapotPacket, sizeof(teapotPacket));

            #endif

            // blink LED to indicate activity
            blinkState = !blinkState;
            digitalWrite(LED_PIN, blinkState);
        }

    }

No need to shout - we can hear you.

Shouldn't you clear the fifo every time you have handled the message or when you start sending a new message? If you usually never clear it, it will get full at some point.

@Paul A FIFO by definition is usually self-emptying.

@Majenko good point, but printing out "fifoCount" may help, to see if/when it starts overflowing or doesn't get handled.

It sounds to me like the MPU is sampling faster than the nRF is able to transmit.

@Eduardo I edited your question and removed the shouting; http://www.netlingo.com/word/shouting.php

@Majenko if thats so, How would I fix the code to it samples slower than the nRF?

I have been playing around with the MPU6050 with DMP library too. I see you have used Jeff's example code (as have I). I was getting a lot of FIFO overflows too, but that was because my "do computational stuff here" was taking too long (code with delay()) and the FIFO on the DMP was filling up. Perhaps your radio.write() is taking too long?
The code as written by Jeff is really quite robust, but perhaps not what is necessary in all cases. I have put an extra mpu.resetFIFO() below the Serial.println's. Kind of a hack, but it works. I found the suggestion here:
How to clear FIFO buffer on MPU6050?
Also check on Jeff's own suggestion of lowering the data rate on the DMP by altering the header file:
https://www.i2cdevlib.com/forums/topic/27-fifo-overflow/#comment-99
Hope this helps.

Yah I  added that and the FIFO overflow goes away. However when you connect it to Processing, the visualization for it " skips" due to this mpu.restFIFO() hack. I'll give it to you anyways but still, its not the right way to fix it.

No, I agree it's not the right way to fix it. But I am not skilled enough to figure out yet what the right way is. Perhaps not resetting the FIFO every iteration of the loop, but once in 3 times might be an idea?
If you are interested, the working code for my sketch, which changes the direction and speed of the pattern on the led strip depending on pitch of the MPU. https://pastebin.com/sU7vEuGf

You are declaring a FIFO overflow every time the mpu sends interrupt 0x10.  Is that correct?
You are using the value in fifoCount before you have set it to a value.  Now with the Arduino IDE you are OK doing that, but its not a good practice.
You are checking that the fifoCount is exactly 1024. It might be better to check if it is >1023 because that will handle the case when it is 1025.
Is there a reason why you have chosen 1024?  Since the packet size defaults to 42 that's 24.3 packets.
Around
while (!mpuInterrupt && fifoCount < packetSize) {

You never get the fifoCount again, so fifoCount < packetSize is always true, therefore you wait until there is an interrupt.  If there first time there is an interrupt is to tell you 0x10 (which I guess is) fifo full from the MPU's perspective) then that will be the reason it is always full.
   // wait for MPU interrupt or extra packet(s) available
    while (!mpuInterrupt && fifoCount < packetSize) {

      /*Do some computational stuff here*/
      fifoCount = mpu.getFIFOCount(); // Don't forget to get the latest fifo size.
    }

1024 was on the MPU6050 datasheet, thats why I left it for that number. So to fix this problem, I should incorporate "fifoCount = mpu.getFIFOCount();" into where I commented " Do some computational stuff here" and put fifoCount > 1023 instead of leaving it at fifoCount = 1024?

I tried what I stated before and I still get a fifo overflow. It is possible to run two loops that we could initialize the MPU-6050 and nRF24L01 after
the counter achieves some number? If so how could I do that?


text:
Directly read analog voltage using PWM duty cycle timer registers
I'm outputting an analog voltage by setting an 8-bit duty cycle using analogWrite. Once set, I'd like a way to read back this duty cycle. I've managed to read the duty cycle back from the OCR4D register, which matches the value set, e.g.:
pinMode(6, OUTPUT);
analogWrite(6, 123);
Serial.print(OCR4D);   // 123

However, when setting the duty cycle to 0 or 255, OCR4D is not actually set at all; instead analogWrite calls digitalWrite behind the scenes and the pin is digitally set to LOW or HIGH. This is seen in the source for analogWrite:
if (val == 0)
{
    digitalWrite(pin, LOW);
}
else if (val == 255)
{
    digitalWrite(pin, HIGH);
}
else
{
// set PWM duty cycle as normal...

The problem with this is that OCR4D is simply left at its previous value, so it's not always possible to tell the actual output by reading OCR4D alone. In other words there is no way to tell the difference between:
- PWM is active and OCR4D reflects the duty cycle
- PWM is disabled and OCR4D reflects a previous duty cycle (which is not useful)
Which register(s) can I read to crosscheck the PWM is active?
I'm also aware of the pulseIn function, but would rather read the PWM register directly.

digitalRead(pin) will tell you if it's 0 or 1

Unfortunately it also turns off PWM for that pin: if (timer != NOT_ON_TIMER) turnOffPWM(timer);. I want to read the value without changing it @dandavis.

i thought you said that PWM was already turned off for those values? you would only use the digitalRead if the other failed.

Ah, sorry @dandavis my question wasn't very clear, I've since updated it. PWM does get disabled for those values, but it's not possible to tell if OCR4D is "wrong" as it always returns a valid duty cycle (it just keeps the old value). What I'm after is a way to tell if the PWM is active and that value is being applied.

ahh. the way i do this in my projects is to define analogWrite2(pin, val), which sets an external array of values by the pin number, then calls the real analogWrite() with the passed values. You can refer to the array from anywhere for a fast reliable read. Just run a replaceAll w/ analogWrite2...

Thanks @dandavis I wanted to avoid caching, but that's also a nice solution.

In the end I managed to do this by reading the timer/counter control register relevant to pin 6:
// read the voltage on an analog output pin
int analogReadOutput(int pin) {
    switch(digitalPinToTimer(pin)) {
        case TIMER4D:
            if (TCCR4C & (1 << COM4D1)) {   // PWM active
                return OCR4D;
            } else {                        // PWM not active
                return 255 * digitalRead(pin);
            }
        case TIMER4A:
            if (TCCR4A & (1 << COM4A1)) {   // PWM active
                return OCR4A;
            } else {                        // PWM not active
                return 255 * digitalRead(pin);
            }
        default:
            return -1;
    }
}

Note that this assumes two things that possibly aren't always true (outside of my simple program):

COM4D1 bit is a reliable way of telling if PWM is enabled,
duty cycle value is 8 bit with a max of 255.

arduino turns on/off the COMx bits for pwm controls -> take a look at turnOffPWM(). So a more reliable way is to read those bits to determine if a pin in in pwm or digital mode. actually a simple modification of turnOffPWM() would be more consistent in my view.

Yes @dannyf that's certainly more reliable. In my case the relevant bit is COM4D1. Edited answer to match.

If your own answer works please accept it.


text:
When writing to SD card the file has all gibberish how do I fix it?
I am working on a class project where I am using a Teensy 3.5 with a Prop Shield with sensor attached that will be loaded into a rocket that I will launch and gather data from the altitude, pressure and temperature sensors and then read into an array and then dump at the peak of the height and when it hits the ground. I believe I have everything working when I test the code but when I open up the txt file I get what looks to be ASCII code but I don't know how to fix it.
Below is the code:
//import statements
#include <SD.h>
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_MPL3115A2.h>

// global variable declarations
Adafruit_MPL3115A2 baro = Adafruit_MPL3115A2();

int seconds = 0;
int secondsPerTick = 0;
int counter = 0;
double pressure[15];
double heightA[15];
double temperature[15];
File myFile;
int tempNum;
const int chipSelect = BUILTIN_SDCARD;

//test to make sure program uploaded
void setup() {
  Serial.begin(9600);
  Serial.println("Adafruit_MPL3115A2 test!");
  while (!Serial){
}

  if (! baro.begin()) {
    Serial.println("Couldnt find sensor");
   return;
  }

if (!SD.begin(chipSelect)) {
    Serial.println("initialization failed!");
    return;
  }

while ( seconds < 5 ){

              double pascals = baro.getPressure();
              pressure[counter] = pascals;
              Serial.print(pascals/3377); Serial.println(" Inches (Hg)");

             double altm = baro.getAltitude();
              heightA[counter] = altm;
              Serial.print(altm); Serial.println(" meters");

             double tempC = baro.getTemperature();
              temperature[counter] = tempC;
              Serial.print(tempC); Serial.println(" *C");
              tempNum ++;

              secondsPerTick++; //increments seconds per tick
              if(secondsPerTick == 3){  //if its 3 reset "secondspertick" and increments "seconds"
                secondsPerTick = 0;
                seconds++;
              }
              counter++;

 }

myFile = SD.open("Sensor4.txt", FILE_WRITE);

   if(myFile) {
    Serial.print("Writing to file...");

    //cycle through the array and store it in the SD card
    myFile.write("Pressure Recordings(going up): ");
    for(int i=0; i< 15; i++){
      myFile.write(pressure[i]);
      }
    Serial.println('\n');

       //header for the height sensor recordings
   myFile.write("Height Recordings(going up): ");
    //cycle through the array and store it in the SD card
    for (int j = 0; j <15; j ++){
     myFile.write(heightA[j]);
    }
    Serial.println('\n');

    //header for the temperature sensor recordings
    myFile.write("Temperature Recordings(going up): ");
    Serial.println('\n');
    //cycle through the array and store it in the SD card
    for (int k = 0; k <15; k++){
     myFile.write(temperature[k]);
    Serial.println('\n');
   }

    // close the file:
    myFile.close();
    Serial.println("done.");
    }
   else {
    // if the file didn't open, print an error:
    Serial.println("error opening sensor_recordings.txt");
  }

     //as the rocket descends
while ( seconds > 5 ){

              double pascals = baro.getPressure();
              pressure[counter] = pascals;
              Serial.print(pascals/3377); Serial.println(" Inches (Hg)");

              myFile.write(pressure[counter]);

             double altm = baro.getAltitude();
              heightA[counter] = altm;
              Serial.print(altm); Serial.println(" meters");

             double tempC = baro.getTemperature();
              temperature[counter] = tempC;
              Serial.print(tempC); Serial.println(" *C");
              tempNum ++;

              secondsPerTick++; //increments seconds per tick
              if(secondsPerTick == 3){  //if its 3 reset "secondspertick" and increments "seconds"
                secondsPerTick = 0;
                seconds++;
              }
              counter++;

 }

myFile = SD.open("Sensor4.txt", FILE_WRITE);

   if(myFile) {
    Serial.print("Writing to file...");

    //cycle through the array and store it in the SD card
    myFile.write("Pressure Recordings(going down): ");
    for(int i=0; i< 15; i++){
      myFile.write(pressure[i]);
      }
    Serial.println('\n');

       //header for the height sensor recordings
   myFile.write("Height Recordings(going down): ");
    //cycle through the array and store it in the SD card
    for (int j = 0; j <15; j ++){
     myFile.write(heightA[j]);
    }
    Serial.println('\n');

    //header for the temperature sensor recordings
    myFile.write("Temperature Recordings(going down): ");
    Serial.println('\n');

    //cycle through the array and store it in the SD card
    for (int k = 0; k <15; k++){
     myFile.write(temperature[k]);
    Serial.println('\n');
   }

    // close the file:
    myFile.close();
    Serial.println("done.");
    }
   else {
    // if the file didn't open, print an error:
    Serial.println("error opening sensor_recordings.txt");
  }
 }

void loop() {

Here is what gets printed to the txt file:

€€€ƒ€ƒ‚ƒ€€„~ƒ‚€€€€ƒ€ƒ‚ƒ€€„~ƒ‚€ƒ‚‚‚„‡€„ƒ„……ƒ‚ƒ„Pressure Recordings: ƒ‚‚‚„‡€„ƒ„……ƒ‚ƒ„
  Height Recordings: 10010110010101111000Temperature
  Recordings: Å……ƒƒ…€€ƒ‡‚w
  Pressure Recordings: Å……ƒƒ…€€ƒ‡‚w
  Height Recordings: 000010100010111     Temperature Recordings:      Pressure Recordings: Å……ƒƒ…€€ƒ‡‚w     Height Recordings: 000010100010111     Temperature Recordings:      Pressure Recordings: Ã‡…„†…„…„ˆ†„„€†     Height Recordings: 000000000000000     Temperature Recordings:      Pressure Recordings: Ã‡…„†…„…„ˆ†„„€†     Height Recordings: 000000000000000     Temperature Recordings:      Pressure Recordings: Â†‰†‡…††‰…‰ˆˆ…ˆ Height Recordings: 000000000000000     Temperature Recordings:      Pressure Recordings: Â†‰†‡…††‰…‰ˆˆ…ˆ Height Recordings: 000000000000000     Temperature Recordings:      Pressure Recordings(going up): ÀŽ‘ŽŒŽŽHeight Recordings(going up): ///000/0/0/0///Temperature Recordings(going up): Pressure Recordings(going down): ÀŽ‘ŽŒŽŽHeight Recordings(going down): ///000/0/0/0///Temperature Recordings(going down): Pressure Recordings(going up): ½–™––•˜–••š™š—™Height Recordings(going up): ///////////////Temperature Recordings(going up): Pressure Recordings(going down): ½–™––•˜–••š™š—™Height Recordings(going down): ///////////////Temperature Recordings(going down):

I also don't know how I can get the data to be formatted to where it reads like:
Pressure(going up):----
Altitude(going up):---
Temperature(going up):---
Pressure(going down):----
Altitude(going down):---
Temperature(going down):---

If you want the data stored as text instead if binary, use myFile.print() instead of myFile.write().

You should convert double to String with this kind of code:
char[9] stringval;
dtostrf(doubleval, 8, 4, stringval);

where 8 is presicion and 4 is number of digits after point.
More info: http://forum.arduino.cc/index.php?topic=282250.0

How would I implement that into my code? Sorry I'm new to Arduino and all of this has been trial and error for the most part with lots of Googling


text:
How to code water flow sensor and solenoid valve?
I want to know if it is possible to put a boundary or limit to the volume that passes through a water flow sensor, and close the pipe using a solenoid valve.
Example: I only want 400 ml of water to pass, so when the water flow sensor reads how much water has passed in the pipe, if 400 is reached, the solenoid will close the pipe.
Sorry for my bad English, it is not my first language. I'm hopping that someone can help me out.

A snippet of code please .. And a explanation

The time that your solenoid is open, could also be an indication of the amount of water passed.

Have you asked the manufacturer of the water flow sensor how it works? What have you tried yourself? What model numbers do these sensors/actuators have? Have you actually tried something? There is no way that we can/will provide code for a project that we do not know the details or issues of...

I try some codes i find in the internet here http://www.bc-robotics.com/tutorials/using-a-flow-sensor-with-arduino/  and the brand and model of my water flow sensor is sea model yf s201 .. i dont have any idea on how to achieve that or to be able to put limit .

hello @kaisar Great you have not mentioned which flow sensor are you using. I am assuming that you are using flow sensor YF-S201 or YF-S401(Hall Effect).You have to do Little calculation for measuring water flow.
In order to measure the quantity of water being passed in particular time through the water flow sensor it was first passed through the water flow sensor which was taken as input interface in the flow. Formulas are applied in order to measure the number of rotations/pulses in a minute of rotation.
Here I have determined flow rate by change in velocity of water. Velocity depends on the pressure that forces the through pipelines. As the pipe’s cross-sectional area is known and remains constant, the average velocity is an indication of the flow rate. The basis relationship for determining the liquid’s flow rate in such cases is
Q=VxA, where Q is flow rate/total flow of water through the pipe, V is average velocity of the flow and A is the cross-sectional area of the pipe
Calibration Factor = The hall-effect flow sensor outputs pulses per second per litre/minute of flow.(check your datasheet) here I have taken 4.5.
Flow Rate(litres/minute) = ((1000.0 / Total time) x Pulse Count) / calibration Factor
Flow Rate(MilliLitres/Second) = (Flow Rate / 60) x 1000
There you have to calculate the total water flow in a given time by adding flow rate for each second.
There after you have check your set point value(400ml)..if condition satisfied you you can turn off your Solenoid valve.
and the code is
int sensorInterrupt = 0;  // interrupt 0
int sensorPin       = 2; //Digital Pin 2
int solenoidValve = 5; // Digital pin 5
unsigned int SetPoint = 400; //400 milileter

/*The hall-effect flow sensor outputs pulses per second per litre/minute of flow.*/
float calibrationFactor = 4.5; //You can change according to your datasheet

volatile byte pulseCount =0;

float flowRate = 0.0;
unsigned int flowMilliLitres =0;
unsigned long totalMilliLitres = 0;

unsigned long oldTime = 0;

void setup()
{

  // Initialize a serial connection for reporting values to the host
  Serial.begin(9600);
  pinMode(solenoidValve , OUTPUT);
  pinMode(sensorPin, INPUT);
  digitalWrite(sensorPin, HIGH);

  /*The Hall-effect sensor is connected to pin 2 which uses interrupt 0. Configured to trigger on a FALLING state change (transition from HIGH
  (state to LOW state)*/
  attachInterrupt(sensorInterrupt, pulseCounter, FALLING); //you can use Rising or Falling
}

void loop()
{

   if((millis() - oldTime) > 1000)    // Only process counters once per second
  {
    // Disable the interrupt while calculating flow rate and sending the value to the host
    detachInterrupt(sensorInterrupt);

    // Because this loop may not complete in exactly 1 second intervals we calculate the number of milliseconds that have passed since the last execution and use that to scale the output. We also apply the calibrationFactor to scale the output based on the number of pulses per second per units of measure (litres/minute in this case) coming from the sensor.
    flowRate = ((1000.0 / (millis() - oldTime)) * pulseCount) / calibrationFactor;

    // Note the time this processing pass was executed. Note that because we've
    // disabled interrupts the millis() function won't actually be incrementing right
    // at this point, but it will still return the value it was set to just before
    // interrupts went away.
    oldTime = millis();

    // Divide the flow rate in litres/minute by 60 to determine how many litres have
    // passed through the sensor in this 1 second interval, then multiply by 1000 to
    // convert to millilitres.
    flowMilliLitres = (flowRate / 60) * 1000;

    // Add the millilitres passed in this second to the cumulative total
    totalMilliLitres += flowMilliLitres;

    unsigned int frac;

    // Print the flow rate for this second in litres / minute
    Serial.print("Flow rate: ");
    Serial.print(flowMilliLitres, DEC);  // Print the integer part of the variable
    Serial.print("mL/Second");
    Serial.print("\t");

    // Print the cumulative total of litres flowed since starting
    Serial.print("Output Liquid Quantity: ");
    Serial.print(totalMilliLitres,DEC);
    Serial.println("mL");
    Serial.print("\t");
    If (totalMilliLitres =< 400)
    {
      SetSolinoidValveON();
    }
    else{
      SetSolinoidValveOFF();
        }

// Reset the pulse counter so we can start incrementing again
    pulseCount = 0;

    // Enable the interrupt again now that we've finished sending output
    attachInterrupt(sensorInterrupt, pulseCounter, FALLING);
  }
}

//Insterrupt Service Routine

void pulseCounter()
{
  // Increment the pulse counter
  pulseCount++;
}

void SetSolinoidValveON()
{
  digitalWrite(solenoidValve, HIGH);
}
void SetSolinoidValveOFF()
{
  digitalWrite(solenoidValve, LOW);
}

What is the difference between RISING and FALLING in this line of code attachInterrupt(sensorInterrupt, pulseCounter, FALLING);

Actually working principle of this flow sensor is its produce pulses(Square Wave) proportional to flow rate of liquid.  When a circuit is rising edge-triggered, it becomes active when its clock signal goes from low to high, and ignores the high-to-low transition. A falling edge is the high to low transition.

I try this code and it doesn't work , totalMilliLitres stores total liters flowed since starting and it will close the solenoid once .

You have to first modify this code according to your flow sensor datasheet otherwise its gives erroneous result cause parameters are assumed based which I given in this code so it will not match with your flow meter datasheet. anyway upload your skech and output along with your flow sensor datasheet

Using a YF201 you cannot measure less than 1 litre / minute or more than 30 l/m.
(ref http://www.bc-robotics.com/tutorials/using-a-flow-sensor-with-arduino/)
The device sends a pulse for every 2.25ml that flows through it.  All you needs to do is take the amount you want to let through (400ml) and divide that by 2.25ml and you get 177.8 pulses.  So once your Arduino counts 178 pulses then you trigger the valve to close.
Its not going to be very accurate, because unless the valve closes instantly there will be a bit of an overshoot.  and you have to measure in units of 2.25ml.


text:
How Arduino IDE works?
You know , a simple arduino sketch has no main function , no include preprocess cmds,so I just want to know how arduino IDE convert a sketch to normal C/C++ source code,and what is the source code looks like.
If possible,I also want to use cmd like  g++ -E   to see the .i file genetated after preprocess.How to do it?
ps: my English is poor.

https://www.youtube.com/watch?v=V-K9tzRqCqM I think this video is the best answer

You can turn on verbose compiling.
This will show all the compiler commands used by Arduino IDE.
The ino file is converted to a .cpp file (which you can see in the verbose output). Basically the conversion is as follows:

merge all .ino files into one big .ino file with the [project].ino
file first
Add arduino.h
Add all function declarations of methods defined in the .ino files
Save as .cpp file

As to the lack of main method.
The core contains a main.cpp file which defines main in avr world this looks like
int main(void)
{
    init();

    initVariant();

#if defined(USBCON)
    USBDevice.attach();
#endif

    setup();

    for (;;) {
        loop();
        if (serialEventRun) serialEventRun();
    }

    return 0;
}

yes,I get it!  I post a brief artical abouts this.link thx :)

I'm not entirely sure what the arduino-builder does, but it should be similar to the traditional method.
Given the "bare minimum" sketch of:
void setup() {
}

void loop() {
}

First the IDE combines all .ino and .pde files together into one large one. I believe the order of concatenation is:

Start with the "main" INO file (the one named the same as the folder it's in).
Append to that each other .ino or .pde file in alphabetical order.

Then the IDE will add the required #include <Arduino.h> and function prototypes for any functions found - so it would end up as:
#include <Arduino.h>

void setup();
void loop();

void setup() {
}

void loop() {
}

Finally it runs normal gcc and g++ commands on the generated file(s).  You can find the generated file(s) in the build folder. Where that is depends on the operating system you are using.  Turn on verbose compilation in the preferences and you can see the gcc and g++ commands that are being executed, and as well the paths for the files involved, which lets you then see where the preprocessed files are stored.
Another important step the IDE performs, which doesn't modify the files themselves, is to look for any #include entries that match libraries and add -I <path> to the compilation commands for those libraries. It also then finds any source files associated with those libraries and compiles them. It also compiles all the core source files, which is where the main() functions is (see @jantje's answer for details on how the main() function is formed).
Once the IDE has finished with its parsing and processing it's all standard gcc and g++.

you beat me ;-)

your answer is helpful! thx! :)


text:
Arduino nano select port option is blurred | Driver issue
I have just bought arduino nano board. when i connect the board via usb, system detects the new device but i am not able to select port in arduino ide for writing any code on board. I checked my device manager it says

The drivers for this device are not installed. (Code 28)
There are no compatible drivers for this device.

I have also updated my board and library list in arduino ide.
please help me out?

What USB<->uart chip is on the board? Usually on the back (often FTDI, CH340G or CPxxxx).

CH340 is on board

My PCs and Raspberry Pis that I use to program Arduinos all have already had the CH340 driver installed.  Vista, Win7, Win8.1, Rpi3B with Raspbian - all worked fine.  But it is possible you need to install a driver.  I see your answer describes how to do so.  Kudos.

on my nano board CH340G USB<-->uart chip was present, so i installed driver for that chip and everything works fine now. :P
link for the driver (windows 8,10): http://www.arduined.eu/ch340-windows-8-driver-download/

Good, looks like you managed to fix the issue yourself!

This is good information to have in the stackexchange database.  Thank you for posting the link.


text:
"No Socket available" for WiFiClient
I have an LDR/Photocell which sends a value 1 or 0 (depending on the value) to a text file on my web address. The code works for a few seconds then prints out No Socket available.
Any help will be appreciated; code below.
#include <SPI.h>
#include <WiFi.h>

int LDR = A0;
int LED = 11;
char ssid[] = "SSID";
char password[] = "password";
int status = WL_IDLE_STATUS;

char server[] = "www.example.com";
int value;

void setup() {
  Serial.begin(9600);
  pinMode(LDR, INPUT);
  pinMode(LED, OUTPUT);
  connectWifi();
  printWifiStatus();
  // postData();
}

void loop() {
  value = analogRead(LDR);
  postData();

  delay(10000);
}

void connectWifi() {
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to ");
    Serial.println(ssid);
    status = WiFi.begin(ssid, password);
    delay(500);
  }
}

void printWifiStatus() {
  // Print the SSID of the network you're attached to
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // Print your WiFi shield's IP address
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // Print the received signal strength
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

void postData() {
  WiFiClient client;
  if (client.connect(server, 80)) {
    Serial.println("Connecting...");
    if (value > 350) {
      Serial.println("0");
      digitalWrite(LED, LOW);
      String data = "value=0";
      client.print("GET /example/client.php?");
      client.print(data);
      client.println(" HTTP/1.1");
      client.println("Host: www.example.com");
      client.println("Connection: close");
      client.println(); client.println();
      //client.stop();
    } else {
      Serial.println("1");
      digitalWrite(LED, HIGH);
      String data = "value=1";
      client.print("GET /example/client.php?");
      client.print(data);
      client.println(" HTTP/1.1");
      client.println("Host: www.example.com");
      client.println("Connection: close");
      client.println(); client.println();
      //client.stop();
    }
  } else {
    Serial.println("Connection failed");
    client.stop();
  }

}

Output:
Attempting to connect to SSID
SSID: SSID
IP Address: 255.255.255.255
signal strength (RSSI):-47 dBm
Connecting...
1
Connecting...
0
Connecting...
0
Connecting...
0
No Socket available
Connection failed
No Socket available
Connection failed
No Socket available
Connection failed
No Socket available

Actual web address omitted.

The text  “No Socket available” isn't in any of the Serial writes shown.  What program produces it, and where does it appear?  Also, perhaps edit question with cut and paste of serial monitor output (as text, not as picture)

@jwpat7 Thanks for that, updated the question.

Do any of the suggestions in Arduino wifi shield - “No Socket available” help?

I assume you actually have a server listening to port 80.  Also are you sure you should be using the WifiClient and not a HttpClient object?

I guess you have commented the command:
 //client.stop();
If you allow it, I guess you will have your code running


text:
How to generate two pulses one with 60 and other 66 duty cycle at same instant in 2 pins?
I have to drive two switches one at a duty cycle of 60% and the other at a duty cycle of 66% simultaneously at 50khz frequency. I am using an Arduino Uno ATmega 328.

Set Timer 1 to waveform generation mode 14, with both outputs in non-inverting mode and ICR1 = 319; OCR1A = 191; OCR1B = 210;.

I proposed a few approaches in generating 100kha pwm pulse trains here in response to someone's ask a couple of days ago. The identical code would work for your purpose as well.
It should come up quickly if you do a scan of topics here.
edit: to make it a little bit easier, here is the code I used to generate 50Khz pulse train with 60% and 66% duty cycles.
void setup() {
  // put your setup code here, to run once:
  //pinMode(led1, OUTPUT);                      //led1 as output
  //pinMode(led2, OUTPUT);                      //led2 as output
  pwm1topr(F_CPU / F_PWM);                      //set tmr1/pwm frequency to F_PWM
  analogWrite(led1, F_CPU / F_PWM * 60 / 100);  //led1 @ 60% duty cycle
  analogWrite(led2, F_CPU / F_PWM * 66 / 100);  //led2 @ 66% duty cycle
}

void loop() {
  // put your main code here, to run repeatedly:
    //digitalWrite(led, HIGH);  // turn the LED on (HIGH is the voltage level)
    //delay(100);               // wait for a second
    //digitalWrite(led, LOW);   // turn the LED off by making the voltage LOW
    //delay(100);               // wait for a second
}

and a quick sim confirms its functionality.

enjoy.

What's a kha ?  Also, please add link for the previous answer, instead of that copout.  Was it perhaps  how can i generate square pulse at 50khz frequency to drive two mosfets at a duty ratio .6, which is almost a duplicate of this question, except for having only one .6 duty cycle instead of a .6 and .66


text:
Fastest way to send serial commands and do something
I am trying to send a lot of serial commands really fast. I basically need to change color of my LED strip many times per second (10 times per second should really be enough). If I do this over WiFi, it will eventually clutter up and make the ESP8266 unresponsive. I need to send the colors as hex, then convert them into usable values (HEX to RGB). Something tells me that's going to cost a lot of resources and the MCU is therefore spending a lot of time just converting the colors into RGB values. Here's a pseudo code example of what I am trying to achieve:
void loop() {
    if(Serial.available()) {
        if(Serial.read().first(8) == "0xABCDEF") {
            //0xABCDEF is basically my indicator saying "this is for individual LEDs"
            //Serial.read() can now be something like 0xABCDEF FF0000 00FF00 0000FF FFFFFF 000000
            char* colors[] = Serial.read().split(" ");
            colorLED(colors);

        }
    }
}

void colorLED(colors) {
    for(i = 1; i < colors.length; i++) {
        strip.SetPixelColor(i, color[i]);
    }
}

I hope this example makes sense. I can send a serial command like 0xABCDEF FF0000 00FF00 0000FF FFFFFF 000000. 5 colors in HEX.
My real question is: How do I take a lot of inputs like above (or another way) and turn them into strings, so I can convert them to RGB? Is there a better way to send commands (like pure RGB values? but remember I need to send many)?. Here is how I convert my colors into RGB:
//hexColor can be "FF0000"
int number = (int)strtol(&hexColor[0], NULL, 16);

int r = number >> 16;
int g = number >> 8 & 0xFF;
int b = number & 0xFF;

Simple answer: don't.
Don't even consider strings in any form. Instead you want a state machine.
In pseudocode:

Start with an invalid count number (-1)
Read a character.
If that character is x then set your counter to 0.
Otherwise, if counter is 0 or more, convert the character to a number and place it into the right byte depending on the value of your counter
Increment counter
If counter is 6 then set your LED colours and set the counter to "invalid".
Return to start.

Or, in untested C:
static int8_t counter = -1;
static uint8_t r = 0;
static uint8_t g = 0;
static uint8_t b = 0;

if (Serial.available()) {
    char c = Serial.read();
    if (c == 'x') {
        counter = 0;
    } else {
        if (c > 0x39) c -= 7;
        uint8_t v = c & 0x0f;
        switch (counter) {
            case 0: r = v << 4; break;
            case 1: r |= v;
            case 2: g = v << 4; break;
            case 3: g |= v;
            case 4: b = v << 4; break;
            case 5: b |= v;
        }
        counter++;
        if (counter == 6) {
            counter = -1;
            analogWrite(3, r);
            analogWrite(5, g);
            analogWrite(6, b);
        }
    }
}

The "clever" bit that may confuse you is:
if (c > 0x39) c -= 7;
uint8_t v = c & 0x0f;

That is, if the character is greater than a "9" (character 0x39) then it should be a-f. Subtracting 7 from it converts ASCII HEX from 0123456789ABCDEF to 0123456789:;<=>?.  If you then mask it with 0x0F you end up with a number between 0 and 15, or 0-F in hex.
The rest just takes each nibble and places it into the right half of the right colour variable.

Damn, I see that is pretty freaking fast! Immediately when I send the command, it's being sent to the serial monitor (even using Serial.println() which I assume is somewhat "slow"). That works pretty damn well! Thanks a lot for the help!

Sorry for hijacking this, but while I have an experienced person here: I use Makuna's NeoPixel library. This requires me to set my LED strip to the RX on the ESP8266. I currently use the NeoEsp8266Dma800KbpsMethod method, which you can read more about here, and this means Serial.read() will be unavailable (as far as I understand). Do you happen to know if there is an alternative? I did try all the other ones, but unfortunately none of them worked. I think I need to hook it up to another pin, so RX/TX is free (at least RX is)

I don't know what is available for the ESP8266. There is probably a software serial implementation, but I don't like them much, they tend to mess with interrupts and block things from happening. Better would be if you could use some other communication protocol, such as I2C, to get the data in.

I probably could, but it all depends on the NeoPixel library I'm using. Can you skim that page really quick and see if I can use any of the other ones, and if it's only a question of specifying the right pin and using another method/bus (and also hook up the LED strip data pin to that pin).

I actually got it to work with NeoEsp8266Uart800KbpsMethod and GPIO02 (D4). Holy freaking hell it's fast now!

Note that you don't need to break the data into R, G and B, as the Neopixel library has an overloaded setPixelColor(uint16_t pixelIndex, uint32_t color) with the color given as 0x00RRGGBB. The switch can then be replaced by color = (color << 4) | v;

@EdgarBonet Indeed. Another method, if you do want separate RGB values is to shift the nibbles into a union with a 32-bit integer overlay divided into a 4 byte struct.

You could get a 50% reduction in serial data by sending the raw binary values rather than as hex. e.g. for each pixel send 4 binary bytes rather than sending 6 bytes of ascii. Less data sent and less decoding = faster code. Decoding becomes as simple as uint8_t r = Serial.read(); Why 4 bytes rather than 3? Because that way the data lines up nicely if you to use a uint32_t at one end or the other (stick to uint8_t's on 8 or 16 bit MCUs but on an ARM part or if a PC is sending the data then this is worth it) and you can then use the top (unused) byte as a start of data marker.

@Andrew Sending binary data is much more tricky than you are suggesting. A single "start of data" byte, when you're working with 8-bit data, is not practical - how do you distinguish it from data? Instead you would need proper packets with data escaping and such - and for such a small amount of data you would end up with a packet only fractionally smaller than (if not bigger than) the 7 bytes of ASCII representation.

@Majenko Sorry, I wasn't clear, I didn't mean an 8 bit start marker, I meant a 32 bit message where that byte was also set could act as a start marker. e.g. 0x01010101. If you look for 4 or more non-zero bytes in a row then you know that the next 0 byte will always be the first (always 0) byte of color data.

@Andrew And if you don't have 4 or more non-zero bytes in a row? Synchronisation is not possible with just one byte when that byte may appear in the data. You need at least 2 bytes for the synchronisation in a specific pattern. Then you need an "escape" byte in the data stream to prevent that pattern from ever appearing in the data, and of course escaping of that escape byte to prevent it being interpreted as an escape byte. Take a look at some existing binary protocols, such as telnet's IAC system, for examples.

@Majenko "Synchronisation is not possible with just one byte when that byte may appear in the data. You need at least 2 bytes for the synchronisation in a specific pattern." Correct. Hence the 32 bit start marker where none of the values are 0. If you don't have 4 non-zeros in a row the you have connected in the middle of a message and must wait for the next start marker, exactly the same as with ascii.

@Andrew Ah, right, got you now. So you would want to re-synchronise periodically to make sure no bytes have been lost - so efficiency depends on how often you want / need to re-sync. You wouldn't want to leave it too long between syncs in case you missed the very first one, and an initial sync never happened. You'd then discard a large number of packets until the next sync - so getting the balance right would be important. Adds a lot of complexity to think about to save a couple of bytes per packet.

@Majenko He's talking about an LED strip with different colours per LED so presumably WS2812 parts. It would be logical to resync at the start of each refresh, exactly how he was doing it in the initial question using ASCII but missing from your solution.

@Andrew Ah, so make the whole stop worth a packet, with a header of, say, 0x5555AAAA. That would work for this specific instance.

Since Majenko is convinced that using binary is far too complicated here's how to do it in binary sending 32 bits per color.
The start of strip marker is any 4 non-zero bytes in a row e.g 0x01010101
Each LED is then sent as four binary bytes: 0x00, 0xRR, 0xGG, 0xBB
In the unlikely event that a byte is lost in transmission then it will re-sync at the start of the next update, depending upon the pattern there is a fair chance that lost data will be noticed and the incorrect colors not get displayed on the strip.
loop() {
  static color_t color;
  static int8_t counter = -1;
  static int ledIndex = 0;
  static bool aligned= false;

  if (Serial.available()) {
    if (aligned) {
    switch (counter) {
      case 0: color.r=Serial.read(); break;
      case 1: color.g=Serial.read(); break;
      case 2: color.b=Serial.read();
              strip.SetPixelColor(ledIndex, color);
              ledIndex++;
              break;
      case 3: // first byte of next data, should always be 0
              // only not 0 if we've lost a byte or want to restart the strip
              if (Serial.read() != 0) {
                aligned=false;
                counter = 0;
              } else
                counter = -1;
              break;
      default: break;
    }
    counter++;
  } else { // not aligned
    ledIndex = 0;
    if (Serial.read() != 0) // count non-zeros
      counter++;
    else {
      if (counter >= 4)     // had a start marker, next byte is r
        aligned = true;
      counter = 0;
    }
  }
}

Is it worth doing it in binary? It gives a 50% decrease in RS232 data which if serial data rate is an issue will be a big help. It also gives a decrease in required calculations, if you look at the code there are virtually no mathematical operations beyond increasing counters.
Personally I prefer this method because it just seems more efficient and cleaner to transfer numbers as numbers rather than converting them to text and back but ultimately if you don't need every last bit of performance then it comes down to what you feel most comfortable with.

So far what I have counted using a high FPS camera, I can easily track 20+ updates a second using Majenko's code. I think that's very, very good considering I won't ever need to do that.

I would hope so, twenty updates a second isn't that fast unless you have a very long chain of LEDs. If you code it right the RS 232 should be the slowest part of the system and you should easily be able to get 20 FPS on chains of several hundred LEDs. As I indicated, binary gives you that little bit more if you need it, if you don't need it then it's simply an alternative approach.


text:
How to send data in response to HTTP get request from ESP8266?
I'm trying to control some RGB LEDs with ESP8266. I have built an HTML page to set the color and send the RGB color code to the ESP using HTTP get request. Everything works as expected. I just want to send an HTTP get request to the ESP and ask what the current color is. But after a couple of hours of searching and trying I don't know how to send data in response to get request, I just can send HTTP ok code. I'm using jquery to send get command as below
$.get("http://192.168.4.1/rgb(120,50,60)", function(data,status){
    //I don't know how to send data fram ESP get it here.
});

this is the corresponding ESP response code written in Arduini IDE
WiFiClient client = server.available();
   if (client) {
  String req = client.readStringUntil('\r');
  client.print("HTTP/1.1 200 OK\r\n");
  client.print("Access-Control-Allow-Origin: *");
.
.
.

This is the HTTP header, How do I send some data(text)?

look at the webserver example. something like server.send(200, "text/plain", someStringOfContentHere); build up the string with the data you need.

Thak you for your input. To use send method I have to include ESP8266WebServer.h and modify my code. I think there should an easy way to send some text (like HTML markup) after the header.

After the last header you need to send two newlines (\r\n\r\n) and then send your data.

Thank you @Gerben! I spent hours searching but no success. It worked like a charm.

@Gerben answered my question in a comment all credit goes to him. I retype it here maybe it helps someone in the future.
I had to send two new line after setting up the header
//header
client.print("\r\n\r\n");
clinet.print("Hello, I'm comming from ESP!!");

And in jQuery I get it like this:
$.get("http://192.168.4.1/rgb(120,50,60)", function(data,status){
    var receivedData=data;  //=Hello, I'm comming from ESP!!
});

It is simple but it may help some newbie like me.


text:
How to display extended ASCII characters, e.g., the standard degree symbol, DEC 167, on the Serial Monitor [not LCD]?
I spent an afternoon researching this, and read a lot of material, but with no successful results.  [I really thought this would be a trivial task.]
Is this problem Windows, or WIN10, specific, as the extended characters all seem non-displayable? Regardless, is there a solution?

in extended ascii, degree '°' is DEC 248 per  http://www.theasciicode.com.ar/   DEC 167 looks a lot like a degree sign, but it is a 'masculine ordinal indicator'   see https://en.wikipedia.org/wiki/Ordinal_indicator

The Arduino serial monitor uses UTF-8, per the discussion at http://forum.arduino.cc/index.php?topic=172814.0 --
For the U+00B0 degree symbol, you'd send the bytes UTF8 0xC2 0xB0 like this:
Serial.print("°");


text:
Help using thermistor with esp8266
So I am trying to use this thermistor to measure temperature and with this code below it always puts the same value (2147483647).  I used this tutorial to do the wiring and coding.  I don't think the wiring is the problem but think the problem is somewhere in my code or perhaps I am using a wrong type of thermistor?  Am I missing something?  Any help is greatly appreciated.
I am only using a 1k resistor in series with the thermistor but don't think that would be a problem, right?
Edit: I should have mentioned I'm using the adafruit huzzah esp8266 so there are a few pins.
#include <DHT.h>
#include <ESP8266WiFi.h>
#include <Phant.h>
#include <ESP.h>

#define DHTPIN 2
#define DHTTYPE DHT22
#define THERMISTORPIN 4

DHT dht(DHTPIN, DHTTYPE);

const char* ssid = "xxxx";
const char* password = "yyyyyy";
const char* host = "data.sparkfun.com";
const String publickey = "uuuuuu";
const String privatekey = "ttttttt";
const byte NUM_FIELDS = 5;
const String fieldNames[NUM_FIELDS] = {"ghumidity", "gtemp", "light", "otemp", "wtemp"};
String fieldData[NUM_FIELDS];

//thermistor variables
const int thermresistor = 987; //value of resistor in series with thermistor
int thermtemp = 0;
uint8_t i;
uint8_t numsamples = 5;
uint8_t To = 25;
const int B = 3950;

void setup(){
    Serial.begin(115200);
    delay(10);
    WiFi.begin(ssid, password);

    while (WiFi.status() != WL_CONNECTED) {
  delay(500);
}

    fieldData[0] = 1; //humidity
    fieldData[1] = 2; //garden temp
    fieldData[2] = 3; //light
    fieldData[3] = 4; //outside temp
    fieldData[4] = 8; //water temp

//turnpumpon();
posttophant();
//turnpumpoff();
ESP.deepSleep(1200000000, WAKE_RF_DEFAULT);

}

void posttophant()
{
    fieldData[0] = dht.readHumidity();
    fieldData[1] = dht.readTemperature(true);

    //read outside temp (otemp) data and convert to a temp
    for (i=0; i<numsamples; i++){
      thermtemp = analogRead(THERMISTORPIN);
      thermtemp += thermtemp;
      delay(10);
    }

    //take the sum of all the readings and divide by # of samples to get avg.
    thermtemp = thermtemp / numsamples;

    #voltage divider equation
    thermtemp = thermresistor / (1023 / thermtemp - 1);

    //Steinhart eqn.
    thermtemp = 1 / (log(thermtemp / thermresistor) / B + (1 / (To + 273))) - 273;
    fieldData[3] = String(thermtemp);

    WiFiClient client;

    const int httpPort = 80;
if (!client.connect (host, httpPort)){
  return;
}

    client.print("POST /input/");
    client.print(publickey);
    client.print("?private_key=");
    client.print(privatekey);
    for (int i=0; i<NUM_FIELDS; i++)
    {
      client.print("&");
      client.print(fieldNames[i]);
      client.print("=");
      client.print(fieldData[i]);
    }
    client.println(" HTTP/1.1");
    client.print("Host: ");
    client.println(host);
    client.println("Connection: close");
    client.println();
}

i would consider using the thermistor as an RC's R, allowing more precise measurement than 10bits.

A 10 kΩ series resistor should give you significantly better resolution.

Can you please give a hint how can I deal with a following issue ? Because of space limitations, I've to share ADC and one of GPIO's, meaning that in one case, controlled by software GPIO should be used for it's original value (digital IO), ignoring ADC, and on another occasion, ADC should be used without being overloaded by GPIO current. Is it theoretically possible to use one terminal for both pins ? Thank you.

Considerations about the ESP8266 analog pin
The ESP8266 has only one pin that allows analog read. This pin is call A0 on the NodeMCU module or A on the ESP8266 Huzzah (some other ESP module don't expose that pad - for example ESP8266-01) or might label it differently - check the documentation of your ESP module.
Following your edit: make sure that you connect your thermistor to the A pin of the Huzzah ESP8266 module.
You should keep in mind that this analog pin is a 10bit ADC with in principle limited input voltage range.
To read an external voltage applied to the ADC pin, use analogRead(A0). Unless you are using a board specially design to increase its range, the input voltage range is 0 — 1.0V. As @dandavis pointed out some boards (Node MCU e.g.) include a voltage divider on board to give you a full 0 - 3.3V input range.
Thermistor equations
The datasheet of your thermistor states that the TCR coefficient is 3000ppm/%C and has a 10K value [note that the manufacturer doesn't provide you with the temperature at which R = 10K]. The equation of the resistance variation ∆R with temperature variation ∆T is given by:
∆R = ∆T*10k*3000ppm = 30*∆T
So if T_0 is the temperature where R = 10k, the equation of the resistance value is given by:
R = 10k + (T-T_0)*30
I am assuming that you are using the 3.3V supply of your ESP and creating a voltage divider using the 1K resistor and the thermistor.
There are two ways to do this divider:
1. Voltage divider option 1

simulate this circuit – Schematic created using CircuitLab
[Note that the thermistor needs to be connected to the A pin of your ESP8266.]
2. Voltage divider option 2

simulate this circuit
Equation of voltage at node A
For both case here is the voltage V_A seen at node A:
1. Voltage divider option 1
V_A = R_series *3.3 / (R_th + R_series)
2. Voltage divider option 2
V_A = R_th *3.3 / (R_th + R_series)
Analysis of the variations of V_A with temperature
Lets look at the difference between the 2 formulas above:
1. Voltage divider option 1
The numerator is a constant with temperature while the denominator changes with T. You will get a strong variation.
2. Voltage divider option 2
Both the numerator and denominator increase with temperature. You won't get a lot of variation on V_A with temperature. You should avoid this configuration.
Analysis of the maximum allowed value of R_series
The important consideration is that for your ESP module V_A cannot be higher than 1V.
1. Voltage divider option 1
Increasing R_series will increase V_A so we compute a maximum value:
1V = 3.3V*R_series_max/(R_series_max+10K)
That gives you: R_series_max = 4300Ohms
2. Voltage divider option 2
Increasing R_series will decrease V_A so we compute a minimum value:
1V = 3.3V*10k/(R_series_min+10K)
That gives you: R_series_min = 23kOhms
This is the reason why it was suggested to you using a 30k resistor in that case.
Considerations about temperature measurement precision
The voltage variation ∆V on the node A of the ESP between temperature T1 and T2 can be computed as follow:
∆V = 3.3 *1K/(1k + 10k + 30*T1) - 3.3 *1K/(1k +10k+ 30*T2)
If we assume that the thermistor is 10K for ambient temperatures the baseline voltage measured on the A pin is:
3.3V*1K/11k = 0.3V
For a 0 to 1V 10bit DAC of the ESP8266 that is around: 2^10*0.3 = 307
A change of 10C would lead to a variation of voltage of:
∆V = 0.3 - 3.3 *1K/(11k + 300) = 8mV ~8ADC code
The equation of ∆T vs ∆V is not linear but for small variation of temperature with your current setup you get ~1ADC code per degree.
Depending of your application this might not be enough for you. As suggested in several comment you could:

Add more thermistors in parallel
Increase the 1K series resistor (but not too much or you will saturate the ADC).
Change the architecture of the measuring circuit (RC oscillator using the thermistor and interrupt counter in the ESP, 555 timer circuit loaded with the thermistor and interrupt counter, ...)
Or since you want to do humidity and temperature measurement why don't you get the BME280 module. It can be read over I2C and libraries are readily available to read it with the ESP8266.

1.0 nodeMCU boards accept 0-3.3v. the ones that fit on a bread board and have cp2102s

@dandavis wasn't aware of this interesting feature (so far I have only be using the ESP-01 myself).

@dandavis thinking about it, this integrated on-board voltage divider can be dangerous if the source impedance is very high. Although not the case here.

might consider two thermos in parallel for a lower R and averaged errors (they are cheap anyway)

vrleboss, denominator (11k + 0.00310), which is 11000.03,  should instead be 1KΩ + (1 + 0.00310)*10KΩ, which is 11300.  That is, 3000 ppm of 10KΩ is 10000 *  3000/1000000 Ω, or 30 Ω per degree

@jwpat7 well spotted. I edited my post.

@vrle, what would be too large of a resistor to use in series with the thermistor?  SortOfEngineer below suggested >30k to get the reading withing the 0-1V range.  Is that too large?  My goal was to put in 2 thermistors (with the DHT22 there) since they are so cheap to measure 2 temp values at 2 locations.  I also want to maximize battery life so power consumption is an issue so thought a simple thermistor would be better than a addon module.  If you have suggestions for another sensor besides the DHT22 to use that is cheap and can use all 3 of them on one of my modules I appreciate the help

@willocks1718 looking at the data sheet from the DHT22 the power consumption doesn't seem very low. I see 1mA reported here: https://www.sparkfun.com/datasheets/Sensors/Temperature/DHT22.pdf. You could get better precision measurement with fewer pieces with modules. I am quoting the BME280 because I am using it it was also a winner in this great side-by-side comparison: https://www.kandrsmith.org/RJS/Misc/Hygrometers/calib_many.html

@willocks1718 as for the resistor value in series with you thermistor it depends how your voltage divider is made: 3.3V - R_series - R_th - gnd or 3.3V - R_th - R_series - gnd. I will update my answer to explain better.

@vrleboss I am not against using the module you stated and am not set on using the dht22, it's just what I purchased first and am using.  I would gladly replace it with something that consumers less power or is better overall.  I don't really even care about the humidity measurement but am taking it since it's with the dht22.  Thanks for the detailed help, I have a lot of research to do now!

Re “the problem is somewhere in my code”, lots of places in the code have problems.
• The following loop does not add up readings; it takes a bunch of readings and throws them away, then doubles the last one.  For example, if the five readings in a row are 300, 400, 500, 600, and 100, thermtemp is 200 after the loop.  To see this, try it out – mentally simulate what the code does, writing down the value of thermtemp after each step.
for (i=0; i<numsamples; i++) {
   thermtemp = analogRead(THERMISTORPIN);
   thermtemp += thermtemp;
   delay(10);
}

• Your “voltage divider equation” (below) has a form like that shown in the Adafruit tutorial, but because your thermtemp is declared as an int (vs Adafruit's float), integer division with truncation will be used, producing inaccuracy.
thermtemp = thermresistor / (1023 / thermtemp - 1);

• Your Steinhart-Hart equation is miscoded.  At that step, the fixed resistor's value, thermresistor, is no longer relevant.  The relevant value is the ADC reading as converted to thermistor resistance.
• In your Steinhart-Hart misimplementation, log(thermtemp / thermresistor) takes log of zero because in integer arithmetic, thermtemp / thermresistor is zero.
• The expression 1 / (To + 273) is zero in integer arithmetic.

As for the for loop I thought saying... thermtemp += thermtemp; would add the just read value to the previous total and store that new value into the variable? I see what you are saying about the integers, haha, still learning and was trying to save storage space. I'll make those changes.

@willocks1718, yes, thermtemp += thermtemp adds  thermtemp to thermtemp, which doubles it.    Go through it manually, writing down the value after each step: 300, 600, 400, 800, 500, 1000, 600, 1200, 100, 200.

sorry I meant if the first reading was 300 that gets stored into thermtemp. With the next reading being 350 or so it would add it to the previous value and store it to get 650. Basically it would sum the next x readings. So that is incorrect thinking?

There are a few possible issues you're having:
First off, from what I understand, the ESP8266 ADC only reads up to 1V. If wired per the Arduino example you cited, and using 1K, you'll have VCC->1K->THERMISTOR->GND. At room temp the thermistor is 10K, so the voltage at the ADC will be 3.3*(10K/(1K+10K)), so pretty close to 3.3V. I don't know the behavior of the ADC when overrange, but I'd assume you'd just get 0xFFFF. You'll probably want >30K in series with the thermistor to get it into a usable range.
I also see a subtle error(I think) in your code:
//read outside temp (otemp) data and convert to a temp
for (i=0; i<numsamples; i++){
  thermtemp = analogRead(THERMISTORPIN);
  thermtemp += thermtemp;
  delay(10);
}

Should be:
//read outside temp (otemp) data and convert to a temp
thermtemp = 0
for (i=0; i<numsamples; i++){
  thermtemp += analogRead(THERMISTORPIN);
  delay(10);
}

Otherwise thermtemp is just the last reading added to itself.
Lastly, I would probably make the part of the code that posts the result to a function and call it throughout your calculations of the temp, to see if anything weird happening.
Hope this helps.

I didn't realize that about the pin only reading 0-1V, thanks.  I have some resistors coming, and will figure out what value I need.  As for the for loop I was trying to add the new value to the previous value and re-store the sum to the variable again, apparently the way I tried to do it doesn't work though so I'll fix the loop

fwiw, on the cp2102-based NODEMCU boards, there's already two high-ohm resistors on A0 to allow a 0-Vcc range, which i find very useful.


text:
Arduino board is turning off when I connect to +5V
I am trying to set up an LCD screen without using a resistor or a potentiometer for an Arduino project. This is the LCD I am using: Basic 20x4 Character LCD.
But when I connect to +5V on the Arduino board, my Arduino board turns off. This is how I have the LCD connected to the Arduino on a breadboard.

Connections:
LCD RS pin to digital pin 12
LCD Enable pin to digital pin 11
Data:
• LCD D4 pin to digital pin 5
• LCD D5 pin to digital pin 4
• LCD D6 pin to digital pin 3
• LCD D7 pin to digital pin 2
LCD R/W pin to ground
LCD VSS pin to ground
LCD Cathode pin to ground
LCD Anode pin to digital pin 9
LCD VCC pin to 5V
Code:
// include the library code:
include <LiquidCrystal.h>
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
  analogWrite(6,20);
  // set up the LCD's number of columns and rows:
  lcd.begin(20, 4);
  // Print a message to the LCD.
  lcd.print("hello, world!");
}

void loop() {
  // set the cursor to column 0, line 1
  // (note: line 1 is the second row, since counting begins with 0):
  lcd.setCursor(0, 1);
  // print the number of seconds since reset:
  lcd.print(millis() / 1000);
}

Anode pin always connects with 5V... See my answer diagram. It will helpful.

Try out this connection. It will helpful.

Looking at your picture, it seems that you're powering everything through a USB cable. USB 1.x and 2.0 can supply up to to 500 mA AFTER the port is enumerated, otherwise the current is limited to 100 mA.
A quick current consumption budget:

LED backlight of your LCD module: typ 240 mA
Arduino Mega2560: min 70 mA
MIDI shield: some 15-35 mA

That's just 325-350 mA to begin with, and probably higher than that. It's still safely within the 500 mA limit, but as I said some computers will provide 500 mA only after successful enumeration of the device connected to the USB port.
My recommendation for you would be to power your Arduino + MIDI shield + LCD through a wall adapter > 7V. If it works, then the problem is your USB port being unable to supply the required current right from the start.

Alright ill try that out. it my not be visible  but i also have an Mp3 shield between  the Midi shield and arduino

Well, that will add some current consumption as well. You might be already above 500 mA! Under that load, the USB port of the computer shuts himself off for protection.

i think i found the issue one of the pins on the LCD might have been causing a short when i connected to 5v pin .i fixed it and it seems to be working. i did this with the shields on the arduino removed. i will add them back on and see if it works. if it dose not i know the issue is related to the power consumption of the USB. thanks for your help