text:
ESP8266 not connecting to WiFi
I am trying to send the temperatures from an DS18B20 to ThingSpeak, using an ESP8266. You can see the code I am using for that.
When I run the code I do not get any errors. In serial monitor it just shows that it is not connected to WiFi. If I change the WiFi name in code to something not even existing I still do not get any errors. I do not think that the ESP even finds the WiFi.
I think that the only problem to get everything work is just to get the WiFi connection to work properly. I have also checked the ESP with another simple code just to check that it is not broken and it actually get the code from my computer.
Here is the code I am using. (I have removed my password etc... )
//nodeMCU v1.0 (black) with Arduino IDE
//stream temperature data DS18B20 with 1wire on ESP8266 ESP12-E (nodeMCU v1.0)
//shin-ajaran.blogspot.com
//nodemcu pinout https://github.com/esp8266/Arduino/issues/584
#include <ESP8266WiFi.h>
#include <DallasTemperature.h>
#include <OneWire.h>

//Def
#define myPeriodic 15 //in sec | Thingspeak pub is 15sec
#define ONE_WIRE_BUS D4  // DS18B20 on arduino pin2 corresponds to D4 on physical board
//#define mySSR 0  // Solid State Relay on pin 0

OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature DS18B20(&oneWire);
float prevTemp = 0;
const char* server = "api.thingspeak.com";
String apiKey ="******";
const char* MY_SSID = "******";
const char* MY_PWD = "******";
int sent = 0;

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

void loop() {
    float temp;
    //char buffer[10];
    //DS18B20.requestTemperatures();
    //temp = DS18B20.getTempCByIndex(0);
    temp=1111;
    //String tempC = dtostrf(temp, 4, 1, buffer);//handled in sendTemp()
    Serial.print(String(sent)+" Temperature: ");
    Serial.println(temp);

    //if (temp != prevTemp)
    //{
    //  sendTeperatureTS(temp);
    //  prevTemp = temp;
    //}

    sendTeperatureTS(temp);
    int count = myPeriodic;
    while(count--)
    delay(1000);
}

void connectWifi()
{
    Serial.print("Connecting to "+*MY_SSID);
    WiFi.begin(MY_SSID, MY_PWD);
    while (WiFi.status() != WL_CONNECTED) {
        delay(1000);
        Serial.print(".");
    }

    Serial.println("");
    Serial.println("Connected");
    Serial.println("");
}//end connect

void sendTeperatureTS(float temp)
{
    WiFiClient client;

    if (client.connect(server, 80)) { // use ip 184.106.153.149 or api.thingspeak.com
        Serial.println("WiFi Client connected ");

        String postStr = apiKey;
        postStr += "&field1=";
        postStr += String(temp);
        postStr += "\r\n\r\n";

        client.print("POST /update HTTP/1.1\n");
        client.print("Host: api.thingspeak.com\n");
        client.print("Connection: close\n");
        client.print("X-THINGSPEAKAPIKEY: " + apiKey + "\n");
        client.print("Content-Type: application/x-www-form-urlencoded\n");
        client.print("Content-Length: ");
        client.print(postStr.length());
        client.print("\n\n");
        client.print(postStr);
        delay(1000);

    }//end if
    sent++;
    client.stop();
}//end send

it prints a dot every second in Serial Monitor? how is the esp8266 powered? can the power source 300 mA?

You should upload the "WiFiScan.ino" example sketch to verify what WiFi stations (and with what signal strength) your ESP can see, if you think you cannot connect to your network.

yes it just shows the dot all the time. The ESP is right now connected to my computer by a micro USB-cable so no external power source if that is what you mean ? I just run the scaning and yes it finds the wifi witch I am trying to connect to.

For me i just changed the AP Band to 2.4Ghz from 5.0Ghz and it's working now

I have the same problem and I was struggled many days.
The solution for my issue was because SSID is case sensitive and I was trying to type all small letter.

Maybe you have a space in your WIFI SSID so you should check this in your router. Also maybe your WIFI is on 5Ghz and the ESP can't see it because it is only for 2.4 Ghz. Also if your WIFI AP is on a channel from 13 - 14 it also couldn't be seen by the ESP. And to test your ESP you can run the scan example and if it works you should try the web server example to connect to your network. If that all will work ok than the problem is in your code.

I had the same problem, when i tried to connect to my home wifi i got stuck with just printing dots and never could connected. First of all i though that my ssid or password had a typo, but it hadn't. Then i changed the nodemcu and the problem persisted. But when i tried to connect to other wifi it worked. So the problem was in my modem/router.So i changed my modem/router configuration to:
Operation mode: 802.11g+n to Automatic
Channel: 11 to Automatic
Channel Bandwich: 20 to Automatic
then the problem was solved.

This worked for me too, thanks for sharing.

In order to connect to Wifi from ESP32 and other boards, the WiFi connection needs to be 2.4GHz, wireless mode must be legacy. It cannot be set to Auto or N only. Go to your router box web page, and change this setting under Advanced Settings > Wireless.
The only code required to connect is.
void setup() {
  ...
  WiFi.begin(MY_SSID, MY_PWD);
}

void loop() {
  while (WiFi.status() != WL_CONNECTED) {
     delay(1000);
     Serial.print(".");
  }
  ...
}

In my experience a NodeMCU / ESP32 works perfectly fine with “N-only” Wifi networks.

Try to add WiFi.hostname("ESP-host"); before  WiFi.begin(ssid, password); - it works in my case.


text:
Arduino USB and 9V
I'm working on a project for interfacing the Arduino with the Raspberry Pi. I need to be able to exchange serial data between the two using the USB port.
My question is, can I do that while having the Arduino powered, by using a 9 V battery connected to the DC pin and at the same time have serial data connection using the USB port?

Why bother? If you are going to use the USB why not just run the Arduino from the Pi power?

@Milliways I'm using the arduino to power many sensors and relays and don't want to damage the pi.

Then you shouldn't use an everyday 9v battery either, as they are not intended for high currents and will quickly die when used in that way.  When the battery dies, you'll be drawing power from the pi.  Likely what you should do is run the Arduino from the pi, but give your sensors and relays their own suitable power supply with common ground to the Arduino/Pi.

@ChrisStratton you are right because when it drops below 6.6v the arduino will use the usb connection for power and ar high currents that might damage the pi.

@ChrisStratton i think im going to use a 12v source to power the arduino not a 9v battery. Thank you

A 12v source is a bad idea and will cause excessive heating at high currents.  Don't power your loads from the Arduino, power them directly.

source: Stack Exchange

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

sort: votes


text:
Serial.read(): Value changes to ASCII when I input from Serial Monitor
I was having some problems on a project, so to test my Arduino, I wrote the following program to check things. When I start the serial monitor, the value of i is 1, but after I start sending numbers, they change into ASCII. Why?
int i = 1;
void setup(){
  Serial.begin(9600);
}
void loop(){
  Serial.println(i);
  if(Serial.available()){
    i = Serial.read();
  }
}

When you send the character 1, Serial.read() returns the integer 49.
Serial.println(i) then sends the characters 4, 9, carriage return and a newline.
If you want to get back the same characters that you sent, change the type of i to char.

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


text:
nRF24l01+ Outputting Garbage Values
I just purchased a set of 10 nRF24l01+ modules with a breakout board that looks like this:

Note: This is the nRF24l01+ chip, not a clone Si24Ri. Also, I'm using an Arduino Mega.
I'm following the Sparkfun tutorial here:
https://learn.sparkfun.com/tutorials/nrf24l01-transceiver-hookup-guide
The wires are hooked up like so:

3.3V → VCC
GND → GND
PWM 8 → IRQ
PWM 9 → CE
PWM 10 → CSN
PWM 11 → MOSI
PWM 12 → MISO
PWM 13 → SCK

I've verified the two modules are hooked up as they should be. I'm using the GettingStarted example program for both units. Whenever I go into the serial monitor when connected to the transmitter, I get garbage values like <¯�SžRÖ being output. Whenever I try to transmit a message by entering t, nothing gets returned. The same problem is happening on the receiver end.
As for troubleshooting:

I've wiggled all of the jumper cables to verify a stable connection.
I've swapped out the modules I was using with others from the package (twice) so the modules probably aren't bad.
After reading that a capacitor is sometimes needed to provide a smoother voltage to the module, I upped the voltage from the 3.3V the Arduino was providing to a stable 3.5V from an external variable power supply to account for any small voltage dips. I don't have any capacitors available to me at the moment, so I figured this would be the next best option.

Unfortunately, my RF modules are still not correctly transmitting any data, and I don't know where to go from here.

Check the SPI pins. They are different on a Mega.

See http://blog.brunodemartino.com.ar/wp-content/uploads/2013/11/connections.png

No luck - garbage values are still being output even after changing the wire configuration. I don't see anything in the example sketch I would need to change either.

Ah, wait! Nevermind, it did work. I just needed to make sure I was on 115200 baud rate in my serial monitor.

Check these things first:

Is your power supply give a constant 3.3V and a minimum of 0.5A(500mA)?
Does your code work for others?
Are you on the right serial baud rate?
Is the path from the radio to the Arduino as short as possible?
Are your MISO and MOSI wires twined into each other?

If none of these things help then, please tell me what library you are using. I had a lot of issues with the RF24 library so maybe try using the NRFLite library.

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


text:
Arduino Yun Analog Read Problem
I am having some major issues with my Arduino Yun.
When attempting to read a value from the analog pins, the Yun is giving me incorrect constant values.
I have attached everything to a common ground, and I am supplying 3.3 volts to the A0 pin on the Yun.
The weird thing is, the pins all give constant values in ascending order, no matter what is connected to them, or if nothing is connected at all.

A0 - 18
A1 - 19
A2 - 20
A3 - 21
A4 - 22
A5 - 23

The code I am running is a very simple script.
float i;

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

void loop() {
  i = A0;
  Serial.println(i);
  delay(1000);
}

You are not reading from any analog pins. You are just printing out the digital pin number of the analog pin.
Look at some basic examples on how to read analog values.
/*
  AnalogReadSerial
  Reads an analog input on pin 0, prints the result to the serial monitor.
  Graphical representation is available using serial plotter (Tools > Serial Plotter menu)
  Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground.

  This example code is in the public domain.
*/

// the setup routine runs once when you press reset:
void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop() {
  // read the input on analog pin 0:
  int sensorValue = analogRead(A0);
  // print out the value you read:
  Serial.println(sensorValue);
  delay(1);        // delay in between reads for stability
}

oh my goodness, wow I feel like an idiot;
I had it set up with "analogRead" at first but I must have removed my code without noticing it. At first, I was reading analog values just fine, then this happened out of no where
Anyhow, thank you!

authors: Алексей Маврин


