text:
ESP8266 & websockets
At the moment, I'm using various operating systems and devices like the Raspberry pi to control lights and other stuff over websockets. I use websockets since they added the support on Chrome. I write a lot of Javascript stuff for fun. Websockets allow you to communicate with another server without the need of reloading a page. It's a lot better than Ajax. Once the connection is open with a web server data can travel both ways. No unnecessary headers to send. No unnecessary requests. You just send only the data you want, this in both directions. AND FAST, DAMN FAST.
For example I use Javascript's requestAnimationframe to send RGB values (based on music frequency) to lamps connected to the network. requestAnimationframe executes approximately at 60 Hz. But that's not the highest speed, I also created some "web controllers" to control servos and other stuff with touch and mouse events. In that case it probably touches transmission frequencies of 200-300 data packets (normally I use JSON- encoded strings) or more per second.
Websocket servers have also broadcast which allows you for example to control multiple RGB lamps based on the music you play from basically every modern device that has a browser. I don't use "normal" sockets because of the simple fact that there is no support for sockets in a standard web browser. So I would need to create a custom iOS app, custom Windows app, custom Android app. I said that we know that websockets are made for a fast multi-user / multi-device / bidirectional communication. And it should be really fast or it's useless.
Lately I have a lot of fun with electronics and MCUs, so I made even more lamps and stuff controlled from Arduinos, ATtinys and other microcontrollers. I'm new to C++ but since I write Javascript code since the previous century I just have to slightly modify old Javascript functions to run in the Arduino IDE.
But for sure I'm not ready to write a perfect library for an MCU, so I need to use what I find online.
Apparently there are not many people into websockets. I tested 2-3 Arduino websockets libraries and couldn't get them to work properly.
The last one I tested(Links2004) works but I can't send a 4 decimal string faster than 2 times per second or it crashes.
All I did was to add this code for testing:
void onWebsocketMessage(uint8_t * payload) {
 analogWrite(13,atoi((const char *)payload));
}

Where payload is the data received.
Problems that could slow down/crash everything:

My code. Does atoi take too much to execute?
My code. Is the (const char *) cast filling memory?
The lib itself?

I know that the CPU memory or whatever else is not the problem because of this video:
https://www.youtube.com/watch?v=8ISbmQTbjDI
He gets realtime stats from the controller at 200-600 Hz.
While it's supercool and I could just install that "custom firmware" I prefer to stay in the Arduino IDE for now.
How to fix websockets on the ESP8266 device using Arduino IDE?
Or maybe can I extract only the websocket part from that firmware (CNLohr's Video)?
Suggest another lib?
I posted here because I use the Arduino IDE. And the ESP8266 has also been part of the Arduino world for a while. And maybe some not so popular Arduino-based websockets work also on the ESP8266.
Wouldn't it be nice to control your ws2812b strip with a web interface showing the preview like this?
http://jsfiddle.net/dgws3usa/5/

EDIT
links2004 @ github

The network should be fine. It's a relatively expensive Cisco/Linksys N router at 20cm/8inch away from the ESP8266 module.
Luckily the module I'm using is one of the modules listed in the Arduino IDE, the MOD-WIFI-ESP8266-DEV, but I have another one with fewer GPIOs.
I just noticed now that I programmed it at 80 Mhz instead of 160 Mhz.
The program I uploaded consists only of the basic websockets server example with in addition just the code posted above.
If atoi is the problem/is slow, what are other ways to convert the received array to a string?
I use both the latest versions of the Arduino ESP8266 port and the arduinoWebSockets. At least I guess so. I followed the install instructions one day before I asked this question.
By crash I mean, while moving the range slider, if updating in realtime with addEventListener('input',function,false) at some point (after 1 sec/ 3-4 messages send/received) it stops sending or receiving data. By the way, the video you posted seems to work properly with a lot more code. Also that guy updates in realtime with oninput vs 'onchange', which would only update when the user releases the slider.
I think for now I can't use Serial.setDebugOutput(true); as I didn't get the serial communication working. I'm using a cheap CH340G to program the chip.

Japanese post.

I'm doing exatly the same thing but in a much simpler way. No web server, no ping pongs, no serial stuff, I don't use complex functions to elaborate the web server's data. Altough his example works.
He is doing, code-wise, a lot more than I do.
for(i=0; i<4; i++) {
  mask[i] = client.read();
}
byte m_data[data_len];
char data_c[data_len];
Serial.print("Receive Data = ");
for(i = 0; i1-0x30);
    break;
  case 3:
    data_b = ((data_c[0]-0x30)*100) + ((data_c1-0x30)*10) + (data_c2-0x30);
    break;
  }
  LED_PWM(data_b);

My full "test" code:
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <WebSocketsServer.h>
#include <Hash.h>
ESP8266WiFiMulti WiFiMulti;
WebSocketsServer webSocket=WebSocketsServer(81);
void webSocketEvent(uint8_t num,WStype_t type,uint8_t * payload,size_t lenght) {
  switch(type) {
    case WStype_DISCONNECTED:
      break;
    case WStype_CONNECTED:
      {
      IPAddress ip=webSocket.remoteIP(num);
      }
      break;
    case WStype_TEXT:
      analogWrite(13,atoi((const char *)payload)); // MY CODE
      webSocket.broadcastTXT(payload,lenght);
      break;
    case WStype_BIN:
      hexdump(payload,lenght);
      webSocket.sendBIN(num,payload,lenght);
      break;
  }
}
void setup() {
  pinMode(13,OUTPUT); // MY CODE
  for(uint8_t t=4;t>0;t--) {
    delay(1000);
  }
  WiFiMulti.addAP("ssid","pass");
  while(WiFiMulti.run()!=WL_CONNECTED) {
    delay(100);
  }
  webSocket.begin();
  webSocket.onEvent(webSocketEvent);
}
void loop() {
  webSocket.loop();
}

I normally write Javascript code. Converting a string to a number or vice-versa is much simpler. num=1; str=1+''; num=str*1; So all this binary array is relatively new for me.
Note that while I convert the binary array to an int now. In the future I need to convert that to a string which then will be parsed. Something like JSON. And so update more channels per message.
On the client side, like I said, I'm sending the data really fast. So if there is no buffer on the server side that could be a problem. Solving that is simple: requestanimationframe. Continuously check if the input changed. That allows you to send the data every 16-17ms. So 60 Hz. Not slower, Not faster. But again that should be the maximum pause between messages.

I said that I will reprogram it at 160 Mhz now and hope there are other ways to convert the received data faster and hope for updates relative to my code.

EDIT2
Right. The serial works. Reprogrammed the ESP8266 At 160 Mhz.
The error I get when when I set Serial.setDebugOutput(true); is:
LmacRxBlk:1

If you need some other information just ask.
EDIT3
Sorry for the late response.
webSocket.broadcastTXT(payload,lenght);

Broadcasting seems to be the problem. I just have a few minutes so for now I can't do the describe debug stuff... But I will do as soon as I have a little more time.
EDIT4 for Aditya Tannu
Added
#include <NeoPixelBus.h>
#define pixelCount 16
NeoPixelBus strip = NeoPixelBus(pixelCount,13);

Inside the webSocketEvent function
case WStype_TEXT:
for(uint8_t i=0;i<pixelCount;i++){
 strip.SetPixelColor(
  i,
  RgbColor(i==(atoi((const char *)payload)%pixelCount)?255:0,0,0)
  // i need to put the above outside of the loop.
  // it does not work if i do so
 );
}
strip.Show();
break;

HTML JS
var ws,form;
function msg(a){
  console.log(a);
}
window.onload=function() {
  form=document.getElementById('form');// change
  ws=new WebSocket('ws://IPNUMBER:PORT');// change
  ws.onopen=function() {
    ws.send('0');
  };
  ws.onmessage=msg;
  form.addEventListener('input',function() {
    ws.send(this.firstChild.value) // firstchild is the range
  }, false);
}

vid, I use a logic level converter from 3.3v to 5v: pca9306.
EDIT 5 for Links2004

I think I should rework the examples. It looks like most users don't
  understand it well.

Nono. At some point you need to broadcast back the actual position anyway.
Sorry. I forgot to test the debug stuff again. But we know it's the broadcast. We just need to send back data only when there is not too much traffic.

I tried to port Charles Lohr's implementation to esp8266/Arduino. An initial working version is up here: https://github.com/AdySan/ESPSocket
I'm able to get ~150Hz without any disconnections or crashes. I'll keep working on it to add more functionality and hopefully improve speed.


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

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

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

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

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

Brzo I2C example
#include "brzo_i2c.h"

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

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

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

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

But I get always the same error.

1 : Bus not free

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

This line
brzo_i2c_start_transaction(0x48,400);

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

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

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

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

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

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

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

source: Stack Exchange

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

sort: votes


text:
ESP8266 returns whatever is sent through Arduino serial
I am a newbie and working on a kind of WiFi-controlled vehicle (car or maybe hovercraft later). My ESP8266 repeats the commands I send. For example, AT gives AT, AT+GWR gives AT+GWR, dabdabik gives dabdabik, etc.
I am using an Arduino Uno to send commands, as I don't have FTDI related stuff (USB to Serial Converter). I use AA cells for power supply (1.5v*2=3v). I don't even have 3.3 volt direct supply. I am using the Arduino IDE Serial Monitor. I connected the Arduino's TX to the ESP8266's RX via a voltage divider (1.66K Ohm(TX) and 1.66K Ohm (GND)->3.29 Ohm(RX)).
My connections are:
ESP8266----------------Arduino Uno
TX---Voltage divider---RX(d0)
RX---------------------TX(d1)
GND--------------------GND
VCC-------**3V**
CH_PD-----**3V**

Sometimes it gives garbage otherwise it just repeats (weird). Garbage ONLY changes if baud rate is changed.
I flashed it (it seems) with the AT 9.5.2 firmware. Flashing works rarely ONLY with TX to TX connected directly without a voltage divider.
I tried as much as I could after searching the web and ESP8266 forum but still couldn't solve problem.
Please help. I am a student in a small town (Manipal) in Southern India so no good stores nearby and I don't want to buy FTDI or anything online. I am a bit new to electronics, but I am a C++ programmer and student.
UPDATE: I noticed after some resets that it gives full garbage to longer commands most of the time, whereas two-letter commands give partial garbage. For example AT gives IT,TT,OT,etc.
There is no coding.
I am sending the commands directly via Arduino hardware serial pins (rx,tx) and a bare minimum program.

