text:
Serial not displaying sketch for MPU6050
I followed this tutorial on youtube: https://www.youtube.com/watch?v=M9lZ5Qy5S2s
Where he provided the code below. The problem I'm having is the serial monitor shows nothing. I tried changing the baud to 115200 and still nothing showed up. I'm using an Arduino nano.
Update: I wrote a Serial.print in each function (printing the name of the function), and I found it just printed up to "recordAccelRegisters" then stopped. Then I put a Serial.print after each line in the function, and it prints until the line
while(Wire.available() < 6);
Is this a problem with the while function or I2C?
Ok, so I reinstalled Arduino and got this message on the serial print with the I2C test:
"Scanning... I2C device found at address 0x69  ! done."
#include <Wire.h>

long accelX, accelY, accelZ;
float gForceX, gForceY, gForceZ;

long gyroX, gyroY, gyroZ;
float rotX, rotY, rotZ;

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

void loop() {
  recordAccelRegisters();
  recordGyroRegisters();
  printData();
  delay(100);
}

void setupMPU(){
  Wire.beginTransmission(0b1101000); //This is the I2C address of the MPU (b1101000/b1101001 for AC0 low/high datasheet sec. 9.2)
  Wire.write(0x6B); //Accessing the register 6B - Power Management (Sec. 4.28)
  Wire.write(0b00000000); //Setting SLEEP register to 0. (Required; see Note on p. 9)
  Wire.endTransmission();
  Wire.beginTransmission(0b1101000); //I2C address of the MPU
  Wire.write(0x1B); //Accessing the register 1B - Gyroscope Configuration (Sec. 4.4)
  Wire.write(0x00000000); //Setting the gyro to full scale +/- 250deg./s
  Wire.endTransmission();
  Wire.beginTransmission(0b1101000); //I2C address of the MPU
  Wire.write(0x1C); //Accessing the register 1C - Acccelerometer Configuration (Sec. 4.5)
  Wire.write(0b00000000); //Setting the accel to +/- 2g
  Wire.endTransmission();
}

void recordAccelRegisters() {
  Wire.beginTransmission(0b1101000); //I2C address of the MPU
  Wire.write(0x3B); //Starting register for Accel Readings
  Wire.endTransmission();
  Wire.requestFrom(0b1101000,6); //Request Accel Registers (3B - 40)
  while(Wire.available() < 6);
  accelX = Wire.read()<<8|Wire.read(); //Store first two bytes into accelX
  accelY = Wire.read()<<8|Wire.read(); //Store middle two bytes into accelY
  accelZ = Wire.read()<<8|Wire.read(); //Store last two bytes into accelZ
  processAccelData();
}

void processAccelData(){
  gForceX = accelX / 16384.0;
  gForceY = accelY / 16384.0;
  gForceZ = accelZ / 16384.0;
}

void recordGyroRegisters() {
  Wire.beginTransmission(0b1101000); //I2C address of the MPU
  Wire.write(0x43); //Starting register for Gyro Readings
  Wire.endTransmission();
  Wire.requestFrom(0b1101000,6); //Request Gyro Registers (43 - 48)
  while(Wire.available() < 6);
  gyroX = Wire.read()<<8|Wire.read(); //Store first two bytes into accelX
  gyroY = Wire.read()<<8|Wire.read(); //Store middle two bytes into accelY
  gyroZ = Wire.read()<<8|Wire.read(); //Store last two bytes into accelZ
  processGyroData();
}

void processGyroData() {
  rotX = gyroX / 131.0;
  rotY = gyroY / 131.0;
  rotZ = gyroZ / 131.0;
}

void printData() {
  Serial.print("Gyro (deg)");
  Serial.print(" X=");
  Serial.print(rotX);
  Serial.print(" Y=");
  Serial.print(rotY);
  Serial.print(" Z=");
  Serial.print(rotZ);
  Serial.print(" Accel (g)");
  Serial.print(" X=");
  Serial.print(gForceX);
  Serial.print(" Y=");
  Serial.print(gForceY);
  Serial.print(" Z=");
  Serial.println(gForceZ);
}

https://github.com/VRomanov89/EEEnthusiast/blob/master/MPU-6050%20Implementation/MPU6050_Implementation/MPU6050_Implementation.ino

I put a serial.print in the first line of each function. It stops after recordAccelRegisters

tried http://playground.arduino.cc/Main/I2cScanner same problem

Got it. I used the address from the I2C test and everything looks great. Guess I'll have to do this for any cheap modules I get on ebay :)

Ground the AD0 pin. I thought the address should be set to 0x68 without this, but from what I've seen it fluctuates between 0x68 and 0x69. If you want the address to be 0x69 short the AD0 pin to 5V. I guess this would be useful if you need to use 2 MPU6050s with different I2C addresses without doing something in software. Haven't looked into that yet
Still, the I2C scanner for arduino may be useful for detecting the address/debugging: http://playground.arduino.cc/Main/I2cScanner


text:
47Effects MIDI Library and serial debugging
I noticed that since I use the MIDI library from 47effects, I cannot use the print(ln) for the serial port for debugging purposes, neither I can find it in the documentation.
It states that the MIDI library uses the serial port, but I really miss the serial port now for debugging.
Update: so my question: The MIDI library uses the RX (pin 0) and TX (pin 1) on my Arduino One. However, I think the internal Serial.print/println also uses these same pins, so I was wondering how I can use Serial.print and Serial.println statements being visible on the Arduino IDE Terminal (emulator) while using the MIDI library.

I assume you have one or more Arduinos, are trying to do MIDI control, and want to know how to debug with the MIDI library having commandeered the hardware serial port.
One approach is to use I2C or SPI to communicate with a second Arduino, which uses its serial port to deliver debugging data to a host system.  See Nick Gammon's excellent page  Debugging using SPI/I2C and a second processor (gammon.com.au forum id=11329), which illustrates communication between two Arduinos, using one of them as a slave to forward information sent by I2C or SPI from a system being debugged.
Another approach might be to use a serial bridge.  I don't know the ins and outs of this or exactly what it does but have read that, for example, the Hairless bridge (which is an open-sourced software package) can display both sides of MIDI communication, possibly depending on use of Serial.write vs Serial.print.  You could designate certain note sequences as standing for various debugging cases.
A third approach is use of Arduino software serial to send debugging data to a serial port on your host system.  This would use some Arduino pins other than the hardware Rx, Tx pins.
Edit 1:  Pin Usage –
For approach 1, using I2C ties up two specific pins, SDA and SCK.  These are shared with other I2C devices, if any.  SPI typically shares three signals – SCLK, MOSI, and MISO – among all SPI devices, and generates one SS signal per device.  For pinout and protocol details, see Nick Gammon's well-organized and clearly-illustrated I2C and SPI pages.
Approach 2 would use no extra pins.
Approach 3 would use one or two extra pins:  one for half-duplex or output-only communication (which may be adequate for debugging), two for separate Rx, Tx lines.  Compared to hardware serial, software serial is CPU-intensive, does not support as-high data rates, and has a higher error rate.  It should work ok for light-weight debugging output, such as occasional text to show what tests succeeded or failed or what branch was taken, or values of a few variables.

Thanks for all the possibilities ... A second Arduino seems a bit like overkill (but if it works, it works, just have one so far, I'm a beginner).
The second sounds a bit troublesome, since my program might be rather complicated in time. However, the third seems very good and exactly what I need.
Can I also ask one additional question? I'm intending in time maybe also to use SRAM, SD and/or an extra EEPROM ... will I get similar problems again (that the SD /SRAM/EEPROM (SPI) also uses hardware RX/TX ?)

@MichelKeijzers, see edit 1

Thank you (again ) for the extra explanation ... it seems the CPU might be a problem if I would go debugging by approach 3. Maybe an extra Arduino is not so bad idea after all. At least it will give many more things to try (still in 'learning' mode).

All of the approaches are easy to try – if you have time to experiment and if you have a  serial port on your host computer  – and you can take debugging out after using it.  Anyway, if you have a serial port or a USB-serial device, it's probably worth trying out software serial, since the extra bit of CPU usage for debugging might be not a problem.

Yes I will go for the software solution first, probably for debugging, timing is not so much a problem.

source: Stack Exchange

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

sort: votes


text:
Use input capture for multiple sensors simultaneously
I want to accurately time multiple digital input channels (readings from sensors) for the rising and falling edges. I need the precision of the Timer1 Input Capture. As far as I know the input capture only listens to pin D8 (for ATmega8). So, is there anyway to capture the inputs of multiple sensors?

Update:
I would like the reading to be as accurate as possible since I'm using the values to calculate motion tracking information. Concretely, I'm trying to build my own tracker for StreamVR's light house.

How accurately? (in microseconds)

As accurate as possible... see my edited question. BTW, I've read your note on Arduino's interrupt... That is very valuable! Thanks! :D

"As accurately as possible" is too vague. You may as well say you want to have "as much money as possible" in a job interview. Do you want accuracy down to 1 ns? 1 µs? 1 ms? 10 ms? Let's say your answer is "1 ns". Then the ATmega8 isn't the chip for you.

If you use pin-change interrupts, then you will get "as much accuracy as possible" that pin-change interrupts will give you.

Then you better use the ATmega328P, because the ATmega8 doesn't have "PCINT" (Pin Change Interrupt).
Some older sensors use frequency output, because a microcontroller could read that. However, today there is I2C and SPI interface. If you can't get another interface than a frequency output and you want the best accuracy, then you have to add extra hardware to read those signals.

If you want input capture (i.e. single cycle) accuracy on multiple input channels, you will need multiple input capture units. The Atmega2560 (powering the Arduino Mega 2560) has four of them, one in each 16-bit timer.

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


text:
74HC595 with 4 digit 7 segment display. Any way to get rid of leading zeros?
I am working on an Arduino based temperature reader using a DS18B20 temperature IC. The display is a 4 digit 7 segment LED common anode display driven by a single 74HC595 shift register. Currently, it is setup to read a variable assigned with a number to test the display portion. It displays to the tenths decimal place I am having troubles trying to get rid of the leading zeros. When the variable 'tempF' is assigned a number such as 12.3, the display yields 012.3 and if the variable is assigned a number such as 1.2, the display will yield 001.2. At the same time, I was wanting to have it place a minus (-) sign when the number is less than zero. So far, the examples I'm finding on the web don't seem to match into the code I'm currently working with or don't work at all. I haven't been able to locate a sketch that seems to work for this type of setup. I have posted below, the code I am working with. The original code was obtained from the link provided in the sketch.
The sketch there does not provide the means of reading negative temps or suppress leading zeros.

   /*
 * www.pial.net/arduino-controlling-a-4-digit-seven-segment-display/
 */

//#include <OneWire.h>
//#include <DallasTemperature.h>

//#define ONE_WIRE_BUS 2

//OneWire oneWire(ONE_WIRE_BUS);
//DallasTemperature sensors(&oneWire);
//DeviceAddress insideThermometer;

const int ledPin =  13;// LED connected to digital pin 13
const int latchPin = 8;//Pin connected to ST_CP of 74HC595
const int clockPin = 9;//Pin connected to SH_CP of 74HC595
const int dataPin = 10;//Pin connected to DS of 74HC595

const int digitPins[4] = {
  3,4,5,6}; //pins to control the 4 common anode pins of the display

const byte digit[10] = //seven segment digit bits
{
  B00111111, //0
  B00000110, //1
  B01011011, //2
  B01001111, //3
  B01100110, //4
  B01101101, //5
  B01111101, //6
  B00000111, //7
  B01111111, //8
  B01101111, //9
//  B00000000, //all segments off
//  B01000000 //-
};

int digitBuffer[4] = {
  1};
int digitScan = 0;
int soft_scaler = 0;
float tempC, tempF;
int tmp;

void setup()   {
  TCCR2A = 0;
  TCCR2B = (1<<CS21);
  TIMSK2 = (1<<TOIE2);
  TCNT2 = 0;
  Serial.begin(9600);

  pinMode(ledPin, OUTPUT);
  for(int i=0;i<4;i++)
  {
    pinMode(digitPins[i],OUTPUT);
  }
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);

//  sensors.begin();
//  sensors.getAddress(insideThermometer, 0);
}