text:
Keep 5V on while sleep with LowPower library
Is it possible to keep the 5V on, while putting the Arduino (ATMEGA328P) in sleep more, using LowPower library?
I'm trying to use this HAT:
https://spellfoundry.com/product/sleepy-pi-2-usb-c/
to control the power of my Raspberry Pi. But on top of it, I want to have a second HAT that I want to feed 5V input, event after I shut down Raspberry Pi and put the Arduino to sleep.

The 5V of an Arduino is always on. It's power, not a controllable pin. Or are you on about some functionality of this Pi hat that you link to (to a site which is completely meaningless TBH...)

If I read the schematics at https://spellfoundry.com/download/sleepy-pi-2-usb-c-schematic/ correctly, you need to draw continuous 5V power from the SUPPLY_5V pin instead of the SUPPLY_EXP_5V pin (the latter seems to be switched via some MOSFETs connected to pin 2 of the ATMEGA328p). Which means that you need to connect the 5V power of your second HAT to JP4 pin 3 on the Sleepy Pi HAT (instead of JP5 pin 3).

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


text:
Issue with incrementing PWM over time
First post here. So I have an issue, which I have identified, but I'm not quite sure how to fix it.
I'd really appreciate some input and suggestions.
I realize that my "pwmDelta" is the problem, but I am not sure what to do to fix it.
I am trying to write a program that will increment the value of the pin 3 a set amount of time, in a somewhat linear fashion, starting at my low point, and finishing at my high point.
The issue is that my equation is incorrect and I can't output a partial bit value. Huge oversight on my part. If you read the data from the serial monitor with the code written as I have it, you'll see that it isn't coming even close to reaching my max value.
I need suggestions on how I can have the program figure out the delta in a way that I can send an integer value to the PWM output pin, yet still keep a somewhat linear increase over time. Would this even be possible?
int motor1 = 3;         //pin for PWM output to motor
float t = 0;            //Variable to keep Track of time
int tLim = 30;          //Time Limit for Ramp
float lowLim = 21;      //Low Limit, in Duty Cycle %
float highLim = 65;     //High Limit, in Duty Cycle %
float motorPWM = 53.55; //Starting Value of PWM, in Bits
float pwmDelta = ((255/100)*(highLim-lowLim))/(tLim); //Delta equation, to calculate how much to change PWM value each time it is incremented
float motorDelta;       //Variable to write value to Motor Output

void setup() {
  pinMode(motor1, OUTPUT);
  analogWrite(motor1, 53.55); //run motor at initial value for 20 seconds before beginnning ramp
  delay(20000);
  Serial.begin(9600);
}

void loop() {
  motorDelta = motorPWM + pwmDelta; //incrementing output value based on Delta Equation
  motorPWM = motorDelta; //Setting new incremented value equal to old value, so incrementing can continue

  if (t <= tLim) {  //Check if time is <= time limit
    analogWrite(motor1, (motorDelta)); //write incremented value to output pin
    delay(1000);  //wait 1 second, increment t, to keep track of time
    t++;
  }
  else {
    analogWrite(motor1, motorPWM = 165.75); //set pin to high value for 60 seconds, then set to 0
    delay(60000);
    analogWrite(motor1, motorPWM = 0);
  }
  Serial.print(motorDelta);
  Serial.println();
  Serial.print(t);
  Serial.println();
}

think about this .... what other parameter can you vary?

@jsotola The 255/100 needs to be constant, as that gives me 2.55 bits per 1 Duty Cycle percent. Any of the other parameters in the pwmDelta can be varied, and it's designed to be as such. So when it's finished a user can input the Low/High Limit in Duty Cycle % and time, and the output will increase in a linear fashion over that time period. If you mean other parameters outside of that equation, I guess I am not following.

float pwmDelta=((255/100)*(highLim-lowLim))/(tLim);

That line should be:
float pwmDelta=((255.0/100)*(highLim-lowLim))/(tLim);

Adding the .0 tells the compiler to do that math using floats and you get 2.55.  Without it the math is done with int and the result is 1 which isn't what you want.
analogWrite(motor1, 53.55);

Just write 54.  analogWrite only accepts integer values.
analogWrite(motor1, motorPWM=165.75);

You should really do that as two lines, an assgnment and then an analogWrite.  This way leads to confusing code.  Also, analogWrite only accepts integer values so your decimals are useless there as well.

analogWrite(motor1, 53.55) outputs 53: float to int conversions do not round, they just truncate the fractional part.

You're right.   But I figured 54 would be closer to what he actually wanted because I rounded.  I was suggesting that he use 54 not that analogRead would treat his float as 54.

You are trying to smoothly ramp up the PWM value from 21% to 65% over a period of 30 seconds at 1 second intervals, which does not work very well because the PWM value has to be a byte.
That means that the value written into the PWM register changes from  21*255/100  to 65*255/100, which is 53.55 to 165.75.
Use values of 53 and 166, which gives a difference of 113.
Your code is written to update the PWM value every 1000 ms, which produces 30 steps, most of which are not integers.
Instead, ramp up the PWM value in 113 steps. Each step will be an integer and each step will be 265486 μs in length.

The previous responses already showed the main issue with the program.
Here I am providing a few suggestions that hopefully could still improve
it:

Instead of using delay(), you could manage the time with
millis(). This will make the ramp smoother, and you will be able to
add code to the loop if needed that will not be blocked by the
delays.
Storing the times in milliseconds and the PWM value in its natural
unit (rather than percent) makes the code simpler.
Remove redundant variables, such as motorDelta, which is the same
as motorPWM.
Consistent indentation and removal of superfluous parentheses help
the readability.

Here is my attempt at implementing those suggestions:
const int motor1 = 3;  // pin for PWM output to motor
const unsigned long tLim = 30000;  // duration of the PWM ramp
const float PWM_unit = 255.0/100;  // convert percent to PWM scale
const float lowLim = PWM_unit * 21;
const float highLim = PWM_unit * 65;
const float PWM_rate = (highLim-lowLim) / tLim;

unsigned long start_time;  // start of the ramp
int previousPWM = 0;

void setup() {
    pinMode(motor1, OUTPUT);
    analogWrite(motor1, round(lowLim));
    delay(20000);
    Serial.begin(9600);
    Serial.println(" t   PWM");
    Serial.println("--------");
    start_time = millis();
}

void loop() {
    unsigned long t = millis() - start_time;

    if (t >= tLim) {  // we are done
        analogWrite(motor1, round(highLim));
        delay(60000);  // keep at highLim for 60 s
        analogWrite(motor1, 0);  // then stop
        exit(0);
    }

    int motorPWM = round(lowLim + t * PWM_rate);
    if (motorPWM != previousPWM) {
        analogWrite(motor1, motorPWM);
        Serial.print(t / 1000.0);
        Serial.print("  ");
        Serial.println(motorPWM);
        previousPWM = motorPWM;
    }
}

This helps tremendously. Thank you so much. I'll check it out later. It will be a part of a much larger program designed to replace a motor controller, with a much more functional one, so the delay would certainly cause issues with it. For the time being, I was just trying to see if I could make it work, and it wasn't working. This code was never intended to be long term, but I will definitely take your suggestions into consideration when it comes time to implement the code into the rest of the controller.


text:
Problem to display Ntp time on an oled using U8G2 lib
So I have this code to get ntp time and display it on serial port. But I want to display it on a 1.30 inch I2C oled with a SH1106 controller using the U8G2 library. The only problem is I don't know the correct syntax. I have tried
Serial.print((epoch  % 86400L) / 3600); // print the hour (86400 equals secs
per day)
int ho = ((epoch  % 86400L) / 3600+9);
itoa(ho,hours,10);
u8g2.clearBuffer();         // clear the internal memory
u8g2.setFont(u8g2_font_ncenB14_tr); // choose a suitable font
u8g2.drawStr(0,20,hours);

and also
{
u8g2.setFont(u8g2_font_ncenB14_tr);
u8g2.firstPage();
do {
u8g2.setCursor(0, 20);
u8g2.print(hours,DEC);
u8g2.setCursor(33, 20);
u8g2.print(minutes,DEC);
}
while ( u8g2.nextPage() );
}

This is my code
//This is a code to display ntp time using Nodemcu

#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include <Arduino.h>
#include <U8g2lib.h>

#ifdef U8X8_HAVE_HW_SPI
#include <SPI.h>
#endif
#ifdef U8X8_HAVE_HW_I2C
#include <Wire.h>
#endif

U8G2_SH1106_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/U8X8_PIN_NONE);

char ssid[] = "123456";     //  your network SSID (name)
char pass[] = "123456";     // your network password

//Your UTC Time Zone Differance  India +5:30
char HH = 5;
char MM = 30;

unsigned int localPort = 2390;      // local port to listen for UDP packets

//* Don't hardwire the IP address or we won't get the benefits of the pool.
//* Lookup the IP address for the host name instead */

//IPAddress timeServer(129, 6, 15, 28); // time.nist.gov NTP server

IPAddress timeServerIP; // time.nist.gov NTP server address

const char* ntpServerName = "time.nist.gov";

const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes
// of the message

byte packetBuffer[ NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing
//packets

// A UDP instance to let us send and receive packets over UDP
WiFiUDP udp;

                              //SETUP

void setup()
{
Serial.begin(115200);
Serial.println();
Serial.println();

// We start by connecting to a WiFi network
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, pass);

while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");

Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());

Serial.println("Starting UDP");
udp.begin(localPort);
Serial.print("Local port: ");
Serial.println(udp.localPort());
}

//  Send an NTP request to the time server at the given address

unsigned long sendNTPpacket(IPAddress& address)
{
Serial.println("sending NTP packet...");
// set all bytes in the buffer to 0
memset(packetBuffer, 0, NTP_PACKET_SIZE);

// Initialize values needed to form NTP request
// (see URL above for details on the packets)
packetBuffer[0] = 0b11100011;   // LI, Version, Mode
packetBuffer[1] = 0;     // Stratum, or type of clock
packetBuffer[2] = 6;     // Polling Interval
packetBuffer[3] = 0xEC;  // Peer Clock Precision
// 8 bytes of zero for Root Delay & Root Dispersion
packetBuffer[12]  = 49;
packetBuffer[13]  = 0x4E;
packetBuffer[14]  = 49;
packetBuffer[15]  = 52;

// all NTP fields have been given values, now
// you can send a packet requesting a timestamp:

udp.beginPacket(address, 123); //NTP requests are to port 123
udp.write(packetBuffer, NTP_PACKET_SIZE);
udp.endPacket();

u8g2.begin();
}
                              //LOOP