Please amend your question and post your code, since it sounds like a code issue.

I noticed when testing my ESP8266 using the Arduino IDE serial console that ending with a CR repeated what was sent, a NL executed the command and combination of the two yielded a combination of the two behaviours. This could have just been the firmware on mine (it seemed to be non-standard), but it is possible that the behaviour is similar on yours. If you are using CR & NL, it would explain repetition. However, I can't explain commands not executing, or executing abnormally.

When I recieved my first ESP I struggled for weeks trying to get it working. First, the voltage divider is a good thing for its longevity but I got it working without it.
Next about baudrate, mine sent some data at startup on 76800 baud then would work on 9600 baud. You might want to check that out for the garbage you're seeing.
Finally, it might be related to a power draw problem. The ESP has 400mA peaks, this is high for an Arduino and even for a 3.3v USB serial programmer. I had to use a 1A breadboard power supply to actually get it to work. Before buying anything you should try putting a big (220µF or more) capacitor in parallel on the 3.3V power.

AT commands must end with '\r\n'.
'ATE'commands can enable/disable echo. (ATE0: disable, ATE1: enable)
AT commands documentation: http://espressif.com/sites/default/files/documentation/4a-esp8266_at_instruction_set_en.pdf

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


text:
Better way than exit(0)?
The following code does what I need it to do (when a start switch is on and door switch is off - a warning light flashes. When the start switch and door switch are both on - a valve opens to allow water in for 2 seconds). I need the light to flash until the door is HIGH too at which point the valve program runs once.  The only way I have to get out of this is to use exit(0). Is there a better way to do this? Ideally, I would like to stay away from anything too Boolean! Thank you.
int start = 2;
int door = 3;
int light = 8;
int valve = 9;
int counter = 0;

void setup() {
  pinMode(start,INPUT);
  pinMode(door,INPUT);
  pinMode(light,OUTPUT);
  pinMode(valve,OUTPUT);
}

void loop() {
  if(digitalRead(start)==HIGH && digitalRead(door)==HIGH) {
    digitalWrite(valve, HIGH);
    delay(2000);
    digitalWrite(valve,LOW);
    exit(0);
    //breaks out of loop. Arduino then needs reset.
  }

  if (digitalRead(start)==HIGH && digitalRead(door)==LOW) {
    digitalWrite(light,HIGH);
    delay(500);
    digitalWrite(light,LOW);
    delay(500);
  }
}

I don't really see what the exit(0) does here. If the door and start buttons remain pressed, the valve will go open for 2 seconds, then close for a while, but then open again for 2 seconds, etc. The only thing exit(0) does is create a bit of a delay. So replacing exit(0), with delay(3000) will do about the same thing. I think want you want is to remember that the valve has already been opened, on not open it again while both button are being pressed.

A better way to stop execution?  Some trap the operation in an endless loop with a while(1){}

I think the infinite loop is the best way.  I have to teach this to High School kids who will only do a small part of programming as part of a course.  I am trying to find Arduino solutions for questions that were originally designed for PBASIC (picaxe). There are a lot of questions which need the code to run once - and I need to restrict the commands to for, while, if....else commands ideally (in BASIC they would have used if/then, for/next and subroutines and that would be enough).

What you made a mistake is instead of using "if"(first one) you had to use "while".  And use the "if" to break out of the "while" using a "break" , what you have done is really a bad practice.

What you need to do is learn what a finite state machine (FSM) is.
An FSM is a way of having the Arduino in one of a finite number of states, such as "light flashing", or "letting water in", etc.
I have written a reasonable (IMHO) tutorial here: https://hackingmajenkoblog.wordpress.com/2016/02/01/the-finite-state-machine/


text:
Dotstar strip goes nuts when connected to MIDI piano
I've got a Dotstar strip, a piano, and an UNO(w a usb host shield).
I can get and properly translate data from the piano to the UNO, so I'm definitely getting the right information to the board. When i hardcode input values into my code it reacts appropriately, so I know my code works.
However, when I attempt to take data from the USB piano keyboard and light a corresponding LED, the whole strip lights up blue and green and flashes brightly between them. This happens before I even hit a key on the keyboard.
When I hit a key, the correct light lights up for roughly a milisecond before returning to flashing green or blue.
I feel like there's some electrical concept that I'm not getting- I've got the MIDI information correctly making it to the board, and it can correctly control the LEDs. I don't know where it could be getting the data that's causing it to do this.
I think I might need a resistor- I tried to set an AND gate from the SS pin and the data pin, but that didn't do anything.

Here's the AND gate setup I attempted.

Please include your code and wiring into the question by editing it

The USB host shield and the LED strip use the same SPI bus. The USB host shield has a cable select line, but the LEDs don't, so they're always listening to the bus, even when the USB shield is using it.
You'll have to add some logic gates on the data and clock lines to the LED strip to turn them on or off, depending on another cable select line for the LEDs.
LED Clock = NOT LED CS AND SPI CLK
LED Data = NOT LED CS AND SPI MOSI
If you're only using two SPI devices, you could do:
LED Clock = USB CS AND SPI CLK
LED Data = USB CS AND SPI MOSI
https://forum.arduino.cc/index.php?topic=644679.msg4363133
Edit: Judging from the image, you're asking the exact same question as the one I already replied to on the Arduino forum a month ago. Why do you ask the same question twice if you're not even going to reply?

Took me a month to get a chance to try it-thought you'd have long forgotten about it.

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


text:
How to upload file from SD card by Micro SD adapter to ftp server using Filezilla?
I use Arduino Mega 2560 to send a file stored in a micro sd by a module "Micro SD adapter" to ftp server. I use the sim800l evb v2.0 module and I proceeded as follows:
I insert the AT command :
AT+SAPBR=3,1,"CONTYPE","GPRS"

AT+SAPBR=3,1,"APN","internet"

AT+SAPBR=1,1

AT+FTPCID=1

AT+FTPTYPE="I"

AT+FTPMODE=0

AT+FTPSERV="197.158.86.105"

AT+FTPPORT=42

AT+FTPUN="user"

AT+FTPPW="password"

AT+FTPPUTNAME="test.txt"

AT+FTPPUTPATH="/"

AT+FTPPUT=1

Results :
+FTPPUT:1,62

sometimes +FTPPUT:1,63
or +FTPPUT:1,64
or +FTPPUT:1,65
or +FTPPUT:1,78
what do I have to do. Please, can anyone help me? thank you

Maybe the next step is to send the data? I don't see what a load of AT commands have to do with an SD card adaptor and an Arduino. Do you have some kind of (unspecified) GSM module attached? Or a network device? Please give us all the information, not just a few random snippets.

Indeed, I'm sorry, yes I forgot to mention that I use the sim800l evb v2.0 module

And what does the datasheet or manual for that module tell you about performing an FTPPUT session?

yes, I have the AT command manual and I applied it

But it does not work :
62 DNS error
63 Connect error
64 Timeout
65 Server error
78 Upload error

Well, then you have some pointers to start debugging your connection.

thank you, exactly, I am aware of the bugs but I don't know how to proceed

Check some points: Is there a FTP server running on the server device "197.158.86.105"? Or just a ssh server for sftp? Are you allowed to used a IP address instead a FQN like "ftp.example.org" with the command AT+FTPSERV.  The standard ftp port is 21. You use 42 is that intended? I don't see something like AT-FTPOPEN or AT-FTPCONNECT. Is this done implicitly or did you forget it? (I don't say there are such commands. But normally you have to connect to a ftp server and to establish a session.)

Thank you for your attention. As far as I know, no, no FTP server isn't running on this device. Since I don't have a domain name yet, so I have to mention an IP adress but I'm going to take a closer look. And yes, the use of port 42 is normal. AT+FTPPUT= 1 is the command that starts the connection to the server. Thank you

So if there is no ftp server running on the target, the problem is quite clear. Also, using port 42 for ftp is not "normal", as mentioned by Peter Paul Kiefer you should try port 21 or 22 (sftp) once you have a server running.

Thank you, I'm going to try.

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


text:
LCD screen suddenly displaying and updating inaccurately
For the final project of my Arduino course, I have decided to make an alarm clock. The actual clock part was easy enough, but when I wired my buttons up, I accidentally loosened a few wires that a classmate with an identical kit helped me wire up. And although that is resolved now, the halves of my screen are flipped and the second ticker is now only updating every 5 seconds with the same code, even when I comment out unrelated code and reupload. I triple checked the wiring and moving wires around didn't do much either, so I have no idea what is causing this glitch, but hope one of you guys can help me figure it out. Here are some images for reference: https://i.sstatic.net/BzrYM.jpg and my code is below:
#include <IRremoteInt.h>
#include <ir_Lego_PF_BitStreamEncoder.h>
/*
 * VSS: GND
 * VDD: 5v
 * V0: Potentiometer
 * RS: D1
 * RW: GND
 * E: D2
 * D4: D4
 * D5: D5
 * D6: D6
 * D7: D7
 * A: 5v
 * K: GN/>
 */

//Variables to make the time work
int hour = 11;
int minute = 59;
int second = 40;
int flag = 1;

void setup() {
  Serial.begin(9600);
  irrecv.enableIRIn();
  irrecv.blink13(true);
  lcd.begin(16, 2); // initialize lcd width width and height
  lcd.clear();
}
void loop() {
// Print the time and make sure there are always 2 digits
    lcd.setCursor(0,0);
    if (hour < 10)
      lcd.print ("0");
    lcd.print(hour);
  lcd.setCursor(2,0);
    lcd.print(":");
  lcd.setCursor(3,0);
    if (minute < 10)
      lcd.print ("0");
    lcd.print(minute);
  lcd.setCursor(5,0);
    lcd.print(".");
  lcd.setCursor(6,0);
  if (second < 10)
    lcd.print ("0");
  lcd.print (second);
  lcd.setCursor(10,0);
    if (flag == 0)
      lcd.print ("AM");
    if (flag == 1)
      lcd.print ("PM");
}```

What do you mean? I noticed that my links aren't working properly, so I'll try again via imgur. link Hope this works. Took the best pictures I could of my wiring and output.

And the code that displays the characters:
    if (hour < 10)
      lcd.print ("0");
    lcd.print(hour);
  lcd.setCursor(2,0);
    lcd.print(":");
  lcd.setCursor(3,0);
    if (minute < 10)
      lcd.print ("0");
    lcd.print(minute);
  lcd.setCursor(5,0);
    lcd.print(".");
  lcd.setCursor(6,0);
  if (second < 10)
    lcd.print ("0");
  lcd.print (second);
  lcd.setCursor(10,0);
    if (flag == 0)
      lcd.print ("AM");
    if (flag == 1)
      lcd.print ("PM");```