ISR(TIMER2_OVF_vect) {
  soft_scaler++;
  if(soft_scaler==15)
  {
    refreshDisplay();
    soft_scaler = 0;
  }
};

void refreshDisplay()
{
  for(byte k=0;k<4;k++)
  {
    digitalWrite(digitPins[k], LOW);
  }
  digitalWrite(latchPin, LOW);
  shiftOut(dataPin, clockPin, MSBFIRST, B11111111);
  digitalWrite(latchPin, HIGH);
  delayMicroseconds(50);
  digitalWrite(digitPins[digitScan], HIGH);

  digitalWrite(latchPin, LOW);
//  if (digitScan==3)
//  {
//    shiftOut(dataPin, clockPin, MSBFIRST, ~(digit[digitBuffer[digitScan]] | B00000000)); //inserting the blank
//    }
//    else
//  {
//    shiftOut(dataPin, clockPin, MSBFIRST, digit[digitBuffer[digitScan]]);
//  }

  if(digitScan==1)
  {
    shiftOut(dataPin, clockPin, MSBFIRST, ~(digit[digitBuffer[digitScan]] | B10000000)); //inserting the dot
  }
  else
  {
    shiftOut(dataPin, clockPin, MSBFIRST, ~digit[digitBuffer[digitScan]]);
  }
  digitalWrite(latchPin, HIGH);
  digitScan++;
  if(digitScan>3) digitScan=0;
}

void loop()
{
  digitalWrite(ledPin, HIGH);
  boolean sign = false;
  //sensors.requestTemperatures();
  //tempC = sensors.getTempC(insideThermometer);
  //tempF = DallasTemperature::toFahrenheit(tempC);
  //tmp = int(tempF*100);
  tempF = 0.2;
  tmp = int(tempF*10);

//   if (digitScan == 4 ){
//    shiftOut(dataPin, clockPin, MSBFIRST, ~(digit[digitScan] | B00000000)); //inserting the blank
//    }
//    else
//  {
//    shiftOut(dataPin, clockPin, MSBFIRST, digit[digitBuffer[digitScan]]);
//  }

//if (tmp < 0){
//sign = true;
//tmp = abs(tmp);
//}

//if (digitScan == 3) {
//  if (tmp < 0){
//    shiftOut(dataPin, clockPin, MSBFIRST, ~(digit[digitBuffer[digitScan]] | B01000000)); // outputs minus sign
//  }
//  else {
//    shiftOut(dataPin, clockPin, MSBFIRST, ~(digit[digitBuffer[digitScan]] | B00000000));
//   }

//  tmp = abs(tmp);
// }
//  else if (digitScan == 3 && digit[digitScan-1] == 0) { // writing on the second display (tens; if there are none, outputs nothing)
//     shiftOut(dataPin, clockPin, MSBFIRST, ~(digit[digitBuffer[digitScan]] | B00000000));
//   }
//   else if (i == 2) { // writing on the third display, where decimal point is needed
//     shiftOut(data_pin, clk_pin, MSBFIRST, digit[digitBuffer[i-1]]);
//   }
//   else { // writing on "other" displays (in fact fourth display AND seecond display only if there are some tens)
//     shiftOut(data_pin, clk_pin, MSBFIRST, digit[digitBuffer[i-1]]);
//   }

  digitBuffer[3] = int(tmp)/1000;
  digitBuffer[2] = (int(tmp)%1000)/100;
  digitBuffer[1] = (int(tmp)%100)/10;
  digitBuffer[0] = (int(tmp)%100)%10;
  Serial.print("number assigned to the variable 'tmp' = ");
  Serial.println(tmp);
  Serial.print("number assigned to the variable 'tempF' = ");
  Serial.println(tempF);
  digitalWrite(ledPin, LOW);
  delay(500);
}

The commented out commands in the sketch were attempts to remove leading zeros and add a minus sign when needed but failed. I have also posted a schematic of the project as well. A 74HC595 was used in this manner to free up pins to be used later in a deep freezer project.
I am by no means an expert programmer but if anyone could help me out or provide some insight on how to solve this problem, it would be most appreciated.

Please edit your question (click "edit") and mark the code as code.  When including code in a stackexchange question or answer, first paste the code into the question or answer editing box; then in that editing box, highlight the code and press ctrl-k. Or highlight the code and click the {} icon in the toolbar at the top of the editing box. To highlight text click-drag across it or use the arrow keys while holding the shift key.

First figure out how you would do it by hand. Then translate that into code.

@IgnacioVazquez-Abrams - For me, easier said than done. I've been trying to find answers to this for a very long time with no luck. That or I don't know what exactly to search for to find the answers.

Remembermyname, I didn't downvote, merely commented, but if you hadn't fixed it, I might have downvoted tomorrow.  Anyhow, I upvoted after you fixed the code formatting.   Now your question has 1 upvote and 1 downvote.

@jwpat7 You're right, it was while before I caught my own error and had to correct it. If I had seen it, I would probably have downvoted it as well. I apologize, I didn't mean to accuse. I've removed the unwarranted comment.

Any way to get rid of leading zeros?

Sure but two conditions have to be true:
1) you have the font information for "blank"; you need to un-comment it in your code for that.
2) you need to get rid of leading zeros, after having calculated the display buffer.
  displayBuffer[0]=(displayBuffer[0]==0)?FONT_BUFFER:displayBuffer[0]; //eliminate leading zero for displayBuffer[0]
  displayBuffer[1]=((displayBuffer[1]==0) && (displayBuffer[0]==FONT_BUFFER))?FONT_BUFFER:displayBuffer[1];
  ...

edit:
here is an example implementation of the concept from above, on a PIC12F675 driving two HC595. The number to be displayed is "12" on a 4-digit display. Blanking done on the first three digits -> you can confirm that by looking at the value of the display buffer lRAM[4]. 0x11 is my blank designator.
The partial display of '1' is due to multiplexing. Code largely based on what I wrote here: https://dannyelectronics.wordpress.com/2017/03/03/driving-7-segment-leds/, modified to drive over HC595s.

it should work on any mcu with minimum changes.
edit 2: here is your code driving a CC display directly. the number to be displayed is 1.23, with the leading zeros in the most significant 2 digits taken out.

I was aware of the uncommenting parts. They were previous attempts that didn't work as explained earlier. I tried the code snip before the display portion with it changed to match the variables in the sketch but I'm not certain of 'FONT_BUFFER'. Please elaborate.

Is there an example anywhere that utilizes this? I've been going in circles on google for far too long. As if it were some kind of state secret. :/

I mean, this looks like a fairly straight forward answer. I tried to add shiftouts to use the masks (albeit poorly) and of course, they don't work. I'm just not aware why.

Well, this appears to be a microchip example. I'm certain that the principles are the same but I haven't been able to get this to work at all.


text:
Virtual analog inputs? Possible?
Just wondering whether it is possible to create 'virtual analog' signals, I am designign a system that uses a tank level sensor (pressure transducer); the component has not yet arrived and I am expecting it in a few weeks.
Is there any way to simulate the signals it would spit out, using some sort of GUI where I can physically control the 'virtual' tank level?
I'm thinking something along the lines of Wonderware's Intouch?
Would appreciate the help! Thanks

Don't spend a ton of time on it, but look up "IOC", "mock input", and "Dependency Injection" software concepts and keep the basic ideas in mind as you build out your sketch. it will help later.

You don't specify the sensor you're trying to emulate, so we can't tell you exactly how to do it.
The obvious hardware approach would be a potentiometer.
You could also do it in software by writing a function to get the value, and temporarily replacing its implementation with one which generates random values, or reads values from a serial port, or reads them in order from a hard-coded array, or calculates them according to the time, or whatever you want.

Thanks for the response! I'm trying to simulate a tank level sensor (so probably a pressure transducer)

If you just want different values on an analog port then you could use a potentiometer, or a second Arduino the reads a value from its serial port and sets the value of its analog port connected to your first Arduino.  Just remember to have a common ground if you do this.

Seconding the potentiometer approach. If you scale the analog result to the output range of the actual component, the rest of your system should never notice the difference when you install the hardware and replace the pot-reading function with a sensor-reading one.


text:
Connecting ACS 712 30A to my Solar Panel with Arduino
I am trying to connect my Solar Panel (array of 2 x 265Wp 24v panels connected in series) to my Arduino UNO R3/Nano so that I can make a current/voltage measurement system that can be connected to the internet for remote data access.
I am not sure if an Allegro ACS712 30Amp chip could handle the voltage/current of my system which is usually over 60v dc and 4-5 amps. I can relate the ACS712 to a simple ammeter which is connected in series of the load where a shunt resistance is used between the two connecting ends of the ammeter.
The confusing part here for me is that the solar panel is connected via an MPPT charge controller to my 1.5 KVA inverter which in turn powers my house equipment, and I am not sure if the two connecting ends of the ACS712 can handle this load (which sometime exceeds to over 450 Wh) if connected in between the wire connecting the panel and charge controller.
Can anyone help me with a suggestion or better with a diagram showing the suggested system.

The question might be better suited to the Electronics SE.