void loop()
{
char hours;
char minutes;
char seconds;

// get a random server from the pool
WiFi.hostByName(ntpServerName, timeServerIP);

sendNTPpacket(timeServerIP);

// send an NTP packet to a time server
// wait to see if a reply is available
delay(1000);

int cb = udp.parsePacket();
if (!cb) {
Serial.println("no packet yet");
}
else {
Serial.print("packet received, length=");
Serial.println(cb);

// We've received a packet, read the data from it
udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer
//the timestamp starts at byte 40 of the received packet and is four bytes,
// or two words, long. First, esxtract the two words:
unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);

// combine the four bytes (two words) into a long integer
// this is NTP time (seconds since Jan 1 1900):
unsigned long secsSince1900 = highWord << 16 | lowWord;
Serial.print("Seconds since Jan 1 1900 = " );
Serial.println(secsSince1900);

// now convert NTP time into everyday time:
Serial.print("Unix time = ");
// Unix time starts on Jan 1 1970. In seconds, that's 2208988800:
const unsigned long seventyYears = 2208988800UL;
// subtract seventy years:
unsigned long epoch = secsSince1900 - seventyYears;
// print Unix time:
Serial.println(epoch);

// print the hour, minute and second:
minutes = ((epoch % 3600) / 60);
minutes = minutes + MM; //Add UTC Time Zone

hours = (epoch  % 86400L) / 3600;
if(minutes > 59)
{
hours = hours + HH + 1; //Add UTC Time Zone
minutes = minutes - 60;
}
else
{
hours = hours + HH;
}

Serial.print("The UTC time is ");       // UTC is the time at Greenwich //Meridian (GMT)

Serial.print(hours,DEC); // print the hour (86400 equals secs per day)
Serial.print(':');

if ( minutes < 10 ) {
// In the first 10 minutes of each hour, we'll want a leading '0'
Serial.print('0');
}
Serial.print(minutes,DEC); // print the minute (3600 equals secs per minute)
Serial.print(':');

seconds = (epoch % 60);
if ( seconds < 10 ) {
// In the first 10 seconds of each minute, we'll want a leading '0'
Serial.print('0');
}
Serial.println(seconds,DEC); // print the second
}
// wait ten seconds before asking for the time again
delay(10000);
}

Adding the second block of code (print one) to the main code gives me correct time on the oled screen but only when the ntp receives a packet. Otherwise its some 10 digit number. How do I get rid of the number and keep displaying the time till it is update with a valid newer value. I have attached images of display.

More generally, you should reduce your code to a minimal, complete, verifiable example example.

Edited. It compiles now.


text:
Arduino keeps blinking when LED is in high
I have implemented a very simple program that turns a LED off when a switch is pressed.
My code works, but, when the LED is in high state, the LED blinks fast then turns off.
When I try to use the switch, the LED lights up without me even touching the switch. It seems like there is an invisible current that flows.
Observing carefully, I found out that the body of my laptop is probably causing this issue. My laptop has a metal body.
Since my Arduino is powered via USB from my Laptop, on "HIGH" state and I touch the body of my laptop, the LED turns off but when I let go of my laptop, the LED turns back on but blinks very fast.
Pushing the switch button, turns off the LED but when I release the button, the LED lights up but blinks very fast again.
I tried using a power adapter set to 12V but it just lights up the LED on the arduino board but not the LED on the breadboard.
I tried plugging the USB to a desktop, it lights up the LEDs on the arduino board but not the LED on the breadboard as well.
The schema is like below.

My code works. It's just the rapid blinking stuff. Is it the static electricity or noise or something that is causing this issue?
const int ledPin = 13;
const int buttonPin = 7;

int buttonState = 0;

void setup(){
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT);
}

void loop(){
  buttonState = digitalRead(buttonPin);
  if(buttonState == HIGH) {
    digitalWrite(ledPin, HIGH);
    Serial.println("LED ON +++++++++++");
  }
  else{
    digitalWrite(ledPin, LOW);
    Serial.println("LED OFF ------------");
  }
}

Please see the update above.

My code works, but, ... - please post that code.

I can actually see in my serial command that the "LED ON +++++++" then immediately goes to  "LED OFF ----------". This goes on and on when I am not touching the switch.

Try making buttonPin INPUT_PULLUP. And get rid of that resistor between the button and earth (what is that for?).

@NickGammon, it is a button which signals HIGH if pressed and needs pull-down to signal LOW. I know it is stupid, but the tutorials teach this https://www.arduino.cc/en/Tutorial/Button

@stackquestions, always use this button connection https://www.arduino.cc/en/Tutorial/InputPullupSerial

I am just following a tutorial and trying to figure things out. Thank you @Nick. Your suggestion worked!

The schema is like below.  Is it like that, or is it actually that?

This weird behavior sound a lot like a floating input. Double check the connections on the pull-down resistor you are using. Try wiggling the wires in the breadboard. Sometimes you get a bad connection in a breadboards. Also note that some breadboards don't have the blue and red lines connected all the way, but have a split in the middle (though that's not applicable if your wiring is exactly the way is shown in the picture).

The input impedance of a digital pin is extremely high. When something changes if you touch something or move your hand, that is an indication of a floating input pin. I prefer that all inputs and outputs have a GND connection, therefor I prefer that one side of the button is connected to GND, and the other one with INPUT_PULLUP or an extra pullup resistor.

@Juraj I know it is stupid, but the tutorials teach this arduino.cc/en/Tutorial/Button - that page shows a Fritzing picture which does not match the schematic further down the page. On the schematic the resistor is in a different place.

remove the ground wire to the LED.  use the busbar ground for the LED (same as the switch) .... the arduino already has an LED on pin 13, use that


text:
Is it possible to replace this delay with millis()? (And issue with other millis loop)
I am working on updating a project and I have a thread over in the Arduino forum which helped me out, but I'm a bit stuck, and there isn't much activity going on there.
This code is for use with a one wire temperature sensor, however, each time it retrieves data for the sensor, it has a 750ms delay as seen here:
ds.reset();
ds.select(addr);
ds.write(0x44, 1);        // start conversion, with parasite power on at the end

delay(750);     // maybe 750ms is enough, maybe not
// we might do a ds.depower() here, but the reset will take care of it.

present = ds.reset();
ds.select(addr);
ds.write(0xBE);         // Read Scratchpad

Now, I'm going to be using a momentary button as a toggle, but for this I need to debounce it, using a delay. With the 750ms delay present for the temperature sensor, that just isn't feasible, it makes it too unpredictable and difficult to use.
I need to replace this delay with a millis counter, but I'm not sure if I can without hanging up the rest of the script. I gave it a try like so, but it completely screwed up the reading.
if (owcurrentMillis - owpreviousMillis >= owinterval) {
owpreviousMillis = owcurrentMillis;
present = ds.reset();
ds.select(addr);
ds.write(0xBE);         // Read Scratchpad
}

I then tried it like so, and the readout does still work, however, I have an LED which lights up when the temperature has "Stabilized", which it's supposed to check every one second, but that has stopped working, and it's basically instant making it useless. I don't know why that millis loop does not work though, it was only working due to the 750ms delay.
if (owcurrentMillis - owpreviousMillis >= owinterval) {
owpreviousMillis = owcurrentMillis;
ds.reset();
ds.select(addr);
ds.write(0x44, 1);        // start conversion, with parasite power on at the end
}

Here is the bit of code controlling the LED illumination.
if (currentMillis - previousMillis >= interval) {  //If it has been 20 seconds, check to turn LED on
previousMillis = currentMillis;
if ((delta < 00.03) && (delta > -00.03)) {      //If temperature hasn't changed by +/- .05 turn led on.
  digitalWrite(A0, HIGH);
}
}
if (delta >= 00.06) {                             //If temperature has changed by more than .1 turn LED off
digitalWrite(A0, LOW);
}
if (delta <= -00.06) {
digitalWrite(A0, LOW);                         // If temperature has changed by more than -.1 turn LED off
}

I think if I can get that one to work properly, instead of messing up like it is now I should be good, then I just need the 50ms delay to debounce the button which will trigger what I need, I just can't figure out why it will not work.
You can see the version which works best here (with the 750ms delay in place):
#include <OneWire.h>
#include <LiquidCrystal.h>
#include <SPI.h>
#include <SD.h>
const int chipSelect = 10;

OneWire  ds(9);                               //Onewire + lcd setup
LiquidCrystal lcd(6, 7, 5, 4, 3, 2);
float lasttemp;                              //Variable for last temperature
float delta;                                 //Variable for temperaturechange
long previousMillis = 0;
const long interval = 1000;                       //Check once every 20 seconds

const long sdinterval = 5000;
long sdpreviousMillis = 0;

File myFile;

void setup(void) {
  pinMode(A0, OUTPUT);
  pinMode(A3, OUTPUT);

  Serial.begin(115200);                       //Start serial + LCD/Light test
  lcd.begin(8, 2);
  lcd.setCursor(0,0);
  lcd.print("STARTING");
  lcd.setCursor(0, 1);
  lcd.print("VER. 1.2");
  digitalWrite(A0, HIGH);
  digitalWrite(A3, LOW);
  delay(1000);
  digitalWrite(A0, LOW);
  digitalWrite(A3, HIGH);
  lcd.clear();                                //End of LCD/Light test

  if (!SD.begin(10)) {                       // Check for SD card
    digitalWrite(A3, LOW);
    lcd.setCursor(0,0);
    lcd.print("SD CHECK");
    lcd.setCursor(0,1);
    lcd.print("  FAIL  ");
    delay(1000);
    lcd.clear();
    digitalWrite(A3, HIGH);
  } else {
    delay(1000);
    digitalWrite(A3, LOW);
    lcd.setCursor(0,0);
    lcd.print("SD CHECK");
    lcd.setCursor(0,1);
    lcd.print("  PASS  ");
    delay(1000);
    lcd.clear();
    digitalWrite(A3, HIGH);
  }
}