Hope that clarifies things enough.

Alright, post is updated. Better now?

the picture showing . 04 AM 01 : 00  is not useful if you do not say what you expect it to display instead .... what should the display be showing exactly?

Oh, right. It should display "1:00.04 AM". It was before, but after my little complication, the screen is flipped. Like the code is the same as before, setting the hour to 0,0, minute to 3,0, second to 6,0 and the flag to 10,0.

it is more than flipped ... look very carefully ... when debugging, it is important to observe the unexpected results in detail

what do you see if you run lcd.print ("0123456789abcdef");? ... no other lcd.print() code

you should also pay attention to the expected results ...  "1:00.04 AM" is missing the leading zero

if the code displays correct text in incorrect places, then it is a sofware issue ... if the wires were crossed, then incorrect text would show up


text:
why is memcpy of unsigned long killing my sampling speed?
I'm using a Mega 2560 to communicate with a mixture of analog (i.e. measured via analogRead()) and I2C based sensors. Sampled data is placed in a 16 byte array, then written to an SD card once a 512 byte buffer is completely filled. The problem I'm running into is that when I collect data from a MAX30102 pulse oximeter using
measure.pox = pulseOx.getIR();

from my code below, the cycle time of my collectHR() loop drops to about 20 mS. If I preallocate this spot by using the line directly below it (storing a constant instead of reading a new uint32_t each loop), my cycle time is about half a millisecond. What's confusing to me is that if I cast the uint32_t into a string using dtostrf:
dtostrf(pulseOx.getIR(),3,0,pOxBuf); // read pulseOx, convert it into a 3 byte string

it only takes about 1.2 mS to actually read a sample from the MAX30102. It seems to me that by favoring a struct over a string (from an earlier iteration of this code that wrote all data as a txt file instead of a bin file) so that I can write binary to my SD card, I'm absolutely throttling my speed. Shouldn't working bytewise be more efficient than working with a string? What is happening to the other 18 mS that occurs between reading the unsigned long and placing it into by byte buffer, buffer1? Implementing this code using string arrays instead of a struct, I was able to run at approximately 125 Hz. Now I'm at roughly 50 Hz. I'd appreciate any insight here. Relevant code shown below:
#include <Wire.h>
#include "MAX30105.h"
#include <SPI.h>
#include <SdFat.h>
#define moisture0 A0 // Upper back sensor analog pin
#define moisture1 A7 // Trunk sensor analog pin
#define ECGpin A3 // ECG analog pin

SdFat SD; // replace SD with SDfat.
File sdLog; // placeholder to create datalogger

struct meas // a 16 byte structure to hold all of our measurements
{
  unsigned long mils;
  int ECG;
  uint32_t pox;
  int tempInt;
  int m1;
  int m2;
};
struct meas measure; // create an instance of the above structure

byte buffer1[512];
byte *measureLoc = (byte *) &measure; // to access measure structure as bytes
char fileName[] = "WIHMSlog.bin";

void setup {
    Serial.begin(230400);
}

void loop() {
sdLog = SD.open(fileName, O_WRITE | O_CREAT | O_AT_END); // Create file for the datalogging and verify its existance
collectHR();
sdlog.close()
}

void collectHR() {
  unsigned int loopCount = 0;
  int buffLen = 0; // starting position in buffer
  int buffSize = 16;

  while (loopCount < 3200) { // some multiple of 32 (since 512 byte/sd block divided by 16 bytes per loop cycle = 32 cycles per sd write cycle

    measure.ECG = analogRead(ECGpin); // read ECG and stick the int into measures
    measure.pox = pulseOx.getIR();
    //measure.pox = 5555; // Placeholder value
    measure.mils = micros();
    measure.m1 = analogRead(moisture0);
    measure.m2 = loopCount; // just a test to ensure this is actually iterating in the card

    if (buffLen == 512) { // SD buffer is full, time to write!
      sdLog.write(buffer1, 512);
      buffLen = 0;
    }
    memcpy(buffer1 + buffLen, measureLoc, buffSize); // place the 16 byte data structure into the buffer
    buffLen = buffLen + buffSize; // increase the index size in the array
    loopCount++;
    Serial.println(micros());
  }

}

The sequence of operations looks a bit strange. Consider what happens at the very start: buffLen is initially 0, then you immediately increase it to 16 and then you copy the data to that buffer at offset 16. But what about the first 16 bytes? Why did you leave them unused? Also, it is not clear why you even need to constantly pump bytes from measure to buffer1, i.e. from memory to memory. Why don't you just declare an array of 32 struct measure elements and use it directly?

Thanks for your input! You're absolutely right that the first 16 bytes remain empty. I had initially thought it would make it easier to determine when each collectHR() loop ended in the file by searching for 16 0's, but now that you point it out it seems like a total waste of memory. I have moved the increment to below. the memcpy call to account for this. I hadn't thought of casting an array of structs; I'll give that a go. Do you have any insight as to why specifically the memcpy of the pulseOx.getIR() call is so much slower than the time it takes to retrieve those 4 bytes from the sensor?

use unsigned int for buffLen, because 15*3200 is more than int can take

Are you sure to have 512 byte of free RAM? The SDfat library holds a 512 byte buffer anyway, and another one for the file system itself. It physically writes to SD only full blocks anyway.

Please fix/remove that millisSet garbage...

Juraj Good catch, thanks! I've amended this above.
@DataFiddler I allegedly have about 5800 bytes left to play with. I'm aware SDfat utilizes a 512 byte buffer, but does that mean that every write() call pushes 512 bytes to the card, or that nothing is sent to the card at all until 512 bytes worth of write() are amassed?
Sorry millisSet() offended you, I've removed it. I tried to post just the relevant portions of the code but seem to have missed that variable in the initial post. Garbage is removed...

A write without flush or close only copies in memory, unless a 512 byte boundary is crossed and a different sector is used. BTW: sorry, did not notice you mentioned atmega2560

did unsigned int solve the problem?

unsigned int did not solve the problem, but did allow longer sets of loops. I implemented AnT's suggestion to create an array of structs and eliminated the memcpy command altogether in favor of write(meas), but this is even slower than using memcpy!


text:
ESP8266 not working with MPU 6050 over wire library and I2C
I'm trying to use this version of ESP8266 to access MPU 6050. However, it's not working.
https://www.amazon.com/gp/product/B07HF44GBT/ref=ppx_yo_dt_b_asin_title_o07_s00?ie=UTF8&psc=1 i.e. NodeMCU CP2102 ESP-12E
The code worked with nano very fine. However, when I tried to scan the I2C device, it's said I2C device not found.
I have tried
  Wire.begin(D2, D1);

and
  Wire.begin(4, 5);

i.e. to change the pin to GIOP 4 5 in case if the default was not working.
I have also tried to put a large capacitor between the power lines, still not working.
Why ESP8266 does not work with MPU 6050?(Serial and wire together)
Updates:
Sometimes it does say device found, but after two updates, it turned to be not found again.
Updates 2:
I watched the video and did what G6EJD suggested, i.e. restarted the IDE and everything. Now it's reading data. However, the data reading was somehow incorrect by a large factor.
For example, at flat the device is reading
42.63/-38.37/7.82

for angle x,angle y,and angular speed z with complementary filter applied and steady at flat surface. It worked for nano but not for ESP 8266.
Also, I tried to adjust the circuit like the spectrum dandavis suggested. I tried resistor range from 4.7 k to 10, even directly connect to the power source. The attempts also included 100 $\mu$F capacitor and power board to stabilize the noise. Both pull up and pull down has been attempted as well as changing boards. However, none of those were working and the issue persisted. The pull up resistor did not seem to be response to what the device was reading.
Update 3:
The power consumption has been ruled out and a pair of 100k resistor was also attempted. Not working.

how long are the leads? do you use pullup resistors?

@dandavis the wire is about 10cm each, what's a pull up resistors?

https://learn.sparkfun.com/tutorials/i2c/i2c-at-the-hardware-level

@dandavis It didn't work even if I put in the resistor.

@dandavis I tried to adjust the circuit like the spectrum you suggested. I tried resistor range from 4.7 k to 10, even directly connect to the power source. The attempts also included 100 $\mu$F capacitor and power board to stabilize the noise. Both pull up and pull down has been attempted as well as changing boards. However, none of those were working and the issue persisted.

I am not an arduino veteran, but I could not get I2C communication to work between two of the exact same MCU (NodeMCU CP2102 ESP-12E). There are a couple of issues on github pointing out issues but the devs don't seem in any hurry to do anything about it.

I've been struggling with getting anything with the MPU6050's to work with either a D1 Mini or an older NodeMCU v1. I'm using D1/D2.
I've used the i2cdevlib MPU6050 library as well as the Electronic Cats' version.
I've used an assortment of sketches and even tried code which uses just Wire (no MPU6050 specific libs).

