text:
Can't print on LCD
I'm a newbie here. And sorry for my bad English first of all.
Right now I'm working on VLC (Visible Light Communication). I have working code, in which output is displayed on the Serial Monitor. But now I want to print this output on an LCD.
I made necessary changes like including the LCD library and instead of Serial.print I used lcd.print. But nothing is displayed on the LCD.
Here is the modified code including LCD:
static int TRESHOLD = 500;
static unsigned int standardDelay = 13500000; //1350 is limit
// include the library code:
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 7,6,5,4);

void setup() {
  Serial.begin(9600); // 9600 bits per second
  pinMode(3,OUTPUT); //digital PWM 3 on output
  int sensorValue = 0;
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // initialize the serial communications:
}

void loop() {
  WriteChar('h');
  WriteChar('e');
  WriteChar('l');
  WriteChar('l');
  WriteChar('o');
  WriteChar('w');
  WriteChar('o');
  WriteChar('r');
  WriteChar('l');
  WriteChar('d');
}

void WriteChar(char str){
  switch (str - '0'){
    case 49:
      //code for a is 011 0001
      LightFlash(false, true, true, false, false, false, true);
      break;
    case 50:
      //code for b is 011 0010
      LightFlash(false, true, true, false, false, true, false);
      break;
    case 51:
      //code for c is 011 0011
      LightFlash(false, true, true, false, false, true, true);
      break;
    case 52:
      //code for d is 011 0100
      LightFlash(false, true, true, false, true, false, false);
      break;
    case 53:
      //code for e is 011 0101
      LightFlash(false, true, true, false, true, false, true);
      break;
    case 54:
      //code for f is 011 0110
      LightFlash(false, true, true, false, true, true, false);
      break;
    case 55:
      //code for g is 011 0111
      LightFlash(false, true, true, false, true, true, true);
      break;
    case 56:
      //code for h is 011 1000
      LightFlash(false, true, true, true, false, false, false);
      break;
    case 57:
      //code for i is 011 1001
      LightFlash(false, true, true, true, false, false, true);
      break;
    case 58:
      //code for j is 011 1010
      LightFlash(false, true, true, true, false, true, false);
      break;
    case 59:
      //code for k is 011 1011
      LightFlash(false, true, true, true, false, true, true);
      break;
    case 60:
      //code for l is 011 1100
      LightFlash(false, true, true, true, true, false, false);
      break;
    case 61:
      //code for m is 011 1101
      LightFlash(false, true, true, true, true, false, true);
      break;
    case 62:
      //code for n is 011 1110
      LightFlash(false, true, true, true, true, true, false);
      break;
    case 63:
      //code for o is 011 1111
      LightFlash(false, true, true, true, true, true, true);
      break;
    case 64:
      //code for p is 100 0000
      LightFlash(true, false, false, false, false, false, false);
      break;
    case 65:
      //code for q is 100 0001
      LightFlash(true, false, false, false, false, false, true);
      break;
    case 66:
      //code for r is 100 0010
      LightFlash(true, false, false, false, false, true, false);
      break;
    case 67:
      //code for s is 100 0011
      LightFlash(true, false, false, false, false, true, true);
      break;
    case 68:
      //code for t is 100 0100
      LightFlash(true, false, false, false, true, false, false);
      break;
    case 69:
      //code for u is 100 0101
      LightFlash(true, false, false, false, true, false, true);
      break;
    case 70:
      //code for v is 100 0110
      LightFlash(true, false, false, false, true, true, false);
      break;
    case 71:
      //code for w is 100 0111
      LightFlash(true, false, false, false, true, true, true);
      break;
    case 72:
      //code for x is 100 1000
      LightFlash(true, false, false, true, false, false, false);
      break;
    case 73:
      //code for y is 100 1001
      LightFlash(true, false, false, true, false, false, true);
      break;
    case 74:
      //code for z is 100 1010
      LightFlash(true, false, false, true, false, true, false);
      break;
    default:
      lcd.print(str - '0');
      lcd.print("CAME IN DEFAULT IN WRITECHAR");
      break;
  }
}

void LightFlash(boolean a, boolean b, boolean c, boolean d, boolean e, boolean f, boolean g){

  digitalWrite(3,LOW);
  if (a == true){
    digitalWrite(3,HIGH);
  }
  delayMicroseconds(standardDelay/2);
  boolean sensorValue1 = (analogRead(A0)>TRESHOLD);
  delayMicroseconds(standardDelay/2);

  digitalWrite(3,LOW);
  if (b == true){
    digitalWrite(3,HIGH);
  }
  delayMicroseconds(standardDelay/2);
  boolean sensorValue2 = (analogRead(A0)>TRESHOLD);
  delayMicroseconds(standardDelay/2);

  digitalWrite(3,LOW);
  if (c == true){
    digitalWrite(3,HIGH);
  }
  delayMicroseconds(standardDelay/2);
  boolean sensorValue3 = (analogRead(A0)>TRESHOLD);
  delayMicroseconds(standardDelay/2);

  digitalWrite(3,LOW);
  if (d == true){
    digitalWrite(3,HIGH);
  }
  delayMicroseconds(standardDelay/2);
  boolean sensorValue4 = (analogRead(A0)>TRESHOLD);
  delayMicroseconds(standardDelay/2);

  digitalWrite(3,LOW);
  if (e == true){
    digitalWrite(3,HIGH);
  }
  delayMicroseconds(standardDelay/2);
  boolean sensorValue5 = (analogRead(A0)>TRESHOLD);
  delayMicroseconds(standardDelay/2);

  digitalWrite(3,LOW);
  if (f == true){
    digitalWrite(3,HIGH);
  }
  delayMicroseconds(standardDelay/2);
  boolean sensorValue6 = (analogRead(A0)>TRESHOLD);
  delayMicroseconds(standardDelay/2);

  digitalWrite(3,LOW);
  if (g == true){
    digitalWrite(3,HIGH);
  }
  delayMicroseconds(standardDelay/2);
  boolean sensorValue7 = (analogRead(A0)>TRESHOLD);
  delayMicroseconds(standardDelay/2);
  delayMicroseconds(3*standardDelay); //1 second passed

  long result = 0;
  result = 1000000*sensorValue1 + 100000*sensorValue2 + 10000*sensorValue3
  + 1000*sensorValue4 + 100*sensorValue5 + 10*sensorValue6 + 1*sensorValue7;
  //lcd.print(result);
  PrintChar(result);
}

void PrintChar(long binary){

  switch (binary){

    case 110001:
      //code for a is 011 0001
      lcd.write("a");
      break;
    case 110010:
      //code for b is 011 0010
      lcd.print("b");
      break;
    case 110011:
      //code for c is 011 0011
      lcd.print("c");
      break;
    case 110100:
      //code for d is 011 0100
      lcd.print("d");
      break;
    case 110101:
      //code for e is 011 0101
      lcd.print("e");
      break;
    case 110110:
      //code for f is 011 0110
      lcd.print("f");
      break;
    case 110111:
      //code for g is 011 0111
      lcd.print("g");
      break;
    case 111000:
      //code for h is 011 1000
      lcd.print("h");
      break;
    case 111001:
      //code for i is 011 1001
      lcd.print("i");
      break;
    case 111010:
      //code for j is 011 1010
      lcd.print("j");
      break;
    case 111011:
      //code for k is 011 1011
      lcd.print("k");
      break;
    case 111100:
      //code for l is 011 1100
      lcd.print("l");
      break;
    case 111101:
      //code for m is 011 1101
      lcd.print("m");
      break;
    case 111110:
      //code for n is 011 1110
      lcd.print("n");
      break;
    case 111111:
      //code for o is 011 1111
      lcd.print("o");
      break;
    case 1000000:
      //code for p is 100 0000
      lcd.print("p");
      break;
    case 1000001:
      //code for q is 100 0001
      lcd.print("q");
      break;
    case 1000010:
      //code for r is 100 0010
      lcd.print("r");
      break;
    case 1000011:
      //code for s is 100 0011
      lcd.print("s");
      break;
    case 1000100:
      //code for t is 100 0100
      lcd.print("t");
      break;
    case 1000101:
      //code for u is 100 0101
      lcd.print("u");
      break;
    case 1000110:
      //code for v is 100 0110
      lcd.print("v");
      break;
    case 1000111:
      //code for w is 100 0111
      lcd.print("w");
      break;
    case 1001000:
      //code for x is 100 1000
      lcd.print("x");
      break;
    case 1001001:
      //code for y is 100 1001
      lcd.print("y");
      break;
    case 1001010:
      //code for z is 100 1010
      lcd.print("z");
      break;
    case 11000:
      lcd.print("dit gebeurt vaak");
      break;
    case 1011001:
      lcd.print("dit ook");
      break;
    case 100001:
      lcd.print("tenslotte dit nog");
      break;
    case 1011000:
      lcd.print("en dit is de laatste denk ik");
      break;
    default:
      lcd.print(binary);
      lcd.print("CAME IN DEFAULT ON PRINTCHAR");
      break;
  }
}

I want to print this output on LCD. But I'm not able to do that. Please help me out.
Circuits:
(1) VLC Circuit

(2) LCD Circuit

I combined both circuits above and made a final circuit.
The VLC circuit is set up in which DATA is transmitted from SIMPLE LED and Capture on PHOTODIODE. And using LCD Circuit I want to display data on LCD.

I don't see any code related to the LCD.

@MichelKeijzers Becuase I remove it and upload original code. Already I mention that thing. Just check it out above the code. Ok...

@LookAlterno Ok, let me.

Connecting a LCD display to an Arduino is not easy because of all those wires and the contrast and the cheap displays need enough voltage (above 4.5 V). I had some trouble with it myself. The second time it was a piece of cake. Forget your project for a moment and make a sketch that only uses the LCD. Start here: https://www.arduino.cc/en/Reference/LiquidCrystal

@Jot Thank you for your advice. I also try out so much code of LCD. Connection setup is all right. But not able to find out what's wrong happen with my code. I uploaded the latest code with. Please check out.

I did. Please make an other small test sketch, just for the display. Your sketch has conflicting things for characters, binary and values. Some improvements can make it easier. But first try to get something on the display. The wires are connected to other pins than in your sketch.

@Jot How? Because I think the whole sketch is necessary. I can't able to make some small sketch.

Of course you can. Make another sketch, a small test sketch that writes "hello" to the lcd display. If that is working, then you know that the display is wired okay and the contrast is okay.

@Jot Oh, you are to say that make simple LCD code which displays "Hello" word. I already do that. And working fine.

Finally, got the problem. My code is working fine. I have a problem with my LCD connection.
I write
LiquidCrystal lcd(12, 11, 7, 6, 5, 4);

Instead of
LiquidCrystal lcd(12, 11, 4, 5, 6, 7);


text:
Use MQ2 Sensor with Arduino Uno without breadboard?
I want to make a small and compact gas sensor using the Arduino Uno and MQ2 sensor. However all sites list a breadboard as a requirement.
Now, the MQ2 has A0, D0, GND, VCC, pins and the Uno also has A0, GND, 3.3V and 5V connectors.
So can I use Male to Female Jumper Wires to directly connect these? I am not using anything else like LEDs or speakers.
My code keeps the inbuilt LED ON when smoke level is LOW and blinks when the Level is HIGH. Also will I need any resistor for it?

You can connect it exactly like this.
I'm using female-female jumper wires and have soldered pins onto the UNO clone to enable me to do this.

Pins on sensor from left to right A0 - D0 - GND - VCC
You can also find the wiring diagram on-line for a barebones sensor
if you've not got the sensor module.
here MQ2- Sensor Information
You can either use the D0 output pin to turn on an LED in the presence of gas / smoke or you can use the A0 to report a gas / smoke level.
The code in my other reply is for the analogue reporting of the sensor value.
The Digital output is either on or off and the potentiometer on the back of the sensor will adjust the point at which the D0 pin report a High output level, if it's not set right then the D0 pin won't actually output a voltage.