void loop(void) {

  unsigned long sdcurrentMillis = millis();
  unsigned long currentMillis = millis();
{
  }

  byte i;
  byte present = 0;
  byte type_s;
  byte data[12];
  byte addr[8];
  float celsius, fahrenheit;

  if ( !ds.search(addr)) {
    Serial.println("No more addresses.");
    Serial.println();
    ds.reset_search();
    delay(250);
    return;
  }

  Serial.print("ROM =");
  for( i = 0; i < 8; i++) {
    Serial.write(' ');
    Serial.print(addr[i], HEX);
  }

  if (OneWire::crc8(addr, 7) != addr[7]) {
    Serial.println("CRC is not valid!");
    return;
  }
  Serial.println();

  // the first ROM byte indicates which chip
  switch (addr[0]) {
  case 0x10:
    Serial.println("  Chip = DS18S20");  // or old DS1820
    type_s = 1;
    break;
  case 0x28:
    Serial.println("  Chip = DS18B20");
    type_s = 0;
    break;
  case 0x22:
    Serial.println("  Chip = DS1822");
    type_s = 0;
    break;
  default:
    Serial.println("Device is not a DS18x20 family device.");
    return;
  }

  ds.reset();
  ds.select(addr);
  ds.write(0x44, 1);        // start conversion, with parasite power on at the end

  delay(1000);     // maybe 750ms is enough, maybe not
  // we might do a ds.depower() here, but the reset will take care of it.

  present = ds.reset();
  ds.select(addr);
  ds.write(0xBE);         // Read Scratchpad

  Serial.print("  Data = ");
  Serial.print(present, HEX);
  Serial.print(" ");
  for ( i = 0; i < 9; i++) {           // we need 9 bytes
    data[i] = ds.read();
    Serial.print(data[i], HEX);
    Serial.print(" ");
  }
  Serial.print(" CRC=");
  Serial.print(OneWire::crc8(data, 8), HEX);
  Serial.println();

  // Convert the data to actual temperature
  // because the result is a 16 bit signed integer, it should
  // be stored to an "int16_t" type, which is always 16 bits
  // even when compiled on a 32 bit processor.
  int16_t raw = (data[1] << 8) | data[0];
  if (type_s) {
    raw = raw << 3; // 9 bit resolution default
    if (data[7] == 0x10) {
      // "count remain" gives full 12 bit resolution
      raw = (raw & 0xFFF0) + 12 - data[6];
    }
  }
  else {
    byte cfg = (data[4] & 0x60);
    // at lower res, the low bits are undefined, so let's zero them
    if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
    else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
    else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
    //// default is 12 bit resolution, 750 ms conversion time
  }

  celsius = (float)raw / 16.0;
  fahrenheit = celsius * 1.8 + 32.0;
  Serial.print("  Temperature = ");
  Serial.print(celsius);
  Serial.print(" Celsius, ");
  Serial.print(fahrenheit);
  Serial.println(" Fahrenheit");

  delta = celsius - lasttemp;                       //Create value to check how much temperature has changed

  if (currentMillis - previousMillis >= interval) {  //If it has been 20 seconds, check to turn LED on
    previousMillis = currentMillis;
    if ((delta < 00.03) && (delta > -00.03)) {      //If temperature hasn't changed by +/- .05 turn led on.
      digitalWrite(A0, HIGH);
    }
  }
  if (delta >= 00.06) {                             //If temperature has changed by more than .1 turn LED off
    digitalWrite(A0, LOW);
  }
  if (delta <= -00.06) {
    digitalWrite(A0, LOW);                         // If temperature has changed by more than -.1 turn LED off
  }

    if (sdcurrentMillis - sdpreviousMillis >= sdinterval) {  //Write to SD card every 5 seconds.
    sdpreviousMillis = sdcurrentMillis;
    digitalWrite(A3, LOW);
    myFile = SD.open("Log.txt", FILE_WRITE);
    myFile.print(celsius);
    myFile.println(" C ");
    myFile.close();
    digitalWrite(A3, HIGH);
  }

  lcd.setCursor(0, 0);
  lcd.print(celsius);
  lcd.print(" C ");
  lcd.setCursor(0, 1);
  lcd.print(fahrenheit);
  lcd.print(" F ");
  lasttemp = celsius;
  }

and this is the one I'm working on as I write this, with the illumination delay messing up:
#include <OneWire.h>
#include <LiquidCrystal.h>
#include <SPI.h>
#include <SD.h>

unsigned long owpreviousMillis = 0;
const long owinterval = 750;
//---------------------------------------------------------------------------------- One wire temperature sensor stuff
OneWire  ds(9);                 //Setting one wire bus pin
byte i;
byte present = 0;
byte type_s;
byte data[12];
byte addr[8];
float celsius, fahrenheit;      //Variables for celsius and farenheit conversions
long previousMillis = 0;
float lasttemp;                 //Variable for last temperature
float delta;                    //Variable for temperaturechange
const long interval = 1000;     //Check once every 1 second

//---------------------------------------------------------------------------------- End of one wire temperature sensor stuff.

LiquidCrystal lcd(6, 7, 5, 4, 3, 2); //Defining pins for the LCD

//---------------------------------------------------------------------------------- SD card stuff
const int chipSelect = 10;              //Setting SD chip select pin (obviously)
File myFile;
long sdpreviousMillis = 0;
const long sdinterval = 5000;           //SD card write interval

//-----------------------------------------------------------------------------------End of pre-setup

void setup(void) {
  pinMode(A2, INPUT);
  pinMode(A0, OUTPUT);    //Green LED for temperature stability indication
  pinMode(A3, OUTPUT);    //Red LED for sd card activity indication
  Serial.begin(115200);
//------------------------- Testing LCD and LED's, displaying version number and checking for SD card.
  lcd.begin(8, 2);
  lcd.setCursor(0,0);
  lcd.print("STARTING");
  lcd.setCursor(0, 1);
  lcd.print("VER. 1.5");
  digitalWrite(A0, HIGH);
  digitalWrite(A3, LOW);
  delay(1000);
  digitalWrite(A0, LOW);
  digitalWrite(A3, HIGH);
  lcd.clear();

  if (!SD.begin(10)) {                    // Check for SD card
    digitalWrite(A3, LOW);
    lcd.setCursor(0,0);
    lcd.print("SD CHECK");
    lcd.setCursor(0,1);
    lcd.print("  FAIL  ");
    delay(1000);
    lcd.clear();
    digitalWrite(A3, HIGH);
  } else {
    delay(1000);
    digitalWrite(A3, LOW);
    lcd.setCursor(0,0);
    lcd.print("SD CHECK");
    lcd.setCursor(0,1);
    lcd.print("  PASS  ");
    delay(1000);
    lcd.clear();
    digitalWrite(A3, HIGH);
  }
//----------------------------------- Setting up one wire temperature sensor.
  if ( !ds.search(addr)) {
    Serial.println("No more addresses.");
    Serial.println();
    ds.reset_search();
    delay(250);
    return;
  }
  Serial.print("ROM =");
  for( i = 0; i < 8; i++) {
    Serial.write(' ');
    Serial.print(addr[i], HEX);
  }
  if (OneWire::crc8(addr, 7) != addr[7]) {
    Serial.println("CRC is not valid!");
    return;
  }
  Serial.println();

  // the first ROM byte indicates which chip
  switch (addr[0]) {
  case 0x10:
    Serial.println("  Chip = DS18S20");  // or old DS1820
    type_s = 1;
    break;
  case 0x28:
    Serial.println("  Chip = DS18B20");
    type_s = 0;
    break;
  case 0x22:
    Serial.println("  Chip = DS1822");
    type_s = 0;
    break;
  default:
    Serial.println("Device is not a DS18x20 family device.");
    return;
  }

}
//----------------------------------------------------------------------------- End of setup.

void loop(void) {

  unsigned long sdcurrentMillis = millis();
  unsigned long currentMillis = millis();
  unsigned long owcurrentMillis = millis();

  if (owcurrentMillis - owpreviousMillis >= owinterval) {
    owpreviousMillis = owcurrentMillis;
    ds.reset();
    ds.select(addr);
    ds.write(0x44, 1);        // start conversion, with parasite power on at the end
    }

  present = ds.reset();
  ds.select(addr);
  ds.write(0xBE);         // Read Scratchpad

  Serial.print("  Data = ");
  Serial.print(present, HEX);
  Serial.print(" ");
  for ( i = 0; i < 9; i++) {           // we need 9 bytes
    data[i] = ds.read();
    Serial.print(data[i], HEX);
    Serial.print(" ");
  }
  Serial.print(" CRC=");
  Serial.print(OneWire::crc8(data, 8), HEX);
  Serial.println();

  // Convert the data to actual temperature
  // because the result is a 16 bit signed integer, it should
  // be stored to an "int16_t" type, which is always 16 bits
  // even when compiled on a 32 bit processor.
  int16_t raw = (data[1] << 8) | data[0];
  if (type_s) {
    raw = raw << 3; // 9 bit resolution default
    if (data[7] == 0x10) {
      // "count remain" gives full 12 bit resolution
      raw = (raw & 0xFFF0) + 12 - data[6];
    }
  }
  else {
    byte cfg = (data[4] & 0x60);
    // at lower res, the low bits are undefined, so let's zero them
    if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
    else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
    else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
    //// default is 12 bit resolution, 750 ms conversion time
  }

  celsius = (float)raw / 16.0;
  fahrenheit = celsius * 1.8 + 32.0;
  Serial.print("  Temperature = ");
  Serial.print(celsius);
  Serial.print(" Celsius, ");
  Serial.print(fahrenheit);
  Serial.println(" Fahrenheit");

  delta = celsius - lasttemp;                       //Create value to check how much temperature has changed

  if (currentMillis - previousMillis >= interval) {  //If it has been 20 seconds, check to turn LED on
    previousMillis = currentMillis;
    if ((delta < 00.03) && (delta > -00.03)) {      //If temperature hasn't changed by +/- .05 turn led on.
      digitalWrite(A0, HIGH);
    }
  }
  if (delta >= 00.06) {                             //If temperature has changed by more than .1 turn LED off
    digitalWrite(A0, LOW);
  }
  if (delta <= -00.06) {
    digitalWrite(A0, LOW);                         // If temperature has changed by more than -.1 turn LED off
  }

    if (sdcurrentMillis - sdpreviousMillis >= sdinterval) {  //Write to SD card every 5 seconds.
    sdpreviousMillis = sdcurrentMillis;
    digitalWrite(A3, LOW);
    myFile = SD.open("Log.txt", FILE_WRITE);
    myFile.print(celsius);
    myFile.println(" C ");
    myFile.close();
    digitalWrite(A3, HIGH);
  }

  lcd.setCursor(0, 0);
  lcd.print(celsius);
  lcd.print(" C ");
  lcd.setCursor(0, 1);
  lcd.print(fahrenheit);
  lcd.print(" F ");
  lasttemp = celsius;
  }

This is the post on the Arduino forum which sort of explains what I'm doing a bit better, if it does not make sense: Best way to set up a button to toggle a second function? (millis issue now).
Edit/update
Alright, so I think it has to do with how I structured that bit of the code, it seems like the arguments to turn the LED off weren't in the if statement which used the delay, so changed it to this, and unfortunately now it is on constantly, but I think I am on the right track.
if (currentMillis - previousMillis >= interval) {  //If it has been 20 seconds, check to turn LED on
previousMillis = currentMillis;
if ((delta < 00.03) && (delta > -00.03)) {       //If temperature hasn't changed by +/- .05 turn led on.
  digitalWrite(A0, HIGH);
} else {
  if ((delta >= 00.06) && (delta <= -00.06)) {
    digitalWrite(A0, LOW);
  }
}
}

It seems like this should work but perhaps there's an issue with having two if statements set up on top of each other like that. I also gave it a try like this, to no avail.
(currentMillis - previousMillis >= interval) {  //If it has been 20 seconds, check to turn LED on
previousMillis = currentMillis;
if ((delta < 00.03) && (delta > -00.03)) {       //If temperature hasn't changed by +/- .05 turn led on.
  digitalWrite(A0, HIGH);
} else {
  if (delta >= 00.06){
    digitalWrite(A0, LOW);
  } else {
  if (delta <= -00.06){
   digitalWrite(A0, LOW);
  }
 }
}
}