The best I've been able to get is the Electronic Cats MPU6050 library, without DMP, where at least it thinks the MPU6050 has been connected to, but it just puts out 0's as raw values.
The second "best", maybe, was some code that just used plain Wire, but except for Wire.endTransmission() returning success (and I had to slow loop() down for that), its numbers are gibberish (either 0's, or Z will just increment.  Nothing is affected by the movement of the board itself).

The DMP versions always fail to initialize the DMP.
I've tried 8.2k and 4.1k pullups on D1 and D2.
It works fine on an atmega32u4-based Pro Micro 16.

try to use
Wire.begin(0x68);

instead of
  Wire.begin(D2, D1);


text:
Can I program Arduino with Python?
I know that I can program Arduino with python but is it possible to make every project, which can be completed by normal IDE?

How do you "know" that you can program an Arduino "with" Python?

possible duplicate of Programming an Arduino using Python, rather than C/C++

Do yourself a favor and learn C/C++. You won't regret it.

"You won't regret it" is a bit optimistic. Especially on those long, cold nights when the memory allocator in your templated class goes tits-up. You'll definitely regret it then. But it will still be the best choice for developing on the Arduino.

@IgnacioVazquez-Abrams we'll agree to disagree.

@PhilVallone: I was being facetious :P

@IgnacioVazquez-Abrams all good. I gave you +1

Python has a bigger memory footprint than c++ in general, and you will have a hard time figuring out the memory layout and allocation using Python

In addition to the existing question.. this question seems very open ended so I'm going to close it to prevent excessive discussion. Feel free to join the chat room for discussions: http://chat.stackexchange.com/rooms/8489/pin-13

I imagine you want to use python because you are already familiar with it, know your way around the syntax, etc. But I would advice against this line of thinking, because microcontrollers need a little more of "low-level" thinking (given the limited resources they generally have) and because of that, it's probably best if you learn some C/C++.
The arduino programming framework provides some not-so-low-level libraries and tools (like the arduino IDE itself) to make it easy for non-C programmers to learn C-like programming.
However, if you want to use python as a proof of concept or anything else, sorry about the misunderstanding! :)

The direct answer is almost certainly not.
There are some auspicious developments so that you might be able to adapt a specific open source Python package, but the resulting software would require a special Arduino board with an MCU chip with much more SRAM and a higher clock speed than we usually see on Arduino boards.
Discussion
I have looked several times and have never found anything.
I did find a "stripped down" implementation of a Python 3.3 interpreter called Micro Python. The software was developed hand in hand with MicroPy, an ARM-based single board computer (also described at the MicroPython website). MicroPy is closer to a Raspberry Pi or Beaglebone than an Arduino. However, the software environment is less complex because the MicroPy doesn't require a Linux-based or other operating system.
The base Micro Python package software package seems to require about 110KB of SRAM to boot up and expects a 1 MB SD chip with a boot record and MicroPython on it.
The Micro Python software was released under the MIT open source license so, in theory, a clever person could adapt it for the Arduino if they built a board with a really powerful chip SD socket.
Although the Micro Python/MicroPy package is very appealing, I don't think I would head down the path. I would rather be programming for hardware that is available from more than one source.
Another potential issue is that the Micro Python implementation uses a mark and sweep garbage collector which might tie up the processor for 4 msec at time. Depending on your application a 4 msec busy period might not be acceptable.

Not really, since python is an interpreted programming language.
If you are not new to the microcontrollers' world and have same experience, maybe this Board is you what you want. More powerful than Arduino and completely programble using Python 3.
Topic: Can I use Python to program Arduino?

The fact that Python is interpreted (or more accurately, byte-compiled for a VM) is not actually relevant. There are several Python VMs for AVR and ARM.

Not exactly. micro controllers, by virtue of not having an os, can only execute compiled code. Hence, using Python is not good as you'll run into a lot of runtime errors and stuff that can be figured out when compiling (exact memory allocation). C++ is better suited.

That's a silly thing to say. Not having an OS means that os and sys are less useful, but an allocator is by no means dependent on an OS. And assuming a working VM implementation, there's little to no reason why a Python program should be any more or less difficult to debug than a C++ application (other than the absence of e.g. debugWire, which can be emulated at a higher level regardless).

@prakharsingh95 Yes, they can only execute compiled code. The compiled code is the interpreter.

@AnnonomusPenguin, an interpreter is the main executing instance which executes Python code. Compiled code allows static scheduling, and memory management, interpreted code will have a harder time optimising. Python programs would need to be internally compiled to byte code , against pythons nature, or the program would need to an interpreter, like you said, which will kill performance. But of course, c++ here makes sense to me, but Python might be feasible.

@prakharsingh95 why would it have to be compiled to byte code? I see no reason, besides program space, to believe that it couldn't at least run a slow, stripped down version of Python from an SD card or EEPROM.

@AnnonomusPenguin, i confess, I don't know how much compromise using python makes, but to me, for tiny processors, nothing beats compile and optimized code. And compiled Python is very hard and probably never done, so people flash interpreters to execute Python, hence the overhead.

@prakharsingh95 speed is a very different thing than possibility. I've seen an AVR chip run Linux somewhere online! BTW it's already been done (kinda): https://micropython.org/

@AnnonomusPenguin yeah, I agree, it's possible, but just doesn't seem efficient to me :P

@prakharsingh95 that link has been already posted by me yesterday. But is not an Arduino board

@prakharsingh95: Python already is compiled to bytecode, so it is hardly "against Python's nature".

@IgnacioVazquez-Abrams Indeed, from this reference, Python is indeed compiled to bytecode, but then is still interpreted. I had meant Python is not compiled to machine code (hex code for Arduino). Like AnnonomusPenguin mentioned, the Python interpreter is loaded on the MCU, not the compiled machine code for the user program.


text:
I2C communication between 2 Arduinos with updated wire library
I would like to enable communication between two Arduino 101. From what I have read, the best method is to use I2C using the wire library. However, it seems as though the newest Arduino IDE has an updated version of the Wire library that no longer includes the begin(int) and onRequest functions.
All of the tutorials for I2C communication use these methods, so I am unable to follow and use them. It looks like when I change the board to Arduino Uno these functions are found, but as soon as I change the board to Arduino 101 the following errors appear no matching function for call to TwoWire::begin(int).
When I try replacing my wire library with the older version, I get other errors for missing libraries and if I replace everything it is unable to compile on Arduino 101.
Can someone please help me or direct me to a I2C tutorial that uses the most updated version of the Wire library?

The problem I see is the Arduino 101 uses an Intel microprocessor (Curie) instead of an Atmel microprocessor.
The only information I could find is on the Arduino page for the 101, which mentions it has dedicated pins for I2C, but it also says that you can use the Wire library. Maybe you just need to update your IDE?
I'd help more, but I can't seem to find any useful information on the Curie...

Although I did not manage to get wire communication to work, I was able to get the Arduinos to communicate through serial port. You just need to ensure to use Serial1 rather than Serial.


text:
Confusion with Serial Communication
Is a buffer used for outputting data from the arduino?
OR
Is the output from the arduino buffered before sending it to Computer?
Is it the same buffer that is used to store the incoming data and the data that we send back from the arduino?
Eg- If am sending a text through the Serial Monitor to the arduino and I am also doing Serial.println("sth") then are they both using the same buffer?
How can i relate Serial buffer with these processes
Please Help!
Arduino Noob
EDIT-1
Can you please explain about the TX buffer overflow

Duplicate of https://arduino.stackexchange.com/questions/1726/how-does-the-arduino-handle-serial-buffer-overflow?s=1|104.2134 and more literally if less informatively  https://arduino.stackexchange.com/questions/16312/is-the-serial-buffer-going-from-arduino-to-pc-and-from-pc-to-arduino-different

Is it the same buffer that is used to store the incoming data and the data that we send back from the arduino?

there are two buffers RX buffer and TX buffer.

Is a buffer used for outputting data from the arduino? OR Is the output from the arduino buffered before sending it to Computer?

TX buffer holds the data until they can be send. Data are send from TX buffer by interrupt routine.

Can you please explain about the TX buffer overflow

TX buffer overflow doesn't happen, because it is easy to handle the situation.
The interrupt routine can send the data only at set baud rate. If the program fills the buffer faster then the interrupt empties the buffer, then the TX buffer fills, but the write function knows that the buffer is full and waits in a while cycle until there is space for that one byte to write.

Can you please explain about TX buffer overflows

This is incorrect.  The TX buffer does not overflow, rather attempted writes to the Serial object block until there is space.  Unfortunately, speculation about this is yet one of the many consequences of the Arduino documentation failing to state the information needed by serious programmers in fine print at the bottom of its its beginner-friendly pages.

https://arduino.stackexchange.com/questions/1726/how-does-the-arduino-handle-serial-buffer-overflow

I edited the section about the overflow, to not only explain what overflow is, but how it is avoided


text:
How to program a BSFrance LoRA32u4 from Arduine IDE 8.5?
I've bought a BSFrance LoRA32u4 from DIYmall on eBay UK.
https://bsfrance.fr/lora-long-range/1311-BSFrance-LoRa32u4-1KM-Long-Range-Board-Based-Atmega32u4-433MHz-LoRA-RA02-Module.html
I've copied the "bsfrance" directory (from the ZIP) into Arduino/hardware (on 64-bit Ubuntu 16.04).
Staring the Arduino IDE, I've selected the correct board (Tools>>Board>>BSFrance>>LoRA32u4).
I've selected the correct port Tools>>Port>>/dev/ttyACM1 (LoRA32u4).
Verifying a trivial sketch looks fine:
void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
}

Result:
Sketch uses 4104 bytes (14%) of program storage space. Maximum is 28672 bytes.
Global variables use 149 bytes of dynamic memory.

The USB device appears in lsusb as: Bus 002 Device 077: ID 239a:800c.
Clicking install causes a white LED to flicker for around ten seconds, but results in:
avrdude: error: buffered memory access not supported. Maybe it isn't
a butterfly/AVR109 but a AVR910 device?
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

or:
Couldn't find a Board on the selected port. Check that you have the
correct port selected.  If it is correct, try pressing the board's reset
button after initiating the upload.

or:
Found programmer: Id = "CATERIN"; type =

or:
Device code: 0x0d

or:
.   Software Version = 1.0; Hardware Version =

or:
An error occurred while uploading the sketch

How do I transfer code onto this board?
(I am new to Arduino, so I may be missing something obvious.  I do have lots of experience programming vanilla ATMEGAs in C without the Arduino IDE.)
--
I have an AVRISP mkII - would burning a new boot-loader help, or just wreck the USB-serial on the device?

which board should be selected