Yes, you can use male to female jumper wires to directly connect them. Breadboard is not a requirement. Also, you don't need any resistors.

MQ2 flammable gas and smoke sensor detects the concentrations of combustible gas in the air and ouputs its reading as an analog voltage.
The sensor can measure concentrations of flammable gas of 300 to 10,000 ppm.
The sensor can operate at temperatures from -20 to 50°C and consumes less than 150 mA at 5 V.
Connecting five volts across the heating (H) pins keeps the sensor hot enough to function correctly. Connecting five volts at either the A or B pins causes the sensor to emit an analog voltage on the other pins.
A resistive load between the output pins and ground sets the sensitivity of the detector. Please note that the picture in the datasheet for the top configuration is wrong. Both configurations have the same pinout consistent with the bottom configuration.
The resistive load should be calibrated for your particular application using the equations in the datasheet, but a good starting value for the resistor is 20 kΩ.
DataSheet PDF Here
    * Smoke/Gas Sensor Module project
     * tutorial url: http://osoyoo.com/?p=671
     */
    void setup()
    {
        Serial.begin(9600);
    }

    void loop()
    {
        int val;
        val=analogRead(0);
        Serial.println(val,DEC);
        delay(100);

}

Usually I don't think at the UNO as "small and compact"; I usually prefer to use a barebone atmega or an arduino pro mini / nano as alternatives (nano has inbuilt usb, pro mini doesn't). But anyway...
The SeeedStudio MQ2 has four pins, but no D0 pin; it has Vcc, GND and A0 and a NC pin (which means do not connect this pin).
So... Yes, The sensor is 5V powered and has an analog out interface, so you should connect the A0 pin to any analog input on the arduino (A0..A7); you are not forced to use A0.
Be careful that the sensor uses 800mW of power (160mA at 5V) in the pre-heating, so you are not advised to use it form a battery source

source: Stack Exchange

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

sort: votes


text:
Connecting NodeMCU with OV7076 camera
I am trying to connect an OV7076 camera with a NodeMCU, but there are no pin diagram available for it. As NodeMCU has 4 MB storage and 128 KB  memory, is there any possibility to use it?
AI thinker esp8266mod
Omnivision OV7076

You cannot connect an OV7076 camera with NodeMCU because OV7076 got 4 analog pins (VGA) and on the other hand NodeMCU got only one analog pin.

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


text:
How to get elapsed seconds since Jan 1, 1970?
I am building a time-critical system using Arduino. Is there any way to get the elapsed seconds like time.h of C in Arduino? I tried time(NULL) but it returns 0. Then moved forward to use now() in Time.h. But the result persists.
How can I get the elapsed seconds since Jan 1, 1970 until now?

https://arduino.stackexchange.com/questions/38765/convert-to-and-from-unix-timestamp

The accepted answer is not the only (nor best) answer. It depends what you have in hand.
The Time library will allow your arduino to keep the current time, it just need to be set the time periodically (because of clock shifting issues)
There are several ways you can get the current time:

Use a GPS module
Get time from NTP server if you have network access to one, using an Ethernet shield or may be wifi
Use a custom Serial interface
Use a GSM service
Use a RTC module, may be the most popular and standalone, like the DS3231. However these kind of module will also require some adjustment in the long term, and they require a backup battery (often a coin like CR2032) to keep time when module is not externally powered.
Use a few push buttons and LCD to have the user manually input it.
Use a light sensor to see when it is the brightest time of the day and using azimuth calculation determine the hour of the day (ok, I might be going to far here, but consider a solar powered device in the middle of nowhere)

I sorted them in the order I would choose it if I have several options available.
Those are a few ways that come to my mind

Brilliant answer. Thanks a lot for enumerating every possible options.

@GLM - generic and broad answers do not help anyone and will only confuse other people looking at the post and answers; using an RTC module is the most standard way of doing it since RTC modules are cheaper and easier to connect and program than spending a lot of time and money on any of the other mentioned alternatives; Answer to the point is the key rather than having a broad array of options; All the best in your journeys;

An arduino does not have a real time clock (RTC) built in. Every time it restarts it will reset the millis counter.
You will need to add a RTC peripheral that you can poll to find the current date and time.

You must use an RTC module like DS3231 or DS1307 for such purposes and there are good libraries available for these modules;
Unlike the standard return value of milli seconds elapsed since Jan 1 1970 00:00 on a computer, the millis() function on arduino just returns the number of milliseconds since the board began running the current program and this number will overflow (go back to zero), after approximately 50 days as per the official documentation at https://www.arduino.cc/en/Reference/Millis
While millis() can be used for very basic time controlled operations, its not really reliable to be used for time critical operations;

“[millis()] is not really reliable to be used for time critical operations”. This sweeping statement should be better qualified. millis() can be fine for time-critical applications. It all depends on the specific timing requirements of your application (resolution, jitter, long-term/short term accuracy, ...).

The reason I said its not reliable for time critical operations is because an arduino can reset for various reasons including but not limited to inefficient SRAM usage which is a common mistake done by most newbies;

Thanks a lot for your detailed answer. It really helped.

There is an 1307 RTC module emulator for Arduino: DS1307Emulator.
You can set this emulator running and save seconds to struct tm *timeStructure and afterwards converting the structure to a time_t variable using time.h functions
DS1307Emulator.init(13);
DS1307Emulator.bufferUserData();
DS1307Emulator.writeToRTC(0x00); // set address 0
DS1307Emulator.writeToRTC(0x00); // start the RTC issuing the clock run command at address 0
DS1307Emulator.setUserData();

Adresses are as follows:

0x00 - seconds
0x01 - minutes
0x02 - hours

If you want to use weekdays, date, year etc. refer to the DS1307 datasheet or check examples on the link I provided.
For reading seconds:
DS1307Emulator.bufferUserData();
DS1307Emulator.writeToRTC(0x00);
temp = DS1307Emulator.readUserData();

temp now holds seconds in binary format, you may want to convert them to dec.
Check out examples in the link I gave for full operation.


text:
To control the relay switching in nextion using esp32 Microcontroller
I have developed the code to control the relay switching on/off using nextion display and esp32. But whenever I press my dual state button in the nextion display there is some delay and I need to press my dual state button continuously in nextion display for about 10 to 15 seconds to switch on/off the relay.
I am stuck in this work and I 'm looking for help. I need to switch on/off the relay on a single tap on the dual sate button on nextion display. Below I have attached my code,
#include "NexDualStateButton.h"
#include "Nextion.h"
#include "DHT.h"

#define DHTPIN 27
#define DHTTYPE DHT22

DHT dht(DHTPIN, DHTTYPE);
int R1 = 2;
uint32_t dual_state ;

NexText tTempC = NexText(0, 4, "tTempC");
NexText tHumidity = NexText(0, 6, "tHumidity");
NexDSButton bt0 = NexDSButton(0, 8, "bt0");

char buffer[100] = {0};

NexTouch *nex_listen_list[] =
{
    &bt0,
    NULL
};

void bt0PopCallback(void *ptr)
{
  uint32_t dual_state;
  NexDSButton *btn = (NexDSButton *)ptr;

  dbSerialPrintln("bt0PopCallback");
  dbSerialPrint("ptr=");

  dbSerialPrintln((uint32_t)ptr);
  memset(buffer, 0, sizeof(buffer));

  bt0.getValue(&dual_state);

  if(dual_state>0)
  {
    digitalWrite(R1, LOW);
  }
  else
  {
    digitalWrite(R1, HIGH);
  }
}

void setup(void) {
   dht.begin();
   Serial.begin(9600);
   pinMode(R1, OUTPUT);

   nexInit();
   bt0.attachPop(bt0PopCallback, &bt0);

   Serial.println("DHT Sensor Reading");
   dbSerialPrintln("setup done");
}

void loop(void) {
  nexLoop(nex_listen_list);
  float t = dht.readTemperature();
  float h = dht.readHumidity();

  if (isnan(h) || isnan(t)) {
    Serial2.println(F("Failed to read from DHT sensor!"));
    return;
  }

  static char temperatureCTemp[10];
  dtostrf(t, 6, 2, temperatureCTemp);
  tTempC.setText(temperatureCTemp);

  char hTemp[10] = {0};
  utoa(int(h), hTemp, 10);
  tHumidity.setText(hTemp);

  Serial.print(F("Humidity: "));
  Serial.print(h);
  Serial.print(F("%  Temperature: "));
  Serial.print(t);
  Serial.print("°C ");
  //Serial2.print(F("tTempC.txt="));

  //Serial.print("");
  //Serial.print(F("tHumidity.txt:\ "));
  //Serial.print(h);
  //Serial.write(0xff);
  //Serial.write(0xff);
  //Serial.write(0xff);
}

Thanks in Advance.

What is the NexDualStateButton class? Is that defined by Nextion? And what is Nextion?

If I didn't include the NexDualStateButton in the include statement, I am getting an error as NexDSButton was not declared. So only I included the NexDualStateButton in the include statement

Also, I downloaded the nextion stable environment library(Nextion 7.0.0) and I added that in Arduino IDE. I can't able to add the Nextion unstable version which contains the dual state button library.

That doesn't answer my question. What is that class? I understand that you need it, but what does it do? You're using classes without explaining where they come from, what they are for, or where they are documented.

If I include that class my dual state button works. The Nextion library is not so stable.

You are not providing enough information for us to help you. I've voted to close your question.

Actually I am new to Arduino programming and whatever I am is like trial and error method. The Class #include "NexDualStateButton.h" is used to declare the library of NextionDualState Button.

I think this method inefficient. Because ESP32  continuously listens to the button state.
You can try this method . Working for me .
    int R1 = 2;
    NexDSButton bt0 = NexDSButton(0, 8, "bt0");
    uint32_t dual_state=0;

    void setup(){
    nexInit();
    pinMode(R1, OUTPUT);
    }
    void loop(){
    bt0.getValue(&dual_state);

    if(dual_state==1) //When pressed dual state button dual_state =1
      {
        digitalWrite(R1, HIGH);
      }
      else if(dual_state==0)
      {
        digitalWrite(R1,LOW );
      }

    }

I am using for taking button state in my case. Don't use if you don't want to use it. Its wait after take button state 200ms and enter if condition . Sometimes there is a delay between arduino and nextion i am waiting because of this .

this delay not for this. in my project i am changing dual_state as 0 after if condition . This is for my case. If you dont want to use it then dont use it.

You're overreacting bye

Thanks Alper Aslan. I will check using your code and will let you know soon.

No, Juraj has a point. Don't include code that does not make sense for most users in your answer. You say "I am using for taking button state in my case." That suggests that most users would not need or want that delay, so edit your answer and delete it. The delay() function causes all sorts of problems, and it should only be used in very special circumstances.

Ok guys i will edit you are right thanks for your advice

@AbhishekhAaron you are welcome i am using this code on my project and working properly its not listen all time. Its just listen when pressed button and take button state.

Thanks, guys. My code works. Alper Aslan I used your code for my dual state button and it works now. Below I have attached my code,

@AbhishekhAaron what a good news :)

@AbhishekhAaron, what is the value of the dual_state variable if it is not 1?

@Juraj Sorry, I didn't get your question?

Its written on if condition its zero

I try to understand the differ3nce between the code in question and code in answer. they look equivalent.

@Juraj in question code bt0 state listen all the time by Esp32. In NexTouch nex_listen_list object.

I don't see what line is different

char buffer[100] = {0};
NexTouch *nex_listen_list[] =
{
&bt0,
NULL
};

ok. sorry I compared the codes in both answers not with the question.

This is my updated code to display the temperature and humidity in Nextion display and also to control the relay switching in Nextion display. It works good.