Edit/update
Quick clarification, I managed to get rid of the delay and use millis instead but it introduced an issue with the LED which indicates stable temperature not working (being lit most of the time, and then flashing off/on fairly quickly as the temperature changes, instead of remaining off until it stabilizes again). It seems to be ignoring the delay I have it waiting for.
Now, after going through it a lot, it seems like this is how I need it set up. It checks if the interval has been reached, if so, it checks if the temperature has changed less than x amount, if so it lights the LED.
However, if the temperature has changed more than that, it checks if it exceeds y amount, and if so turns the light off.
I have tried reversing these and it has had no effect, it just seems like the boolean arguments aren't working and I don't know why, but at least the delay issue is solved.
if (currentMillis - previousMillis >= interval) {  //If it has been 20 seconds, check to turn LED on
previousMillis = currentMillis;
if ((delta < 00.03) && (delta > -00.03)) {       //If temperature hasn't changed by +/- .05 turn led on.
  digitalWrite(A0, HIGH);
} else if ((delta >= 00.06) || (delta <= -00.06)) {
    digitalWrite(A0, LOW);
  }
}

Here? Best way to set up a button to toggle a second function? - you posted this issue there 30 minutes ago. there isn't much activity going on there - maybe everyone's eating dinner? Try to let a little longer elapse before running off cross-posting that "nothing is happening" on another site. Like, 12 hours.

There hasn't been activity on that thread much longer than that, and I wanted to get feelers out in multiple places, different sites are likely to be used by different people, who are in different places in the world, so why not try and maximize the chances of getting a response? Especially at this time of day when the majority of people who use this forums north america) will be asleep?
Besides, this also puts out the issue as it's own thing relating to the millis function, which means that people searching for something similar will be able to find this more easily, what's wrong with that?

Besides, chances are most of the people who read that thread and did not reply were not interested in it or could not offer advice, so they will likely not visit it again, and I don't want to spam their forum.
So, I'll just wait for an actual helpful reply on either of these, unfortunately this forum has turned out unhelpful in that regard thus far.

Looks like you got a good answer here from Edgar Bonet. Especially at this time of day when the majority of people who use this forums north america) will be asleep? However on the Arduino forum I note that you also got answers 49 mins, 83 mins, and 102 mins after the post I referred to. so they will likely not visit it again - apparently not.

I was referring to people who have previously looked at a thread, when it was in it's infancy, and were not interesting in the original problem.
If that was the case, they would likely not revisit and see that there was a new problem. Apparently you are incapable of contributing though, and instead decide to just spit out useless and pointless comments.

Currently, your algorithm for reading the temperature in loop() looks
like:
request_temperature_conversion();
delay(1000);
float temp = read_temperature();
report_temperature_to_user(temp);

If you take care to send the first request in setup(), then you can
roll these pieces around so that your loop() code looks like:
delay(1000);
float temp = read_temperature();
report_temperature_to_user(temp);
request_temperature_conversion();

And that's the trick: you send the new request in the same loop
iteration. Once you do that, it becomes quite simple to remove the delay
and use millis() instead. Your compete loop code could then look like:
void loop() {
  uint32_t now = millis();

  if (now - last_temp_read >= temp_read_interval) {
    float temp = read_temperature();
    report_temperature_to_user(temp);
    request_temperature_conversion();  // make request now, will read next time
    last_temp_read = now;
  }

  if (now - last_led_update >= led_update_interval) {
    update_led_display();
    last_led_update = now;
  }

  if (now - last_SD_card_write >= SD_card_write_interval) {
    write_data_to_log_file();
    last_SD_card_write = now;
  }
}

Make sure to account for for the fact that the first temperature read is bogus. Other than that, an excellent technique.

@Gerben: Could you explain why the first read is bogus?

Sorry, not really the most accurate word here. The first time you start the code it will read the temperature before you started the first conversion. So the value you get back could be anything.

Sorry again. It seems you already explained/fixed that: If you take care to send the first request in setup() ....


text:
Problem Atmel Studio 7 with uploading
I have a problem with the interworking between Atmel Studio 7 and Arduino IDE 1.6.10.
I recently upgraded from IDE 1.0 to 1.6.10 and I can no longer upload my code to the Arduino. Everything works including compiling and it does recognise my COM3 port. Atmel Studio is configured for no external programmer.
When I compile with the Arduino IDE it does upload the code. My question is what goes wrong here, what do I need to do solve it. Thanks for your help
This the message I have in the end:
Compiling 'GridMonintor_V1R1' for 'Arduino Nano w/ ATmega328' Binary sketch size: 12,268 bytes (used 40% of a 30,720 byte maximum) (22.20 secs)

Minimum Memory Usage: 774 bytes (38% of a 2048 byte maximum) Uploading to I/O board using 'COM3'

avrdude: no programmer has been specified on the command line or the config file
         Specify a programmer using the -c option and try again

Switch on verbose so that we can see the upload command

...Specify a programmer using the -c option and try again

For Arduino, the programmer switch must be -c arduino. The full arguments for avrdude, in the Atmel Studio 7 External Tools window, are:
-c arduino -p m328p -P COM3 -b 57600 -D -V -U flash:w:"$(TargetDir)$(TargetName).hex":a

See avrdude options.

Switch on vMicro>Uploader>verbose then try the upload and post the output as a .txt file in a new thread in the visualmicro.com forum.
http://www.visualmicro.com/forums
Because you are using the Visual Micro plugin the forum is the best place to see help.
We will also check that you have configured the new arduino location against the arduino 1.6.x option in Visual Micro and not the Arduino 1.0. option as you had it originally. In fact you can have both IDE versions configured in Visual Micro at the same time and switch between them using the tool bar.
Thanks

you might want to try the following command:
-C “C:\Program Files\Arduino\hardware\tools\avr\etc\avrdude.conf” -patmega328p -carduino -PCOM3 -b115200 -D -Uflash:w:$(TargetDir)$(TargetName).hex:i
where i is used at the end for intel. the one provided above by @flanker uses a
see this detailed tutorial How to program Arduino using ATMEL Studio 7


text:
Arduino and GPS module Neo 6m
I have an Arduino Leonardo and a GPS module "NEO 6M"
Pinout:
PPS->free
rxd->11
txd->10
gnd->gnd
vcc->5v

I'm running this code:
#include "SoftwareSerial.h"
SoftwareSerial gps(10,11);
void setup(){
  Serial.begin(9600);
  gps.begin(9600);
}

void loop(){
  while (gps.available())
    Serial.write(gps.read());
}

In serial monitor I'm getting random characters like this

Where am I going wrong?
I tried the same with an Arduino Mega but have the same result.

Solved: GPS module was broken. Now I use another GPS module, same model. Sorry for my English.

How did you ascertain that the module was broken? Did you try it with a different GPS module and it then worked? Could you edit and expand your answer a little, as it could be useful for someone else who has the same issue...

i used another GPS module and resolve all my problem :) sorry for late response


text:
Accelerometer MPU-6050 marks timeout in Unity
I've been having this problem, that I am trying to use an accelerometer MPU-6050 to get the rotation and pass that information to Unity.
I also have some buttons in the same Arduino. I'm using an Arduino Uno. With those buttons, everything works well, but the moment I put something related to the accelerometer in the Arduino code, Unity marks a time out. When I run it on Arduino it sends me all the info I'm asking, so I don't really know what's the problem. I really appreciate if someone could help me.
Here is code on Arduino:
#include<Wire.h>
#define A_R 16384.0
#define G_R 131.0
 #define RAD_A_DEG = 57.295779
const int MPU_addr=0x68;  // I2C address of the MPU-6050
int AcX,AcY,AcZ,GyX,GyY;

float Acc[2];
float Gy[2];
float Angle[2];
int button = 0;
int button2 = 0;
int button3 = 0;

float arriba=0, abajo=0,mouse=0;

void setup(){
  Wire.begin();
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x6B);  // PWR_MGMT_1 register
  Wire.write(0);     // set to zero (wakes up the MPU-6050)
  Wire.endTransmission(true);
  pinMode(7, INPUT); // declare pushbutton as input
pinMode(6, INPUT);
pinMode(5,INPUT);
  Serial.begin(9600);
}

void loop(){
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  //Wire.requestFrom(MPU_addr,14,true);  // request a total of 14 registers

  AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
  AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
 AcZ=Wire.read()<<8|Wire.read();

  Acc[1] = atan(-1*(AcX/A_R)/sqrt(pow((AcY/A_R),2) + pow((AcZ/A_R),2)))*RAD_TO_DEG;
   Acc[0] = atan((AcY/A_R)/sqrt(pow((AcX/A_R),2) + pow((AcZ/A_R),2)))*RAD_TO_DEG;

  GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
  GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)

  Angle[0] = 0.98 *(Angle[0]+Gy[0]*0.010) + 0.02*Acc[0];
   Angle[1] = 0.98 *(Angle[1]+Gy[1]*0.010) + 0.02*Acc[1];

        button = digitalRead(7);
  button2 = digitalRead(6);
  button3 = digitalRead (5);

   //Mostrar los valores por consola
   if(button == HIGH){
 arriba=1;
  }else if(button==LOW){
  arriba=0;
  }

  if(button2 == HIGH){
    abajo=1;
  }else if(button2==LOW){
    abajo=0;
  }

  if(button3 == HIGH){  //boton 3
    mouse=1;
  }else if(button3==LOW){
    mouse=0;
  }
  Serial.print(arriba);
  Serial.print(",");
  Serial.print(abajo);
  Serial.print(",");
  Serial.print(mouse);
   Serial.print(",");

   Serial.print(Angle[0]);
   Serial.print(",");
   Serial.println(Angle[1]);

  delay(200);
}

I know this isn't an Unity forum, but here is the code in Unity. The only thing it does, is read it and put the results in an array.
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.IO.Ports;
using System.Globalization;
using System;

using UnityEngine;

public class ConectarArduino: MonoBehaviour
{
    string Recibidos;
    public string Linea, Linea1,Linea2;
    public int Arrib, Abajo,Boton;
    SerialPort stream;
    // Use this for initialization

    void Start()
    {
        stream = new SerialPort("COM3", 9600);
        //  stream.
        stream.Open();
        stream.ReadTimeout = 300;

    }