I emailed BSFrance and they were very helpful, coming back with a few suggestions which I could not get to work.
I then tried the Sketch>>Upload Using Programmer with my AVRISPmkII and it worked.  I'm guessing there is a bootloader/Linux issue with the board I bought, and bypassing it let me program the board.
It also works flawlessly with my Mac Mini.

I've had the same problem, but couldn't fix it with the "Upload using programmer".
Instead i sound that the problem was that the serial connection kept dropping after a couple of seconds. My colleague, also on Ubuntu, had the same issue.
This fixed it for me: https://learn.adafruit.com/adafruit-arduino-ide-setup/linux-setup#udev-rules
The board registers as an Adafruit board on my system, and apparently the ModemManager is not too keen on that.
After running first command in the link and restarting, i could upload to the board from Arduino IDE with no errors.


text:
ESP8266 (Huzzah Feather) I2C scanner finds nothing
I am trying to address an I2C device on my Huzzah Feather (Adafruit) ESP8266, but the I2C scanner tool does not detect anything.  All is sufficiently powered and quadruple checked the wiring.
Is there something I am missing for this board in regards to I2C connections?
I've had no issue on an Arduino, which uses the 2 pins on the Analog rail for I2C...
The Huzzah has no Analogue But the one pin, regardless, Huzzah Feather has different (still pin 4 & 5 tho) I2C,  and not via A0 A1 like on the Uno.
Do I need to dig deep and change some pin configurations for the Huzzah?
Thought I would ask before wasting more time on trial and error experiments.
Update Note:
I failed to mention there is a Feather Neopixel board (4x32) hard soldered to the board. Which I suspect is not the culprit as this issue also persists on same board without the neopixel shield attached.
Update
The soldering job was good, but discovered a faulty wire.  This allowed the I2C scanner to detect the i2C controller (LCD2004) at the address of 0x3F...
I checked with a I2c LCD library example, and I don't get any characters to come up... This is the same with both Huzzah Feather boards, one with Neopixel shield and the other is bare.

use Wire.begin(SDA_PIN, SCL_PIN);

@Juraj The Wire library has an overloaded ::begin() that does that for you for the default pins SDA and SCL.

@Majenko, the begin() without parameters uses pins defined in variant. but, yes, I checked it now and the Huzzah Feather has 4 and 5 defined

I tried this Wire.begin(4,5);   and issue persists.

This particular issue was due to a faulty wire on the I2C bus. I replaced the wire and I was able to scan and get an address to the I2C LCD controller.
I still cannot get text to the LCD.  I will start a new question for that.
EDIT:
Upon scrapping my I2C_LCD_DISPLAY library, I downloaded one that was linked in a ESP32/8266 tutorial for the LCD, and finally got it working.


text:
XBee on Arduino Fio - how to read the status of a local digital XBee output pin?
I am using a Fio to control a set of relays. The unit uses an XBee (series 1 Pro) in transparent mode to receive commands over serial UART and everything works fine. The XBee is also configured for digital Input/Output Line Passing and the XBee on the Fio "mirrors" on an output pin the input state on a remote XBee and also this works fine.
How can I interrogate from the Fio the state of the output pin (e.g. D0) of the local (receiving) XBee? Is there an AT command that I could send via Serial.println("ATxx") that would trigger the XBee to send back over UART the status of the pin (high or low)?

You cannot read the state of output pins via an AT command, you can only read the state of input pins using the ATIS command.
See: http://ftp1.digi.com/support/documentation/90000982_S.pdf


text:
Using SCL and SDA of ESP8266-01 with GY-30 BH1750FVI for lux measurement
I followed this tutorial to get lux measurement from GY-30 BH1750 with Arduino.
It's working fine. But now I want to use it with ESP8266-01.
I read Pin 4 is SDA and 5 is SCL for it. But it's not working. Can someone tell me what do I need to change in the code? I'm a "bit" confused about the addressing.
Following is the code for Arduino:
#include <Wire.h>

int BH1750_address = 0x23; // i2c Addresse
byte buff[2];

void setup() {
  Wire.begin();
  BH1750_Init(BH1750_address);

  delay(200);
  Serial.begin(9600);
  Serial.println("Starte Beleuchtungsstaerkemessung - blog.simtronyx.de");
}

void loop(){
  float valf=0;
  if(BH1750_Read(BH1750_address)==2){
    valf=((buff[0]<<8)|buff[1])/1.2;

    if(valf<0)Serial.print("> 65535");
    else Serial.print((int)valf,DEC);

    Serial.println(" lx");
  }
  delay(1000);
}

void BH1750_Init(int address) {
  Wire.beginTransmission(address);
  Wire.write(0x10); // 1 [lux] aufloesung
  Wire.endTransmission();
}

byte BH1750_Read(int address) {
  byte i=0;
  Wire.beginTransmission(address);
  Wire.requestFrom(address, 2);
  while(Wire.available()){
    buff[i] = Wire.read();
    i++;
  }
  Wire.endTransmission();
  return i;
}

Wire is not setup for the ESP01 by default. There is no GPIO 4 or 5. you can specify the pins as arguments to the begin() method, ex: Wire.begin(sda, scl). Using GPIO of (0,2) is common. Since the ESP01 is picky about pin states during power-up, don't use external pullups (you don't need them anyway).


text:
How to use AtMega328P-PN
I am making an AC (the summer kind) control circuit with an AtMega328P chip. I bought the AtMega328P-PN instead of the P-PU. I followed the instructions on how to burn the bootloader, but nothing seems to work on the P-PN. I searched on Google for it and could find nothing anywhere.
Thanks in advance,
Iain

I followed the instructions -- which instructions? Did they also include instructions on setting the right fuses for your clock source?

And what do you mean nothing seems to work...? What doesn't work about it? Does the bootloader fail to flash? Does it flash but fail to be identified by avrdude? What...?

The ATmega328P-PN differs from the ATmega328P-PU essentially only in being rated over a wider temperature range.
It is for all ordinary purposes a direct substitute for where an ATmega328P-PU could be used, and has the same signature word.
Whatever your actual problem is, it is elsewhere.
(The chips that do require some special accommodation if ordered are the ATmega328 without a "P" before the dash and the ATmega328PB)


text:
Unable to compare char from radio (RF24)
The code below is receiver code using nRF24L01. In the loop section I'm comparing the char that was being sent from the Arduino transmitter. In this case the char array says "I'm off" just like the char array compare below. Even though the text is the same, it does not do what it is supposed to do.
Basically the if function below does not seem to work for some reason, both are char arrays (the text[32] and compare[32]) and both will have the same value which is "I'm off" yet it is not registered as the same thing. I cannot figure out what is wrong with the code, please help.
This is the receiver code. The question is about the if function in the loop below.
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

RF24 radio(7, 8); // CNS, CE
const byte address[6] = "00001";

void setup() {
  Serial.begin(9600);
  radio.begin();
  radio.openReadingPipe(0, address);
  radio.setPALevel(RF24_PA_MIN);
  radio.startListening();
}

void loop() {
  if (radio.available()) {
    char text[32] = "";
    char compare[32] = "I'm off";
    radio.read(&text, sizeof(text));
    Serial.println(text);
    Serial.println(compare);
    // this is the problem  -->
    if (text == compare) {
      // it is supposed to print this but it does not -->
      Serial.println("not on");
    }
  }
}

This is the transmitter code
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
RF24 radio(7, 8); // CNS, CE
const byte address[6] = "00001";
const int button = 5;

void setup() {
  radio.begin();
  radio.openWritingPipe(address);
  radio.setPALevel(RF24_PA_MIN);
  radio.stopListening();
  pinMode(button,INPUT);
}

void loop() {
  int reading = digitalRead(button);
  if(reading == HIGH) {
    // send a message to the radio
    const char text[] = "I'm on";
    radio.write(&text, sizeof(text));
    delay(1000);
  }
  if(reading == LOW) {
    // send a message to the radio
    const char text[] = "I'm off";
    radio.write(&text, sizeof(text));
    delay(1000);
  }
}