#include "NexDualStateButton.h"
#include "Nextion.h"
#include "DHT.h"

#define DHTPIN 27
#define DHTTYPE DHT22

DHT dht(DHTPIN, DHTTYPE);

int R1 = 2;
NexDSButton bt0 = NexDSButton(0, 8, "bt0");
NexText tTempC = NexText(0, 4, "tTempC");
NexText tHumidity = NexText(0, 6, "tHumidity");
uint32_t dual_state=0;

void setup(){
  dht.begin();
  nexInit();
  pinMode(R1, OUTPUT);
}

void loop(){
  bt0.getValue(&dual_state);

  if(dual_state==1) //When pressed dual state button dual_state =1
  {
    digitalWrite(R1, HIGH);
  }
  else if(dual_state==0)
  {
    digitalWrite(R1,LOW );
  }
  float t = dht.readTemperature();
  float h = dht.readHumidity();

  if (isnan(h) || isnan(t)) {
    Serial2.println(F("Failed to read from DHT sensor!"));
    return;
  }

  static char temperatureCTemp[10];
  dtostrf(t, 6, 2, temperatureCTemp);
  tTempC.setText(temperatureCTemp);

  char hTemp[10] = {0};
  utoa(int(h), hTemp, 10);
  tHumidity.setText(hTemp);

  Serial.print(F("Humidity: "));
  Serial.print(h);
  Serial.print(F("%  Temperature: "));
  Serial.print(t);
  Serial.print("°C ");

}

It's OK to accept you're own answer as the solution to the problem.

There is a simpler way to print the temperature to the display and call the BT button without using the Nextion Library. In this example, I am using a TCA9548A because I am using 2 BMP280s.
void TEMP() {
  delay(125);
  TCA9548A(0);
  HMISerial10.print("t8.txt=\"");
  HMISerial10.print((bmp.readTemperature() * 1.8) + 32);
  HMISerial10.print("\"");
  HMISerial10.write(0xff);
  HMISerial10.write(0xff);
  HMISerial10.write(0xff);
  Serial.print("Inside Temp: ");
  Serial.println((bmp.readTemperature() * 1.8) + 32);

  TCA9548A(1);
  HMISerial10.print("t7.txt=\"");
  HMISerial10.print((bmp.readTemperature() * 1.8) + 32);
  HMISerial10.print("\"");
  HMISerial10.write(0xff);
  HMISerial10.write(0xff);
  HMISerial10.write(0xff);
  Serial.print("Outside Temp: ");
  Serial.println((bmp.readTemperature() * 1.8) + 32);
}

Here I have it looking for a button from the Nextion
void dfd_listen() {

  delay(30);
  dfd = ""; //dfd means Data From Display
  while (HMISerial5.available()) { //This will look to see if there is something coming from the Nextion
    dfd += char(HMISerial5.read());
  }

  if (dfd.substring(1, 4) == "bt4" && dfd.substring(0, 1) == "0") {
    digitalWrite(R6, LOW);   // Roof Lights
    HMISerial5.write(0xff);  // We always have to send this three lines after each command sent to the nextion display.
    HMISerial5.write(0xff);
    HMISerial5.write(0xff);
    Serial.println("Roof Lights OFF");
  } else if (dfd.substring(1, 4) == "bt4" && dfd.substring(0, 1) == "1") {
    digitalWrite(R6, LOW);   // Roof Lights
    HMISerial5.write(0xff);  // We always have to send this three lines after each command sent to the nextion display.
    HMISerial5.write(0xff);
    HMISerial5.write(0xff);
    Serial.println("Roof Lights ON");
  }

  if (dfd.substring(1, 4) == "b17") {
    HMISerial5.print("page 1");
    HMISerial5.write(0xff);  // We always have to send this three lines after each command sent to the nextion display.
    HMISerial5.write(0xff);
    HMISerial5.write(0xff);
    Serial.println("Change to Page 1");
    dfd = "";
    delay(100);
  }

Now this shows both BT and B buttons. The HMISerial are my serial ports the Nextion are attached to. The "dfd" is set as a string before your setup.
For the Nextion button, you just have to add a value and set it as a string, in this case, my value is va11. Then on the button on the press event, you would put something like this.
  if(bt4.val==1)
{
  cov bt4.val,va11.txt,1
  va11.txt+="bt4"
  print va11.txt
  t4.pco=17576
}else if(bt4.val==0)
{
  cov bt4.val,va11.txt,1
  va11.txt+="bt4"
  print va11.txt
  t4.pco=57033
}

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


text:
BMP280 pressure as a DC motor switch - issues
I'm attempting to control a DC vacuum pump to turn off when it hits a BMP-280 reads a set pressure lower than when it spins up (guesstimate pressure, I've got it hooked up to tweak in person). Everything works fine for pressure until I get to the runPump() subroutine, when the pressure callouts go from pascal to very large odd numbers.  I've tried variations of INT/FLOAT/LONG but I still either get a 0 pascal reading or an OVF. The BMP later in runPump does return pressure in pascal.

#include <Wire.h>    //This library allows you to communicate with I2C devices (BMP280)
#include "i2c.h"     //same
#include "i2c_BMP280.h"   //same
BMP280 bmp280;
int inches = 0;
int motorPin2 = 10;
int motorPin1 = 9;
int triggerPin = 7;  // For ultrasonic sensor
int echoPin = 4;    // For Ultrasonic sensor
long duration;
long distance;