    // Update is called once per frame
    void Update()
    {
        try
        {
            Recibidos = stream.ReadLine();
            Debug.Log(Recibidos);
        }
        catch (System.Exception e)
        {
            Debug.Log(e.Message);
            throw;
        }

        string[] Values = Recibidos.Split(',').Select(str => str.Trim()).ToArray();
        Linea = Values[0];
        Linea1 = Values[1];
        Linea2 = Values[2];

There's too many things call Unity these days. Which Unity are you talking about?

Can you add the timeout error to your question? What is/are the line(s) that when you add, causes the timeout? Could you be a bit more explicit about what works, and what doesn't (a sort of "before and after")..?

Running MPU-6050 at 57600bps seemed to be the good rate for me:
  pinMode(5,INPUT);
  Serial.begin(57600);
}

It worked for me and I found these guys for whom it was the good rate :
From MPU-6050-simple-library, specifically MPU6050_test.ino:

void setup() {
  Serial.begin(57600);
  MPU6050mgr.begin(); // Initializes IMU module
}

From Another Arduino as external i2c device for MPU6050:

void setup() {
  Wire.begin(0x1E);                // join i2c bus with address #8
  Wire.onReceive(receiveEvent); // register event
  Serial.begin(57600);           // start serial for output
}

From Library for Arduino and MPU-6050 communication:

void setup() {
  Serial.begin(57600);
  MPU6050mgr.begin(); // Initializes IMU module
}

You may also find this link useful: MPU-6050 Redux: DMP Data Fusion vs. Complementary Filter.

You may be correct but can you provide evidence that 57600 bps is its preferred rate?

That may not be a proof from the datasheets, but in my project in worked, and there is a lot of people for whom it worked too :
https://github.com/dadez87/MPU-6050-simple-library
http://www.geekmomprojects.com/mpu-6050-redux-dmp-data-fusion-vs-complementary-filter/
https://www.i2cdevlib.com/forums/topic/538-another-arduino-as-external-i2c-device-for-mpu6050/
https://www.monocilindro.com/2017/02/25/library-arduino-mpu-6050-communication/

Excellent, could you edit your answer, and include that information then? Important information should not be in comments, as they are rather ephemeral and, as such, may be deleted at any time. Thanks

sorry for this, it s okay now

You omitted two links, and you should have included the relevant code from the links, because if the links die (which is often the case), then your answer becomes (effectively) useless. I have edited your answer for you. Please take the time to see how I have done the edits. Oh, and welcome to SE Arduino... :-)

thank you for your edit, i understand the links problem !


text:
Do all pins of Arduino Uno output 5V?
I am currently working on a project which uses PIR motion sensor and 5V relay.
Since you might be familiar that both the motion sensor and the relay requires a 5V connection.
My problem is, I don't want messy connections (parallel and series) and want to use any other pin for power and ground.
Also, can you suggest which resistor I might require for the motion sensor and relay?
Thanks for any help.

You might get away with powering a PIR sensor from a logic line. Check the specs. If it draws less ≤20mA you'd be fine. If you nee to drive more current than that you can use a CMOS TTL Driver or a properly selected N-channel MOSFET. Adafruit sells these, for example.
A relay is another matter. If you this is one of those optically isolated relays and all you're driving is the optioisolator then you might get away with that too if you only need ≤20mA. If you're looking to actually power the relay coils with your Arduino, forget it. it's a bad idea to even have the relay driven from the 5V line on the Arduino. Relays take quite a bit of current, and their load is quite "dirty" and likely to cause problems.
As to "which resistor I might require for the motion sensor & relay", I'm not sure what you mean. You shouldn't need any resistors. If the relay draws more current than the Arduino can supply, a current limiting resistor might protect the Arduino from damage but the relay won't work correctly.
What resistors are you referring to?

In the last para I am talking about the resistance value 1omhs or 100 ohms etc

I know what resistors are. I don't think you need any in this application, but you need to determine how much current your devices draw.

"(On most Arduino models the absolute max current for each pin is 40mA but the recommendation is to stay at half that, or ≤20mA."  Actually, the datasheet says Vout with Vcc = 5V is guaranteed to be >= 4.2V for up to 20mA, and may drop above that "If IOH exceeds the test condition [20mA at VCC = 5V], VOH may exceed the related specification. Pins are not guaranteed to source current greater than the listed test condition."

@CrossRoads that will teach me to trust things posted by other people on these boards as truth without validating for myself. Thanks for correcting me. I've deleted that part of my answer.


text:
Interfacing TTP229 touch sensor with arduino and gsm module
I have been working on an Arduino based call and message project which I am following from this link https://circuitdigest.com/microcontroller-projects/call-and-message-using-arduino-sim900-gsm.
This project uses a membrane keypad for inputting the phone number and etc., but I intend to use a TTP229 16 channel Touch sensor module.
I need help in taking input from the touchpad rather than the keypad. As I need to submit the project within a month it is my humble request if someone can help.
Thanks for replying!

how does the touch panel communicate with the arduino?  ..... what code are you using? ..... what problems are you facing?

It communicates over serial im using the below code to get the data from the sensor.http://forum.hobbycomponents.com/viewtopic.php?f=73&t=1781&hilit=hcmodu0079

I am able to fetch the data from the sensor but i am not able to call that function in the main gsm program.


text:
Comparing byte array with multi-dimensional array
I am having a byte array let us say
byte arr[7]={123456};

How to compare this array with a list of of other array like this for example
byte  buffers[5][7] = {123456,654321,987654,456789,765432};

if this method is wrong how can I declare that ?

what do you think byte arr[7]={123456}; actually does?

so how can i make a list of arrays to compare with ?

what do you WANT arr to be? 1,2,3,4,5,6,0? or 64,0,0,0,0,0,0

i want it to be 1,2,3,4,5,6

well, you're doing it wrong

so what do u suggest for doing it correctly?

to learn how to initialise an array - see answer

How is this an Arduino question? This is more a "help me understand basic C/C++ programming"-question.

byte arr[7]={123456};

sets arr[0] = 64 - which is 123456 % 256 - and arr[1-6] are left at 0
And you also only want 6 (not 7) values - so the code would be
byte arr[6]={1,2,3,4,5,6}; // this is how to initialise an array
byte  buffers[5][6] = {{1,2,3,4,5,6},{6,5,4,3,2,1},{9,8,7,6,5,4},{4,5,6,7,8,9},{7,6,5,4,3,2}}; // this is how to initialise a 2d array

void setup() {
  Serial.begin(74880);
  delay(100);
  // this code will find a match, the vlaue of `i` will be the matched index
  int i;
  int j;
  for(i = 0; i < 5; i++) {
    for(j = 0; j < 6; j ++) {
      if(arr[j] != buffers[i][j]) {
        break;
      }
    }
    if(j == 6) {
      break;
    }
  }
  if (i < 5) {
    Serial.print("Found at index ");
    Serial.println(i);
  }

}

@JaromandaX Might want to make this an Arduino QA by adding how to use program memory for a constant value vector/array.

not sure what you mean @MikaelPatel


text:
ESP8266 MQTT periodically disconnecting
I use an MQTT to communicate with an ESP8266. I'm using cloudmqtt.com and PubSubClient. Sometimes the ESP disconnects from the MQTT and reconnects.
I checked the log from cloud and I got this data
2019-02-18 20:11:18: New connection from 89.64.15.184 on port 18127.

2019-02-18 20:11:22: New connection from 89.64.15.184 on port 18127.

2019-02-18 20:11:35: New connection from 89.64.15.184 on port 18127.

2019-02-18 20:11:35: New client connected from 89.64.15.184 as ESP8266Client-80:7D:3A:69:6C:2E (c1, k15, u'userName').

2019-02-18 20:11:53: Client <unknown> has exceeded timeout, disconnecting.

2019-02-18 20:11:53: Socket error on client <unknown>, disconnecting.

2019-02-18 20:11:56: Saving in-memory database to /var/lib/mosquitto/18127/db.

2019-02-18 20:11:58: Client ESP8266Client-80:7D:3A:69:6C:2E has exceeded timeout, disconnecting.

in setup I have this method:
void setupMQTT() {

  while (!client.connected()) {
    Serial.println("Connecting to MQTT...");
    String clientId = "ESP8266Client-";
    clientId += WiFi.macAddress();
    if (client.connect(clientId.c_str(), mqttUser, mqttPassword )) {

      Serial.println("connected");

    } else {

      Serial.print("failed with state ");
      Serial.print(client.state());
      delay(2000);

    }
  }
  client.publish("esp/blind/out", "hello world");
  client.subscribe("esp/blind/in");
}

and in loop I have
client.loop();

without any delay.
I think that the ESP id in MQTT cloud is unique, because I use the MAC address.

which version of arduino/esp8266 are you using - I ask, because I had to put in a delay(10) or so in loop for some ESP chips when using the latest (2.5.0dev) branch

I use wemos D1 mini with ESP-12F and about month ago I update firmware because I wanted to try micropython

but your code isn't written in micropython .... it looks like typical arduino (i.e. C/C++) ... which version of the esp8266 arduino core are you using? Actually, nevermind, try adding a delay(10) in your main loop or even a yield()

no it isn't written in micropython it's written in c++, adding delay(10) do nothing. How can I check a esp8266 arduino core version ?