the ACS712 is not based on shunts, it's based on the Hall-effect, like a clamp meter.

If you're going to post a question about a specific part, always post a link to the datasheet you're using. (If you're not using a datasheet, go find one and read it!) Making people hunt around for the specs for your part is a good way to discourage them from answering.

I am not sure if an Allegro ACS712 30Amp chip could handle the voltage/current of my system which is usually over 60v dc and 4-5 amps.

Easily. It's designed for mains voltages up to 30A. You're using a fraction of that. You could even use the 20A version to get more accuracy and resolution.

The confusing part here for me is that the solar panel is connected via an MPPT charge controller to my 1.5 KVA inverter which in turn powers my house equipment, and I am not sure if the two connecting ends of the ACS712 can handle this load (which sometime exceeds to over 450 Wh) if connected in between the wire connecting the panel and charge controller.

Why is that confusing? If you're monitoring the feed between the solar panel and the charge controller what comes out of that system at the other end is of no concern. Just because you are drawing a larger current from the output doesn't mean that the solar panels are providing that current - that comes from the batteries. Now if you were monitoring the current to/from the batteries that would be a different matter. You'd need to calculate the peak current that your house would draw at mains voltage then convert that to the current at the battery voltage (converting to watts in between is a good step. Note that Wh is meaningless when you want a peak value - Wh is a total power over a period of time ["area under a curve"], but you don't care about time, only peak ["maximum value of curve"]).

I know what you mean.
It can read it, but sure the terminals and the power going though it are tiny and therefore have to take a current at the terminals.
Try a ASC758LCB-100U-PFF-T.
You say your 60V 5 Amps. therefore for I will say "yes" this is 300 watts
There are two terminals per side for the connection
1-2 and 3-4.. I would Solder Join them to enure it can hold the current.
Im looking at this issue and I have made the suggestion above on what you could use as a alternative. it has been used for more powerful systems, in a 30 amp MPPT charge controller.
The area of each terminal is 0.51x0.25x1.27 (0.6477mm2) AWG puts it as a 1.8 amp current area or AWG 19
At worst case, the chip legs will be like a fuse and it will just "pop". so dont go to the fuse box first. they are also internally fused.

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


text:
How to stop transmission i2c on LCD 16x4 i2c
i want to try to stop communicaton I2C between arduino and lcd I2C but i don't see any command to stop this communication. I try with Wire.endTransmission or Wire.end but the transmission to the LCD continue without problem. I'm using this library NewliquidCrystal and inside no command for end transmission. I need to interupt that communicaton for have a good management of lcd or if know a new library with best features. Thank's for help

What do you mean "stop" communication? If you don't perform any LCD manipulation commands you won't be communicating, so just don't do anything if you don't want to do anything.

i wan't to interrupt communcication becouse after some time i have some spikes on i2c bus and lcd print casual char, and i thinked with interrupted communication i can avoid this stuff , thanks for help

No. If you have noise on the I2C bus you need to find and suppress the cause of that noise, or harden your I2C bus. The simplest way to harden the I2C bus is to not rely on the (completely incorrect) internal pullups on the GPIO pins and instead fit (protocol standard) 3.3kΩ pullup resistors.

I need to interupt that communicaton for have a good management of lcd or if know a new library with best features. Thank's for help

This sounds like a classical X-Y problem. You have decided on a solution and asking about some "magic" functionality without understanding the library or how the I2C bus works.
It would be better to try to describe the original issue, investigate, propose and discuss solutions. Basically better understand the original issue.
Back to your question:

Wire.endTransmission()

does not really do what you think. It marks the end of a block to be transmitted (previous Wire.write()) and starts the actual transmission to the slave.
This is what the manual says:

Wire.endTransmission()
Description
Ends a transmission to a slave device that was begun by beginTransmission() and transmits the bytes that were queued by write().


text:
WiFiESP constantly losing connection
I am working on a traffic light with a ESP8266-01 wifi module on an Arduino.
The wifi card should act as a server and wait for a request to come in at /R (red), /Y (yellow), /G (green) or /O (off) and open the relay for that light.
The Arduino with wifi starts perfectly, and I can switch to a color.. but after a short while it dies and doesn't respond to requests. Sometimes after uploading a few times it seems to get the >>> TIMEOUT >>>, but that usually is resolved by turning of the power to the Arduino for a short while.
The ESP is set to 9600 baud and uses pins 9 and 10. Ping 6, 7 and 8 go to the relay shield for turning off/on the lights.
What is it I am missing here:
#include <SoftwareSerial.h>
#include "WiFiEsp.h"

#define PINGREEN 6
#define PINYELLOW 7
#define PINRED 8

#define OFF HIGH
#define ON LOW

// WIFI Settings
char ssid[] = "somewifi";
char pass[] = "somepass";
int status = WL_IDLE_STATUS;

// Serial settings
SoftwareSerial Serial1(9, 10);

// WiFi settings
byte mac[] = { 0xDE, 0xAD, 0xDA, 0x0D, 0x14, 0xBF }; // WIFI Sheild MAC address
int reqCount = 0;                                    // number of requests received

// NETWORK: Static IP details...
IPAddress ip(10, 0, 0, 223);

WiFiEspServer server(80);

// The state of the trafic light, default state should be off
enum traficLight {
  off,
  green,
  yellow,
  red
};

// The type of data that we want to extract from the page
struct TrafficLightData {
  char red[32];
  char yellow[32];
  char green[32];
};

// Set the default of the trafic light
traficLight currentLight = off;

// use a ring buffer to increase speed and reduce memory allocation
RingBuffer buf(8);

// Change the active light of the trafic light
void changeLightTo(traficLight light, int setDelay = 1000) {
  // Start with turning all lights off
  digitalWrite(PINGREEN, OFF);
  digitalWrite(PINYELLOW, OFF);
  digitalWrite(PINRED, OFF);

  // Check if the new light requested is not off
  if (light != off) {
    int pin;
    switch (light) {
      case green:
        pin = PINGREEN;
        break;
      case yellow:
        pin = PINYELLOW;
        break;
      case red:
        pin = PINRED;
        break;
      default:
        pin = -1;
        break;
    }

    if (pin > 0) {
      digitalWrite(pin, ON);
    }
    currentLight = light;
  } else {
    currentLight = off;
  }

  if (setDelay > 0) {
    delay(setDelay);
  }
}

// Test if all the lights work
void doLightTest() {
  // Turn all lights on for 2 sec
  changeLightTo(off);

  delay(500);

  digitalWrite(PINGREEN, ON);
  digitalWrite(PINYELLOW, ON);
  digitalWrite(PINRED, ON);

  delay(1000);

  changeLightTo(off);
}

void setup() {
  // start the serial library:
  Serial.begin(115200);
  Serial1.begin(9600);

  // Setup pins
  pinMode(PINGREEN, OUTPUT);
  pinMode(PINYELLOW, OUTPUT);
  pinMode(PINRED, OUTPUT);

  // Start with light test
  doLightTest();

  setupWifi();

  // Set the pins
  Serial.println("Settings pins:");
  Serial.print(" - GREEN: ");
  Serial.println(PINGREEN);
  Serial.print(" - YELLOW: ");
  Serial.println(PINYELLOW);
  Serial.print(" - RED: ");
  Serial.println(PINRED);

  delay(1000);

  changeLightTo(off, 0);
}

void setupWifi() {
  Serial.println("Starting wifi...");

  WiFi.init(&Serial1);
  //WiFi.config(ip);

  if (WiFi.status() == WL_NO_SHIELD) {
    changeLightTo(red, 1000);
    Serial.println("Wifi shield not present!");

    // Don't continue
    while (true);
  }

  while (status != WL_CONNECTED) {
    Serial.print("Attemting to connect to SSID: ");
    Serial.println(ssid);

    status = WiFi.begin(ssid, pass);
  }

  Serial.println("You're connected to the network");
  printWifiStatus();

  server.begin();
}

void loop() {
  WiFiEspClient client = server.available();

  if (client) {
    Serial.println("New client");
    buf.init();

    while (client.connected()) {
      char c = client.read();
      Serial.write(c);
      buf.push(c);

      if (buf.endsWith("\r\n\r\n")) {
        sendHttpResponse(client);
        break;
      }

      if (buf.endsWith("GET /R")) {
        Serial.println("LIGHT RED!");
        changeLightTo(red, 0);
      } else if (buf.endsWith("GET /Y")) {
        Serial.println("LIGHT YELLOW!");
        changeLightTo(yellow, 0);
      } else if (buf.endsWith("GET /G")) {
        Serial.println("LIGHT GREEN!");
        changeLightTo(green, 0);
      } else if (buf.endsWith("GET /O")) {
        Serial.println("LIGHT OFF!");
        changeLightTo(off, 0);
      }
    }

    // Give the browser time to recieve the data
    delay(10);

    client.stop();
    Serial.println("Client disconnected");
  }

  /*if (WiFi.status() == WL_DISCONNECTED || WiFi.status() == WL_CONNECT_FAILED) {
    setupWifi();
  }*/
}