Finally i found a solution, turns out the problem was that Arduino will not comparison between char == char like this if (char == char). then i decided to CONVERT char to string. this is the example code for Receiver.
void loop() {

  if (radio.available()) {
    char text[32] = "";
    char compare[32] = "im off";
    radio.read(&text, sizeof(text));
    // you must convert char to String for it to work
    test1 = String(text);
    test2 = String(compare);

    Serial.println(text);
    //Serial.println(compare);

    if (test1 == test2)
    {
    delay(500);
    Serial.println("not on");
    }

  }

i have convert char to String then i compare the value of it, and it works like a charm. if any of you have the same problem with me and solve it after this please give me thumbs up

What you have said is incorrect.  An Arduino will quite happily perform char == char but that is not what you are expecting it to do.  char text[32] is a string (not the String object you are talking about) and to compare two strings you must use either a loop of strcmp() (or similar).  By making text a string and comparing that object you are letting the class do the same thing.  I know it seems pedantic, but an array of something is not the same as the something and arrays cannot be compared without some function to do it (even if that function is operator==).  Nice fix though!

That is not a good way to solve it.  That is a hack.  The String class does bad things on microcontrollers and it is something you should try to stay away from.  What you need to compare two char arrays is the strcmp function.
if(strcmp(someCharArray, anotherCharArray) == 0){
    // the strings are the same
}

Use google to find out more about strcmp.


text:
ESP8266 NodeMCU CP2102 ESP-12E I2C with MPU 6050 Error
So the previous two questions could be found here:
ESP8266 computtion error and ESP8266 not working with MPU 6050 over wire library and I2C
However, it was not resolved, and with updates and debugs, I'm going to delete them later and summarize in this single post.
Issue:
An ESP8266  CP2102 ESP-12E was trying to access MPU 6050. However, it's not working.
Attempts:

You can see the diagram picture. I tried pairs of pull up resistor from 0 to 100 k(the one used in the picture was standard 4.7 k).
Many MPU 6050s have been attempted and tested. They were working, and you can see in the picture, the green light lighted up.
Different ESP 8266 -12E from two different brands have been attempted, both have the same issue.
Various of version of board manager has also been attempted.
Different wires have been attempted. The I2C bus in the graph are twisted wires.
The adjustment of the program has also been attempted. Eventually, an online version of code  was attempted, and not working.
The power supply was ruled out through the usage of power board, capacitors, and external power sources. The issue persisted.
Wire library pins, frequencies, have been checked as correct. As well as constant restart of IDE and hardware.
Different bread boards and have also been attempted, the issue persisted.

The above attempts all resulted failure. Could you help me to figure out why ESP 8266 does not work with MPU 6050 over I2C?

Comments are not for extended discussion; this conversation has been moved to chat.

This is not the answer to your question, but I don't know where you get the idea of using a 100k pull up resistor for I2C communication. The value of pull-up resistor depends on the speed of I2C communication, 4.7k will probably enable the I2C to communicate at fast mode, but 100k will sure too high even for 9600bps, you should read this application node for better understanding of pull up resistor requirements.

@hcheung please read, resistor from 0 to 100k has been attempted and the one in the graph was 4.7k

Well, sorry to be blunt, you are all over the places and don't know what you are doing. It is fine if you don't appreciate the sharing. ESP8266 works for MPU6050, it works for me, works for other people as some pointed out. Good luck...


text:
CH340 chip getting fried after connecting Arduino to a powerful 12V souce
I'm using a 120 W DC power supply connected in parallel with ESC and Arduino nano through Vin. However, somehow the Arduino get fried near the CH340 chip, i.e. around the big black square chip near the micro usb port on the back of the board, kept getting fried. It's working for a while, until it melted.
This didn't quite make sense, since Arduino Vin can take voltage from 6V to 12V. The ESC also had a maximum current consumption of over 30A, equivalent to 360W. Thus there wasn't an obvious reason for which Arduino ought to get fried at all.
Why CH340 chip getting fried after connecting Arduino to a powerful 12V source?

@jsotola It's just standard ESC wiring, and Vin and Vground are in parallel of the power input of ESC with the power souse positive and ground. It's descripted in the post, no tricks. The arduino nano was only used to supply a PWN wave.

Precisely which chip is it that gets fried? Is it actually the CH350G or one of the smaller components near it?

@Majenko It definitely fried CH300 chip set once, because my computer's usb port got fried once. After that, it's always appear to be near CH300 chip set. However, it wasn't clear weather it's CH300 or the nearby resistor.

It could be that you have a very noisy power supply - one with huge electrical switching spikes in the output.

Maybe the 3-pin voltage regulator is bad, the large chip on the right, and is letting more than 5V thru.

It's impossible to say for sure what is going on without proper equipment (mostly you need oscilloscope), but I'm pretty sure that due to very high current consumption of the motors, there are voltage spikes at the input of the voltage regulator. If voltage exceeds safe value (15V for most of them), then regulator fails and all the input voltage is now on the output (that's how they fail 99% if the time, not as an open unfortunately, but as a short). Then for some reasons the weakest IC is CH340G which is fried. Try to use destroyed Arduino without ESC, and see what's on the 5V pin.
You say that you have currents up to 30A, but PSU is rated for 120W which means it can deliver only 10A at 12V. So at some point PSU falls into protection mode, switches off the output, and after some time tries to switch it on again. Situation with voltage spikes can be very nasty during this period.
Also please post your schematic and photo of the actual wiring, this can also give us some clues.


text:
Converting string to byte array and byte array to string?
I am trying to create a string message and then encrypt it via AES but the example only accepts byte array as input. How can I convert fullmessage string to message byte array to encrypt it? Checked similar questions but couldn't resolve the problem.
void loop ()
{
  dt = clock.getDateTime();
  String dash = "-";
  String comma = ",";
  String time = dt.year + dash + dt.month + dash + dt.day + dash + dt.hour + dash + dt.minute + dash + dt.second;
  String status = "OK";
  String fullmessage = time + comma + status;
  byte message[]= "anything";
  plainLength = sizeof(message)-1;
  padedLength = plainLength + N_BLOCK - plainLength % N_BLOCK;
  prekey(256,message);
  delay(2000);
}

do you get an error?

"cannot convert ‘String’ to ‘byte {aka unsigned char}’ in assignment" I get this when trying to put fullmessage directly as message. Now I was trying to use message[i] = fullmessage[i] in a for loop, seems like it worked.

strcpy(message, fullMessage.c_str()); allocate message as char message[MESSAGE_SIZE]; https://www.tutorialspoint.com/c_standard_library/string_h.htm


text:
NPN transistors level shifter
I'm going to use this for Arduino Pro Mini (5v version) to communicate with ESP32 via UART so I need level shifting. I found this circuit which uses NPN transistor and I'm also going to use it. This is the circuit I'm going to use...

simulate this circuit – Schematic created using CircuitLab
Are the resistors' value appropriate or do I have to change the collector resistor?

You don't have a collector resistor, you have a pullup resistor.

Can a moderator migrate this to the Electronical Engineering stackexchange please? This is purely about level shifting with transistors.

Are you aware that you can just use a voltage divider? Two resistors.

Those values look fine to me.


text:
Using While Loop For Accurate Delays
I was trying to get the timing in between events right, (Event time is around 150ms and i need it to be accurate within +-1ms) and came upon this implementation. The actual application will not be affected by the roll over, but would like to see if any of you guys (experts) can point out any flaws in using an empty while loop for time events, besides slightly higher power consumption.
This implementation gave me very accurate time spacings:
unsigned long previousMillis = millis();
Serial.print("ONE: ");
Serial.println(millis());
while(millis() - previousMillis < 1000);
Serial.print("SECOND: ");
Serial.println(millis());

compared with...
Serial.print("ONE: ");
Serial.println(millis());
delay(1000);
Serial.print("SECOND: ");
Serial.println(millis());

Which yields some errors after every step.

±1 ms accuracy is borderline for millis(). Use micros() instead.

Thanks for pointing that out. I added that my event time is actually around 150 ms. The micros() function is stated in the documentation to be accurate up to 16000us/16ms only. But does not state how much is the drift. Might need to test it out..

Have you looked at the source code for delay()? What makes you think your while loop would use more power than the while loop in the delay() function?

“The micros() function is stated in the documentation to be accurate up to 16000us/16ms only.” That's incorrect. In what documentation did you find that? micros() can be used to measure times up to 71.6 minutes, which is its rollover period. The drift of micros() is the drift of the ceramic oscillator clocking your MCU. Typically less than 0.5%. Any timing method (delay(), millis(), micros(), hardware timers, etc...) will suffer the same drift, unless using an external time source, like an RTC.

@EdgarBonet "In what documentation did you find that?" The official delayMicroseconds reference page: https://www.arduino.cc/reference/en/language/functions/time/delaymicroseconds/

If you want to be sure of the time between event, you need to use interrupt timer. In all other cases, even a small change in your code will affect the time needed for the loop to execute, and will change the delay between event.

delayMicroseconds does not use micros() which is what was suggested. micros() has a granularity of 4 µs. However delayMicroseconds can be used inside an ISR as it does not rely upon interrupts, whereas micros() does (need interrupts - eventually).

See the documentation for micros

There are many options for executing a task periodically. The most
straightforward is to use a slight variation of code given in the Blink
Without Delay[] Arduino tutorial:
const uint32_t PERIOD = 150000;  // 150 ms

void loop() {
    static uint32_t last_time;
    if (micros() - last_time >= PERIOD) {
        last_time += period;
        do_periodic_task();
    }
    do_other_tasks();
}

Note two changes relative to the code in the tutorial:

This is using micros() instead of millis(). This way the timing
resolution is 4 µs instead of 1 to 2 milliseconds.
last_time is updated as last_time += period instead of
last_time = micros(). This way, even if the periodic task got
delayed by the other tasks, these delays don't add up.

The timing will not be perfect: you will have both drift and jitter.
The drift comes from the inaccuracy of the ceramic resonator clocking
the microcontroller. These resonators have typically 0.5% frequency
tolerance, although the typical frequency error is more likely to be
around ±0.1% (i.e. 0.15 ms error in a 150 ms period). Note
that a poorly written code would add it's own drift, e.g. if you do
last_time = micros(), but this does not.
The jitter comes from the fact that the clock is checked only once per
loop iteration, and your periodic task can then be delayed by the other
tasks. The amplitude of the jitter is the maximum time taken by a loop
iteration.
Despite these imperfections, this would be my first choice unless I
really needed better timing accuracy.
If you need lower drift, one option is to calibrate your Arduino clock.
You measure how fast or slow it is, and you tweak the PERIOD constant
accordingly. For example, if you measure the clock to be 700 ppm
slow, you would fix it like this:
const uint32_t NOMINAL_PERIOD = 150000;  // 150 ms

// Adjust the period to account for clock drift.
const float FREQUENCY_OFFSET = -700e-6;  // -700 ppm
const uint32_t PERIOD = NOMINAL_PERIOD * (1 + FREQUENCY_OFFSET);

This technique allows you to tune the frequency with about 6.7 ppm
resolution, for a period of 150 ms. You cannot reasonably expect
anything better, as the frequency of the ceramic resonator is not very
stable anyway.
If you need lower jitter, one option is to perform a blocking wait:
you ask the processor to do nothing but wait until it's time to perform
the periodic task. This is similar to the code you posted in your
question:
void loop() {
    static uint32_t last_time;
    while (micros() - last_time < PERIOD) ;  // busy wait
    last_time += period;
    do_periodic_task();
}

This will not completely suppress the jitter, but it will reduce it to
just the time taken by the while loop. However, there is a big issue
with this way of coding: now your processor does nothing but the
periodic task. It may not be a problem right now, but as your project
grows, it is more than likely that at some point you will want to handle
extra tasks like, e.g. responding to some user input.
If you want to avoid completely blocking the processor on the busy wait,
yet you want the smallest possible jitter, you could try some sort of
compromise: you let the processor take care of other tasks until it is
almost time to perform the periodic task. Then you switch to the
blocking mode where the processor does nothing but wait for the clock.
Here, “almost time” would be defined by the maximum time your loop can
take:
const uint32_t MAX_LOOP_TIME = 2000;  // assume 2 ms

void loop() {
    static uint32_t last_time;
    if (micros() - last_time >= PERIOD - MAX_LOOP_TIME) {
        while (micros() - last_time < PERIOD) ;  // busy wait
        last_time += period;
        do_periodic_task();
    }
    do_other_tasks();
}

Another option, that has been mentioned in comments, is to trigger the
task by a timer. This will work if it is a very short task that can
safely be run with interrupts disabled. You have four 16-bit timers on
your Mega, so you can presumably spare one for timing this task. This
could be done with Timer 1 as follows (warning: untested code):
const int TIMER_PRESCALER = 64;
const float F_TIMER = F_CPU / TIMER_PRESCALER;
const float PERIOD = 150e-3;
const uint16_t TIMER_PERIOD = F_TIMER*PERIOD + 0.5;  // round to nearest

void setup() {
    TCCR1B = 0;            // stop the timer
    OCR1A  = TIMER_PERIOD - 1;
    TIFR1 |= _BV(OCF1A);   // clear TIMER1_COMPA interrupt flag
    TIMSK1 = _BV(OCIE1A);  // enable TIMER1_COMPA interrupt
    TCCR1A = 0;            // no PWM
    TCCR1B = _BV(WGM12)    // CTC mode, TOP = OCR1A
           | _BV(CS10)     // clock at F_CPU / 64
           | _BV(CS11);    // ditto
}

ISR(TIMER1_COMPA) {
    do_periodic_task();
}

Note that TIMER_PERIOD will be 37500. If you want to tune it to
account for an inaccurate clock frequency, your tuning resolution will
be about 26.7 ppm.
The interrupt technique should get you sub-microsecond jitter most of
the time. However, every now and then the Timer 0 interrupt (the
one responsible for updating the millis() counter) will delay your
interrupts for a few microseconds. Beware also that some libraries can
delay interrupts for excessive amounts of time. Software Serial is an
infamous offender.

For better accuracy, you should not be "delaying until it's time to do something", but instead "checking if it's time to do it yet".
It's all very well saying you want something to happen every 150ms and delaying between actions for 150ms, but that won't yield you an event that happens every 150ms - it yields you an event that takes X amount of time with a delay of Y between each event, resulting in an overall period of X+Y, which is not what you want.
I cover the proper ways to deal with timing of regular events in this existing answer:

delay(time); vs if(millis()-previous>time); and drift


text:
ESP8266 Connection to Arduino Mega 2560
Im trying to connect my esp8266-01 to my arduino mega 2560 to get the code working from the following video tutorial found on youtube:
https://www.youtube.com/watch?v=zGgUfAB4m24
This is the code Im using from the youtube video:
#include <SoftwareSerial.h>

#define ESP8266_rxPin 4
#define ESP8266_txPin 5

//SSID + KEY
const char SSID_ESP[] = "SSID";
const char SSID_KEY[] = "PASSWORD";

// URLs
const char URL_youtube[] = "GET https://api.thingspeak.com/apps/thinghttp/send_request?api_key=S7QNK85SG9D9YD27 HTTP/1.0\r\n\r\n";
const char URL_current_temp[] = "GET https://api.thingspeak.com/apps/thinghttp/send_request?api_key=S7QNK85SG9D9YD27 HTTP/1.0\r\n\r\n";

//MODES
const char CWMODE = '1';//CWMODE 1=STATION, 2=APMODE, 3=BOTH
const char CIPMUX = '1';//CWMODE 0=Single Connection, 1=Multiple Connections

SoftwareSerial ESP8266(ESP8266_rxPin, ESP8266_txPin);// rx tx

//DEFINE ALL FUNCTIONS HERE
boolean setup_ESP();
boolean read_until_ESP(const char keyword1[], int key_size, int timeout_val, byte mode);
void timeout_start();
boolean timeout_check(int timeout_ms);
void serial_dump_ESP();
boolean connect_ESP();
void get_youtube();
void get_current_temp();
void get_hilo_temp();

//DEFINE ALL GLOBAL VAARIABLES HERE
unsigned long timeout_start_val;
char scratch_data_from_ESP[20];//first byte is the length of bytes
char payload[150];
byte payload_size=0, counter=0;
char ip_address[16];
char youtube_subs[10];
char youtube_views[13];
char current_temp[5];
char hi_temp[5];
char lo_temp[5];

//DEFINE KEYWORDS HERE
const char keyword_OK[] = "OK";
const char keyword_Ready[] = "Ready";
const char keyword_no_change[] = "no change";
const char keyword_blank[] = "#&";
const char keyword_ip[] = "192.";
const char keyword_rn[] = "\r\n";
const char keyword_quote[] = "\"";
const char keyword_carrot[] = ">";
const char keyword_sendok[] = "SEND OK";
const char keyword_linkdisc[] = "Unlink";

//keywords for youtube
const char keyword_html_start_b[] = "b>";
const char keyword_html_end_b[] = "</b";

//keywords for current temp
const char keyword_html_start_temp[] = "p\">";
const char keyword_html_end_temp[] = "<s";
const char keyword_html_start_body = "<body>";
const char keyword_html_end_body = "</body>";

void setup(){//        SETUP     START
  //Pin Modes for ESP TX/RX
  pinMode(ESP8266_rxPin, INPUT);
  pinMode(ESP8266_txPin, OUTPUT);

  ESP8266.begin(9600);//default baudrate for ESP
  ESP8266.listen();//not needed unless using other software serial instances
  Serial.begin(115200); //for status and debug
  delay(5000);//delay before kicking things off

  setup_ESP();//go setup the ESP
}//                    SETUP     END

void loop(){//         LOOP     START

  //get_youtube(); // get youtube views and subs
  //delay(15000);//thingspeak needs ~12 secs before next connection

  get_current_temp();//current temperature
  delay(15000);

}//                    LOOP     END

Whenever I run the code everything just fails and Im not able to send AT commands from my arduino to the ESP.
Im using the following connection between the arduino and the ESP:
**ESP <---------------------> ARDUINO
GND -------------------------- GND
GP2 -------------------------- Not connected
GP0 -------------------------- Not connected
RXD -------------------------- DIGITAL PIN 4
TXD -------------------------- DIGITAL PIN 5
CHPD ------------------------ 3.3V
RST -------------------------- Not connected
VCC -------------------------- 3.3V**

If I connect RESET pin on the arduino to GND and the RX and TX pins on the ESP to digital pins 1 and 0 on the arduino and run the serial monitor and try the AT commands they work fine.
But when I try to run the AT commands by sending them from the arduino to the ESP (by running the code) I get the failed every time. What am I doing wrong?
Here is the link to the full code:
http://www.kevindarrah.com/wp-content/uploads/2015/01/ESP8266_BASE_01_28_15.zip

Watching a video shouldn't be a requirement to understand the question.

You are right I will edit the question by adding the code Im using.

There is a lot of unnecessary code and get_current_temp() isn't even implemented.

And what do you mean "everything just fails"? It doesn't even compile?

Why are you using software serial on a Mega? It has 3 additional hardware serial interfaces.

The code compiles just fine, but the debug info on the serial monitor shows that it failed to connect, etc.

I added the link to the full code, all of the methods are implemented.

(9600);//default baudrate for ESP - it's either 74880 or 115200 - never seen an ESP default at 9600

It works just fine with baud set to 9600 when I connect directly to the ESP from PC

A good coding practice when you fail to get it to work is "KISS" Keep It Simple and Stupid. What I mean is, trim away all unnessecary code and try to get the basics to work. Even start with the serial example that is included in the Arduino IDE.

Further to what @MatsK suggests, what you want is a minimal, complete, verifiable example, for two reasons: because it will make it easier for people to help and hence you're likely to get better help, and because you'll likely find the problem yourself in the process of creating it.

Newb question here but the RX pin of the ESP should be connected on the TX pin on the Arduino and the TX pin on the ESP should be connected on the RX pin of the Arduino ?

yes. did you remove the SoftwareSerial and use a hardware Serial?

How do I do that?, I'm still learning sorry...

I fixed it by changing everything on the code from SoftwareSerial ESP8266 to the hardware serial: Serial1.
I used the pins 18 and 19 of the hardware serial. I also made sure connect the RX pin of the ESP to the TX pin of the Arduino and do the same with the TX pin.


text:
My shield does not have further female headers? How do I stack more shields?
I purchased a motor shield (L293D) and it doesn't have the female header which I can connect to another shield. What can I do to stack up more shields?
For being more specific I ordered my shield from here:
https://www.amazon.in/Simple-Labs-SLAEX039-Shield-Arduino/dp/B00K2Z3GAE/ref=sr_1_1?ie=UTF8&qid=1518767182&sr=8-1&keywords=motor+shield+for+arduino+uno&dpID=41h0ag2SCgL&preST=_SX342_QL70_&dpSrc=srch
And please tell me how to do it because it is new for me. A guide or something?

Many shields cannot be stacked, even if you replace the headers. The biggest reason is that the shield uses most of, if not all, the available pins. Motor shield often fall into this category, so they don't add the pointless expense of stackable headers.
Before you consider stacking any shields, whether they have stackable headers or not, you first need to learn how the shields work and what pins they require to ensure there are no conflicts.


text:
Build a timer that starts and stops timing when 2 wires are broken
I need to build a timer that uses the breaking of copper strips to trigger its starting and stopping. The intention is to measure the speed of a rocket with this - it will break the first wire, starting the timer, and then break the second, stopping it.
I am using an Arduino Uno, and a couple of lengths of wire for now.
I can plug one wire into the 1st 5V power supply on the board, and the other end into one of the analog pins (AO), (and then the second wire into the 2nd 5v supply and A1) so that when it is pulled out of the pin socket, it is 'broken'. Is this the correct method to go about this, and if so, how do I tell the Arduino to look for those signals as its 'start' and 'stop' and then record the time difference accordingly?
So far, I have managed to read a signal from the wire using the Analog Read Signal tutorial on Arduino.cc (https://www.arduino.cc/en/Tutorial/AnalogReadSerial). I noted whilst watching the printed data that once the wire is removed from the pin, the voltage value slowly decreased, and held at around 290 (starting at 1023, as per the tutorial). Is this simply a side effect of not using a grounded potentiometer, but a wire?
void setup() {
  // set up comms:
  Serial.begin(9600);
}

void loop() {
  // check and read value of input:
  int sensorValue = analogRead(A0);
  Serial.println(sensorValue);
  delay(1);
}

I am new to Arduino, so please explain in detail, or point me to a thread that will! Thanks in advance for help!
UPDATE
Having played around with analogWrite some more, I have managed to get a situation where I can output the relative value from both A0 and A1. However, I am still struggling to make it operate as a timer.
// declare variables
unsigned long startTime, stopTime;
unsigned long totalTime = (stopTime - startTime);

void setup() {
  Serial.begin(9600);   // set up comms
}

void loop() {
  // check and read value of input:
  int sensorValue1 = analogRead(A0);
  int sensorValue2 = analogRead(A1);

  if (sensorValue1 < 1023) {
    startTime = micros();
    Serial.println(sensorValue1);
  }
  if (sensorValue2 < 1023) {
    stopTime = micros();
    Serial.println(sensorValue2);
  }

  Serial.println("Time: ");   // prints "Time: "
  Serial.println(totalTime);  // prints time value
    delay(1000);
}

I have also tried to convert this to use digitalRead rather than analogRead but have not had much success - I am still failing to get a time. I know my method is wrong, but have struggled to find guidance on how to correct it.
    // declare variables
boolean timingFinished = false;
unsigned long startTime, stopTime;

String strTime = "Time:";

void setup() {
  Serial.begin(9600);   // set up comms
  pinMode(7, INPUT);   // set up pin 7
  pinMode(6, INPUT);   // set up pin 6
}

void loop() {
  // check and read value of input:
  int sensorValue1 = digitalRead(7);
  int sensorValue2 = digitalRead(6);
  Serial.println(sensorValue1);
  Serial.println(sensorValue2);

  if (sensorValue1 = HIGH) {
    startTime = micros();
    Serial.println(sensorValue1);
  }
  if (sensorValue2 = HIGH) {
    stopTime = micros();
    Serial.println(sensorValue2);
  }
  unsigned long totalTime = (sensorValue1 - sensorValue2);
  String strPrint = strTime + totalTime;
  Serial.println(strPrint);      // prints "Time"

}

You have a number of problems in your code. For one thing, you are doing a lot of printing:
void loop() {
  // check and read value of input:
  int sensorValue1 = digitalRead(7);
  int sensorValue2 = digitalRead(6);
  Serial.println(sensorValue1);
  Serial.println(sensorValue2);

  if (sensorValue1 = HIGH) {
    startTime = micros();
    Serial.println(sensorValue1);
  }
  if (sensorValue2 = HIGH) {
    stopTime = micros();
    Serial.println(sensorValue2);
  }
  unsigned long totalTime = (sensorValue1 - sensorValue2);
  String strPrint = strTime + totalTime;
  Serial.println(strPrint);      // prints "Time"

}

At 9600 baud each byte output takes 1/960 seconds (about 1 ms). A println adds a carriage-return/linefeed to what you are printing so I estimate:
3 + 3 + 7 + 7 = 20 bytes (20 ms)

That is every time around the loop! You will soon find the output buffer filling up, and thus are limiting the rate at which you can test times to be the nearest 20 ms which makes using micros() a bit redundant. You won't get that accuracy.

Plus, the String class does dynamic memory allocation which will slow things down. Why use String at all? For example, you can print "Time" like this:
Serial.println ("Time:");

Next, this assigns not compares:
  if (sensorValue1 = HIGH) {

That statement makes sensorValue1 HIGH (always) and then tests if it is true, which it always will be. You want:
  if (sensorValue1 == HIGH) {

Finally, as mentioned by Majenko, make the inputs INPUT_PULLUP and wire the other end to ground, like this:
  pinMode(7, INPUT_PULLUP);   // set up pin 7
  pinMode(6, INPUT_PULLUP);   // set up pin 6

Edit - after amended question.
// declare variables
unsigned long startTime, stopTime;
unsigned long totalTime = (stopTime - startTime);

You don't declare totalTime like that. It appears you want totalTime to eventually subtract startTime from stopTime.
Just declare totalTime without any calculations, and do the calculation when it is needed. eg.
// declare variables
unsigned long startTime, stopTime;
unsigned long totalTime;

...

  if (sensorValue2 == HIGH) {
    stopTime = micros();
    totalTime = stopTime - startTime;
    Serial.print ("Time: ");
    Serial.println (totalTime);
    }  // end of second sensor tripped

Note the "==" there, without it the code thinks both sensors tripped immediately.

A broken wire is just a button that's held in until you release it.  Just treat it like any other button.

simulate this circuit – Schematic created using CircuitLab
Just like a button, when it's all connected (button is pressed), it reads LOW, and when it's disconnected / broken (button is released) it reads HIGH. No need for messing around with analog inputs - you only care about two states, OPEN (HIGH) and CLOSED (LOW).
You can even use interrupts to make it respond even faster.
Here is an example using a simple state machine for how you could code it (untested):
const uint8_t startPin = 4;
const uint8_t stopPin = 5;

uint32_t startTime;
uint32_t stopTime;

#define ARMED = 0
#define STARTED = 1
#define STOPPED = 2

uint8_t state = ARMED;

void setup() {
    Serial.begin(115200);
    pinMode(startPin, INPUT_PULLUP);
    pinMode(stopPin, INPUT_PULLUP);
}

void loop() {

    switch (state) {
        case ARMED:  // If first wire disconnects then start.
            if (digitalRead(startPin) == HIGH) {
                startTime = micros();
                state = STARTED;
            }
            break;

        case STARTED:  // If second wire disconnects then stop
            if (digitalRead(stopPin) == HIGH) {
                stopTime = micros();
                state = STOPPED;
                Serial.print(F("Duration: "));
                Serial.print(stopTime - startTime);
                Serial.println("us");
            }
            break;

        case STOPPED:  // If both wires reconnected then start over
            if ((digitalRead(startPin) == LOW) &&
                (digitalRead(stopPin) == LOW)) {
                    state = ARMED;
            }
            break;

        default:
            break;
    }
}

Thanks, but could you go into more detail please? How would I write such a code? I had previously tried using digitalWrite, but could not work out how to get a time out of it.

As I said above: Think buttons. How would you read the state of a button? How could you use that to start or stop a timer (or more properly, record two times and then subtract one from another)?

If you have a chance to glance over my updated code, I would appreciate it. I haven't managed to get a time value other than 0 (suggesting that it is recording the startTime and stopTime at the same time.

The problem with your code is you are constantly setting your timestamps all the time the inputs are HIGH, not just at the moment they go HIGH. You only want to set them once, and once only. Simplest way: first set them to 0, then only set them to micros() if they are currently 0.

A better approach for your problem which was to measure the speed of a rocket (i am assuming at launch) would be to use non touch style sensors. Rather then the rocket having to hit two wires which would interrupt the flight path. You could use IR sensors Like in this article.
It would use much of the same logic you are working on now, but would use the IR sensors rather then wires (buttons)

Regardless of what you use as the sensors, wires or photo detectors, you should use interrupts.  Each sensor should go to an interrupt and that interrupt routine should be as short as possible, basically just saving the processor time micros(), into a storage location and returning.  Your main loop can then look at the storage and see if a calculation or printout is necessary.  That way your result will not be dependent on where in your loop the event was detected. The inputs should be digital, high or low as described above.  If you are using photo detectors that are analog, build some external circuits to turn their outputs into digital signals.  I would say this isn't rocket science, but apparently it is. I just hope I am not helping a terrorists :-)


text:
Two-wire Conductivity Sensor and Arduino Hook-up?
For the conductivity meter shown in the photo below, it is a non-NPN sensor for measuring conductivity / impedance.
I am trying to figure out the best method for measuring the output of the sensor using an Arduino.
I am told from the supplier that there is no polarity.  I was planning to connect one of the leads through a 10k resistor to an analog input (A0) on my Arduino; and the other lead to 5V?
Without much other information on the sensor, is a 10k resistor a good place to start?

what does "non-NPN" mean? ... the picture shows what looks like two metal prods ...there may be a component inside the long tube ... do you have a link to the spec sheet for the sensor? ... if it is just two metal prods, then connect +5V -> 10k -> prod#1 -> A0  and  prod#2 -> GND (0V)  ... if the long tube has a resistor, then connect +5V to long prod without using a 10k resistor

I think the npn dictates the type of output (logarithmic vs. linear).  I am using a 10k resistor.  What would the effect of adding a higher resistance or lower resistance be?  Would it change the resolution of the sensor output?  It looks like, for example when I use a 10k resistor, my numbers are much higher and change quicker than when I use a 1k resistor.  It appears that there is higher resolution?

It depends on the conductivity of the liquid which it is going to be placed/submerged to. For example if the liquid is highly conductive(ex. saltwater), then a 10k Ohms resistor should be fine. But if the liquid conductivity is low(ex. tap water), then its best to measure the output voltage of one lead with respect to the Arduino's ground to be sure what value of resistor to apply to or if there is no resistor needed at all.
But generally if you are going to supply it with 5 Volts, it should be fine to connect it with the Arduino's Analog inputs directly as the operating voltage of the Arduino itself is also 5 Volts.
Cheers!

Thanks for your comment!  Could you just elaborate on what the resistor is doing in this case?  For example, if I am using a 10k versus a 1k, does the conductivity sensor with the 10k keep it from getting too saturated from the high conductivity of the salt water?

See photo that I posted in the original post.  I have a probe in tap water, and used different resistor values between GND and A0, as per my Fritzing schematic also shown.  My question is; why does the non-resistor value have a higher value than the 300k resistor value?

I see, from the picture you posted that is a pull-down resistor. Why pull-down, because it is connected between the input(A0) and ground(GND), so when a positive signal comes in, the resistor acts as a "pull-down" voltage.
For additional info: On the contrary there is "pull-up" resistor when the resistor is connected between the positive supply(5V) and the input pin(A0). this type of setup is used when the output of a sensor for example is going from high to low, so to determine there is a change the default state is "pulled-up" by the resistor to 5V so the sensor's output can be read.

By the way, I think why they used a 10k ohms value of resistor is because probably the output of the sensor is 12Volts, so that it won't damage the Arduino, there is a 10k value of pull-down resistor.
But if the output of the sensor is 5V, there should be no resistor needed at all.