you downloaded it and installed it ... what did you download and install ... another possibility is the router you connect to- which make model? (e.g I have a linksys wrt32x - and ESP's have lots of issues staying connected to it)\

I have version 2.5 updated from 2.5 beta 2. I connect esp to airport from apple

try setting a lower "keep alive" ... e.g. #define MQTT_KEEPALIVE 10 before #iclude <pubSubClient.h>

It works, thank you very much for helping

I have the same problem again, I added #define MQTT_KEEPALIVE 10 and delay(50)


text:
Where does the Arduino core include the name of the sketch?
I'm trying to look through the Arduino core to find where "mySketch.ino" is included or implemented. In 'Arduino.h', the prototypes void setup(void) and void loop(void) are defined, in 'main.cpp', setup(void) and loop(void) are called, but I'm not sure where 'main.cpp' or any other related files makes a reference to the sketch.
Where does this occur?

The files don't reference the sketch. They don't need to. That's not how C compiling works. Look up "Linking (Compiling)" in Google to understand more.

Here is the "main()" source file for the Arduino core. https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/main.cpp

Compilation doesn't start with the Arduino.h or the core files; rather, it starts with your own sketch, "whatever.ino". Your .ino file includes Arduino.h into the compilation which makes references to core modules. That compilation leaves many references to to be satisfied, and itself satisfies several - setup() and loop(), for two. At link time, the linker is told to read not only your compiled module(s), but also the compiled core files, from which it can extracts the modules required to satisfy references made by your compiled code. Then it combines your module, and those modules required by it, into the load file that avrdude uploads to the Arduino.

Just want to add, that the Arduino IDE also concatenates all the .ino files in the same sketch together; .cpp, files are compiled automatically as well, but are not modified like the .ino files.


text:
Is it possible to use I2C and SPI ons the same Clock line?
I'm trying to connect an I2C OLED display and an n RF24L01 WiFi module to an ATTiny85. But I only need 1 extra pin. Is it possible to use the same clock wire/pin for the I2C and SPI device? Maybe with some extra code? Thanks a lot!

Do you have CS pin? Then yes, easily. When the SPI device is deselected, it doesn't care what you put on SCLK and the I2C will get it normally. The other way around, the I2C device doesn't have a CS and will listen to its address byte on the I2C SCL and SDA lines.. If SDA is seperate to the SPI bus, it will just read 0... and not do anything, even if there's a clock.

Yes, in theory it is possible. You can use the scl for other things as long as you keep the sda high. The scl is a input clock for most i2c devices. I assume that the display itself does not pull the scl low. Changing between a open-collector and a digital ttl signal for the scl should therefor not be a problem. If the display has a microcontroller for i2c, then it might pull the scl low. Is the USI used for the i2c bus? Then there might be a shortcut when the SPI library keeps the scl high and the USI/I2C pulls it low. Can you share chipselect with scl? Then you can release the scl pin.

@MaximilianGerhardt it is about the start condition for i2c. When sda does not turn low, there is no start condition and the i2c devices do nothing.

@Jot oh right, you'd have to take that into account, too..

Perhaps it is safer to do Wire.begin, then normal i2c, then Wire.end() and the same for the spi.

Can Software I2C be a solution for this? If so, how do I need to program this so it can communicate with the ssd1306 oled library?

I'll suggest you to use Mode-2 or 3 of SPI, as in that case, SPI device will get clk pulses only when you have LOW to HIGH transition, & thus, the I2C device will not get the start bit condition ( SCLK should be HIGH and SDA should have a falling edge for start bit of I2C frame). When you need to communication with I2C device, make SCLK as HIGH and start the I2C frame which will result in SPI device to wait for  the CS pin. Also, try pulling SCLK line with CS pin line as this would pull it down for SPI mode, & when HIGH, it will enable I2C & SPI will not have CS signal for its functionality.


text:
Changing PWM on Arduino Mega, pins 9 & 10 to 20 to 25 KHz
I'm trying to run a Nema 17 motor with a l298N motor Driver for a school project. The issue is that I am running the motor with PWM to avoid overheating of the driver, however the resulting noise at the default frequency is extremely aggravating.
How can I change the frequency for pins 9 & 10 to 20-25 KHz? Any tips tricks and code examples would be highly appreciated (emphasis on code examples).

Fortunately, the timer for PWM on both pins 9 and 10 on the Arduino Mega (but not necessarily other boards) is timer 2, so changing the PWM frequency of one will change the PWM frequency of the other.
You should also check that changing the the timer frequency does not effect any other libraries (eg Servo, from memory typically uses timer 2).
The frequency for the timer is set by the TCCR2B register (bits CS22, CS21 and CS20) see p 185 of the datasheet for the Mega2560 IC http://ww1.microchip.com/downloads/en/devicedoc/atmel-2549-8-bit-avr-microcontroller-atmega640-1280-1281-2560-2561_datasheet.pdf
As far as code goes, try the following (just tested with a small speaker, appears to change to pitch as expected, but I don't have a motor to try it on:
Each line sets the frequency for timer2 (PWM 9 and 10), should be ok to do during setup, and settings will remain. Note that the first line is equivalent to normal default values:
  TCCR2B=(TCCR2B&248)|4;    //prescaler=64, f=977Hz

  TCCR2B=(TCCR2B&248)|3;    //prescaler=32, 1953Hz

  TCCR2B=(TCCR2B&248)|2;    //prescaler=8, 7812Hz

  TCCR2B=(TCCR2B&248)|1;    //prescaler=1 62500Hz

Also check that your motor driver can handle the frequency.

Thanks. That helps a bit but I really need to get to 20-25 kHz. That is the only frequency I've had luck using with this motor and not getting any audible artifacts. Any ideas?

Those dividers and frequencies are based on a 16MHz clock and 256 step PWM range. If you can change the basic processor frequency, that would help, but will probably break a lot of other things.
Changing the number of PWM steps is possible, but not something I've tried. You would need to change the value at which the PWM counter wraps around back to zero. This is normally 255, but if you used prescaler=8 and got the wrap around to occur at 85, you should get 23.4kHz, but your useful PWM range would be 0-84 instead of 0-255 steps.

That helps some but I am still having a lot of difficulty understanding why getting a PWM range at the correct frequency is such a battle. I'm getting ready to look at hardware solutions. Is there really no effective procedure for making these kinds of changes? One that doesn't break other things or restrict functionality?

The short answer to why it's so hard is that 'Arduino isn't designed to do that', and for the most part, it seems most people don't need it. And for pretty much any other language apart from Arduino, you're going to have to deal with tweaking the registers at this level (even to set up PWM to work at all, let alone customise it).


text:
Generated frequency is not as expected
This code sets a pin HIGH for 1 microsecond and then LOW for 1 microsecond. The expected frequency should be about 500 kHz. When measuring the output the frequency is about 96.4khz. Why ?
int del = 1;

void setup() {
   // put your setup code here, to run once:
pinMode(3, OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:

digitalWrite(3, HIGH);
delayMicroseconds(del);
digitalWrite(3, LOW);
delayMicroseconds(del);

}

Your code says 1 microsecond, but delayMicroseconds is actually much slower than that.  Also the loop has some overhead.  Try putting the code inside while(true){ }.  Recent versions of the Arduino IDE have got better at making code faster, but if you want timing accuracy it is better to use low-level timer/counters of the AVR.

digitalWrite() takes a few microseconds to execute as well. There is also some overhead around the delayMicroseconds() function.
If you need exactly 500 kHz, you would want to consider using a timer.
You can read up on how to set one up in the microcontrollers datasheet.
Unfortunately, I don't have access to an Arduino Leonardo, but here is an example code for the ATmega328P. The register names will be different, but you should be able to adapt the code to fit your Arduino.
// 500 kHz frequency

void setup() {
  cli();                 //Disable interrupt during setup
  TCCR2A = 0;
  TCCR2B = 0;

  TCCR2B |= (1 << CS20); //Enable timer without prescaler
  OCR2A = 15;            //Do interrupt TIMER2_COMPA after reaching this counter value
  TIMSK2 |= (1 << 1);    //Enable TIMER2_COMPA interrupt

  DDRD |= (1 << PORTD3); //Set Digital Pin 3 as Output Pin
  sei();                 //Enable interrupts again
}

ISR(TIMER2_COMPA_vect) { //If the counter has reached the point where the output needs to be low
  TCNT2 = 0;
  PIND |= (1 << PORTD3); //Toggle Digital Pin 3
}

void loop() {
  //your looping code here
}

Explanation:
TIMER2 is an 8-bit timer, which means it will always count from 0 to 255, regardless of what the CPU is doing.
Normally, it counts up at the Arduino's clock frequency, like 16 MHz.
When the counter hits 15, a special code is immediately executed, called an "Interrupt Service Routine". In this code, we reset the timer and change the state of your output pin, resulting in a 500 kHz square wave on that pin.
We count to 15 since there are 16 steps in between "0" where the counter begins and 15, where we reset it.
16'000'000 Hz / 1 (no prescaler) / 16 (counter) / 2 = 500 kHz
The divisor of 2 comes from the fact that we need to change the pin state twice for every full square of the output signal.

Sometimes you write 500kHz, then you write 500Hz. As calculated the code is for 500Hz. As the OP asked for 500kHz, the prescaler could be set to 1 and the compare value (at which the timer fires the interrupt) to 16. In my calculation this gives you exactly 500kHz. Am I right?

But as you wrote, digitalWrite() takes to long, so bit manipulation on the port registers are the right way to go: https://www.arduino.cc/en/Reference/PortManipulation

Yes, of course, I'm so sorry. This is what happens when you recycle code after a long work day. I'll fix it. And you're also right, digitalRead and -Write are too slow for 500 kHz, I'll implement it via the registers.

You could use one of the hardware time outputs like OC2A or OCRB and avoid the ISR/digitalWrite/bitbanging overhead entirely.

It's fixed now - so sorry again.
My scope isn't fast enough for 500 kHz, but it works as intended for 50 kHz.
The "standard" outputs are nice, but you're then limited to the two pins per timer. Is that already necessary at 500 kHz?

I think you answered the question as to 1) why: b/c overhead, 2) solving the 500kHz problem.  But if ISR overhead is still a problem  at this or higher freqs, he might have to tune with a smaller-than-calculated threshold, or go to hardware toggling on an OCxx pin.

https://www.arduino.cc/en/Tutorial/SecretsOfArduinoPWM has a "Fast PWM Mode with OCRA top" section for this use case.

delayMicroseconds() has a minimum lower value of 3-4 us per the IDE documentation. It won't do 1.
loop() also adds some delay mechanisms doing it's background stuff.
You will see better results with a while() :
loop(){
  while (1){
  digitalWrite(3, HIGH);
  delayMicroseconds(del);
  digitalWrite(3, LOW);
  delayMicroseconds(del);
  }
}

with direct port manipulation in place of the digital writes.
There will also be jitter from the millis() background time keeping, if you want a smoother signal it will be best to turn off interrupts as well.


text:
Reading values with HC-05 and sending commands at the same time working inconsistently
Not good at coding at all, so I'm at a total loss here.
But I'm doing a project that involves controlling a larger DC voltage through a mosfet.
What I'm doing is I'm using a HC-05 to transmit data between a phone and the Arduino Uno. Seeing the value within a couple of seconds is necessary.
However, sending the mosfet gate a command to open or close up work very inconsistently. Sometimes never and sometimes it takes up to 30 seconds for it to register.
The code here is a short version of the project that I'm working on, but behaves similarly.
#define mosfet 11
int state = 0;
int gate = 0;
int maxgate = 255;
int mingate = 0;

void setup() {
  delay(2000);
  pinMode(mosfet, gate);
  analogWrite(mosfet, 0);   //starts closed
  Serial.begin(9600);
}

void loop() {
  while(Serial.available() > 0){
    state = Serial.read();

    for (int y=0; y <= 5; y+=5){
      delay(500);
      Serial.println("testphase 1");
      delay(500);
    }

    for (int y=5; y >= 0; y--){
      delay(250);
      Serial.println("testphase 2");
      delay(250);
    }

    if (state == '0') {
    gate = gate + 1;
    if(gate > maxgate) gate = maxgate;
    analogWrite(mosfet, gate);
    Serial.println(int(gate));Serial.print(", +1");
    state = 0;
    }

  if (state == '1') {
    gate = gate + 10;
    if(gate > maxgate) gate = maxgate;
    analogWrite(mosfet, gate);
    Serial.println(int(gate));Serial.print(", +10");
    state = 0;
    }
}
}

When sending 'State == 1', for example it will go through both for loops multiple times and the maybe sometimes do gate + 10. Sometimes the commands goes completely ignored.
I have no idea how I would interrupt a loop to execute the given command and then go back.

Why do you have these for loops? If you want to do something timed but also be responsive to commands you can make your code non-blocking, like in the BlinkWithoutDelay example of the Arduino IDE.

The pinMode() seems incorrect (because of the variable gate bring where the pinmode constant should be). But that shouldn't be a problem, since analogWrite() configures the pin correctly.

How do you know, that it takes so long? Are you measuring the PWM signal, which goes to the MOSFET? You would need to send many times '0' or '1' to get to the maximum value

Those state changing IF-loops are just a few of the many I have in my code, but I cut out most to just test the code. Even adding a +1 or a +10 to the gate variable should show some signs of life on an LED I'm using to test the system, before I hook it up to a more powerful DC source.

Also, adding to my previous comment. How do I know it takes so long? It should print the current value + the added amount when a change is detected and the change should be easily observable with the green LED that I'm using for testing. Although I now see that it actually just prints the current value + the added amount.

Also, why for loops? Honestly it is just me lack of experience with coding stuff and something I thought I'd try out. I have a version that doesn't have the for loops now. Work quite similarly to be honest.. maybe a tab bit more responsive. How important would the placing of those 'if(state == x)' statements be?

Actually got it working myself, but thank you so much for your help @chrisl
Ditched the for loop completely just to try things out and reorganized my code a bit. Surprisingly it started to work well enough.
Basically just moved my measuring stuff outside the while loop*(and now that I think about it, why would it ever be withing the while loop? Literally makes no sense)* and to the end of the whole void loop part, and only polled for state changes within the while loop while the BT connection was active.
Doesn't miss a command as far as I can tell, and the adjustment is within 2 seconds when using my whole code, which is perfect. Also the whole program doesn't just freeze itself while trying to think what happened when the change set was send.
Here's a short version, should somebody bump into this thread in the future.
void loop() {
   while(Serial.available() > 0){
    state = Serial.read();

  if (state == '0') {stuff happens here,
    }
    }  //End of the while loop.

  sensors.requestTemperatures();
  delay(1000);
  Celcius=sensors.getTempCByIndex(0);
}


text:
Arduino based attendance system
I am working on a RFID based attendance system. I am using Grove-125 kHz RFID reader, SD card module, DS1307 RTC and Arduino Mega. Each component works alone (separately) with the Arduino well, but whenever I combine them, nothing happens. If I remove the ground or VCC pin of the SD card module, than the code works well. Here is my code:
#include <SPI.h> // for the RFID and SD card module
#include <SD.h> // for the SD card
#include <RTClib.h> // for the RTC
#include <SoftwareSerial.h>
SoftwareSerial RFID(10,11); // RX and TX
#define CS_SD 4
File myFile;
RTC_DS1307 rtc;
int count=0;
const int buzzer1= 5;
int data1 = 0;
int tag1[14] = {2,48,67,48,48,55,52,51,52,66,66,70,55,3};
int tag2[14] = {2,48,67,48,48,55,52,57,48,48,55,69,70,3};
int tag3[14] = {2,48,67,48,48,55,52,56,65,65,55,53,53,3};
int tag4[14] = {2,48,67,48,48,55,52,51,68,65,70,69,65,3};
int tag5[14] = {2,48,67,48,48,55,52,57,51,69,68,48,54,3};
int newtag[14] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0}; // used for read comparisons