void sendHttpResponse(WiFiEspClient client) {
  Serial.println("Sending response");

  client.print(
    "HTTP/1.1 200 OK\r\n"
    "Content-Type: text/html\r\n"
    "Connection: close\r\n"
    "\r\n");
  client.print("<!DOCTYPE HTML>\r\n");
  client.print("\r\n");
  client.print("\r\n");
  client.print("<title>Traffic light</title>\r\n");
  client.print("\r\n");
  client.print("\r\n");
  client.print("
Main page for traffic light!
\r\n");
  client.print("
Select light to use:
\r\n");
  client.print("
 - Red
\r\n");
  client.print("
 - Yellow
\r\n");
  client.print("
 - Green
\r\n");
  client.print("
 - Off
\r\n");
  client.print("\r\n");
  client.print("\r\n");
  client.print("\r\n");
}

void printWifiStatus() {
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // Print the 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.print(" dBm (Signal strength is ");
  Serial.print(rssiToText(rssi));
  Serial.println(")");
}

String rssiToText(float rssi) {
  if (rssi > -30) {
    return "Amazing";
  } else if (rssi > -67) {
    return "Very good";
  } else if (rssi > -70) {
    return "Okay";
  } else if (rssi > -80) {
    return "Not good";
  } else if (rssi > -90) {
    return "Unusable";
  }

  return "";
}

The output I get is the following:
Starting wifi...
[WiFiEsp] Initializing ESP module
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] Initilization successful - 1.5.4
Attemting to connect to SSID: somewifi
[WiFiEsp] Connected to somewifi
You're connected to the network
SSID: somewifi
IP address: 10.0.0.145
signal strength (RSSI):-62 dBm (Signal strength is Very good)
[WiFiEsp] Server started on port 80
Settings pins:
 - GREEN: 6
 - YELLOW: 7
 - RED: 8
[WiFiEsp] New client 0
New client
GET / HTTP/1.1
Host: 10.0.0.145
Connection: keep-alive
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding: gzip, deflate, sdch
Accept-Language: sv-SE,sv;q=0.8,en-US;q=0.6,en;q=0.4,nl;q=0.2

Sending response
[WiFiEsp] Disconnecting  0
Client disconnected
[WiFiEsp] New client 0
New client
GET /favicon.ico HTTP/1.1
Host: 10.0.0.145
Connection: keep-alive
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
Accept: image/webp,image/*,*/*;q=0.8
Referer: http://10.0.0.145/
Accept-Encoding: gzip, deflate, sdch
Accept-Language: sv-SE,sv;q=0.8,en-US;q=0.6,en;q=0.4,nl;q=0.2

Sending response
[WiFiEsp] Disconnecting  0
Client disconnected
[WiFiEsp] New client 0
New client
GET /GLIGHT GREEN!
 HTTP/1.1
Host:�[WiFiEsp] TIMEOUT: 416
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] No tag found
Client disconnected

Usually just stopping after a while is a memory leak, but I can' t see anything obvious apart from you circular buffer.  Could it be the web side is writing data into the buffer faster that it can be read.  Try a 1024byte buffer?  If it isn't that could the ESP be faulty in some way, can you swap it for a different one?

Please help us to help you by replacing your code with a minimal, complete, verifiable example .

Except for the debugging Serial.println() I would argue it pretty much is mcve. Maybe its a good idea to read the question, @MarkSmith?

@Matt good idea. I've ran the Arduino with the ESP over night now with the red light turned on and it is still on. The router stil sees the ESP connected with uptime of 17h, but when connecting to the IP I get a time out.

@PaulPeelen I respectfully disagree. Does the problem go away if you remove the LED lighting code?  What about if you only send a dummy HTTP response?

Yes and no, the LED code can impose a memory issue which gets the server to not respond. However, I can't seem to find that. The LED work on their own and the HTTP works a lot longer on its own. I removed the html return body and only return a one line text, which also keeps the module responding for a longer time.


text:
Light up more than one LED connected to 74HC595 Shift Register
I have a 74HC595 Shift Register with a LED (and resistor) on each of the 8 output pins.
I can light them all up
I can light one up
How do I light two up?
For example the one on pin 2 and the one on pin 7
I used this a my starting point.
https://learn.adafruit.com/adafruit-arduino-lesson-5-the-serial-monitor?view=all
Is 74HC595 Shift Register  the correct componet to use?

You don't mention if you are using and Arduino, but I will assume that is the case.
Using the shift register to light up LEDs is fairly straight forward.
You can use the ShiftOut() function to send out an 8bit binary value to the register. https://www.arduino.cc/en/Reference/ShiftOut
In summary however, if you want to light up the LEDs on the output pins 2 and 7 you would shift out b01000010 to the shift register. If you wanted pins 4, 5 and 7 to light up, you shift out b01011000. These assume the least significant bit is sent first.
Here's an example:
// set shift register output pins 2 and 7 to high
uint8_t data = 1<<2 | 1<<7; // use bit shifting

digitalWrite(latchPin, LOW);
shiftOut(dataPin, clockPin, LSBFIRST, data); // send the data
digitalWrite(latchPin, HIGH);

Cheers, that works a charm

How do I light two up? For example the one on pin 2 and the one on pin 7

If the LEDs are active high, sending 0x82 lights up the two LEDs.
If they are active low, sending ~0x82 lights up the same LEDs


text:
Can't send SoftwareSerial to Class Object
I have a problem when I try to use SoftwareSerial in a class..
Here my detail My class
class MyEsp8266
{
 protected:
     SoftwareSerial *esp8266;
 public:
     MyEsp8266(SoftwareSerial *_esp8266){
           esp8266 = _esp8266;
     }
     void begin(int baud){
        esp8266->begin(baud);
     }
     String testAT(){
          esp8266->println("AT");
          return esp8266->readString();
     }
}

My Arduino code
#include <SoftwareSerial.h>
#include "MyEsp8266.h"
// the setup function runs once when you press reset or power the board

SoftwareSerial _esp(10, 11);
MyEsp8266 wifi(&_esp);

void setup() {
    Serial.begin(9600);
    wifi.begin(115200);
    Serial.println(wifi.testAT());
}

It doesn't log anything But when I have used all code in Arduino code it worked.
#include <SoftwareSerial.h>
// the setup function runs once when you press reset or power the board

SoftwareSerial _esp(10, 11);

void setup() {
    Serial.begin(9600);
    _esp.begin(115200);
    _esp.println("AT");
    Serial.println(_esp.readString());
}

Thank any tips.
Regards.

You forgot to print the return value of wifi.testAT();...?

it my mistake when post question I have updated it

This is more of a work-around than a solution, but the code you're trying to get to work, worked for me once I changed
wifi.begin(115200);

to
wifi.begin(9600);

(sorry I don't have enough karma to just comment)

Hi baud 115200 worked with secondary code.

I agree! and when testing your desired block of code, I got it to output the test line by changing the baud from 115200 to 9600.

I think that means your Wifi module use baud 9600.

To clarify, I was using the bluetooth HC-05 which a quick Google search tells me It can go up to 1382400. But besides, I tried both code samples, the second worked without modification (meaning my hardware can handle 115200) and then when I tried the first, and once I changed the baud to 9600 it worked. Did adjusting the baud rate on the first code sample not fix the problem for you?

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


text:
What difference between readString and while loop read
From Arduino code, I have a question for SoftwareSerial Class
First: when I use more example for Esp8266 those functions use while loop to read response string from Esp when we send AT_Command to ESP.
getResponse(const uint32_t  wait) {
    String tmpData = "";
    long int time = millis();
    while ((time + wait) > millis()) {
        while (esp8266->available() > 0) {
            char c = esp8266->read();
            if (c == '\0') continue;
            tmpData += c;
        }
    }
    tmpData.trim();
    return tmpData;
}

I know that SoftwareSerial Class have a public method is readString() then I'm tried to use that and it return same result returned by while loop read:
getResponse(const uint32_t  wait) {
    String tmpData = "";
    tmpData = esp8266->readString();
    return tmpData;
}

Thanks for any. I'm working on improving my Eng.
Regards

Your while loop reads all the characters up until it reaches character 0 (it also has a timeout, although the timeout has been coded wrong since it can't deal with clock rollover). The .readString() method reads characters until no characters arrive within a timeout period (1s if memory serves me correctly).
Your while loop is the more reliable method since it uses a specific delimiter to identify blocks of data (strings) rather than assuming that:

The string will all arrive with no delays greater than the timeout
The strings will be sent with a gap of at least the timeout length between them.

Personally I would never recommend using any of the "helpful" functions provided for reading from a Stream object other than the basic .read() function.


text:
Using an esp8266, how can I create a circuit to measure 2 different analog inputs (not simultaneously) with only one ADC pin available (A0)
I'm currently using a circuit with 2 separate transistors that can be switched on or off to measure 2 separate voltage inputs.
The reason for this is because I'm using an esp8266 which has only one ADC input at pin A0 and I need to measure light intensity from an LDR as well as voltage from a solar panel.
The LDR is wired with a voltage divider. The voltage input from the solar panel is 0 - 5v, so I have that wired with a voltage divider to output a max of 3.3v (pin A0 is 0 - 3.3v). The problem is that in complete darkness, the ADC is still reading the LDR with a value of around 260 (should be close to zero) and with bright light reading around 850 (should be close to 1023). Also, the voltage measured from the solar panel (divided to 3.3v) is returning anywhere from 600 (0v) to around 840 (3.3v).
I've tried these input measurements separately with expected results. It's having the option to switch inputs is what is tripping me up.
So, is my approach correct or is there another way to do this?
Note: I would have included a circuit diagram if I knew anything about circuits and making diagrams.

you can measure resistance quite accurately with a digital pin and some passive components using RC timing. I have a reisistor finder sketch that uses this, as it works better than a voltage divider for identifying unknown values on a large range of ohms, not just ones that work well as voltage dividers when close to the known resistor.... you can also use a plain old relay to switch between two analog inputs.

Could use a multiplexer to switch analog input.  You connect one pin to youe esp, and then you can connect 4-16 inputs/output depending on the chip.  Use  2-4 control pins to select the pin you want to read/write on.

Can anyone explain what's up with the down vote? Was my question too detailed?

For what it's worth, I solved the problem by simply condensing the range of values with the light and voltage readings in my script along with adding a higher ohm resistor to the base of both transistors. The resolution isn't as high, but still very accurate.

There's two basic solutions, both of which require the addition of an external chip:

Use an analog multiplexer to select the different devices to connect to the ADC input
Use an external (I2C or SPI) ADC chip. These can give you higher resolutions than the internal ADC and many more inputs (depending on the chip you choose).

My recommended solution would be to get an external ADC chip.

Thank you, I'll look into those solutions. So, why wont simple transistors work in this scenario? Isn't a transistor just a switch?

I can be done with transistors but you have to select the right kind of transistors and wire them in the right way. A transistor is not just a switch - certainly a BJT isn't just a switch.


text:
Instance does not name a type, in function void loop (8x8 matrix)
Hey guys I'm doing a beginners project 8x8 matrix and I have some errors when compiling
The Errors are;

MyBlink:0: error: 'Instance' does not name a type
MyBlink.cpp: In function 'void loop()':

-MyBlink:40: error: 'row1' was not declared in this scope
 Instance code:
//the pin to control ROW
const int row1 = 2; // the number of the row pin 9
const int row2 = 3; // the number of the row pin 14
const int row3 = 4; // the number of the row pin 8
const int row4 = 5; // the number of the row pin 12
const int row5 = 17; // the number of the row pin 1
const int row6 = 16; // the number of the row pin 7
const int row7 = 15; // the number of the row pin 2
const int row8 = 14; // the number of the row pin 5
//the pin to control COl
const int col1 = 6; // the number of the col pin 13
const int col2 = 7; // the number of the col pin 3
const int col3 = 8; // the number of the col pin 4
const int col4 = 9; // the number of the col pin 10
const int col5 = 10; // the number of the col pin 6
const int col6 = 11; // the number of the col pin 11
const int col7 = 12; // the number of the col pin 15
const int col8 = 13; // the number of the col pin 16
void setup(){
int i = 0 ;
for(i=2;i<18;i++)
{
pinMode(i, OUTPUT);
}
pinMode(row5, OUTPUT);
pinMode(row6, OUTPUT);
pinMode(row7, OUTPUT);
pinMode(row8, OUTPUT);
for(i=2;i<18;i++) {
digitalWrite(i, LOW);
}
digitalWrite(row5, LOW);
digitalWrite(row6, LOW);
digitalWrite(row7, LOW);
digitalWrite(row8, LOW);
}
void loop(){
int i;
//the row # 1 and col # 1 of the LEDs turn on
digitalWrite(row1, HIGH);
digitalWrite(row2, LOW);
digitalWrite(row3, LOW);
digitalWrite(row4, LOW);
digitalWrite(row5, LOW);
digitalWrite(row6, LOW);
digitalWrite(row7, LOW);
digitalWrite(row8, LOW);
digitalWrite(col1, LOW);
digitalWrite(col2, HIGH);
digitalWrite(col3, HIGH);
digitalWrite(col4, HIGH);
digitalWrite(col5, HIGH);
digitalWrite(col6, HIGH);
digitalWrite(col7, HIGH);
digitalWrite(col8, HIGH);
delay(1000);
//turn off all
for(i=2;i<18;i++) {
digitalWrite(i, LOW);
}
delay(1000);
}

MyBlink:0: error: 'Instance' does not name a type

Once I deleted the line Instance code: on the first line both errors went away.
Cheers

There is typo in your program. Exactly you should comment out the first line of your code. Adding two slashes at the beginning of the first lines.
Instance code:

As this is not a valid syntax for your code. The compiler is not recognizing what are you trying to do. So it generates a second error because everything that comes after may generate an unknown error.
Next time try to solve these kind of problems by reading your console log as it describes exactly at which lines the compiler has found an error. You can see that it generates an error at line 0:

Myblink:0:error....

You have multiples errors on this program because as i said before sometimes they are generated as a consequence of your previous error. So you should also try to fix your errors from top to bottom.

The colon is a bit misleading, it is used in C++ to denote inheritance like this:
E.g.
class Form
{
  int _area;

  public Form(area)
  {
    _area = area;
  }
}

class Circle : class Form
...

However, this is not your intention probably.
Also the colon is used for calling base constructors and for labels to go to (goto, never use this).


text:
Arduino Uno with ESP8266
#include <stdlib.h>
#include <SoftwareSerial.h>

#define SSID "name-of-my-network" //replace XXXXX by your router SSID
#define PASS "password-of-network" //replace YYYYY by your router password
#define IP "184.106.153.149" //thingspeak.com IP

const int tempPin = A0; //configure Arduino pins
String GET = "GET /update?key=thingspeak-api-key&field1=";
SoftwareSerial mySerial(10,11); //Serial communication to ESP8266 module(RX, TX)
unsigned long starttime;
unsigned long sampletime_ms = 30000;
unsigned long delay_time = 60000;

void setup() {
  Serial.begin(57600);
  while(!Serial) {
    ;
  }
  mySerial.begin(115200);
  Serial.println("Initializing...");
  //communication with wifi module
  mySerial.flush();
  mySerial.println("AT");
  delay(2000);
  if(mySerial.find("OK")) {
     Serial.println("Communication with ESP8266 module: OK");
   } else {
     Serial.println("ESP8266 module ERROR");
   }
   connectWiFi();
   //initialize timer
   starttime = millis();
}

void loop() {
  // put your main code here, to run repeatedly:
  if ((millis() - starttime) >= sampletime_ms) {
    char buffer[10];
    int analogReading = analogRead(tempPin);
    String temperatureStr = dtostrf(analogReading, 4, 1, buffer);
    temperatureStr.replace(" ","");
    updateSensors(temperatureStr);
    //wait next sampling cycle
    Serial.print("Wait ");
    Serial.print(delay_time/1000);
    Serial.println("s for next sampling");
    Serial.println();
    delay(delay_time);
    //initialize new cycle
    Serial.println();
    Serial.print("Sampling (");
    Serial.print(sampletime_ms/1000);
    Serial.println("s)...");
    starttime = millis();
  }
}

void updateSensors(String tempStr){
  String cmd = "AT+CIPSTART=\"TCP\",\"";
  cmd += IP;
  cmd += "\",80";
  mySerial.println(cmd);
  delay(2000);
  cmd = GET;
  cmd += tempStr;
  cmd += "\r\n";
  delay(1000);
  int strsize = cmd.length();
  mySerial.println("AT+CIPSEND=" + String(strsize));
  delay(2000);
  mySerial.print(cmd);
  if(mySerial.find("OK")) {
    Serial.println("Transmission completed with success");
  } else {
    Serial.println("Transmission failed!");
  }
}

boolean connectWiFi(){
  Serial.println("Connecting wi-fi...");
  String cmd ="AT+CWMODE=1";
  mySerial.println(cmd);
  delay(2000);
  mySerial.flush(); //clear buffer
  cmd="AT+CWJAP=\"";
  cmd+=SSID;
  cmd+="\",\"";
  cmd+=PASS;
  cmd+="\"";
  mySerial.println(cmd);
  delay(5000);
  if(mySerial.find("OK")) {
    Serial.println("Connection succeeded!");
    return true;
  } else {
    Serial.println("Connection failed!");
    return false;
  }
  Serial.println();
}

I am using the above code and have connected the ESP8266 to the Arduino as follows:

TX of ESP8266 to pin number 11 of Arduino
  Rx of ESP8266 to pin number 10 of Arduino
  Vcc of ESP8266 to 3.3V power supply taken from Arduino
  GND of ESP8266 to GND taken from Arduino
  CH_PD of ESP8266 to GND

It seems that I can't get the ESP8266 working. Could anyone could help me? I would really appreciate any help since I cannot continue my project.

Does your ESP module have the AT firmwware?

If you interconnect two serial devices, the RX of device 1 is connected to TX of device 2. You appear to have connected RX to RX and TX to TX.

CH_PD of ESP8266 to GND should be at 3.3v instead of 0v...

Often the issue with this module is that the 3.3v of Arduino is unable to maintain enough current for the ESP8266 to work properly. I assume you have the proper firmware flashed to the wifi module

Yes, you are right. After many different attempts p, I figured that out. When I use the module with h a 3.3V FTDI, it works perfectly. When I use it with Arduino, data that is being sent to or received from the module, is corrupted. Arduino can't supply enough current to the ESP8266 module.

This code is used to upload temperature data on pin A0 to things speak
Create thingspeak account and create channel you get api key it seems that this code uses field1 to upload data upload this code to arduino the change ssid and password


text:
Cutting off OneWire/SDA line with transistors
I am developing a pcb for a design I am working on and I need to share a pin to be used by a ds18b20 (onewire) and some possible I2C sensors. There would be just one of each at a time.
I was thinking about using a couple of transistors. One would cut or enable ds18b20 data line and the other one, the same for SDA line. So I would enable the first one and disable the second one or viceversa.
Do you think this is possible? I don't have transistors right now to test it. I have to order some of them. I was thinking about a bd228. Would this add some errors/delays/whatever in signal information? A kind of distorsion I mean. Or should it work?
EDIT: I will try to explain a bit my project.
My idea is to have a box with 5 sockets. Each one of them will be a different data input. They should be able to use a wide variety of sensors, ds18b20, dht22, open/close door (1 or 0 signal)... Also I would want to include some I2C sensors.
I was thinking about BME280 for example.
My idea is that the user could set which sensor is connected each time so the arduino can switch transistor behaviour to allow the connectivity to the digital pin or the I2C SDA (or SCL) pin.
I was thinking about using an I2C multiplexer to allow multiple BME280 to be at the same time so the first line would go to the socket1, second line socket 2...

You could use a I2C-to-1-Wire bridge. The DS2483 solves the problem; https://datasheets.maximintegrated.com/en/ds/DS2482-100.pdf. An example driver may be found in Cosa; https://github.com/mikaelpatel/Cosa/blob/master/libraries/DS2482/DS2482.hh. The example sketch shows how to talk to a DS18B20; https://github.com/mikaelpatel/Cosa/blob/master/libraries/DS2482/examples/CosaDS2482/CosaDS2482.ino

Thank you. At the end I removed that part from my pcb but I will keep in favorites your links, they could be useful in future when we have to do some rework on the pcb.

For multiple I2C busses, it is allowed to share a single SCL and have a separate SDA line for each I2C bus. That means that as long as the SDA is inactive (high), you can do with the SCL whatever you want.
It might even be possible to share the SCL signal for I2C and 1-Wire, and use both. The SCL signal would then also be the 1-Wire signal. The I2C pulses are probably shorter than the start pulse of the 1-Wire. You would also have to do it right in the software to switch the function of the pins. As far as I know that has never been done, so you might get into a lot of trouble.
Transistors are not the right choice to multiplex signals, and the BD228 is definitely not okay. The I2C bus is a open-collector or open-drain bus with a current of maximum 3mA. The 1-Wire bus is roughly the same. It is possible with mosfets or with multiplexers (see: Nick Gammon about multiplexers). However, if you are going to add extra hardware there are probably better solution than combining I2C with 1-Wire.
Have you thought about the voltage levels ? Are you using a 5V Arduino board ? Most sensors are 3.3V. The DS18B20 will work with voltages as low as 3.0V, so 3.3V is no problem for the DS18B20.
Tell us what else is connected to your Arduino board. I'm sure there are better solutions.
Could you better specifiy what it is that you want to achieve ? When there is only I2C sensors or only 1-Wire sensors connected, you could run a i2c-scanner to check for I2C sensors. If nothing is found, do a Wire.end() and start the OneWire using the SCL pin. That could be done during startup and then you don't need extra hardware.
How long are the wires ? The 1-Wire bus can have long wires, but the I2C bus can only have short wires.

I added an explanation about what I want to get

The Arduino is for fast prototyping. With an Arduino board and a small breadboard, all the sensors that you mentioned can be used. However, 5 universal ports that can do everything might be too much. I'm not sure if you can make that work. With Software I2C it is possible to create multiple I2C busses, and the same two pins can also be set as 1-Wire bus or for the DHT22 signal. It might be possible if you are a software wizard.
The most practical solution is to use only a BME280.
There is still the problem with voltage levels, and I don't know if you want to change sensors runtime.


text:
Arduino String memory allocation
When a String variable is declared and modified inside a function, where does it go? To the heap(as string declaration is a part of dynamic memory allocation) or to the stack(as it is a part of function)? And is the space regained after the function goes out of the scope?
For example
void loop()
{
  Serial.println(foo("def"));
  while(1);
}

String foo(String arg1)
{
 String test = "abc";
 test = test + arg1;
 return test;
}

So, in this case, the variable "test" is declared in stack or heap? And this space is regained at the end or not?
Modified:
What if inside loop variable is declared like below?
String foo_test = F("def");
Serial.println(foo(foo_test));

In this case what will be the status of variables?

There is the String object, and then there is the character data referenced by that object. They don't live together.

It compiled fine and showed the output too. What's wrong with that?

@EdgarBonet    you mean to say that string object will reside in stack and the char data reference will stay in heap? Pardon for misunderstanding in previous comment.

The string object may reside in the function's stack, in the caller's stack, or in CPU registers. That's a matter of compiler optimization. For a simplified mental picture, you may assume it's in the function's stack. Everything should work “as if” that's the case.

@EdgarBonet     @Mikael@Michel Please see the modified

This is an excellent question to illustrate the amount of string copying and heap operations (malloc/free) going on when using the Arduino String class.
void loop()
{
  Serial.println(foo("def"));
  while(1);
}

The compiler will generate loop() something like this:
void loop()
{
  // String literal is stored in program memory. Needs to be copied
  // to temporary variable. This is done before main() is called.
  static const char temp0[4] PROGMEM = "def";
  static const char temp1[4];
  copy_from_program_memory(temp1, temp0);

  // The parameter to the call to foo() is actually a temporary String
  // variable constructed from the string literal. Storage is allocated
  // on the heap and the assigned from the value of the string literal.
  String temp2;
  temp2.constructor(temp1);

  // The return value of the call to foo() is a String that is passed
  // to Serial.println(). This is also a temporary String variable.
  String temp3;
  temp3.constructor(foo(temp2));
  Serial.println(temp3);

  // The String class destructor has to be called for the temporary
  // String variable so that the string values on heap are deallocated.
  temp2.destructor();
  temp3.destructor();
}

Note that each call to the constructor involves allocating and copying data to the heap.
String foo(String arg1)
{
 String test = "abc";
 test = test + arg1;
 return test;
}

The function foo() needs to copy strings several times to perform the string concatenation. The operator+ will require an intermediate String copy.
Cheers!
PS: For more details please see the assembly listing below with the calls to String member functions. The compiler reduces inline member functions and reuses temporary local variables. Also the call to foo() is inlined. The member function reserve() is part of the constructor.
00000198 <main>:
 1de:   60 df           rcall   .-320       ; 0xa0 <String::reserve(unsigned int)>
 1fc:   50 d2           rcall   .+1184      ; 0x69e <strcpy>
 212:   46 df           rcall   .-372       ; 0xa0 <String::reserve(unsigned int)>
 230:   36 d2           rcall   .+1132      ; 0x69e <strcpy>
 248:   62 df           rcall   .-316       ; 0x10e <String::operator=(String const&)>
 26a:   1a df           rcall   .-460       ; 0xa0 <String::reserve(unsigned int)>
 27e:   0f d2           rcall   .+1054      ; 0x69e <strcpy>
 28e:   3f df           rcall   .-386       ; 0x10e <String::operator=(String const&)>
 294:   60 df           rcall   .-320       ; 0x156 <String::~String()>
 29a:   5d df           rcall   .-326       ; 0x156 <String::~String()>
 2a0:   5a df           rcall   .-332       ; 0x156 <String::~String()>

Bottom-line is that the String class uses a lot of instruction cycles and memory, and there is a potential risk of heap fragmentation and allocation failure.

I would expect copy_from_program_memory(temp1, temp0); to be done only once, by __do_copy_data(), from the C runtime.

Yes, that would also make temp1 static. Should correct that.

This is a nice explanation. Can you please suggest some good reference or articles to this memory issue?

Please see https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/

See also http://www.nongnu.org/avr-libc/user-manual/malloc.html

And last the source https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/WString.h and https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/WString.cpp.

The truth here turns out to be a bit more complicated than the other answers express. There's more than one implementation of the Arduino String library, and some are better than others. Which one you get depends on which board you deploy to.
The newer code handles strings a whole lot more efficiently, particularly in terms of memory usage, and changes the whole dynamic around the answer to this question.
Compare the original version of the Arduino String library, the one for AVR, to the version for the ESP8266.
(As of writing this answer, these were this snapshot and this snapshot, respectively.)
Looking in particular at the functions like changeBuffer you can see that the ESP version contains something called "SSO" ("Small String Optimization") added with this PR here. Basically, for small strings—small enough to fit in the structure would otherwise be used to track the string buffer on the heap—it'll just store the string in that space (in the String object itself) instead.
In practice, this means strings smaller than 12 characters don't require memory allocation; they're stored on the stack inside the String object.
This is a pretty huge deal if you push around a lot of tiny strings, like in the example listed in the question. It means that the code works about as efficiently as you might hope, without problematic side-effects.

The string is an instance of an object, high likely keeping the administration like the offset and size (unless it is implemented as a 0-delimited string).
This is a local variable and will be stored on the stack and will be nicely removed after finishing the function.
The characters itself ("abc" ...) will be stored on the heap since this needs to be dynamic. This data will be freed by the string object after returning from the function and possibly when needed to relocate the string.
Normally a string instance will keep some memory allocated, when it is increased (or increased too much) the string content will be copied. This all happens in heap and 'holes' in the heap can occur by this.
That's why in a memory/time critical process it's best to allocate the string before hand, of course this is only possible if you know the (maximum) string size.

You said this is a local variable and will be stored in stack. Did you mean to say variable "test" will be stored in stack?But when string manipulation occurs i.e test += arg1; isn't it that the size of test will increase in heap or is it stack?

As Edgar already wrote, there are two items: the instance (keeping the administration), this is probably the pointer and possible the size of the string; this will be kept in stack. The memory allocation will never change. However, the characters itself are stored on the heap since this will change. When you add a character, depending on the implementation, possibly the whole string will be copied from one heap space to another location in the heap (using one more byte), and the pointer (stored in the stack) is pointing to the new allocated space in the heap.

Also you can use the F(" ..." ) way, this puts the fixed strings in flash memory (of course for altering strings this is not possible).

Yes, Explanation is good.


text:
Possible error in CAN-Bus shield schematic?
This is a part of SeeedStudio CAN-Bus shield schematic. The vertical green line on the left seems suspicious to me. Am I missing something?

No, it's not a mistake. It's related to this statement on their Wiki:

When you use more than two CAN Bus Shield in one net, you should take the impedance into consideration. You should either cut P1 in the PCB with a knife, or just remove R3 on the PCB.

If you look closely at the pads of P1 you will see a small trace joining them together. That is the "rogue" green line you found. By cutting that trace you disconnect the termination resistor. You can then re-connect the termination resistor by soldering the pads together again.

Yes, that very remark is what drew my attention to the pad jumper. I assumed "P1" is what I will be cutting. Also on the PCB the part is labelled as "P1". Now you are telling me the part I will be cutting has no special symbol in the schematic and is merely described by a boring green line. :) That is... unexpected.


text:
How can I call the variable **Servo::write** in Arduino for my 360 servo?
I'm trying to control a Servo with a push button and to help me watching if it is working I am using a LED but I'm not sure if I'm doing it well the Servo::write so I need you to tell me what am I doing wrong that my Servo::write function its not working but the LED does the function. Here is the code I am using:
#include <Servo.h>

Servo myservo;

const int  buttonPin = 2;    // the pin that the pushbutton is attached to
const int ledPin = 13;       // the pin that the LED is attached to
const int serPin = 9;

// Variables will change:
int buttonPushCounter = 0;   // counter for the number of button presses
int buttonState = 0;         // current state of the button
int lastButtonState = 0;     // previous state of the button

void setup() {
// initialize the button pin as a input:
pinMode(buttonPin, INPUT);
myservo.attach(serPin);
// initialize the LED as an output:
pinMode(ledPin, OUTPUT);
// initialize serial communication:
Serial.begin(9600);
}

void loop() {
// read the pushbutton input pin:
buttonState = digitalRead(buttonPin);

// compare the buttonState to its previous state
if (buttonState != lastButtonState) {
// if the state has changed, increment the counter
if (buttonState == HIGH) {
  // if the current state is HIGH then the button
  // wend from off to on:
  buttonPushCounter++;
  Serial.println("on");
  Serial.print("number of button pushes:  ");
  Serial.println(buttonPushCounter);
} else {
  // if the current state is LOW then the button
  // wend from on to off:
  Serial.println("off");
}
 // Delay a little bit to avoid bouncing
delay(50);
}
// save the current state as the last state,
//for next time through the loop
lastButtonState = buttonState;

Servo::write(myservo);

// turns on the LED every four button pushes by
// checking the modulo of the button push counter.
// the modulo function gives you the remainder of
// the division of two numbers:
if (buttonPushCounter % 2 == 0) {
 digitalWrite(ledPin, HIGH);
 myservo.write(serPin < 180);
} else {
 digitalWrite(ledPin, LOW);
 myservo.write(serPin > 0);
}

}

I think you should look at some servo examples in the IDE. You will then see that you have done the servo code completely wrong.

(in fact your code doesn't even compile).


text:
What Are The Differences Between Arduino Language and Standard C for MCU?
What the differences between Arduino language and standard C used for MCU programming (like AVR).I heard Arduino language is C.What happen if i use Arduino language with bare-bones AVR chips.Or with PIC mcu.Will it work?
And, if i use just use AVR chip without arduino, will it work with sensor that designed for Arduino (lets say HC-SR04 ultrasonic sensor).And will sensor designed for arduino work with PIC mcu or other non AVR mcu?
I'm a beginner mcu programmer and currenly learning Arduino.Which is good starting point learning Arduino first or just go straight to MCU programming (without Arduino, just bare bones chip)?
Thank you

There's really no such thing as the 'Arduino language'. The Arduino IDE supports C & C++ with some syntactic sugar added.

@m.Alin As far as I know, it supports C++ only. C and C++ are not compatible languages.

@Lundin Arduino "IDE" supports C files quite happily.

@TomCarpenter Try loading a C file that has int new = 5; in it then ;)

@marcelm try loading a file that has int main = 10;. What's your point?

@TomCarpenter His point is that C is not C++. int new = 5; is perfectly valid C but invalid C++. More relevant, try compiling a C file that has VLAs, designated initializers, flexible array members, the _Generic keyword or other such C-specific features in it. C and C++ stopped being compatible languages somewhere around the year 1995, well over 20 years ago.

@Lundin if you include a C file in the Arduino IDE, it will treat it as C. Having just tried it int new = 5 in a .c extension file compiles perfectly well...

C files are compiled using avr-gcc, C++ files are compiled using avr-g++. The only thing you have to do to mix the two is to have #ifdef __cplusplus extern "C" #endif ... in header files that are shared between the C++ and C codes.

@TomCarpenter Ah, I was under the impression that the Arduino IDE only dealt with C++ source files, potentially leading to the C/C++ issues mentioned above. Apparently I was wrong :)

@TomCarpenter int main = 10; compiles perfectly fine in C. You will have trouble using standard library, but you can link directly to C runtime which has a different entry point (_start() in Linux and WinMain() in windows).

There's no "Arduino language", it is C++ with some pre-written libraries to provide an abstraction layer on top of the hardware. You cannot use that library on other microcontrollers because it was designed for the specific MCU (AVR).
Pretty much all microcontrollers on the market have compiler support for the C language, which is similar to C++. There is also often C++ compilers available. But overall, C is by far the most popular language to use when programming embedded systems, with the best tool support.
I would probably avoid spending too much time learning about the Arduino library, since that is not useful knowledge for other platforms. Focus on learning C and study at least one assembler (to grasp what happens underneath the hood of C).

While it is c++ the libraries aren't quite true c. There is no printf, doubles are only 32 bit floats and I'm sure there are some other oddities. So it's just different enough from c to trip you up.

@Andrew C doesn't guarantee double to be 32 bit, or even be supported. That's why you have fancy constants in float.h which tell you how big your numbers really are. And printf is part of libc, not the C language.

@Andrew: printf() is seldom used on the Arduino platform, but it is supported. You will have to setup your stdout before using it. You could quite easily have stdout print through Serial.

Given that, why does arduino still work on non AVR MCUs like the ESP8266?

@dandavis there are Arduino cores for each architecture that all follow a standard API. When you install the ESP8266 hardware package the ESP8266 core library and tools are installed in addition to the hardware definitions and these are used when you compile for any of the boards of that package. The Arduino IDE is certainly not restricted to AVR, though that is currently the most commonly used architecture.


text:
Is something wrong with my Adafruit motor shield?
I think something may be wrong with my shield, as I looked at the other forums related to this question and still can not get help.
I know that I can't run it from a 9V source by itself, as the Adafruit website specifically said I can't. So they said to use a LiPo battery or 8 AA batteries. So I tried powering the shield with 8 AA batteries and the light comes on to confirm that.
I then added a 9 volt battery to power the Arduino itself. My motor is a DC motor from RadioShack that can work at 9V, 12V or 18V. I have the motor connected to M2. What am I doing wrong? Here is the site I am following.
Here is the DC motor.
Again, if anyone knows what I am doing wrong, that would be very helpful to know. Thank you for your time and effort.
Edit 1:
#include <AFMotor.h>

AF_DCMotor motor(2, MOTOR12_64KHZ); // create motor #2, 64KHz pwm

void setup() {
  Serial.begin(9600); // set up Serial library at 9600 bps
  Serial.println("Motor test!");
  motor.setSpeed(200); // set the speed to 200/255
}

void loop() {
  Serial.print("tick");
  motor.run(FORWARD); // turn it on going forward
  delay(1000);
  Serial.print("tock");
  motor.run(BACKWARD); // the other way
  delay(1000);
  Serial.print("tack");
  motor.run(RELEASE); // stopped
  delay(1000);
}

Please describe what is not working

The motor is not spinning even though I know the motor is working. I think there was a thread called motor not spinning or something but that thread did not help. So what am I doing wrong that the motor doesn't spin?

Can you provide more information about how the 8 AA batteries are configured? Are they in series or parallel or some combination? How are you initiating the signal to motor that it should turn? Do you have some code?

The batteries are in series as they are in a battery holder that I got from radio shack. All battery holders are in series. I will provide the code at edit number 1.

Does anyone know what is wrong? I have been searching for days.

You haven't provided enough information yet. So far it could be a) the motor is not getting the signal to rotate, or b) if it is receiving the signal, then the motor can't source enough current from your battery setup. Without a code example we're just guessing.

That is the code. I gave the code. What are you talking about? Also, the motor is firmly attacked to the shield. I have the right current set up or at least I think I do. I said what it was, I have given the code at edit number 1. What other information do you need? Someone has got to tell me what information or else how am I suppose to give you the information needed?


text:
Two solenoid valves, both independent
I am currently working an automatic home gardening system. There are two moisture sensors and two solenoid valves to allow water to plant two different zones. Preferably, I want to water the plants for x amount of time. I started programming this and I noticed that with my code below, if one solenoid valve goes off, the entire program will delay until one of the solenoid valves closes and thus the other solenoid valve will not open until the other one is closed.
However, I want to prevent this from happening and I want the program to continue reading the moisture readings while one of the solenoid valves is open so that the other solenoid valve can open whenever the zone needs water as well.
int solenoidPin1 = 1; //connected to Digital 1
int solenoidPin2 = 2; //connected to Digital 2
void setup(){
  pinMode(solenoidPin1, OUTPUT);
  pinMode(solenoidPin2, OUTPUT);
}
void loop(){
  int moisture1 = analogRead(moisturePin1);
  int moisture2 = analogRead(moisturePin2);
  if (moisture1 <= 250){ //if moisture is less than reading 250
  digitalWrite(solenoidPin1, HIGH); //switch solenoid ON
  delay(300000); //water for five minutes
  digitalWrite(solenoidPin1, LOW); //switch solenoid OFF
  }
  else {
  digitalWrite(solenoidPin1, LOW); //switch solenoid OFF
  }

  if (moisture2 <= 250){ //if moisture is less than reading 250
  digitalWrite(solenoidPin2, HIGH); //switch solenoid ON
  delay(300000); //water for five minutes
  digitalWrite(solenoidPin2, LOW); //switch solenoid OFF
  }
  else {
  digitalWrite(solenoidPin2, LOW); //switch solenoid OFF
  }
}

I was thinking that I should do the following for the conditioning part. Will this work instead for what I'm trying to do?
  if (moisture1 <= 250){ //if moisture is less than reading 250
  digitalWrite(solenoidPin1, HIGH); //switch solenoid ON
  }
  else if (moisture1 >= 550){
  digitalWrite(solenoidPin1, LOW); //switch solenoid OFF
  }

  if (moisture2 <= 250){ //if moisture is less than reading 250
  digitalWrite(solenoidPin2, HIGH); //switch solenoid ON
  }
  else if (moisture2 >= 550){
  digitalWrite(solenoidPin2, LOW); //switch solenoid OFF
  }

Note: I'm using a capacitive moisture sensor, so the output voltage/reading is higher the drier the dirt is.

The essence of your problem is that the delay() function blocks
your program until the delay is over. This is only acceptable if the
program is doing one single things at a time. If you need to do multiple
things in parallel, like monitoring two moisture sensors, this approach
does not work.
Then, the first thing is to get read of delay() and instead use
millis() for managing time in a non blocking fashion. The essence of
this approach is to never wait. Instead, if it is time to do something
right now, you do it. If not, you just don't do it this time, but you
don't wait. This is nicely covered in the Blink without delay
Arduino tutorial. You should get familiar with this technique, as it is
essential for many Arduino projects.
Your problem is slightly more complex than blinking an LED though, as
the valve can be in two different states, and the action to perform
depends on that state. This is managed by a software construct called a
finite state machine. Essentially you have to remember the current
state and, depending on it, you decide what to do and what the next
state should be. Here is how you could do the timed watering with this
approach:
static enum { OFF, ON } stateValve1, stateValve2;
static uint32_t startedValve1, startedValve2;  // time when started

if (stateValve1 == OFF && analogRead(moisturePin1) <= 250) {
    digitalWrite(solenoidPin1, HIGH); //switch solenoid ON
    startedValve1 = millis();
    stateValve1 = ON;
} else if (stateValve1 == ON
        && millis() - startedValve1 >= WATERING_TIME) {
    digitalWrite(solenoidPin2, LOW); //switch solenoid OFF
    stateValve1 = OFF;
}

// and the same for valve 2.

For more in-depth coverage of the subject, I recommend you read the
Majenko's tutorial on finite state machines
At this point, the next step would be to throw in some modularization in
order to make the code less repetitive. I suggest making a class for
representing a “timed valve”. The valve has a turnOn() method that
turns it on, but does nothing if the valve is actually already on. The
class takes care of turning the valve off when the time has elapsed. But
since it cannot do that all by itself, you have to call an update()
method periodically to give it a chance to check whether it's time to go
off. Here is my implementation of that class:
const uint32_t WATERING_TIME = 100000;  // for example

class TimedValve
{
public:
    TimedValve(uint8_t pin) : valvePin(pin), state(OFF) {}
    void turnOn() {
        if (state == ON) return;  // do nothing if already ON
        digitalWrite(valvePin, HIGH);
        state = ON;
        timeStarted = millis();
    }
    void update() {
        if (state == ON && millis() - timeStarted >= WATERING_TIME) {
            digitalWrite(valvePin, LOW);
            state = OFF;
        }
    }
private:
    uint8_t valvePin;
    enum { OFF, ON } state;
    uint32_t timeStarted;
};

And you would use it like this:
const int solenoidPin1 = 1;
const int solenoidPin2 = 2;
const int moisturePin1 = A1;
const int moisturePin2 = A2;

void setup(){
    pinMode(solenoidPin1, OUTPUT);
    pinMode(solenoidPin2, OUTPUT);
}

void loop()
{
    static TimedValve valve1(solenoidPin1), valve2(solenoidPin2);

    // Turn the valves ON if needed.
    if (analogRead(moisturePin1) <= 250)
        valve1.turnOn();
    if (analogRead(moisturePin2) <= 250)
        valve2.turnOn();

    // Let them turn OFF if it's time.
    valve1.update();
    valve2.update();
}

Excellent. Thank you so much for you help. I had no idea about the Arduino being finite state machine. I also didn't know you could create an "object" with the Arduino IDE. Interesting...

@KingDuken: Any computer is, in a sense, a finite state machine (an “FSM” for short). But here, I am not using the term to describe what the Arduino actually is, but rather as a name for a software construct, i.e. a way to write a program. This construct could be implemented on any computer, big or small. The Wikipedia article I linked to describes the FSM as an abstract model of computation, whereas Majenko's tutorial is a good introduction to the FSM as a software construct, with a bias towards Arduino programming.

I finally managed to get around and test this out. AND IT WORKS! However, I wasn't able to use D1 because using the TX pin isn't exactly ideal. I don't know why but it worked when I used a different digital pin. Thank you again for your help!

There is one slight problem. I need it delay before the water cycle because the moisture sensor is really sensitive and if it detects water before the water settles in the soil, it will turn off the water valve.

@KingDuken: I can't understand your last comment. With this program, the moisture sensor controls the opening of the valve, but not the closing: the valve closes only after a fixed watering time. The sensor cannot “turn off the water valve”.


text:
Receiving message from arduino through wifi
I am new to arduino . I went through the basics . I want to receive message from arduino uno r3 in my laptop(ubuntu) . I have esp8266 wifi module . Arduino and esp8266 connection done . How do I proceed further ?

the simplest way is probably a running web server on your laptop, or perhaps mqtt/sockets, or a common cloud-based sever.

Download the ESP8266 extension for the Arduino board in Arduino IDE,desktop. Then select the example code for ESP8266, use the Server example. If you wanna access your board outside your home then you need to open a port in your router.


text:
Arduino as Slave to Return Multiple Values
I'm having trouble trying to get my two Arduino Unos to communicate with each other over i2c. I'm trying to have the master request for analog values from the slave by sending a request to the slave device for one of the six ADC pin values.
Master Code
#include <Wire.h>

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

void loop()
{
  Wire.beginTransmission(0x22); // Start communication with Arduino slave at address 0x22

  for(byte i=0;i<4;i++)
  {
    Wire.write(i);              // Request data from analog pin 'i'
    delay(5);                   // Give the slave a moment to sample ADC and respond
    while(Wire.available())
    {
      byte c = Wire.read();
      Serial.println(c);        // Print returned value to serial window
    }
  }

  Wire.endTransmission();       // End communication with Arduino slave
  delay(500);
}

Slave Code
#include <Wire.h>

void setup() {
  Wire.begin(0x22);
  Wire.onReceive(receivedHandler);
}

void loop() {
}

void receivedHandler() {
  byte data = Wire.read();
  byte analogValue;

  if(data == 0) analogValue = analogRead(A0)>>2;
  else if(data == 1) analogValue = analogRead(A1)>>2;
  else if(data == 2) analogValue = analogRead(A2)>>2;
  else if(data == 3) analogValue = analogRead(A3)>>2;
  else analogValue = 0;

  Wire.write(analogValue);
}

I can see that the data is being received by the slave, but the slave is not sending any data back, so I'm a bit confused how to send data back to the master. For the master there is "Wire.requestFrom(address, num of bytes)" to request a specific number of bytes, and for the slave "Wire.onRequest()" which will call a handler function to send back the number of bytes requested by the master, but for my application I won't be able to return more than 1 byte at a time.

I found this page http://www.berryjam.eu/2014/07/advanced-arduino-i2c-communication/ the most complete one about I2C comms between Arduino. I tested it and works.

If all you have to do is send 1 byte value for each of the 6 pins and your response from slave may be 32 bytes long, why not return ALL values, comma separated, and parse the answer on your master?  Thats what I do in these cases.  Treating multiple requests can make for lots of coding to get things right.

Bidirectional communication in I2C is a two stage thing.
First you have to tell the slave which pin (or register) you want to read. Then you have to read it.
A typical master sequence would be:
Wire.beginTransmission(0x22);
Wire.write(1);
Wire.endTransmission();
Wire.requestFrom(0x22, 2);
byte b1 = Wire.read();
byte b2 = Wire.read();

And of course your slave has to respond to the write() and remember which pin is being selected, then separately respond to the requestFrom() and return the data corresponding to the pin that was selected earlier.


text:
DS3231 AT24C32 IIC making digital outputs not work
I have just taken the code from
https://learn.adafruit.com/adafruit-ds3231-precision-rtc-breakout/wiring-and-test
to get DS3231 AT24C32 IIC to work fine with my Aduino and its working fine.
I have then taken
https://learn.adafruit.com/adafruit-arduino-lesson-4-eight-leds
and expanded it to work with three 74HC595 Shift Register. And this is working fine with all three sets of LEDS lighting up one after an other like in the demo.
So I do not think there is anything wrong with my wiring.
When I merge the two demos together, all the output pins on my this shirt register just give out positive current constantly.
I have walked through each line of the code and the problem is caused by
if (! rtc.begin()) {

if I take out that if statement everything works.  But since that is the bit that starts the clock I want that.
So how do I get the DS3231 started and not have all the pins on the third shift register high?
Also if it matter it is an official Leonardo board.
#include <Wire.h>
#include "RTClib.h"

RTC_DS3231 rtc;

int latchPinOne = 5;
int clockPinOne = 6;
int dataPinOne = 4;

int latchPinTwo = 11;
int clockPinTwo = 10;
int dataPinTwo = 8;

int latchPinThree = 3;
int clockPinThree = 13;
int dataPinThree = 2;

byte leds = 0;

void setup()
{
#ifndef ESP8266
  while (!Serial); // for Leonardo/Micro/Zero
#endif

  pinMode(dataPinOne, OUTPUT);
  pinMode(latchPinOne, OUTPUT);
  pinMode(clockPinOne, OUTPUT);

  pinMode(dataPinTwo, OUTPUT);
  pinMode(latchPinTwo, OUTPUT);
  pinMode(clockPinTwo, OUTPUT);

  pinMode(dataPinThree, OUTPUT);
  pinMode(latchPinThree, OUTPUT);
  pinMode(clockPinThree, OUTPUT);

  Serial.begin(9600);
  Serial.println("Start");

  delay(3000); // wait for console opening
  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }
}

void loop()
{
  leds = 0;
  for (int i = 0; i < 8; i++)
  {
    bitSet(leds, i);
    updateShiftRegister();
    delay(500);
  }
}

void updateShiftRegister()
{

  digitalWrite(latchPinOne, LOW);
  shiftOut(dataPinOne, clockPinOne, LSBFIRST, leds); // send the data
  digitalWrite(latchPinOne, HIGH);

  digitalWrite(latchPinTwo, LOW);
  shiftOut(dataPinTwo, clockPinTwo, LSBFIRST, leds); // send the data
  digitalWrite(latchPinTwo, HIGH);

  digitalWrite(latchPinThree, LOW);
  shiftOut(dataPinThree, clockPinThree, LSBFIRST, leds); // send the data
  digitalWrite(latchPinThree, HIGH);
}

Check for pin conflicts. What pins are used for the RTC? SDA and SCL but they are also pins 2 and 3. Opps!

This looks like a classical case of pin conflicts when merging several sketches.
In this case it is hidden by the fact that TWI SDA and SCL are separate pins on the Arduino Leonardo. But they are also connected to pins 2 and 3 (not A4 and A5 as on Arduino Uno).
Selecting other pins (latch/data) for the third shift register should help.
Cheers.

It was the fact I was using Pin 2 And 3 for output.  I didn't know that the SCL and SDA were connecting Pin 2 and 3.  I Changed it to Pin 7 and 9, and everything worked.

https://en.wikipedia.org/wiki/The_devil_is_in_the_detail


text:
Arduino TCP Server establishes connection with client but does not receive data
I am trying to send and receive data with the TCP server but I am not receiving data.
#include <ESP8266WiFi.h>
#include <WiFiClient.h>

// Parametros de conexion a red WIFI.
const char* ssid = "bits";
const char* password = "12345";

// Start a TCP Server on port 5000
WiFiServer server(5000);

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid,password);
  Serial.println("");
  //Wait for connection
  while(WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
 Serial.println(WiFi.localIP()); // IP

  // Start the TCP server
  server.begin();
}

void loop() {
  TCPServer();
}

void TCPServer () {
   WiFiClient client = server.available();
    if (client) {
      Serial.println("We have a new client");
      Serial.println("Hello, client!");
        if (client.available() > 0) {
            char thisChar = client.read();
            Serial.println("We got data");
            Serial.println(thisChar);
            delay(200);
        }
    }
}

Test Capture: In the capture it is seen that the code is executed until the following instruction.
Serial.println("We have a new client");
Serial.println("Hello, client!");

I found the solution by modifying the code
void TCPServer () {
   WiFiClient client = server.available();
  if (client)
  {
    Serial.println("New Client");

    while(!client.available()&&client.connected())
    {
    delay(1);
    }

    String linea1 = client.readStringUntil('r');
    Serial.println(linea1);
  }
}

You have created a TCP server. You need to connect other clients to it to start data send and receive process between them. If you just simply run this and wait, then you probably won't get anything because nobody is attempting to connect to it.


text:
Directly powering a single 32x16 RGB LED matrix (without external PSU)
All the guides I've found suggest to use an external PSU to power an RGB matrix like this.
However I know it is possible to blink the LEDs at high rates (eg. 2ms) and still give the impression to the eyes they are fully on. I've verified this myself on a small 4x4 matrix, but I am not sure if the same can be done with these bigger matrices.
In my case I could tolerate reduced brightness and color space, but I'd like to power the matrix with the Arduino's 5V pin directly.

give it a try, you won't break anything. probably won't break anything. that said, 512 LEDs is a lot to power from an MCU...

@dandavis: I will power only 1 led at a time, not all 512 at the same time! btw i've also found this monocromatic matrix that can also be powered directly by an arduino. In this case they suggest to not connect the 5V pin at all.  Maybe i should do the same with my RGB matrix?

Don't those matrices already have bypass capacitors on the backside?

I've received yesterday the 32x16 LED matrix I've ordered from AliExpress and I've done some measurements with a multimeter in series with the power wire.
LED multiplexing does not seem a good idea as the matrix is already doing that internally.
Instead I've found that using the minimum color intensity helps a lot reducing the current usage.
E.g. for blue use matrix.Color333(0, 0, 1) instead of matrix.Color333(0, 0, 7); for white use matrix.Color333(1, 1, 1) instead of matrix.Color333(7, 7, 7), etc.
With the minimum brightness I've measured:

All blue LEDs lit = ~170mA
All LEDs lit as white (red+blue+green) = ~400mA

In the average case (not all LEDs are lit) I am getting around 250mA, so I should definitely be fine powering the matrix directly from the 5V pin if I keep the brightness as low as possible.

When powered through USB, the total current consumption is limited to 500mA by the USB interface. If you are using the power connector, the total current is limited by the on board 5V regulator to 1A.
The board will also require some current, so you can draw around 400mA, if powered through USB or 900mA, if powered through the connector; from the 5V pin.
While the matrix on average may not draw than 300 - 400mA, the voltage regulator can overheat and shut off temporarily, and you will never be able to reach 900mA. The regulator is linear, so any extra voltage you supply will result in waste heat.
It is best to get a buck converter or power the matrix externally. You won't be wasting as much power, and avoiding possible thermal shutoff.

but, as you said, if i power the whole thing via a single usb port i can skip the regulator, so there is no risk of shutoff. And if the matrix ICs takes less than 400mA i should be fine because i will have max 1 led on at a time. Now the big question is if the arduino can refresh all the 512 leds at acceptable speed to avoid flickering.

based on my "charger doctor" readings, few USB sources provide only 500ma; 0.8-1.6A is common.