void setup() {

  pinMode(triggerPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(motorPin1, OUTPUT);
  pinMode(motorPin2, OUTPUT);

  Serial.begin(9600);
  Serial.print("Probe BMP280: ");
  if (bmp280.initialize()) Serial.println("Sensor found");
  else
  {
    Serial.println("Sensor missing");
    while (1) {}
  }

  // onetime-measure:
  bmp280.setEnabled(0);
  bmp280.triggerMeasurement();
}

void trig() {
  Serial.println("Ping!");
  digitalWrite(triggerPin, LOW);
  delay(2);
  digitalWrite(triggerPin, HIGH);
  delay(10);
  digitalWrite(triggerPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  inches = (duration / 2) / 74;
  Serial.print("Inches: ");
  Serial.println(inches);
  delay(250);
}

void runPump() {
  //  Serial.println("Running Pump!!!!!!");
  //  #include <Wire.h>    //This library allows you to communicate with I2C devices (BMP280)
  //  #include "i2c.h"     //same
  //  #include "i2c_BMP280.h"   //same
  //  BMP280 bmp280;
  //  int motorPin1 = 10;
  //  int motorPin2 = 9;

  bmp280.awaitMeasurement();
  float  pascal;
  bmp280.getPressure(pascal);
  bmp280.triggerMeasurement();

  float runningpressure;
  float deflatepressure;
  runningpressure = (int) pascal;
  deflatepressure = (runningpressure - 600); //pascal minus a bit
  Serial.print("Starting pressure: ");
  Serial.println(pascal);
  Serial.print("Goal pressure: ");
  Serial.println(deflatepressure);

  while (runningpressure > deflatepressure) {
    Serial.println("Engaging Vacuum Pump!!!");
    digitalWrite(motorPin1, HIGH);
    digitalWrite(motorPin2, HIGH);
    delay(250);
    bmp280.awaitMeasurement();
    bmp280.getPressure(pascal);
    bmp280.triggerMeasurement();
    Serial.print("Current pressure: ");
    Serial.println(runningpressure);
    Serial.print("Goal pressure:");
    Serial.println(deflatepressure);
    Serial.print(runningpressure - deflatepressure);
    Serial.println(" more to go.....");
    delay(250);
  }
  //  else{
  Serial.println("Shutting Down!!!!!!!!!!!!!!");
  digitalWrite(motorPin1, LOW);
  digitalWrite(motorPin2, LOW);
  delay(2000);
  //  }
}

void loop() {

  bmp280.awaitMeasurement();
  float  pascal;
  bmp280.getPressure(pascal);
  bmp280.triggerMeasurement();
  Serial.print("Pressure: ");
  Serial.print(pascal);
  Serial.println(" Pa;");
  trig();

  if (inches > 4 && inches < 10) {
    runPump();
  } else
    digitalWrite(motorPin1, LOW);
  digitalWrite(motorPin2, LOW);
  delay(5);
}

//  Serial.println("Extruding Glove!@!!!");
//  digitalWrite(motorPinR, HIGH);  //extrudes gloves
//  delay(500);                      // waits .5 seconds
//  digitalWrite(motorPinR, LOW);   // stops extruding

Try manually controlling the pump with it powered from a different power source. The sensor might be acting erratically due to noise caused by the DC motor. Just make a loop to read the sensor. Turn on and off the pump (powered externally) and see if you have the expected behaviour. If the readings are OK then continue looking at the software.

Rudy, thanks!  I was already running the battery from a separate source and had modified the circuit to reduce noise.  What ended up fixing it was adding a diode on the ultrasonic sensor as a diagnostic to show it was working.  It just wasn't where I was expecting noise from.

I was concerned that you would be trying to figure out what was wrong with your program when then the problem could have been a hardware issue. Normally I am telling our programmers that it isn't a hardware problem and the problem is with their code.  I'm glad you figured it out.

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


text:
Newbie question - Biltong Box Project
I am a newbie to electronics, but I do have experience working with electrical wiring in the UK, so I am comfortable working with 240V reasonably safely. I have also built a camper including all the 12V electrics from scratch. I am fairly technically able, as a building physicist and academic researcher. However, my expertise is in mechanical engineering and physics rather than electronics or electrical engineering.
The Project
I am designing a new generation biltong box. My previous biltong boxes had electrical devices wired individually into plugs and then manually switched.
For those who dont know 'biltong' is the South African equivalent of US jerky. We simply dry the raw beef as opposed to light cooking.

Image 1 - first generation manually switched biltong box
The first generation boxes worked great - they were a test bed for the physics - airflow/heat and drying rates. However, they lacked finesse and were technologically challenged. So I have set myself the goal of building a new smaller box, laser cut from acrylic and packed with more intelligence.
My inspiration is drawn from this great project
Technical details
The biltong dryer design currently comprises of:

1no 240V AC 60W tubular heater - this one specifically. I might want to add another in the future.
2no 12V DC 14.4W axial fans - these ones
1no 12V LED strip light - not yet selected

What I want to do / Problem Statement
I would like to have an Arduino based system, to facilitate the following features:

2no temperature and humidity sensors (one at the inlet at the bottom and one at the outlet at high level)
Touch screen to: 1. display temperature and humidity over time, 2. enable manual control of the heater, fans and LED light, 3. allow me to modify the temperature and humidity setpoints
The ability for the Arduino to control the heater (on/off) and the fans (ideally variable) based on setpoints for temperature and humidity. But also to allow me to operate the heater and fans individually from the touchscreen - on / off / auto for all.

Please help
I know all the kit I am trying to control and how I want to do it (conceptually). Now I need some advice on how to make this happen please.
To kick things off I have purchased an Arduino MEGA 2560 board and kit and have experimented with a few small projects. I now want to use this to control the above.
Questions

Is my idea sensible and achievable (technically)?
I know that I will need a 240V relay to control the heater. Is this safe and reliable? ** This is my biggest concern. What can you recommend for this - there are so many available on the market.
I think I will also need 3 more additional relays for the 2no fans and LED strip light. Is this the best way to control the 12V fans and LED light?
Can I control the speed of the proposed 12V fans? And how is this achieved?

Huge thanks in advance.
First Edit
My calculated current for the heater is 60W / 240V = 0.25A
Questions:

So for a SSR - this looks like a good option - what do you think?
Found a four channel, four route MOSFET - what do you think? Once I have the switching working, i will consider working out the PWM. But switching will be fine for now.
How do I go about designing the circuitry - are there any good online Arduino resources for this?

Second Edit

Not sure where to go from here!
Also, cannot find MOSFET's in Fritzing.

It may be better to post your question on a different SE, like electrical engineering.  Questions here need to be specifically about an aspect of Arduino programming.

Thanks Paul - can the MOSFET control the speed or do i need additional PWM module for that. Excuse the noob question. Please see the first edit in the original question where i have found some options, which I would appreciate some advise on.

Personally I do not feel it being on topic, basic electric control imho is on topic (As in, what component do I need from my Arduino to control x). Nor do I think it would be worth the hassle to close or move the question as it's perfectly answerable and has been already answered.

Regarding components, if it matches your requirements, they should be fine. I think you should separate it in smaller projects, first try controlling a single fan and then build on that. The mist simple designing tool is "Fritzing".

My biggest concern would be the touchscreen, the Arduino has quite limited processing power and interfacing a touchscreen can be difficult.
However, if you purchase the screen from a source that supplies example code, tutorials and libraries (such as adafruit or other known vendors), you should be OK. Alternatively you can check if an 2x16LCD with buttons/'rotating knob' suffices as user interface.

If you switch from Arduino to chipKIT you would get plenty of resources for running a touch screen - as well as my premium DisplayCore library suite.  Unfortunately discontinued now, the 4D Systems Picadillo-35T used to be the ideal solution - chipKIT plus nice touch screen in one. Such a shame they discontinued it :(

I am tending towards a simplified solution of LCD and switches. I am also concerned that the touch screen will add another layer of complexity to the project

Where is the best place for me to now learn how to connect all this up physically? I have downloaded Fritzing and got all the components in there that I need to model the circuitry, but not got much of a clue of how they physically connect and how to plan the physical connections. The Arduino for example has so many connections.

Ruling this "off-topic" seems unnecessarily strict and unfortunate. It sounds like a perfectly good Arduino project to me, and not unlike some other recent, and accepted, questions about components choices and/or connectivity. Voted to unhold/reopen.

I am confused about why this is off topic...?

https://arduino.stackexchange.com/tour

Is my idea sensible and achievable (technically)?

Yep, sure is. It's not really much different to a DIY Reflow Toaster Oven.

I know that I will need a 240V relay to control the heater. Is this safe and reliable? ** This is my biggest concern. What can you recommend for this - there are so many available on the market.

I would suggest an SSR instead of a mechanical relay. Easier to drive, and less electrical noise.

I think I will also need 3 more additional relays for the 2no fans and LED strip light. Is this the best way to control the 12V fans and LED light?

No. Use MOSFETs for those. You can drive those with PWM to change the speed / brightness.

Can I control the speed of the proposed 12V fans? And how is this achieved?

Yes - see above.
As far as control goes you may want to investigate PID as your calculation method.

Thank you for the advice. I have added an edit to the original post with some suggestions on possible devices. Would be grateful for any comments.

@CairanVanRooyen Yeah, looks OK.  I use these SSRs in my reflow oven simply because they are easier to mount in a chassis than a PCB-based one.MOSFETs look fine.

Thanks Majenko. All ordered, just got to wait for the postman!


text:
D1 mini does not resume operation as expected after deep sleep
I'm trying to get the D1 mini to return operation after ESP.deepsleep(). The code below compiles and gives the expected output for the first run. Five seconds after the announcement that that the device is going to sleep, there is a brief flash on the on board LED and I get a string of garbage on the serial monitor. Ideas for things to try would be appreciated.
// Testing d1 mini deep sleep
// D0 and RST are connected

/*  platformio.ini:
  [env:d1_mini]
  platform = espressif8266
  board = d1_mini
  framework = arduino
  monitor_speed = 115200
*/

#include <Arduino.h>

void blink();

void setup() {
  Serial.begin(115200);
  pinMode(D0, WAKEUP_PULLUP);
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  blink();
  delay(1000);
  Serial.println("Going for some deep sleep");
  ESP.deepSleep(5e6); // 5e6 is 5 seconds
}

void blink() {
  digitalWrite(LED_BUILTIN, LOW);
  delay(500);
  digitalWrite(LED_BUILTIN, HIGH);
  delay(500);
}

As you can guess I'm running this with platformio. The output on the serial monitor is:
stefan@Cameron ~/.../Projects/Deep sleep $ platformio device monitor --baud 115200
--- Miniterm on /dev/ttyUSB0  115200,8,N,1 ---
--- Quit: Ctrl+C | Menu: Ctrl+T | Help: Ctrl+T followed by Ctrl+H ---
Going for some deep sleep
sl␀l��|␀�l�|␂␌␌␄�␄l�␌c|ǃ␃�␛�r�cd�c��gg�doo���␌cpp��$sd{d␛�{��o�c�gbx␀�

There is a blink of the LED on the first run, nothing there either after the apparent reset.

I've got same issue after a deep sleep. Here is the error code @74880bps : epc1=0x40100000, epc2=0x00000000, epc3=0x00000000, excvaddr=0x00000000, depc=0x00000000 Fatal exception (0): But when I see this issue, if I manually push the reset button or manually plug RESET to GND, the board is rebooting and restart my code as expected. Only the wakeup from deepsleep generates this issue. Have you fixed your issue ? Thanks,

The garbage is because the ESP8266 outputs boot information at 76800. This should include the boot reason and may help you understand why the code's not working as expected.
Try changing your Serial speed to 76800 in your code (just so that your messages don't end up being gibberish), use 76800 on platformio's monitor and you should be able to at least see what the D1 says it's doing.
You should see a line that ends in something like:

rst cause: x, boot mode:(y, z)

x should be 1 ("Power reboot"), 2 ("External reset or wake-up from Deep-sleep" - obviously what you want), 3 ("Software WDT" - the software watchdog went off) or 4 ("Hardware WDT reset" - the hardware watchdog timer went off)
boot mode indicates where the runtime image came from - y should be 3 ("Flash"); anything else is really unlikely for your setup.
There's more info on this at ESP8266 Reset Causes
and Common Fatal
Exception Causes
If you try this please post how it goes! I'd like to hear more about what's going on here.

Thanks a lot! The baud rate is right to capture that "garbage" - this is the output after setting the serial rate to 76800 everywhere:
--- Miniterm on /dev/ttyUSB0  76800,8,N,1 ---
--- Quit: Ctrl+C | Menu: Ctrl+T | Help: Ctrl+T followed by Ctrl+H ---
Hello I'm in the setup now
Going for some deep sleep

 ets Jan  8 2013,rst cause:5, boot mode:(1,6)

ets_main.c```

Don't know how to format code in the comments...

So the reset cause was the deep sleep wake up. The deviation in boot mode is something I'll have to dig in for tomorrow.

Yeah, unfortunately there's not a good way to format comments :( bites me all the time. Boot mode 1 should mean it's trying to boot via the UART (download new code) rather than the flash. Do you have anything wired up to D3 or D4? If you do try disconnecting them or try wiring D3 to 3.3V via a high value resistor (say, 47K or more, shouldn't really matter exactly the value). More info on boot mode at https://github.com/esp8266/esp8266-wiki/wiki/Boot-Process#esp-boot-modes

So the 1 in `boot mode(1,6) seems to mean my d1 mini is expecting to download code from the UART like you say: https://github.com/esp8266/esp8266-wiki/wiki/Boot-Process#esp-boot-modes
That message doesn't make a lot of sense to me. Sending code over serial doesn't seem like something the board can request.
Anyway - a little frustrated with this - I do appreciate all the input from folks, but for now deep sleep is eluding me.

@SEngstrom - yeah, the board can be forced into a mode where it boots code provided through the serial port, definitely not useful here. That's why I was asking about the D3 and D4 lines on the board - are they wired to anything? They're what controls the boot mode. If they're not wired to anything, try forcing D3 high and D4 low - that should force the ESP8266 into the mode where it boots from the SPI flash.

When I D3 high and D4 low the on-board LED goes on and stays on and I am not able to talk to the board any more. However, now I get a boot mode: (3,6) instead after pulling off the D3, D4 pulls, but it still stops after reporting that after the deep sleep wake-up.

It seems like there's something different between your D1mini and mine. I'm pretty much out of ideas here, sorry! Like @Rudy said, it should work (and I see it work with the same setup). I'll post a new comment if I can think of anything else to try.

Try and clear out the whole memory. Maybe there is something that is messing it up.
I tried your code and it works for me. I do not have a D1 mini but I can't see any reason for it not to work. (due to hardware reasons)
I would include a delay and then output a newline in the setup. As it is your loop print is written after the boot info and gets lost at the end of the line.
Like I said, your code worked for me. But I find this more user friendly. https://raw.githubusercontent.com/wemos/D1_mini_Examples/master/examples/02.Special/DeepSleep/Blink/Blink.ino
Check again your connections. (I'm sure you have done that a dozen times)

Thanks. Did what I think is a firmware reset by connecting D3 to GND for 5 seconds. Added a delay and a Serial.println() in setup(). Same results. I came across the link you suggested before but there is no difference if I put it all in setup().
It seems it is not only that the Serial communications are borked, the blink() should still happen if the code gets there (and it should reset again a little later).

Yeah. Like I said, your code works. (even though I don't like it) Do you have another board you can try?

I think @Rudy is right. I just tried the code on a D1 mini and it works fine for me. You can completely reset the firmware with PlatformIO with a command like this (you may need to change the serial device name): ~/.platformio/packages/tool-esptool/esptool  -vv -cd nodemcu -cb 115200 -cp /dev/cu.usbserial-1430 -ce

Thanks John - executing that results in:
stefan@Cameron ~ $ ~/.platformio/packages/tool-esptool/esptool -vv -cd nodemcu -cb 115200 -cp /dev/cu.usbserial-1430 -ce –
esptool v0.4.13 - (c) 2014 Ch. Klippel ck@atelier-klippel.de
setting board to nodemcu
setting baudrate from 115200 to 115200
setting port from /dev/ttyUSB0 to /dev/cu.usbserial-1430
espcomm_erase_flash
opening port /dev/cu.usbserial-1430 at 115200
error: cannot access /dev/cu.usbserial-1430

seems there were some success, but no change in the behavior when running the code.

@rudy - I did try another previously unused board and same result. Too bad you don't like my code :)

@SEngstrom the error on clearing the flash means the serial port name (/dev/ttycu.usbserial-1430) is wrong - if you want to try that again you'll need to find use the correct one for your system. Platformio probably prints it somewhere. It's probably just the "1430" part that'll be different.

@JohnRomkey thanks again - I did run that  esptool command but no dice.


text:
ESP-01S Relay V1.0 connection with Arduino
I am new to Arduino
Let me ask you about IOT(internet of things).
I want to connect ESP-01S Relay v1.0
Where does the NC port goes on Arduino? Is it TX or RX?
Also, where does the NO goes on Arduino? Is it TX or RX?

Could you please edit and improve your question:  See How to ask and How to ask a good question for Arduino Stack Exchange

The 2 connections you refer to (NC and NO) are connections to the relay switch.

NO stands for normally open
NC stands for normally closed
C or COM stands for common

When the relay is unenergised, the common is connected to the NC terminal. When power is applied to the relay, the coil energises and switches, so now common is connected to the NO terminal.
From my reading of the usage document located on the GitHub repository, you are supposed to program the ESP module before plugging it into the relay board. There are no terminals broken out for you to connect to the Tx and Rx on the relay board.
However, the following board from AUS-eParts has a header to connect a 3V TTL cable. This can be used to program the ESP module.

the RX/TX header is good, but you need io 0 LOW at boot to put the esp8266 into flashing mode

Common, Normally Connected and Normally Open are terminals switched by the relay. There you connect what should be switched. Common is input and the two other terminals are connected, one if the coil is powered and the other when the coils is without power. The relay is controlled by the esp-01. No Arduino should be connected to this.
Disconnect the esp-01 from the relay board and use an 3.3 V USB-to-TTL Serial adapter to program the esp-01 with Arduino IDE
Add Over The Air support to your esp8266 sketch with ArduinoOTA library and then you can upload new versions of your sketch over WiFi. To debug the sketch with print use Telnet server or my TelnetStream library.

How to communicate with server? I have no RX or TX port

what server? with network server you should communicate over WiFi

I mean how i can access server via wifi? This module doesnt have RX and TX pins. Only NC, COM and NO

as I can see on the picture in the question, there is an esp-01 connected to the 2x3 header

esp is connected but this relay what i got, got no RX and TX pins

the esp-01 has RX TX. you must disconnect it from the relay to flash a sketch to it


text:
Send serial data to local server
I am new to arduino coding.
I am reading data from serial port and storing it in char array.
I want to send that data to the local server but it is not getting converted to string
Code :
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
ESP8266WebServer server;
char* ssid = "Office RTPL";
char* password = "********";
char data[64];
char data1[64];
String str;
void setup()

{
  // put your setup code here, to run once:
  WiFi.begin(ssid,password);
  Serial.begin(115200);
  while(WiFi.status()!= WL_CONNECTED)
  {
    Serial.print(".");
    delay(500);
  }
  Serial.println("");
  Serial.print("IP Address: ");
  Serial.print(WiFi.localIP());
  server.on("/",[](){server.send(200,"text/plain","Data Test");});
  server.on("/toggle",serialData);
  server.begin();
}
void loop()
{
  // put your main code here, to run repeatedly:
  server.handleClient();
 ;
}
void serialData()
{
  if(Serial.available() > 0)
      {

        server.send(200,"text/plain","Data");
         for(int n=0; n<64; n++)
         {
           data[n] = (Serial.read());

         }
         String str (data);
         server.send(200,"text/plain",str);

  else
        {
        String no_data = "No Serial Data";
        server.send(200,"text/plain",no_data);
        delay(5000);
        }

}

Please help

As I mention in my answer about serial communication:

Before reading, always make sure data is available. For example, this is wrong:
if (Serial.available ())
  {
      char a = Serial.read ();
      char b = Serial.read ();  // may not be available
  }

The Serial.available test only ensures you have one byte available, however the code tries to read two. It may work, if there are two bytes in the buffer, if not you will get -1 returned which will look like 'ÿ' if printed.

In your code:

if(Serial.available() > 0)
    {
    server.send(200,"text/plain","Data");
     for(int n=0; n<64; n++)
     {
       data[n] = (Serial.read());

So you know that one byte is available, but you are reading 64. No, that won't work.

May u please guide how should i read it.

Read how to read incoming serial data without blocking.

Alternatively you could change that if test to be: if(Serial.available() >= 64)


text:
Problem connecting Android app to Arduino
Sorry for doing this, I really don't know where to post beacuse this is both Android Studio code and Arduino code so I've posted to both sites.
I want to create a project of using controlling pan-tilt (2 servos combined) using the accelerometer and gyroscope data in smartphone. Creating Android app and sending the accelerometer and gryroscope data to Arduino so that the pan-tilt can determine its location.
My problem is when I connect the Android app to Arduino, no data is shown in serial monitor of Arduino and the pan-tilt is not locating the smartphone.
Please help me to solve this problem.
This MainActivity is the class to identify the data of accelerometer and gyrscope.
MainActivity:
public class MainActivity extends AppCompatActivity implements SensorEventListener{

    private final String TAG = "MainActivity";//log our activity

    SensorManager sm;//define sensor manager
    Sensor accelerometer, gyrometer;//define accelerometer

    TextView xValue, yValue, zValue, xGyroValue, yGyroValue, zGyroValue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        xValue = (TextView)findViewById(R.id.xValue);
        yValue = (TextView)findViewById(R.id.yValue);
        zValue = (TextView)findViewById(R.id.zValue);

        xGyroValue = (TextView)findViewById(R.id.xGyroValue);
        yGyroValue = (TextView)findViewById(R.id.yGyroValue);
        zGyroValue = (TextView)findViewById(R.id.zGyroValue);

        Log.d(TAG, "onCreate: Initializing Sensor Services");

        sm =(SensorManager) getSystemService(Context.SENSOR_SERVICE);//permission to use the sensor

        accelerometer = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        if (accelerometer != null) {

            sm.registerListener(MainActivity.this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
            Log.d(TAG, "onCreate: Registered accelerometer listerner");
        }else {

            xValue.setText("accelerometer is not supported");
            yValue.setText("accelerometer is not supported");
            zValue.setText("accelerometer is not supported");
        }
        gyrometer = sm.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
        if (gyrometer != null) {

            sm.registerListener(MainActivity.this, gyrometer, SensorManager.SENSOR_DELAY_NORMAL);
            Log.d(TAG, "onCreate: Registered gyrometer listerner");
        }else {

            xGyroValue.setText("gyrometer is not supported");
            yGyroValue.setText("gyrometer is not supported");
            zGyroValue.setText("gyrometer is not supported");
        }
    }

    public void connect(View v){

        DataSender dataSender = new DataSender();
        dataSender.execute((String) xValue.getText(), toString());
        dataSender.execute((String) yValue.getText(), toString());
        dataSender.execute((String) zValue.getText(), toString());
        dataSender.execute((String) xGyroValue.getText(), toString());
        dataSender.execute((String) yGyroValue.getText(), toString());
        dataSender.execute((String) zGyroValue.getText(), toString());

    }

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        Sensor sensor = sensorEvent.sensor;
        if(sensor.getType() == Sensor.TYPE_ACCELEROMETER){

            Log.d(TAG, "onSensorChanged: X: " + sensorEvent.values[0] + "Y: " + sensorEvent.values[1] + "Z:" + sensorEvent.values[2]);

            xValue.setText("xValue:   " + sensorEvent.values[0]);
            yValue.setText("yValue:   " + sensorEvent.values[1]);
            zValue.setText("zValue:   " + sensorEvent.values[2]);
        }else if (sensor.getType() == Sensor.TYPE_GYROSCOPE){

            xGyroValue.setText("xGyroValue:   " + sensorEvent.values[0]);
            yGyroValue.setText("yGyroValue:   " + sensorEvent.values[1]);
            zGyroValue.setText("zGyroValue:   " + sensorEvent.values[2]);

        }

    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }
}

This DataSender is the class for sending the data to Arduino.
DataSender:
public class DataSender extends AsyncTask<String, Void, Void> {

    Socket s;
    DataOutputStream dos;
    PrintWriter pw;

    @Override
    protected Void doInBackground(String... voids) {

        String data = voids[0];

        try {
            s = new Socket("192.168.1.100",80);
            pw = new PrintWriter(s.getOutputStream());
            pw.write(data);
            pw.flush();
            pw.close();
            s.close();

        } catch (IOException e){
            e.printStackTrace();
        }

        return null;
    }
}

This is code that are uploaded in wifi module (esp8266-01) that are connected in Arduino.
Arduino code:
#include <SoftwareSerial.h>
#include <Servo.h>

#define DEBUG true

SoftwareSerial esp8266(10, 11); // RX, TX

char tiltChannel=0, panChannel=1;

//These are the objects for each servo.
Servo servoTilt, servoPan;

//This is a character that will hold data from the Serial port.
char serialChar=0;

// Center servos
int tiltVal = 90;
int panVal =90;

//smaartphone value
String inText;
float value0, value1, value2;

void setup() { // Open serial communications and wait for port to open:

  servoTilt.attach(2);  //The Tilt servo is attached to pin 2.
  servoPan.attach(3);   //The Pan servo is attached to pin 3.
  servoTilt.write(90);  //Initially put the servos both
  servoPan.write(90);      //at 90 degress.

  Serial.begin(9600); //for monitoring purposes
  esp8266.begin(9600);

  //sendCommand("AT+CIFS+RST\r\n", 2000, DEBUG); // reset module
  sendCommand("AT+IPR=9600\r\n", 1000, DEBUG);
  sendCommand("AT+CWMODE=1\r\n", 1000, DEBUG); // configure as access point
  sendCommand("AT+CWJAP=\"EceConnect\",\"1234\"\r\n", 3000, DEBUG); //connec to
a network with name EceConnect with password 1234
  delay(1000);
  sendCommand("AT+CIFSR\r\n", 1000, DEBUG); // get ip address
  sendCommand("AT+CIPSTA=\"192.168.1.100\"\r\n", 1000, DEBUG);
  sendCommand("AT+CIPMUX=1\r\n", 1000, DEBUG); // configure for multiple
connections
  sendCommand("AT+CIPSERVER=1,80\r\n", 1000, DEBUG); // turn on server on port
80
  Serial.println("Server Ready");

  Serial.println("Android Sensor Type No: ");
  Serial.println("1- ACCELEROMETER  (m/s^2 - X,Y,Z)");
  Serial.println("2- GYROSCOPE (rad/s - X,Y,Z)");
  Serial.flush();

}

void loop() { // run over and over

  Serial.flush();
  int inCommand = 0;
  int sensorType = 0;
  unsigned long logCount = 0L;

  if (Serial.available() < 1) return; // if serial empty, return to loop().

    char getChar = ' ';
    if (esp8266.available()) {
      if (esp8266.find("+IPD,0,")) {
        delay(10);
        esp8266.find(":");
        delay(10);
        char letter = esp8266.read();
        Serial.print(letter); //for monitoring purposes
        //Gets the value/char from android app
      }
    }

    // parse incoming command start flag

    if (getChar != serialChar) return; // if no command start flag, return to
loop().

    // parse incoming pin# and value
    sensorType = Serial.parseInt(); // read sensor typr
    logCount = Serial.parseInt();  // read total logged sensor readings
    value0 = Serial.parseFloat();  // 1st sensor value
    value1 = Serial.parseFloat();  // 2rd sensor value if exists
    value2 = Serial.parseFloat();  // 3rd sensor value if exists

    // send smartphone readings to serial monitor/terminal
    if (DEBUG) {
      Serial.print("Sensor type: ");
      Serial.println(sensorType);
      Serial.print("Sensor log#: ");
      Serial.println(logCount);
      Serial.print("Val[0]: ");
      Serial.println(value0);
      Serial.print("Val[1]: ");
      Serial.println(value1);
      Serial.print("Val[2]: ");
      Serial.println(value2);
      Serial.println("-----------------------");
      delay(10);
    }

    // Check sensor type. If not for  Accelerometer (#1) then ignore readings
    // sensorType 1 is the Accelerometer sensor

  if (sensorType !=1) return;

  panVal = value0; // value0 = X sensor reading
  tiltVal = value1;  // value1 = Y sensor reading

  tiltVal = map(tiltVal, 10, -10, 0, 179);   // Map Accelerometer Y value to
tilt servo angle.
  servoTilt.write(tiltVal);
  delay(10);

  panVal = map(panVal, -10, 10, 0, 179);  // Map Accelerometer X value to pan
servo angle.
  servoPan.write(panVal);
  delay(10);
}

String sendCommand(String command, const int timeout, boolean debug) {
  String response = "";
  esp8266.print(command); // send the read character to the esp8266
  long int time = millis();
  while ((time + timeout) > millis()) {
    while (esp8266.available()) {
      // The esp has data so display its output to the serial window
      char c = esp8266.read(); // read the next character.
      response += c;
    }
  }

  if (debug) {
    Serial.print(response);
  }
  return response;
}

"SoftwareSerial esp8266(0, 1); // RX, TX" you can't do that without breaking the serial monitor - whatever tutorial you are following is dead wrong.  Those pins are the hardware serial, you need to move your ESP to some other pins.

Possible duplicate of cannot read from softwareserial which covers the pin conflict mistake you have repeated here.

i change it to (10, 11) sir..
but still no data..

Try some basic ESP8266 examples before your worry about the whole Android integration problem.  Until you've proved your ESP8266 is connected and working, this has far too many parts to debug.

do you use Arduino Uno WiFi? you did tag the question with it

oh sorry sir..
i only use arduino uno and esp8266

In the loop function you have a line
If (Serial.available() < 1) return;

This prevents further code to be processed if there is nothing in the hardware serial buffer. Think about that.


text:
How will I solve my problem : expected primary-expression before '>' token
// defines pins numbers
const int trigPin = A0;
const int echoPin = A1;
// defines variables
long duration;
int distance;

#include <moving.h>
#include <Servo.h>

Servo servo;

moving car(6, 2, 3, 5, 4, 7, 11, 8, 9, 10, 12, 13); // setting up a new RC car with pins EN1, IN1, IN2, EN2, IN3, IN4, EN3, IN5, IN6, EN4, IN7, IN8

void setup() {
{
  for (int i=2; i<14; i++)
  {
    pinMode(i, OUTPUT);
  }
  servo.attach(10);
  servo.write(90);
}
{
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
Serial.begin(9600); // Starts the serial communication
}
}

void loop() {
  if (distance) > 10; // this is the problem
  car.set_speed(127);
  car.forward();
  delay(3000);
  if (distance) < 10; // and this
  car.set_speed(0);
  car.forward();
  delay(600);
  car.set_speed(127);
  car.right();
  delay(700);
  car.set_speed(127);
  car.forward();
  delay(700);
}

if (distance > 10). What should be in if condition? ; after it is an empty command. I am sure you do not want to have a condition to execute an empty command. https://www.arduino.cc/reference/en/language/structure/control-structure/if/

@Juraj is 100% correct... Presumably car.set_speed() and car.forward() are meant to be executed conditionally? Otherwise, what is the point of the if() statement? Also, is the delay() meant to be part of the conditionally executed code? Or not?

You need curly brackets around your if block.
if (distance > 10) { // this solves the problem
  car.set_speed(127);
  car.forward();
  delay(3000);
}

etc
Edit: Thanks to the commenter.

That is not sufficient.  The entire condition must be enclosed in parentheses if (distance > 10) {

Maybe you could expand upon your answer.  Your answer is a little terse. Which statements need to be contained in the {} block and why..? Also you need to fix your suggestion as per @Craig's comment.

@karlo: The error message refers to line 38, a badly-formed 'if' statement. You probably meant something like "if (distance < 10){ do something; } else { do somethingelse; }", but as written, it is not correct C or C++.


text:
MAX7219 with 8digit 7seg array
I have a concern about the library port handling. I have used direct port direction manipulation successfully in previous projects but there seems to be a problem here.

// This code mostly taken from the example
#include "LedControl.h"

LedControl lc=LedControl(11,13,10,1);
//LedControl lc=LedControl(12,11,10,1); // original
// pin 12 is connected to the DIN pin (now MOSI 11)
// pin 11 is connected to the CLK pin (now SCK 13)
// pin 10 is connected to the CS pin  (now SS 10)
// 1 as we are only using 1 MAX7219

// I am actually using all arduino pins except 12 for my project
#define PD_MSK  B11111100 // Data pins PD2..7 (pins2..7)
#define PB_MSK  B00000011 // Data pins PB0,1 (pins8,9)
#define PC_MSK  B00001111 // Data pins PC0..3 (pins 14..17)

void setup()
{
// set pins 2..9 as inputs
  DDRD = DDRD & !PD_MSK; // this works OK
  DDRB = DDRB & !PB_MSK; // configure ports D,B inputs *** doesnt work with this
 // pinMode(8, INPUT); //*** does work with this
  //pinMode(9, INPUT); //*** does work with this

  DDRC = DDRC | PC_MSK; // configure PortC0..3 as outputs
  PORTC |= 0x0F; // set PortC0..3 high (default)

  // the zero refers to the MAX7219 number, it is zero for 1 chip
  lc.shutdown(0,false);// turn off power saving, enables display
  lc.setIntensity(0,8);// sets brightness (0~15 possible values)
  lc.clearDisplay(0);// clear screen

}
void loop()
{
  //numbers 7 to 0
  for (int a=0; a<8; a++)
  {
    lc.setDigit(0,a,a,false);
  }

  delay(1000);

  //display number 8 on all segments
  for (int a=0; a<8; a++)
  {
    lc.setDigit(0,a,8,false);
  }
  delay(1000);

  // numbers 7 to 0 reverse order
  for (int a=8; a>=0; a--)
  {
    lc.setDigit(0,a,a,false);
    //delay(100);
  }
  delay(1000);

}

The direct port direction setting does not seem to allow the library to work while the pinMode commands doing the same job do. I note that the library uses software SPI but I would like to use hardware if possible. I have certainly used hardware SPI with frequent port direction changes on the remaining pins for other projects.
Any insight as to why this problem occurs?
Thanks.

What is the connection between "the library does not work if I setup ports manually" and "I would like to use hardware SPI"?

Since most libraries come as Open Source, did you peek into its sources? Is this one open? If so, what did your research reveal?

The ! is a logic operator. Bitwise variant is ~

However after the start/restart DDRx are cleared and configured as inputs, so I don't see any point in those &=

What tells "LedControl.h" that you are using hardware SPI vs software SPI?

As always I recommend the old RTFM (read the f***ing manual) of the LedControl.h library.
In the FAQ its clearly stated:

Why don't you use the hardware SPI-Bus of the Arduino?
When I wrote the first version of the library I didn't knew much about
  the Arduino or AVR processors in general and I knew nothing about
  writing code for the hardware SPI-bus on an ATMega. But I knew how the
  SPI protocol works and how I could make this work using simple
  digitalWrite() commands. I turned out the library code is fast enough
  for common use cases, so there is no need for doing Hi-Speed
  communications.
Other strong points in favour of the (admittedly trivial) code design
  are - Use any three free IO-Pins of your board for the hardware -
  Simple to debug. Much easier than managing 3 differnt SPI devices
  connected to the same hardware bus - Library is easily portable to
  other platforms, since it uses only two very basic functions from the
  Arduino language

So with this library you clearly have never used hardware SPI (although you could use the pins, but only via softwareSPI)

Answer #2 pointed out that I had used the wrong operator to set the port direction. (! instead of ~ - bitwise.) My mistake! I want to use hardware SPI in my eventual project (this was just a test) as it can be faster. I used this library to ensure that the external hardware worked -it does now. Using different pins has no benefit in my case so I will probably write my own (hardware) SPI driver. I already have a port direction control system to create a 8bit IO bus for use with other external hardware - if I copy it correctly this time. Thanks to all who took time and found my error.


text:
GPS date and time not displaying correctly in Arduino Uno,NEO6M GPS module
I am learning how the Arduino and GPS module work so I can apply it to another project.
My components are an Arduino Uno, NEO-6M GPS module, and a Adafruit 1.8" TFT display.
The code did not work as expected.  It does display "waiting for sats".
However, it still displays the generic time and date, 1-1-1970 and 12:00:00 AM, for a while until the local time adisplays.
Plus the updated code takes a lot longer to display the time
Here is the code so far.  What I would like it to do is:

Display "waiting for sats"
continue when a successful GPS signal is received
adjust GPS time & date to local
display date and time

Eventually this will be the basis for a Speed and GPS trackker for my RC vehicles.
Any help is greatly appreciated.
#include <SPI.h>
#include <Adafruit_GFX.h>
#include <Adafruit_ST7735.h>
#include <TimeLib.h>

#define cs   10
#define dc   8
#define rst  9

#include <TinyGPS++.h>
#include <SoftwareSerial.h>
Adafruit_ST7735 tft = Adafruit_ST7735(cs, dc, rst);

static const int RXPin = 2, TXPin = 3; //GPS communication

// Change this value to suit your Time Zone
const int UTC_offset = -4;   // Eastern Australia Time is 10

static const uint32_t GPSBaud = 9600;

TinyGPSPlus gps;
SoftwareSerial ss(RXPin, TXPin);

time_t prevDisplay = 0; // Count for when time last displayed

void setup()
{

  Serial.begin(9600);  //set baud rate for serial monitor
     ss.begin(GPSBaud);  //set baud rate for GPS

   tft.initR(INITR_BLACKTAB);     //correct INITR for my display

  tft.fillScreen(ST7735_BLACK);
  tft.setCursor(20, 58);
  tft.setTextSize(1);
  tft.setTextColor(ST7735_GREEN,ST7735_BLACK);
  tft.println("GPS Date & Time");
  tft.print("        Monitor");
  delay(3000);
  tft.fillScreen(ST7735_BLACK);
}

void loop()
{

  tft.setTextSize(1);
  tft.setTextColor(ST7735_GREEN,ST7735_BLACK);

     if (ss.available() < 1)
{
       gps.encode(ss.read());
 }

        GPS_Timezone_Adjust();  // Call Time Adjust Function

}

void GPS_Timezone_Adjust(){
  while (ss.available() > 0) {
    gps.encode(ss.read());
    if (gps.location.isUpdated()) {

      int Year = gps.date.year();
      byte Month = gps.date.month();
      byte Day = gps.date.day();
      byte Hour = gps.time.hour();
      byte Minute = gps.time.minute();
      byte Second = gps.time.second();

//Hour = hourFormat12();
        // Set Time from GPS data string
        setTime(Hour, Minute, Second, Day, Month, Year);
        // Calc current Time Zone time by offset value
        adjustTime(UTC_offset * SECS_PER_HOUR);

    }
  }

  if (timeStatus()!= timeNotSet) {
  if (now() != prevDisplay) {
      prevDisplay = now();
      ClockDisplay();
    }
 }
}

void ClockDisplay(){
    tft.setCursor(5, 8);

    tft.setTextColor(ST7735_GREEN,ST7735_BLACK);
    tft.print("Date:   ");
    tft.setTextColor(ST7735_CYAN,ST7735_BLACK);

      if(month() < 10){
        tft.print("0");
        }
      tft.print(month());

      tft.print("-");

      if(day() < 10){
        tft.print("0");
        }
      tft.print(day());

      tft.print("-");

      tft.print(year());

    tft.setCursor(4, 30);
    tft.setTextColor(ST7735_GREEN,ST7735_BLACK);
    tft.print("Time:   ");
    tft.setTextColor(ST7735_CYAN,ST7735_BLACK);

      if(hourFormat12() < 10){
        tft.print("0");
        }
    tft.print(hourFormat12());
    tft.print(":");

      if(minute() < 10){
        tft.print("0");
        }
    tft.print(minute());
    tft.print(":");

      if(second() < 10){
        tft.print("0");
        }
    tft.print(second());

    if (isAM()) {
    tft.println(" AM ");
    } else {
    tft.println(" PM ");
    }

    tft.setCursor(5,50);
    tft.setTextColor(ST7735_WHITE,ST7735_RED);
    tft.println("RAW GPS DATE & TIME");

    tft.setCursor(5,58);
    tft.print(gps.date.month());
    tft.print("-");
    tft.print(gps.date.day());
    tft.print("-");
    tft.print(gps.date.year());

    tft.setCursor(5,66);
    tft.print(gps.time.hour());
    tft.print(":");
    tft.print(gps.time.minute());
    tft.print(":");
    tft.print(gps.time.second());

  smartDelay(400);
  }
    // deadline for a good recption
      static void smartDelay(unsigned long ms)
  {
  unsigned long start = millis();
  do
  {
    while (ss.available())
      gps.encode(ss.read());
  } while (millis() - start < ms);
}

Display "waiting for sats" ... continue when a successful GPS signal
is received

You are (or the Arduino library you are using is) using the time.h library which starts on January 1st, 1970.  If no adjustments are made, time.h will report January 1st, 1970.
You are not (or the Arduino library you are using is not) waiting for a "good GPS signal" indication from the GPS module before displaying the time.

adjust GPS time & date to local

If you are using time.h you (or the Arduino library you are using) should set a time-zone offset instead of correcting the time by hand.  This will take advantage of the time.h library utilities which take care of troublesome cases like calculating a time & date which crosses midnight with respect to UTC (aka GMT).

display date and time

The time.h library stores the date / time as the number of seconds since January 1st, 1970.  So when displaying the current time, use time.h function calls to convert this counter to the current local time.
Hints / Suggestions:

The GPS module is a radio receiver.  It works best when the view of
the sky is unobstructed by buildings, trees, hills or bad weather.
Such obstructions results in slow lock times or no lock at all.  The
more satellites the GPS module can see the better.
The GPS module is a computer in and of its self.  The computer will
analyze messages form satellites several times before it is ready to
report location and time data.  If possible, leave the GPS module
powered up even if the Arduino is not.  This should likely reduce or
eliminate the delay the GPS module needs before  reporting location
and time.

Added later...
@Tvr4 brings up a good point.  While time.h is more ubiquitous (used almost everywhere in C programming), in the Arduino paradigm, the built in Arduino time library is often used.  For more, this is discussed in this stackoverflow question / answer.  If you want to dive into the Arduino time library, the code is in this github repository.  Also, you should find more help with this time libaray in the readme file displayed on that web page.

timeStatus() is part of the TimeLib
Here is the page on the library
https://playground.arduino.cc/Code/Time/

...thanks.  Added additional text to the answer according to you suggestion.

I'm guessing that the GPS module doesn't receive a time reading until it acquires a GPS lock. That can take many seconds.
You haven't posted your code so we can't tell how you're handling the time reading.
I would suggest checking for the midnight 1970 time (which is the UNIX "epoch time") and handling that with special-case code. If you're reading the time as a numeric value it is almost certainly 0.

I am wondering if the problem is with this part of the code
if (timeStatus()!= timeNotSet)
{
if (now() != prevDisplay)
{
prevDisplay = now();
ClockDisplay();
}
}

what library defines the function timeStatus()? You need to tell us what libraries/frameworks you are using.


text:
Creating a sine with PWM Arduino DUE
I've been trying to create a sine wave using the pwm function of the Arduino DUE.
The sine wave has te be at higher rates than the analogWrite() function can handle, so I've been using the native capabilties of the SAM3X8E.
To test it, instead of creating sinus I've been doing it linear. The code to do that is:

  REG_PWM_ENA = REG_PWM_SR | B11111111; //enable output
  REG_PWM_CMR3 = 0x00000; //deadtime 0
  REG_PWM_CPRD3 = value;
  REG_PWM_CMR2 = 0x00000; //deadtime 0
  REG_PWM_CPRD2 = value;
  int i =0 ;
  waittime = 100;
  value = 30

  while (!Serial.available()) {
    REG_PWM_OS = 0x0000C;

for (i = 0; i < value; i++) {
      pwmc_duty(i);
      pwmc_duty4(i);
      wait(waittime);
    }

for (i = value; i > 0; i--) {
  pwmc_duty(i);
  pwmc_duty4(i);
  wait(waittime);
}
REG_PWM_OS = 0xC000C;
wait(1);
pwmc_duty(value);
pwmc_duty4(value);
REG_PWM_OS = 0xC0000;

for (i = value; i > 0; i--) {
  pwmc_duty(i);
  pwmc_duty4(i);
  wait(waittime);
}

for (i = 0; i < value; i++) {
  pwmc_duty(i);
  pwmc_duty4(i);
  wait(waittime);
}

REG_PWM_OS = 0xC000C;
wait(1);
pwmc_duty(0);
pwmc_duty4(0);
}

inline void pwmc_duty(unsigned short duty0) {
   // REG_PWM_CPRD3 = duty0;
    REG_PWM_CDTY3 = duty0;
}
inline void pwmc_duty4(unsigned short duty0) {
   // REG_PWM_CPRD3 = duty0;
    REG_PWM_CDTY2 = duty0;
}

void wait(int times){
  for (int i =0;  i < times; i++){
    __asm__("nop\n\t");
  }
}

I expect the code to gradually increase the duty cycle of the signal and than slowly decrease. And that works!
The problem is that i do not get a normal PWM signal out of it.
I've attached one of the previous test signals to this post, with a bit different code, to show the problem.

i've expected the pwm more clear like demonstrated in this paint picture:

How do I get from these spikes to a more normal block signal?

"I expect the code to gradually increase the duty cycle of the signal and than slowly decrease. And that works! The problem is that i do not get a normal PWM signal out of it." - what exactly doesn't work?! Or, how do you know that incrementing the duty cycle works?

Maybe its just an aliasing problem, can you configure a lower pwm frequency?

@SimSon I saw on the scope that the pwm increased and decreased as expected. The picture is not really showing it, but it does show the problem.
It could indeed be an aliasing problem, but I have tried slowing it down and it was without a different result.

Or play with the scope settings. Zooming into a signal that strong probably won't work... also, I still don't understand: if you see the pwm increase and decrease, what is "the problem" then?!

why you don't use the DAC of DUE?

By "create a sinus" I assume you mean that you want to generate a sine wave?

The scope works with 12.5 kS/sec so according to Pete (ahh no) according to Nyquist you can measure signals up to 6.25kHz (sinus wave). That's a theoretical limit, the scope must also be capable of reconstructing the original wave.  As you have a rectangle PWM wave, there are much higher frequencies in the signal than the PWM frequency. So I would say, you have aliasing problems. Can you configure the oscilloscope to a higher sampling rate? e.g 500 kHz?  It is also possible that your PWM Frequency is too low for the sinus wave you want to modulate on it.

As @Juraj mentions - the DUE has a real 12-bit DAC built in. Use that to create an actual analog waveform rather than trying to emulate one with PWM.

@DuncanC I meant sine wave, yes.


text:
How to post HTTP POST requests on my website?
I am working on a NodeMCU board to post sensor data on my website service. Basically my project is about POST and GET requests both in single code.
I am succeeding in sending GET requests from my website. However, I just can't post data to my website.
To post I have 2 different links (asp services): one will post data and another will be used to get data same as transmitted by first link.
Here is my code, and also how to post 2 variables in http post request?
#include (ESP8266WiFi.h)
#include (ESP8266HTTPClient.h)

const char* ssid = "oppo";
const char* password = "11111111";
int giSwitchNum = 1, buttonPin = 2;

void setup () {
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  pinMode(D1, OUTPUT);
  pinMode(D2, INPUT);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print("Connecting..");
  }
  giSwitchNum = 1;
  Serial.print("Connect");
}

void loop() {
  if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status
    HTTPClient Post;
    Post.begin("http://lemontechnologies.net/Services/Service.svc/SetData");
    Post.addHeader("operator", "text/plain");
    Post.POST("Key=hi&val=jagrut1");
    String payload = Post.getString();
    Post.end();
  }
  delay(500);
}

remove the 'operator' header and add a "Content-Type" header with value "application/x-www-form-urlencoded"

void wifi_connect(){
  WiFi.mode(WIFI_OFF);        //Prevents reconnection issue (taking too long to connect)
  delay(1000);
  WiFi.mode(WIFI_STA);        //This line hides the viewing of ESP as wifi hotspot
  //WIFI_STA It's very important !!!!

  WiFi.begin(ssid, password);     //Connect to your WiFi router
  while(WiFi.status() != WL_CONNECTED){
    delay(1000);
    Serial.print(".");
  }

  Serial.println("Wifi connected");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  return;
}

I think you may try "WiFi.mode(WIFI.STA)"


text:
Communicating between two Arduinos wirelessly only works when both are connected to the same computer
The transmitter is an Arduino Mega 2560 (China) that is connected to a computer over Serial, from which it only reads data and sends it using a SYN115 433mhz transmitter.
The receiver is an Arduino Nano (China) that drives an 8x8 * 5 led matrix and it reads data using a SYN480R 433mhz receiver.
Everything works as it should, when both devices are connected to my computer over USB.
If I unplug the receiver, the transmitter now stops responding to Serial data and I have to upload a sketch to make it work again, no resetting or power cycling works. But even after "fixing" the transmitter, if the receiver is not to connected to my computer but an external USB power supply (2A) it never receives any data.
I can then plug the receiver back into the computer and things work again.
Also, if I unplug the transmitter while the receiver is still plugged into the computer, the receiver crashes and resets itself.
Obviously there's some power issue when unplugging USB devices causing feedback, but the real issue is the wireless stops working on external power supply.
Both devices are running, it's easy to confirm since the receiver has some scrolling text, and the transmitter blinks an LED when it receives and sends data.
I read at Serial communication not working between two Arduinos unless connected to computer that both systems need to share ground if connected by wires. Could this affect the wireless signal somehow?
UPDATE: Connecting the receiver to a second computer works! (thanks Chris!! I know it was simple, but one can get stuck in one's own thought process ;))
So this is probably power related... Or can the Nano I have require more than just power over USB? I don't touch the serial device on the receiver side at all btw, all it does is read from PIN 2 and pushes data over HW-SPI to the LED matrix.
UPDATE-2: Added reciever code as suggested, though I doubt it's the problem here as it's very simple.
#include <MD_MAX72xx.h>
#include <RadioHead.h>
#include <RH_ASK.h>

#define RADIO_RX 2
#define RADIO_TX 3 // not used in this scetch but still needed by RH_ASK
#define RADIO_EN 4 // -||-

RH_ASK radio( 1200, RADIO_RX, RADIO_TX, RADIO_EN, true);
MD_MAX72XX mx( SS, 5);

void setup() {
  radio.init();
  mx.begin();
  mx.control(MD_MAX72XX::INTENSITY, 0);
  mx.control(MD_MAX72XX::TEST, 0);
  mx.clear();
}

uint8_t sc_text[128] = "-- No Data --     ";
uint8_t sc_pos;
uint8_t sc_charWidth;
uint8_t sc_charPos;
uint8_t sc_buf[8];

int scrollText() {
  mx.update(MD_MAX72XX::OFF);
  if(sc_text[sc_pos] == '\0') {
    sc_pos = 0;
    return 1;
  }
  if(sc_charPos == 0) sc_charWidth = mx.getChar(sc_text[sc_pos++], sizeof(sc_buf)/sizeof(sc_buf[0]), sc_buf);
  if( sc_charPos < sc_charWidth + 1) {
    mx.transform(MD_MAX72XX::TSL);
    if(sc_charPos < sc_charWidth) mx.setColumn(0, sc_buf[sc_charPos++]);
    else sc_charPos = 0;
  }
  mx.update(MD_MAX72XX::ON);
  delay(100);
  return 0;
}

char desc[64];
int temp1, temp2;
int wind1, wind2;

uint8_t radio_preamble[] = { 0x7d, 0x6f, 0xe4, 0x26, 0xb5 };

struct wttr_packet {
  uint8_t preamble[sizeof(radio_preamble)];
  int8_t temp1, temp2;
  uint8_t wind1, wind2;
  uint8_t desclen;
  char desc[32];
};

bool get_wttr_data() {
  struct wttr_packet packet;
  uint8_t len = sizeof(packet);
  int hasdata = radio.recv( (uint8_t*)&packet, &len);
  if(hasdata && len == sizeof(packet)) {
    if(memcmp( packet.preamble, radio_preamble, sizeof(radio_preamble))) return false
    temp1 = packet.temp1;
    temp2 = packet.temp2;
    wind1 = packet.wind1;
    wind2 = packet.wind2;
    memcpy( desc, packet.desc, packet.desclen);
    desc[packet.desclen] = '\0';
    return true;
  }
  return false;
}

bool hasnewdata = false;

void loop() {
  if(get_wttr_data()) hasnewdata = true;
  if(scrollText() && hasnewdata) {
    if(temp1 == temp2 && wind1 == wind2) sprintf( sc_text, "%s     %d %cC     %d km/h      ", desc, temp1, 0xF7, wind1); // 0xF7 == '°'
    else if(temp1 != temp2) sprintf( sc_text, "%s     %d/%d %cC     %d km/h      ", desc, temp1, temp2, 0xF7, wind1); // 0xF7 == '°'
    else if(wind1 != wind2) sprintf( sc_text, "%s     %d %cC     %d/%d km/h      ", desc, temp1, 0xF7, wind1, wind2); // 0xF7 == '°'
    else sprintf( sc_text, "%s     %d/%d %cC     %d/%d km/h      ", desc, temp1, temp2, 0xF7, wind1, wind2); // 0xF7 == '°'
    hasnewdata = false;
  }
}

UPDATE-3: Turns out this wasn't a power issue after all. I had forgotten about a voltage divider I put on the board for using it as a transmitter! The radio module has 3.3V TTL so this is needed for the transmitter but NOT the receiver!
Why this made it work plugged in to USB and not any other power brick I have no idea.

Can you try them on two different computers?  It's vaguely possible that some fault trigger by unplugging a device is forcing a re-start of the whole USB bus.  And it's also possible that a random power adapter may be too noisy to use for a radio receiver.

you use 5V power adapters connected to barel jack?

Its a 2A USB power adapter, cheap :p though not from china, i think.    About a second PC,  il have to do that when i get home, though it will be an old eee901 netbook, for proximity, those radio modules aren't exactly great ;)

Yep, powering the receiver from another computer works!   Ive tried 3 different USB power adapters now, none of them is able to handle wireless.  Even the charger for my brand new Huawei P10 with super charging doesnt work.

Perhaps there's something about your sketch that requires a computer.  You should probably include the receive code with an edit to your question.

Glad you solved your problem, though that solution is a little weird.  On Stack Exchange sites, if you solve your own problem, rather than editing it into the question, you should post an answer. Then come back in a few days when the self-answer timer has expired and accept it; this is the only way the system will consider your question to be resolved, otherwise it will keep getting churned back up for years.

It is weird indeed, all i did was bypass the divider and it works every time :)   I was also wondering about how stackexchange handles that.. so i will do just that. thanks :)

Turns out I forgot I had put a voltage divider on the data-line from the receiver since I originally build the board for transmission.
This in turn, somehow, caused the signal from the radio receiver to fall short of the TTL signals when powered by anything other than USB.
I bypassed the divider and everything works as it should again :)


text:
Getting an error while uploading code to Arduino when ESP8266 is attached
I am trying to use an ESP8266 and an Arduino to access the Arduino from the network. I tried to do something but I'm facing some challenges. I hope I am using the correct board "Generic ESP8266 Module".

#include <SoftwareSerial.h>

const byte rxPin = 2; // Wire this to Tx Pin of ESP8266
const byte txPin = 3; // Wire this to Rx Pin of ESP8266

// We'll use a software serial interface to connect to ESP8266
SoftwareSerial esp8266(rxPin,txPin);

void setup() {
  Serial.begin(9600);
  esp8266.begin(9600);
  delay(1000);
}

void loop() {
  Serial.println("Sending an AT commands");
  esp8266.println("AT");
  delay(30);
  while(esp8266.available()) {
    String data = esp8266.readStringUntil('\n');
    Serial.println("Got response from esp8266: " + data);
  }
}

Error
Archiving built core (caching) in: C:\Users\XYZ~1\AppData\Local\Temp\arduino_cache_322251\core\core_esp8266_esp8266_generic_CpuFrequency_80,FlashFreq_40,FlashMode_dio,UploadSpeed_115200,FlashSize_512K64,ResetMethod_ck,Debug_Disabled,DebugLevel_None_____feb0d75f3cf4e05271af4f91549cd009.a
Sketch uses 226657 bytes (52%) of program storage space. Maximum is 434160 bytes.
Global variables use 32464 bytes (39%) of dynamic memory, leaving 49456 bytes for local variables. Maximum is 81920 bytes.
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed

Select the Arduino/Genuino Uno in the Arduino IDE Board menu and try again. You are simply using the wrong configuration.

First off you have the wrong board selected. It's the Arduino Uno that you are programming, not the ESP8266. Just because you have connected an ESP8266 to the Arduino doesnt't magically change what the Uno is.
Secondly you cannot have anything connected to pins 0 and 1 of the Arduino while programming. Those pins are used for communication with the PC. As a general rule it is best to never use ghem for anything.
To communicate between the Arduino and the ESP8266 you should either pick two other pins and use SoftwareSerial or invest in a board that has at least one independent UART (such as the Mega2560 or the Leonardo).

I changed Board to Arduino Uno and using pins 2 and 3 of the Arduino https://i.sstatic.net/PK7K9.jpg . I am unable to upload https://pastebin.com/AyUWvDxf

@Williams You have the right port selected in the IDE?

It is COM3(Arduino/Genuino Uno and I updated question

Try pressing the reset button on the Arduino just as the upload is starting.

I tried, but didn't work :(

When you press RESET does the LED on the Arduino blink 3 times very rapidly?

Let us continue this discussion in chat.

Uploading programs to the Arduino requires the RX and TX lines. The ESP8266 module is probably interfering. You will need to disconnect the ESP8266 module, or at least, don't power the module while uploading.
Connecting the ESP8266 to RX/TX pins will probably also prevent you from using the serial terminal to output debugging information.
An alternative would be to use the (not so great, but it works) SoftwareSerial library.

I am using pins 2 and 3 of the Arduino Uno https://i.sstatic.net/PK7K9.jpg and if you see snippet of code in question, there you will find I am using SoftwareSerial

I believe you are trying to directly program the ESP8266 and you're simply using the Arduino Uno as a USB to serial interface for your computer. There are many tutorials on the web on how to do this. First thing I see wrong with your setup is you've left the Arduino Uno MCU attached to the board. The first thing you'll want to do is remove this chip carefully (the pins can bend easily so apply force evenly). Right now when the Arduino IDE tries to talk to the ESP8266 the communication is going to both the ESP8266 and the Arduino. Physically removing the Arduino MCU chip will ensure any communication is directly with the ESP8266.
Also make sure you are connecting the correct voltage. ESP8266 can only handle 3.3V max, while the Arduino runs at 5V mostly. I believe the Uno board provides a 3.3V output but I'm not 100% sure.


text:
How do I know the IP address assigned to an ESP8266?
I have programmed an ESP8266 using the circuit and program below. I tried to open the SerialMonitor once the program is uploaded to the ESP8266. I am getting an error when I am trying to open the SerialMonitor.

Error opening serial port 'COM5'. (Incorrect serial port)

What is the way to get the IP address assigned to the ESP8266?
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>

//SSID and Password of your wifi router
const char* ssid = "Moto";
const char* password = "reset1234";

ESP8266WebServer server(80);

void setup() {
  Serial.begin(9600);
  WiFi.begin(ssid, password); //Connect to your WiFi router
  Serial.println("");
  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  //If connection successful show IP address in serial monitor
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());  //IP address assigned to your ESP
  server.begin(); //Start server
  Serial.println("HTTP server started");
}

void loop() {
  server.handleClient(); //Handle client requests
}

you can't run the wifi off the 3.3v of most ftdi adapters; when it's idle in the "ready to flash" mode, it uses less power and works just fine. power the ESP from an external source and your serial port should work again.

if you have GPIO permanently wired to GND, as your diagram implies, then your "sketch" will never be executed on the ESP

@dandavis do you mean that should I plug VCC and CH_PD of ESP8266 to other power source instead of FTDI ? I have 2XAA cell holder https://s3-ap-southeast-1.amazonaws.com/a2.datacaciques.com/wm/307176851/3849027817/859640786.JPG and what voltage cell should I use here ?

@JaromandaX Alright, I will remove it so should we only GND to GND other than no wire to GND in any circuit ?

you are supposed to give the 01 3.3v. Two fresh AAs will probably be enough to get it working, but won't last the full battery charge. This is why ESP8266 devboards are popular. i keep a few of these around, but you can use an AMS1117@3.3v and feed it the raw 5v to save cash...

@dandavis "you are supposed to give the 01 3.3v." - Do you mean I should keep connected VCC and CH_PD  to 3.3 of FTDI and GPIO1 of ESP8266 with other power source ?

no, don't use the 3.3v of the ftdi at all. run the batteries to vcc+chpd+gnd, and the ftdi to rx+tx+gnd

@dandavis Ah Well, Gotcha :) I will try it

i edited that in; forgot becuase i always solder a wire between vcc on chpd on my 01's when i unwrap them

@dandavis can you suggest what battery should I use in 2XAA cell holder https://s3-ap-southeast-1.amazonaws.com/a2.datacaciques.com/wm/307176851/3849027817/859640786.JPG what voltage it should be to avoid esp8266 burn ?

you won't burn out an 01 easily: they have internal protection; don't ask how i know ;). two plain fresh alkaline AAs should give about 3.2v; the ESP-01 works from ~2.8-3.7...

@dandavis Alright! I will buy cells today in evening, will try it. :)

@dandavis Do you think Serial Monitor is not opening because of insufficient power to ESP8266 ? I am getting this error on opening SerialMonitor Error opening serial port 'COM5'. (Incorrect serial port)

If you give your board a name with
WiFi.hostname("MyESP8266");

(for example) you can then look on your router in the section that lists DHCP assignments (on my Netgear it's Attached Devices). That should then show you the IP address of all the attached devices, including the ESP8266 which you will easily identify by its name.
Another option is to use mDNS. Look at some of the examples that come with the ESP8266 core and libraries to see how.

I used the app "Fing" on my phone. It shows you the devices that are connected to your WiFi. After entering all freacking IP adress aviable, found that the last one was the one of my esp8266 and a beautiful window saying "hello from esp8266!" appeared.

I like that app :-) Small thing is that it doesn't work when you put your esp in deep sleep like I did ;-)


text:
Sparkfun OpenLog both lights flashing
I'm building a simple RS232 data logger with the Sparkfun OpenLog and a SEEED RS232-TTL adaptor. I'm powering it with a 9 volt battery and a 7805 voltage regulator.
It's dead simple. I built it on a breadboard first and determined that TX-TX and RX-RX connections are called for. I logged several files on the breadboard then soldered it all up. Now it's not working, sigh.
When I power it up  both lights will flash rapidly for about a second and then it settles down to a steady on-off with both lights.
If I delete the config file a new one is created, which shows that it recognizes the card at least.
I've triple checked my wiring and confirmed I have no shorts, and that the voltage is good.
I'm attaching a photo as built. Hopefully it's obvious what's what. The purple trace is ground.

It can be so many things. Be careful when one wire is on the top of another wire, when you solder them the plastic could melt and they could connect. A 7805 without capacitors is an oscillator. You need 100nF at the input and output at least. The Sparkfun OpenLog is a ATmega328P running at 3.3V at 16MHz. That is not okay. It will work in most cases, but it is not okay according to the datasheet. And last but not least: something could be broken.

Sorry Jot, I don't understand, what part is "not ok"? I've added caps to the 7805 and quaduple checked there are no shorts. Still no improvement.

The problem with the circuit was a bad rs232-ttl converter. Not sure how that messed up the openlog, but replacing it fixed the problem.
In the photo above, D1 on the converter is an led which should be normally on.

If the OpenLog's RX pin is held low for too long at startup, it'll reset to 9600 baud to attempt to recover. A bad rs232-ttl converter could cause this, if the RX pin was being held low. If you need the OpenLog to ignore this, see the ignoreRX parameter in config.txt and the hookup guide.