void setup()
{
  pinMode(buzzer1, OUTPUT);
  RFID.begin(9600);    // start serial to RFID reader
  Serial.begin(9600);  // start serial to PC
  while(!Serial);
  SPI.begin();
  Serial.print("Initializing SD card...");
  if(!SD.begin(CS_SD)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");

  // Setup for the RTC
  if(!rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while(1);
  }
  else {
    // following line sets the RTC to the date & time this sketch was compiled
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  }
  if(!rtc.isrunning()) {
    Serial.println("RTC is NOT running!");
  }

}

boolean comparetag(int aa[14], int bb[14])
{
  boolean ff = false;
  int fg = 0;
  for (int cc = 0 ; cc < 14 ; cc++)
  {
    if (aa[cc] == bb[cc])
    {
      fg++;
    }
  }
  if (fg == 14)
  {
    ff = true;
  }
  return ff;
}

void checkmytags() // compares each tag against the tag just read
{
  if (comparetag(newtag, tag1) == true)
  {
  count=1;
     Serial.print(count);
   Serial.println("Amimul");
  }
  else if (comparetag(newtag, tag2) == true)
  {
  count=2;
     Serial.print(count);
   Serial.println("Amimul");
  }
   else if (comparetag(newtag, tag3) == true)
  {
   count=3;
      Serial.print(count);
   Serial.println("Amimul");
      Serial.print(count);
   Serial.println("Amimul");
  }
   else if (comparetag(newtag, tag4) == true)
  {
   count=4;
   Serial.print(count);
   Serial.println("Amimul");
  }
   else if (comparetag(newtag, tag5) == true)
  {
   count=5;
      Serial.print(count);
   Serial.println("Amimul");
  }
}

void readTags()
{
  if (RFID.available() > 0)
  {
    delay(100); // needed to allow time for the data to come in from the serial buffer.
    for (int z = 0 ; z < 14 ; z++) // read the rest of the tag
    {
      data1 = RFID.read();
      newtag[z] = data1;
    }
    RFID.flush(); // stops multiple reads
    tone(buzzer1,4000);
    delay(300);
    noTone(buzzer1);
    checkmytags();
  }
}
void logCard(){
     digitalWrite(CS_SD,LOW);
    myFile=SD.open("Sir.txt", FILE_WRITE);
    if(myFile){
      if(count=="1"){
        myFile.print("Ridwanul basit,1\n");
        Serial.println("Ridwanul basit");
      }
        if(count=="2"){
        myFile.print("Afik Arman,2\n");
        Serial.println("Afik Arman");
        }
        if(count=="3"){
        myFile.print("Afnaf Tahmid,3\n");
        Serial.println("Afnaf Tahmid");
        }
        if(count=="4"){
        myFile.print("Al Mahmud,6\n");
        Serial.println("Al Mahmud");
        }
       if(count=="5"){
        myFile.print("Fahim Muntasir,11\n");
        Serial.println("Fahim Muntasir");
      }
    myFile.print(", ");
    DateTime now = rtc.now();
    myFile.print(now.year(), DEC);
    myFile.print('/');
    myFile.print(now.month(), DEC);
    myFile.print('/');
    myFile.print(now.day(), DEC);
    myFile.print(',');
    myFile.print(now.hour(), DEC);
    myFile.print(':');
    myFile.println(now.minute(), DEC);
    myFile.close();
    }
    digitalWrite(CS_SD,LOW);
    delay(100);
}
void loop()
{
  readTags();
  logCard();
  delay(10);
}

Does the initializing code send the correct messages, marking that the initialization was successfull? You should see some serial output, if the sketch is running. Please copy&paste the serial output to your question.

why do you use SoftwareSerial on Mega with 4 hardware serials?

what did you try to debug the problem? some debug prints? removing one of the components?

Yes.It initializes the sd card.And then nothing happens.@chrisl

Because I have to change the code multiple time.So,if i use hardware serial,i will have to remove Tx and Rx pin again and again.@Juraj

The Serial output is only this line:"Initializing Sd card..........Initialization done"

Please don't post images of text. Copy&Paste the text directly into the question an format it with the {} button as code. (Is easier to read then)

Get's something written into the file on the SD card?

And please show us your wiring (schematics or wiring diagram)

@amimulahsan Only Serial (pins 0/1) are affected by uploading the sketch. The other three serial ports are completely independent. You should be using those, not SoftwareSerial. SoftwareSerial is a last resort.

RFID.flush(); // stops multiple reads -- No it doesn't. It blocks until all pending writes have completed. Flush changed in operation with Arduino 1.0.0.

Yes.Only an empty text file is written.@chrisl

So what should i do@Majenko

can anyone please give me a better coding idea to make a 125hz rfid reader based attendence system?

@amimulahsan What should you do with what? The flush? Just delete it, it's pointless. The SoftwareSerial? Use TX1/RX1 pins and the Serial1 object. Or TX2/RX2 and Serial2. Or TX3/RX3 and Serial3.

I just deleted it.But the result are still the same@Majenko


text:
Totally unresponsive card with RFID-RC522 Module
I bought an RFID-RC522 module including two attached PICC cards: a blue key chain tag and a white card with the type of MIFARE 1KB. In addition, I bought two other separate cards from the same seller.
I connected the module to an Arduino board and ran some examples of the library MFRC522.
Everything was OK with the two attached PICC cards (blue tag, and white card), BUT NOTHING worked with the other two cards, even they have no UID and NEVER RESPOND to the module. It seems to me that the internal microcontroller is not programmed. The seller doesn’t have any explanation. So, I need to know how to make them work.

so, the card you bought separately don't work ... are they 125KHz or 13.56MHz rfid? because they do look the same, but the MFRC522 only with one of those frequencies

Do you think that the cards bought separately are of the frequency 125KHz, so they don't respond to 13.56MHz  MFRC522 ?


text:
Alternate between 2 relays with one button
I have a very basic programming knowledge, but the thing I want to achieve is to alternate between switching 2 relays with a button or a RPi input pulse.
So something like this:

Press the button
Switch relay 1 on and off (1 second delay)
Press the button
Switch relay 2 on and off
Press the button
Switch relay 1 on and off (1 second delay)
Press the button
Switch relay 2 on and off
Press the button
Switch relay 1 on and off (1 second delay)
Press the button
Switch relay 2 on and off
etc.

Here's my code, I thought if I'd just put the second relay after the first else everything would work. But I'm missing some basic knowledge to figure this out.
const int ledPin = 2;
const int ledPinA = 3;

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(ledPinA, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  int sensorValue = analogRead(A0);
  Serial.println(sensorValue);
  delay(1);
  if (sensorValue > 500) {
    digitalWrite(ledPin, HIGH);
  } else {
    digitalWrite(ledPin, LOW);
  }
  if (sensorValue > 500) {
    digitalWrite(ledPinA, HIGH);
  } else {
    digitalWrite(ledPinA, LOW);
  }
}

I'm thinking I should use while.

Do you want it to swtch the relay on ONCE or repeatedly (so make them blink)?

Can you also switch between relays with a long press?

So something like this:

easy:

increment a counter based on button presses;
run a state machine on that counter to decide on relay actions.

the state machine can be a simple switch / case statement.

Thank you dannyf. It was simple indeed. Made a counter, ==1 switches relay 1 and ==2 switches the other and resets the counter.

The way you have it, both if blocks will be evaluated each time you call to loop(). Instead, you need to create a variable that remains "alive" in between each call to loop() to keep track of which relay you want to activate:
const int ledPin = 2;
const int ledPinA = 3;
int active_relay = 2;   // State variable for current relay pin

void setup() {
    pinMode(ledPin, OUTPUT);
    pinMode(ledPinA, OUTPUT);
    Serial.begin(9600);
}

void loop() {
      int sensorValue = analogRead(A0);

      Serial.println(sensorValue);

      delay(1);    // This delays for 1ms, not 1s ??

      if (sensorValue > 500) {   // Pulse received
          digitalWrite(active_relay, HIGH);  // Relay on
          delay(1000);                       // Wait 1 second
          digitalWrite(active_relay, LOW);   // Relay off

          // Update variable for next call to loop
          if (active_relay == ledPin) {
              active_relay = ledPinA;      // Swap
          }
          else {
              active_relay = ledPin;       // Swap
          }
      }
      // Remove 2nd if block
}

I'd use the digital reading of the pin with some debounce; if the read value must be analog (but only the OP knows this) maybe a bit of filtering is needed