text:
All AT commands return Fail
I'm trying to send data from sensor to ThingSpeak, but the AT commands always return Fail. They work sometimes and send data.  But, most of the time they return fail.
My Connections:

ESP
Arduino

Gnd
Gnd

Vcc, ChPD/En
3.3v

Rx
2

Tx
3

My code:
#include <SoftwareSerial.h>

#include "DHT.h"

#define DHTPIN 10
#define DHTTYPE DHT11

#define RX 2
#define TX 3

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

#define SensorPin 0          // the pH meter Analog output is connected with the Arduino’s Analog

#define ONE_WIRE_BUS 8

LiquidCrystal_I2C lcd(0x27, 16, 2);
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
DHT dht(DHTPIN, DHTTYPE);
float phValue;

String AP = "Mukadam";       // AP NAME
String PASS = "28oct1997"; // AP PASSWORD
String API = "ZIGGVWBPU0BJ9A0I";   // Write API KEY
String HOST = "api.thingspeak.com";
String PORT = "80";

String f1 = "field1";
String f2 = "field2";
String f3 = "field3";
String f4 = "field4";

int countTrueCommand;
int countTimeCommand;

boolean found = false;

int valSensor = 1;

SoftwareSerial esp8266(RX,TX);

float Celcius=0;
float Fahrenheit=0;

float b;

int buf[10],temp;

unsigned long int avgValue;

void setup()
{
  lcd.begin();
  lcd.backlight();
  Serial.begin(9600);
  dht.begin();
  pinMode(13,OUTPUT);

  sensors.begin();

  lcd.print("WT:");

  esp8266.begin(115200);

  sendCommand("AT",3,"OK\r\n\r\n");
  sendCommand("AT+CWMODE=1",5,"OK");
  sendCommand("AT+CWJAP=\""+ AP +"\",\""+ PASS +"\"",20,"OK");
}

void loop()
{
  sensors.requestTemperatures();
  Celcius=sensors.getTempCByIndex(0);
  Fahrenheit=sensors.toFahrenheit(Celcius);

  Serial.print("C:");
  Serial.print(Celcius);

  lcd.setCursor(3,0);

  lcd.print(Celcius);

  String getData = "GET /update?api_key="+ API +"&"+ f1 +"="+String(Celcius);

  sendCommand("AT+CIPMUX=1",5,"OK");
  sendCommand("AT+CIPSTART=0,\"TCP\",\""+ HOST +"\","+ PORT,15,"OK");
  sendCommand("AT+CIPSEND=0," +String(getData.length()+4),4,">");

  esp8266.println(getData);

  delay(1500);countTrueCommand++;

  sendCommand("AT+CIPCLOSE=0",5,"OK");

  for(int i=0;i<10;i++)       //Get 10 sample value from the sensor for smooth the value
  {
    buf[i]=analogRead(SensorPin);
    delay(100);
  }

  for(int i=0;i<9;i++)        //sort the analog from small to large
  {
    for(int j=i+1;j<10;j++)
    {
      if(buf[i]>buf[j])
      {
        temp=buf[i];
        buf[i]=buf[j];
        buf[j]=temp;
      }
    }
  }

  avgValue=0;

  for(int i=2;i<8;i++)                      //take the average value of 6 center sample
    avgValue+=buf[i];

  float phValue=(float)avgValue*5.0/1024/6; //convert the analog into millivolt
  phValue=3.5*phValue;                      //convert the millivolt into pH value

  digitalWrite(13, HIGH);
  delay(1000);
  digitalWrite(13, LOW);

  lcd.setCursor(9,0);
  lcd.print("pH:");
  lcd.setCursor(12,0);
  lcd.print(phValue);

  getData = "GET /update?api_key="+ API +"&"+ f2 +"="+String(phValue);
  sendCommand("AT+CIPMUX=1",5,"OK");
  sendCommand("AT+CIPSTART=0,\"TCP\",\""+ HOST +"\","+ PORT,15,"OK");
  sendCommand("AT+CIPSEND=0," +String(getData.length()+4),4,">");

  esp8266.println(getData);delay(1500);countTrueCommand++;

  sendCommand("AT+CIPCLOSE=0",5,"OK");

  lcd.setCursor(12,0);
  lcd.print(phValue);

  float h = dht.readHumidity();

  lcd.setCursor(0,1);
  lcd.print("H:");
  lcd.setCursor(2,1);
  lcd.print(h);

  float t = dht.readTemperature();

  lcd.setCursor(8,1);
  lcd.print("AT:");
  lcd.setCursor(11,1);
  lcd.print(t);
  lcd.setCursor(12,0);
  lcd.print(phValue);
}

void sendCommand(String command, int maxTime, char readReplay[]) {
  Serial.print(countTrueCommand);
  Serial.print(". at command => ");
  Serial.print(command);
  Serial.print(" ");

  while(countTimeCommand < (maxTime*1))
  {
    esp8266.println(command);//at+cipsend

    if(esp8266.find(readReplay))//ok
    {
      found = true;
      break;
    }

    countTimeCommand++;
  }

  if(found == true)
  {
    Serial.println("OYI");
    countTrueCommand++;
    countTimeCommand = 0;
  }

  if(found == false)
  {
    Serial.println("Fail");

    countTrueCommand = 0;
    countTimeCommand = 0;
  }

  found = false;
}

And here is serial monitor output:

work sometimes and always fail are contradictory statements ... you cannot have both .... how do the commands fail? .... what errors do you get? .... does any specific command work more often?

SoftwareSerial is unreliable at 115200 baud. use 9600 baud. you must change the baud rate in AT firmware too

@jsotola always fails as in it always give Fail & sometimes work means just 1 day or 2 it will send data

I'm fairly new to using esp8266 how to change firmware baudrate?

This answer (mine) describes how to change the ESP's power-on baud rate.

write and run a sketch which sends AT+UART_DEF=9600,8,1,0,0 at 115200 baud. you only need to run it once. the esp remembers the baud rate. or you can use this one https://github.com/jandrassy/WiFiEspAT/blob/master/examples/Tools/ChangeATBaudRate/ChangeATBaudRate.ino

@Juraj Can provide me with the change I have to make in my sketch. As I have mentioned I'm new to esp and am getting confused by the instruction and tutorials on the internet


text:
Pn532 and Node MCU SPI
I'm trying the Android Hce example in this PN532 library. The serial monitor gives me "Didn't find PN53x board". Can someone help me?
#if 1
  #include <SPI.h>
  #include <PN532_SPI.h>
  #include "PN532.h"

  // SPI connections
  //GPIO 12   MISO
  //GPIO 13    MOSI
  //GPIO 14    SCK
  //GPIO 15 SS

  PN532_SPI pn532spi(SPI, 15);
  PN532 nfc(pn532spi);
#elif 0
  #include <PN532_HSU.h>
  #include <PN532.h>

  PN532_HSU pn532hsu(Serial1);
  PN532 nfc(pn532hsu);
#else
  #include <Wire.h>
  #include <PN532_I2C.h>
  #include <PN532.h>
#endif

void setup()
{
  Serial.begin(115200);
  Serial.println("-------Peer to Peer HCE--------");

  nfc.begin();

  uint32_t versiondata = nfc.getFirmwareVersion();
  if (! versiondata) {
    Serial.print("Didn't find PN53x board");
    while (1); // halt
  }

        // Got ok data, print it out!
  Serial.print("Found chip PN5"); Serial.println((versiondata>>24) & 0xFF, HEX);

Please share the full void setup as well as the loop and add your circuit. Did you check your connections if it doesn't find it?

@Juraj, So it is.  Thanks.

@PythonSchlange . I have shared the setup code above but it is not going in the loop part because when chip is not found it halts. I am mentioning here connections between esp8266 and pn532                                                                                //GPIO 12      MISO
//GPIO 13    MOSI
//GPIO 14    SCK
//GPIO 15    SS

@MuhammadUsman Are you sure all wires are perfectly connected? Did you measure the connection? I think it rather is a connection problem not a code problem, because you use the example. Please add an image of your setup to the question.

@PythonSchlange. Thank you for your help I was able to solve the problem by changing the SS line from GPIO 15 to GPIO 10. Thanks again for your help

source: Stack Exchange

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

sort: votes


text:
Getting different numbers after sending an unsigned int 8-9 times between Arduinos via Serial
I am trying to transfer unsigned int values between 2 Arduinos. When sending 61805 for the first 8-9 times, I am getting 61805.  But after then after these numbers: 61937 28013 61937.
Sender's code:
unsigned int s = 0;

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

void loop()
{
  s = 61805;
  Serial.write(highByte(s)) ;
  Serial.write(lowByte(s));
}

Receiver's code:
unsigned int upperByte, lowerByte, r=0,p=0;

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

void loop ()
{
  if (Serial.available() > 1)
  {
    upperByte = Serial.read();
    lowerByte = Serial.read();
  }

  r = (upperByte << 8) + lowerByte;
  Serial.println(r);
}

There's no flow control on the Uno and Nano serial and you are sending fast enough that bytes are being dropped, and there's no way your protocol or lack of one demarcates separate messages (separate numbers).
This will become more clear if you write your numbers in hexadecimal:

Dec
Hex

61805
0xf16d

61937
0xf1f1

28013
0x6d6d

61937
0xf1f1

Adding a delay between messages can serve to separate the messages if the receiving side makes use of a timeout and can prevent the receiving side from being overwhelmed with data.
If you don't want to use time to slow down and separate your data, you can change what is sent instead.  One idea is to have the receiver actively request data when it's ready to receive some. The receiver should expect only entire messages between requests, and if anything gets garbled, it can just read whatever data has come in and throw it out before the next request.
Your messages can also be separated by some characters that aren't part of the messages themselves.  A common way to do that is just to encode your numbers as separate text lines, the line terminator \n serving as the separator between messages.
I have not tested these yet, but here are some very minimal modifications to your code that approach having a protocol with fewer of these problems:
Sender:
void setup () {
  Serial.begin(9600);
}

void loop() {
  // await message request
  while(Serial.read() != '.') {
  }

  //
  const unsigned int s = 61805;
  Serial.write(highByte(s)) ;
  Serial.write(lowByte(s));
}

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

void loop () {
  // request message
  Serial.write('.');

  // await two-byte response
  const unsigned long request_sent = millis();
  while (Serial.available() < 2 && millis() - request_sent < 1000) {
  }

  if (Serial.available() != 0) {
    if (Serial.available() == 2) {
      // two byte response receive
      const unsigned upperByte = Serial.read();
      const unsigned lowerByte = Serial.read();
      const unsigned r = (upperByte << 8) + lowerByte;
      Serial.println(r);
    }  else {
      // Something went wrong, too or too few bytes received;
      // throw them out and start over.
      delay(100);
      while (Serial.read() != -1) {}
    }
  }
}

It's a long way from doing it properly, but it should behave at least better than what you started with.  There's a lot to designing even simple protocols.  Typically there are start and end frame bytes, a checksum or CRC, a message number counter, etc.

thanks brother it worked .....thanks a lot....

We use to send 8,N,2 and receive on 8,N,1. That gave us an extra bit time to adjust for clock skew.

This line of the receiver's code:
Serial.println(r);

is transmitting 7 bytes (5 digits, CR and LF). At 9600/8N1, each byte
takes 1.04 ms, so the whole message is transmitted in 7.28 ms. In the
meantime, the sender is sending 2-byte messages at full speed (no pause
between the bytes). The receiver thus gets a new message every 2.08 ms.
So, this receiver is given a new message to relay every 2.08 ms, and it
needs 7.28 ms to relay each message. Something has to give...
The reason it works in the beginning is that the receiver has a buffer
where it stores the bytes that have been received, and another one for
the bytes that have been made ready for transmission. As long as there
is room in those buffers, everything works fine. The transmit buffer
fill-up first, as it gets 7 bytes to transmit every 2.08 ms. Once it's
full, Serial.println() becomes a blocking function: it has to wait
for the buffer to have enough room. Your loop() then slows down to
match the speed of the transmission, which means you do not read the
receive buffer often enough. Then the receive buffer fills up, and you
start loosing bytes.

thanks brother for you effort.... nicely explained... got the point

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


text:
Arduino nano timing precision
How precisely can an Arduino nano be timed? The project I am working on needs two Arduino nano to work synchronously. Arduino one have to activate a relay after 2700 sec and Arduino two have to activate a second relay after 2700.360 sec (360 milli seconds after )
With the code given below the required accuracy is not achieved.
volatile uint32_t ovfCount = 0UL;
volatile uint32_t currentTime = 0UL;
volatile unsigned long time_prev = 0UL;
volatile unsigned long dT = 0UL;

unsigned long delayTime = 2700UL;     //Seconds
unsigned long coilActivateTime = 5UL;  // seconds

volatile unsigned long _waitTime = delayTime * 1000UL + 360UL;
uint32_t _burnTime = coilActivateTime * 1000UL;

volatile bool coilOn_flag = false;

ISR(INT0_vect) {

  EIMSK = 0b00000000;

  TCCR1B = B00011100;
  PORTB ^= (1<<0);
  ovfCount = 0;
  TIFR2 = 0;
  TCNT2 = 0;

}

ISR(TIMER2_OVF_vect) {
  ovfCount++;
}

ISR(TIMER1_OVF_vect) {
  //pass
}

ISR(TIMER1_COMPA_vect) {
  //pass
}

ISR(TIMER1_COMPB_vect) {
  uint8_t tcnt2 = TCNT2;
  uint32_t ovf_count = ovfCount;

  if (bit_is_set(TIFR2, TOV2) && tcnt2 < 128) {
    ovf_count++;
  }

  uint32_t totalCount = ovf_count << 8 | tcnt2;  // raw count
  // uint32_t currentTime = totalCount * 0.004;     // milli second
  currentTime = totalCount * 4UL/1000UL;  // milli second

  if (currentTime >= _waitTime) {
    PORTC ^= (1 << 5);   // relay Switch
    TCCR1A = B00000010;
    TIMSK1 = B00000101;
    PORTB |= (1<<1);
    if (coilOn_flag) {
      TCCR1B = 0;
      PORTB ^= (1 << 1) | (1<<0);
    }
    coilOn_flag = true;
    _waitTime = _burnTime;
    ovfCount = 0;
    TCNT2 = 0;
  }
}

void setup() {
  Serial.begin(115200);
  /*setting the pin directions*/
  DDRB |= (1 << 1) | (1 << 0); // gL, rL
  DDRC |= (1 << 5);  // relay
  DDRD &= B11111011; // interrupt- interrupt

  /* INITIAL STATE SETTING FOR THE PINS */
  PORTB &= B11111100; // rL, gL
  PORTC &= B11011111; // relay

  /* 8Bit Timer*/
  TCCR2A = 0;
  TCCR2B = 0;
  TCCR2A = B00000011;
  TCCR2B = B00001100;
  OCR2A = 250;
  TCNT2 = 0;
  TIFR2 = 0;
  TIMSK2 = B00000001;

  /* 16 bit timer */
  TCCR1A = 0;
  TCCR1B = 0;
  TCCR1A = B10000010;
  // TCCR1B = B00011100;
  TCCR1B = 0;
  ICR1 = 62461;
  OCR1A = 6206;
  OCR1B = 624;
  TCNT1 = 0;
  TIFR1 = 0;
  TIMSK1 = B00000111;

  /* External INTERRUPT */
  EICRA = 0b00000010;
  EIFR = 0;
  EIMSK = 0b00000001;

  PORTB ^= (1<<0);
}

void loop() {

}

How to correct the code.?

you said nothing about the required precision of the two values ... you also did not say if there is anything wrong with the code

The internal clock of an Arduino is not really good for timing long durations with high precision (due to manufacturing differences and clock drift with temperature). For that a RTC (Real Time Clock) would be needed. Though: If you only need precision in the time difference between the two relay activations, then you could trigger the second Arduino from the first to start the timing there. Millisecond range is normally easily reached with Arduinos

why can't one Arduino control both relays?

both are going to be inside 2 different systems. I do start the clock on both at the same time using a common interrupt signal.

The Arduino Nano is nowhere accurate enough for your application, and
this has nothing to do with your code: it is a hardware limitation. 360
extra milliseconds after 2,700 seconds is a difference of only
133 ppm (parts per million). The Arduino Nano is clocked off a
ceramic resonator, and these time sources carry a typical error of the
order of 1,000 ppm. The best thing the code can do is count the
clock cycles with perfect accuracy, which makes the software timing as
good as the underlying hardware, but never better.
Some options you may try:

The one that seems most obvious is to have the first Arduino somehow
send a trigger signal to the second one when it activates the first
relay. Or have the second Arduino sense the state of that relay.
Then, all the second Arduino has to do is wait for 360 ms, which
it can easily do with reasonable accuracy.

If there is no way the Arduinos can communicate, then you could try
to add external time sources to the Arduinos. Some RTC modules can
output a 32,768 Hz signal that could be accurate enough for your
needs. Look for a temperature-compensated RTC, as those are more
accurate.

If you cannot add extra hardware, you could try to calibrate the
clocks of your Arduinos in order to compensate for their relative
drift. Keep in mind though that the drift rate is
temperature-dependent, and wanders randomly even at constant
temperature. First read the article Arduino clock frequency
accuracy, by Joris_VR, to get an idea of the accuracy you
could expect from such calibration.


text:
AMIS30543 - Library code | Order of pinDirection and pinOut
This piece of code was taken from AMIS30543- Arduino library,
void init(uint8_t slaveSelectPin) {
    ssPin = slaveSelectPin;
    digitalWrite(ssPin, HIGH);
    pinMode(ssPin, OUTPUT);
}

Facts I know

digitalWrite - makes the pin to the corresponding voltage level
pinMode - makes the pin either input or output
ssPin is active low pin usually.

So I was wondering before setting the pinDirection why the pin is made HIGH, Then immediately after that the pinDirection was declared as OUTPUT
Also I know , if a pin was made HIGH and on the next line if the direction of the same is set as  INPUT will bring the internal pull up resistor in action .
So what am I missing here. More over in Arduino does the order of pinMode/digitalWrite matter.? if So what is the meaning of this particular lines of code Github link to the library

The library is doing this to make sure, that the pin will never go low during initialization.
Imagine doing it the other way round:
pinMode(ssPin, OUTPUT);
digitalWrite(ssPin, HIGH);

If the corresponding PORT bit is set to zero (LOW) previously (which is also the standard after reset/power cycle), the pin will go LOW for a very short time, until digitalWrite() sets it HIGH again. That LOW time is short, but it might needlessly activate the slave. If you first use digitalWrite(ssPin, HIGH), you activate the internal pullup (as standard mode after reset/power cycle is INPUT) and set the corresponding PORT bit to 1. Thus, when you now change the pin mode, the pin is HIGH immediately, without ever going to LOW in between.
Internally the Arduino uses 3 SFRs (Special Function Registers), which are directly connected to the IO hardware of the pins. The DDR register of each port controls the "pin mode" aka direction of the pin (input or output). The PORT register controls the output value (HIGH or LOW; or turning the pullup resistor on or off in input mode). The PIN register reflects the current state of the pin (for reading it). In this case the double function of the PORT register is important, as it activates the internal pullup resistor, when set while in input mode.

This initialization will work with spi communication for PIC32 microchip too?


text:
How to use LCD Screen and IR Remote to broadcast a countdown
I am trying to use an IR Remote to input date's and time's for a countdown, so then the LCD will display a countdown, like this:
LCD: Enter Year
Remote-Input: 2021
LCD: Enter Month
Remote-Input: 08
LCD: Enter Day
Remote-Input: 20
LCD: Enter Hour
Remote-Input: 08
LCD: Enter Minute
Remote-Input: 00
LCD: Enter Second:
Remote-Input: 00
LCD: You have __ Years, __ Months, __ Days, __ Hours, __ Minutes, __ Seconds.

How do I do this?

GLHF! (You forgot to ask a question). However, my advice would be to do one thing at a time before connecting them all together.

@Paul Thanks for letting me know :)

https://arduino.stackexchange.com/tour

I know how to ask a question. I was just in a rush.

Thanks for editing my question, @timemage

No problem.  As is, the question is more of a "how do I do my project" type question, which isn't what the site is meant for.  Presumably you've made an attempt at this and ran into at least one specific problem, ideally an Arduino specific problem.  If so, you can edit your question to make it about that one thing, and then the answer might be of use to others.

How do I do this?

I have no clue how you do that but I do know I would do that.

I know how to ask a question.

Apparently not, your question is far from perfect (and my answer above is technically the only correct answer to that specific question). It doesn't tell us what you've tried, it doesn't tell us what you haven't tried. It not specific nor practical. Doesn't state your experience with Arduino, doesn't state which hardware you (would) be using. (Though I must say your example output thing is quite nice)

I was just in a rush.

Isn't everyone nowadays? And why would we invest time in an answer on a question which has no effort put into it?

You're basically asking "How to do an Arduino project" (or any project), there's many ways but let's dive into it.
0. Split up your project into smaller projects.
Since it sounds as if you have no clue on how to get started or if you feel this project is daunting, it may help to make the 'problem' easier to get started. You can always add more complexity.
Make one Arduino program, which shows "Hello World" on the LCD.
Make one Arduino program, which receives IR codes and depending on which button pressed, shows "Hello" or "World" in your terminal.
1. Research
Search the internet, maybe there's projects like this. Try to google for "Arduino Countdown Timer". Check what design choices they made, what hardware they use and how they work in general.
2. Design
Make a design, not only about the aesthetic part, but also functionally. What happens if the timer depletes? Should it also have a buzzer? Does it need an enclosure?
And technically, how will it be powered?
3. Acquire hardware
As a starter; it can help to buy hardware from stores that also include example code.
Use the example code to test and verify your hardware and connections.
4. Software
If you're asking "How to write software", you're better off starting out with some example projects/tutorials which include the code and explain it.
But basically you should use the example code to drive the hardware, use examples on the internet combined with your own experience to create a program that matches your required behavior.

If, along this path, you have a practical question. We will be much more able to, and happy to, help.

I apologize for not meeting your criteria. I was just trying to get some help before my class started, hopefully someone like you would come across and help me. I appreciate your tips. I will follow these and then come back to re-ask the question if necessary. Thanks again!

I found this website, which seemed to help:
https://create.arduino.cc/projecthub/hugonator/simple-lcd-timer-with-arduino-uno-ff3376

I like the buzzer idea. Would I use the active buzzer or passive buzzer? I don't know the difference.

An active buzzer will generate a tone by itself, so for simplicity use an active one. If you'd like to adjust the tone by yourself, you need a passive one.

Thanks! I have both :)

So I found a create.arduino.cc project that I had thought it was a countdown, but when I create it and upload it to my board, I found out that it's a timer. Like a kitchen timer. :I

A countdown is only different by doing -1 second instead of +1 second. And that you start at the maximum value instead of 0

Nice! thank you


text:
Servo starts spinning 360 degrees after a few minutes
I'm using my ESP8266 as a web server to tilt a camera with the servo Tower Pro Micro Servo 9G.
#include <Servo.h>
#include <ESP8266WiFi.h>

const char* ssid     = "SSID";
const char* password = "password";

Servo tilt;

WiFiServer server(8082);

void setup() {
  Serial.begin(9600);
  WiFi.begin(ssid, password);
  Serial.println("Connecting");
  while(WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to WiFi network with IP Address: ");
  Serial.println(WiFi.localIP());
  server.begin();
  Serial.println("Server started");
  tilt.attach(2);
  tilt.write(100);
}

void loop() {
  WiFiClient client = server.available();
  if (!client)
  {
    return;
  }
  Serial.println("Waiting for new client");
  while(!client.available())
  {
    delay(1);
  }
  String request = client.readStringUntil('\r');
  Serial.println(request);
  client.flush();

  int value = LOW;

  if(request.indexOf("/SERVO=UP") != -1){
        int t = tilt.read();
        if(t <= 125) {
          delay(10);
          tilt.write(t+8);
        }
  }
  if(request.indexOf("/SERVO=DOWN") != -1){
        int t1 = tilt.read();
        if(t1 >= 75) {
          delay(10);
          tilt.write(t1-8);
        }
    }

  client.println("HTTP/1.1 200 OK"); //
  client.println("Content-Type: text/html");
  client.println("");
  client.println("<!DOCTYPE HTML>");
  client.println("");
  client.print(" CONTROL Servo: ");

  if(value == HIGH)
  {
    client.print("ON");
  }
  else
  {
    client.print("OFF");
  }
  client.println("

");
  client.println("<button>ON</button>");
  client.println("<button>OFF</button>
");
  client.println("");
  delay(1);
  Serial.println("Client disonnected");
  Serial.println("");
}

The first minutes it works fine but after a few minutes it starts turning 360° nonstop. Although, you can't turn this servo over 180°?!
Does anyone of you know what is going on here?
Thanks!

Edited your link into the question.  You can get rid of the message.   So, this has been modified for continuous rotation or not?

No I haven't modified it.

Without it having been modified, I'm unable to make sense of "it starts turning 360° nonstop".

Thats why I'm confused ^^
Maybe it is some cheap china stuff ^^
But do you know why it starts rotating randomly?

You could remove the two calls to tilt.write in loop to eliminate the basic logic of the program from consideration.  If it is still behaving oddly, consider removing all of the WiFi related code, even the header, and see if that changes the behaviour.  If you servo still acts weird with nothing but a virtually empty sketch with little more than a call to tilt.write (and prerequisites) in setup(), if nothing else it makes for a cleaner question.

tilt.attach(2);  Did you attach the servo signal pin to GPIO #2 or to pin "D2" (which is probably GPIO #4)?

Why the use of client.flush() during the receive?  flush block until all data is sent.  It has nothing to do with the receive buffer.

If it works and then doesn't, it makes this seem like a mechanical issue.
To check, write a simple program that just moves the servo around. Leave out all the extra web code. Wait to see if starts behaving erratically and you can save yourself the headache of hunting issues in your code that don't exist.


text:
Buzzer+Push button+arduino
I want to stop the sound of a buzzer after I push the push button. I tried a code, but when the button is not pushed, the buzzer continue to make sound. How can I fixed it?
const int pin_contact= 6;
const int buzzer = 9; //buzzer to arduino pin 9

void setup(){
  pinMode(buzzer, OUTPUT); // Set buzzer - pin 9 as an output
  pinMode(pin_contact, INPUT);
  Serial.begin(9600);
}

void loop() {
  tone(buzzer, 200);

  int stare_contact = digitalRead(pin_contact);
  if (stare_contact == HIGH) {
    noTone(buzzer);
  }
}

i tried with screen capture, but I couldn't upload in the comment, this is why i used a link. But in the end, I succeeded, using the first code and added 2 resistors in the circuit. Thank you!

If one of the answers helped you, you can vote it up.  If neither helped you and you think you can provide an answer that someone else would find useful, you can answer your own question.  If the question is both unanswered and unanswerable, then it's probably better off deleted.

It is good to know. Right know I was trying to vote the answer, but i have to earn 15 reputation to upvote posts.

Ah, well, there's 10 for you.

You restart the buzzer sound on every iteration of loop() so as soon as you stop pushing the button, the sound starts again. The simplest solution would be to move the tone (buzzer, 200); command out of loop() and place it at the end of setup(). Also make sure your button actually reads “HIGH” when pressed. Many buttons are active “LOW”.

Try this
int LEDState = 1;
int SwitchPin = 6;
int LEDPIN = 9;

void setup()
{
  pinMode(LEDPIN,OUTPUT);
  pinMode(SwitchPin,INPUT);
  digitalWrite(LEDPIN,LEDState);
}

void loop()
{

  int SwitchState = digitalRead(SwitchPin);

  if(LEDState==1 && SwitchState==HIGH){
   LEDState = 0;
  }

  digitalWrite(LEDPIN,LEDState);
    delay(10);
}

Sorry Jsotla, i have fixed it now...  @Biancaaa I have fixed the code and i tried with an led except a buzzer because at this time buzzer is not available in my collections, afterall, try this code, this code worked very well for me using the LED as an output indicator instead of a buzzer

Is your buzzer active low? try this code below.
it will toggle buzzer pin output.
const int buzzerPin = 9;
const int buttonPin = 6;
int buzzerState = 1;
int buttonState;
int buttonTemp = 0;

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

void loop() {
  buttonState = digitalRead(buttonPin);
  digitalWrite(buzzerPin,buzzerState);
  if (buttonState == HIGH && buttonTemp == 0){
    Serial.print("Buzzer toggle to : ");
    if (buzzerState) {
        Serial.println("LOW");
        buzzerState = 0;
    } else {
        Serial.println("HIGH");
        buzzerState = 1;
    }
    buttonTemp = 1;
  } else if (buttonState == LOW) {
    buttonTemp = 0;
  }
}


text:
I2C pull up resistors and an I2C MUX
I have a rig with 5 light sensors on an I2C mux and I am wondering if I need only 1 pull-up resister set for the whole bus or one on each branch from the mux?
Or should I remove all the pull-ups from the branches and leave the one on the mux?
My issue is that the Arduino softlocks after 5-60 min of running, and it always softlocks on a read lux call.

From what I can tell, the I2C bus multiplexer itself receives and re-transmits on what amounts to a completely separate bus.  So, each bus would need its own pull-up resistors.  That said, the board you've linked that breaks out the multiplexer chip has pull-up resistors on each bus that it's providing:

The breakout also has pull-ups on the bus going to the multiplexor itself:

Beyond that, the ambient light sensor breakout seems to provide its own 4.7K pull-ups. AVR-based Arduinos (and probably others) also enable their own, admittedly weak, pull-ups in the guts of the wire library.
It seems you should not necessarily need to add any additional pull-up resistors of your own to what is already on the buses.

With regard to the O.P. comment given below concerned about too many pull-up resistors.
At some point probably below (perhaps far below) 500 ohms some devices may have trouble sinking enough current to create a LOW. The AVR wouldn't have a problem with 500 ohms for example.
The ATMega328P datasheet (along with most other AVR datasheets) will tell you that the internal pullup value is between 20K-50K.  If you're concerned about too-many-parallel-resistors/too-many-current-paths/too-little-total-resistence, you can take the 20K figure along with multiplexer breakout's 4.7K figure, to calculate pow(1 / 20e3 + 1 / 4.7e3, -1), for about 3.8K, which should be fine.  If you do the same calculation on the multiplexor's individual bus resistor 4.7k and the ambient light sensor breakout's own 4.7k resistor, you get 2.35 k (half), which is also probably fine.  If anything both of these total figures can be made smaller (by adding yet another parallel resistor) for longer buses and at higher frequencies.  If you're worried about these figures you can lower the I2C clock rate.  You can also examine the edges of your signal with a scope.  Also if you really want to dig into this stuff, you read in the official I2C manual.  But, really I think what you have is probably fine.

but do i have too many pull up resistors? i thought i am supposed to only have 1 set? should i remove the ones on the lux sensors then?

I've converted the bulk of my previous (now deleted) comment, addressing yours, into an addition on the answer.

Try replacing some of the bulk 1.0uF caps with something in the 10 - 100 nF range to add high frequency bypassing.


text:
WS2812B NeoPixels no longer working after cutting the strip and adding an extension
I am trying to use WS2812B LEDs with an Arduino.
I have 24 LEDs connected to pin 6.
When I first received the strip I connected it to 12V and data.
Using the cyclone example in the FastLED library worked.
But then I cut them and added extension wires.
I have 3 LEDs on single strip; so it is 8 strips of 3 LEDs.
The extension is about 30cm long.
Now when I power them, they just glow bright white.
So, I thought the extension wire was the problem.
I removed extension and connected them as they came.
But still, they are turning on bright white.
I connected the Arduino out to DIN.

I thought WS2812B LEDs took 5V, and not 12. If I'm right, you may have fried something. Also, check to see if you reconnected them the right way around; there are usually arrows/labels on the strip for guidance. You could try if you can get one strip of three LEDs to work with the right voltage, and take it from there.

WS2812Bs work at 5V. You may have fried them at 12V. Also, take care to connect the Dout of the first strip to the Din of the second, and so on.

Mate, I think you may fried the led strip, as the strip work on 5V (even with 3.3V iirc)... Anyways, just try to cut the first led and hook up your uC (arduino or any other) to the (back in time) 2nd led (now your first led of the strip)

Are these actually WS2812B or one of the other WS281x series parts?  A link to the exact thing you bought may help.


text:
Sharing clock pin on Pro Micro
I am trying to get both a SPI LED matrix display and an NRF24L01 to both work on the same Arduino Pro Micro. I know they both want to use the clock pin but how do I get them to share? Can I use the CS pin to turn off one device while trying to use the other? The display does can be set only when something needs to change so it's not always running.

"isp led matrix" was meant to read "SPI LED matrix" right?

Yes sorry I fixed it

You can indeed use different CS (chip select) lines to address individual SPI devices on a single bus run by an SPI “master”. The MOSI, MISO and SCLK lines can be reused and shared between perpiheral devices, as long as only one device is actively being addressed at any point in time.

It is indeed possible and supported to use different CS (chip select) or SS (“slave select”) lines to address individual SPI devices on a single bus run by an SPI “master”.

Image from Wikipedia
Many SPI TFT Touch displays need this to address the display controller and the touch controller as individual SPI devices and/or an integrated SD Card interface (wich also uses SPI).
The MOSI, MISO and SCLK lines can be reused and shared between perpiheral devices, as long as only one device is actively being addressed at any point in time. I.e. only one SS/CS may be active at any time and the software must support such sharing of SPI resources.

Welcome to 1K =)

@timemage Thanks!


text:
Mistake in keyboard typing by Digispark
I want to open notepad by my Digispark. I use this code:
/*  * Generated with <3 by Dckuino.js, an open source project !  */

#include <avr/pgmspace.h>
#include "DigiKeyboard.h"

const char line1[] PROGMEM = "notepad.exe";
const char line2[] PROGMEM = "Hello World!";

char buffer[256];

#define GetPsz(x) (strncpy_P(buffer, (char*)x, 256))
#define KEY_UP_ARROW      0x52
#define KEY_DOWN_ARROW    0x51
#define KEY_LEFT_ARROW        0x50
#define KEY_RIGHT_ARROW       0x4F
#define KEY_LEFT_GUI          0xE3
#define KEY_ESC               0x29
#define KEY_TAB               0x2B

void digiBegin() {
  DigiKeyboard.sendKeyStroke(0,0);
  DigiKeyboard.delay(50);
}

void digiEnd() {
  const int led=1;
  pinMode(led, OUTPUT);
  while (1) {
    digitalWrite(led, !digitalRead(led));
    DigiKeyboard.delay(1000);
  }
}

void printText(char *txt) {
  DigiKeyboard.print(txt);
  DigiKeyboard.update();
}

void setup() {
  digiBegin();

  DigiKeyboard.sendKeyStroke(KEY_R,MOD_GUI_LEFT);

  DigiKeyboard.delay(50);

  // notepad.exe   printText(GetPsz(line1));

  DigiKeyboard.sendKeyStroke(KEY_ENTER);

  DigiKeyboard.delay(100);

  // Hello World!   printText(GetPsz(line2));

  digiEnd();
} /* Unused endless loop */ void loop() {}

My program opened RUN Windows, but instead of typing "notepad.exe" it types "fgl]hY&]p]" and I don't know where am I am making mistakes. Please help me.
I have to write my code similar this:
#include "DigiKeyboard.h"

int pinled = 1;

void setup()
{
    pinMode(3, INPUT);

    digitalWrite(3, HIGH);
}

void loop()
{
    DigiKeyboard.sendKeyStroke(0);

    if(digitalRead(3) == LOW)
    {
        DigiKeyboard.sendKeyPress(KEY_R, MOD_GUI_LEFT);
        DigiKeyboard.delay(10);

        DigiKeyboard.sendKeyStroke(0, 0);

        DigiKeyboard.sendKeyStroke(KEY_C);
        DigiKeyboard.sendKeyStroke(KEY_M);
        DigiKeyboard.sendKeyStroke(KEY_D);
        DigiKeyboard.sendKeyStroke(KEY_ENTER);

        DigiKeyboard.delay(500);

        DigiKeyboard.sendKeyStroke(KEY_I);
        DigiKeyboard.sendKeyStroke(KEY_P);
        DigiKeyboard.sendKeyStroke(KEY_C);
        DigiKeyboard.sendKeyStroke(KEY_O);
        DigiKeyboard.sendKeyStroke(KEY_N);
        DigiKeyboard.sendKeyStroke(KEY_F);
        DigiKeyboard.sendKeyStroke(KEY_I);
        DigiKeyboard.sendKeyStroke(KEY_G);
        DigiKeyboard.sendKeyStroke(KEY_ENTER);
    }
}

What keyboard layout do you have active on your PC?

I tried to clean up the question a bit. You have // notepad.exe   printText(GetPsz(line1));, but I'm guessing these are two separate lines in the code you're actually running; likewise for line2.

when debugging code like yours, always print strings like 1111122222233333 or aaabbbccc .... that way you can tell if characters repeat, even if they are the wrong characters ... in your example, one character appears to repeat, but it us uncertain


text:
Rasberry Pi Controlling Arduino - Reads "Ghost" Input - Doesn't Complete Logic Loop
I am using an Arduino Atmega2560 clone, I have used it many times before with satisfactory results - although I haven't used it with my Rpi before.
My Raspberry Pi is model 4 (B I think?).
#define knap 49
#define motorOutput 8

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(knap, INPUT);
  pinMode(motorOutput, OUTPUT);
  digitalWrite(motorOutput, LOW);
}

void loop() {
  // put your main code here, to run repeatedly:
  int knapSensor = digitalRead(knap);
  Serial.print(knapSensor);
  if (knapSensor == 1) {
    int knapSensor = digitalRead(knap);
    Serial.print("aktiveret");
    digitalWrite(motorOutput, HIGH);
    delay(500);
    digitalWrite(motorOutput, LOW);
  }
}

Now I have double checked, the motor and the button is wired correctly. There is no hardware issue, aside from the cables being sh- quality.
Problem is, whenever I run this program two things will happen;
Either it starts fine by displaying "0000..." on the serial monitor.
Then when I press the button it goes to
"AktiveretAktiveretAktiveret..." even when I depress the button.
Or, it will just display "AktiveretAktiveretAktiveret...".
In either case the motor won't work.
Once again, I have done tests where I have removed the power from the breadboard and replaced the voltage pin for the motor with the voltage pin leading from the button.
First thing didn't change the input (i.e still "AktiveretAktiveret,") the latter started the motor.
I.e this isn't about bad wiring.
EDIT:
Added schematics and changed the code

checked, the motor and the button is wired correctly ... how do you know?

I strongly suspect a hardware issue. How are you providing power to the Mega2560 and the motor? How are you controlling the motor and how is the button wired (pulldown)? You are aware that, with the code you've shown, once you activate the motor output, it will never turn off?

Please show your wiring. You say the wiring is not bad, but we'll be the judge of that, not you.

Alright, I have added the schematics now.

@StarCat4 Wouldn't it change once the button reads nothing?

You set the motorOutput to HIGH when you detect that the button is pressed, bu you do not set it to LOW again when it is released. So it stays HIGH.

There's also nothing to pull the button output to LOW when the button is released so it is very vulnerable to noise. You should put a pulldown resistor of around 10K Ohms between pin 49 and ground to make the button more reliable.

@StarCat If I connect the button to ground won't it create a short circuit? How do you mean connect 10K ohms between pin 49 and ground?

See here The resistor needs to be between the button input pin and ground to give it a defined value when the button is released. The resistor to ground will make sure the pin reads "low" when no button is pressed. When the button is pressed, it will be connected directly to +5V and will read high. Only a small current (0.5mA) will flow from +5V to ground through the 10K Ohm resistor in that case. It will not create a short circuit.

@StarCat Thanks! It works great now! If you want to, you can post your comment as an answer and I will accept it.

I've made my comment into an answer. Good luck with your project!

Your button needs a pulldown resistor to work reliably.
See the discussion and solution here
The resistor, with a value of around 10K (but any value between 3K and 20K will probably do), needs to be between the input pin or your Arduino and ground to give it a defined value when the button is released.
Putting a resistor between the Arduino pin and ground will make sure the pin reads "low" when no button is pressed. When the button is pressed, it will be connected directly to +5V and will read high. Only a small current (0.5mA) will flow from +5V to ground through the 10K Ohm resistor in that case. It will not create a short circuit.

What motor are you using? If it works straight from the 5v but not from a GPIO, it could be an issue of insufficient power.
As @StarCat4 mentioned, you also need to add a digitalRead inside your while loop if you want the motor to ever turn off.

Well, the problem here is, that it doesn't even read the inputs correctly. So regardless of the motor, it still won't function.

It reads when you press the button in, correct? You'll never see a state change after pressing in the button because you haven't instructed the Arduino to look for it. Even if you release the button, the Arduino does not know to check state. Your while loop should read while (knapSensor == 1){  Serial.print("aktiveret");  digitalWrite(motorOutput,HIGH);  delay(500);  knapSensor = digitalRead(knap); }

Oops, forgot to edit the code.
It will occasionally print out "Aktiveret" and then go "0000...." i.e "000001Aktiveret " is the default pattern, when I am not pressing the button.
When I press the button it will go complete "00000".


text:
Can't manually connect HC-05 master to slave
Using this as a tutorial, I've tried to connect the master Bluetooth module from my Nano to the slave module in my Mega. After following the steps in the tutorial, when I enter the command to my serial monitor:
AT+BIND=98d3,31,30690

I receive:
ERROR:(7)

After looking up the error, I only get results for ERROR:(0)
Does anyone know what the error means or how to fix it?

Error Codes and their definitions

I found the solution.
Apparently, both of my modules were at 9600 baud rate when the optimal rate is of 38400. I had to use AT+ORGL in command mode to reset both slave and master. Afterwards I was able to connect them manually.
So apparently ERROR:(7) represents a failed connection? Just don't forget to make sure everything is exactly like the tutorial that's teaching you.

Error 7 is "Bluetooth address LAP is too long" Other Error Codes are here

You need to add zeros to your address.
For example my address of slave is "FCA8:A7:A134"
So command to bind it to master will be "AT+BIND=FCA8,7A,00A134"
XXXX:XX:XXXXXX

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


text:
Read frequency to voltage with Arduino
How to read frequency into voltage with Arduino with an external source of frequency of 0-1Khz max?

Wait, first of all what are you trying to achieve? Second, "what chip ... with arduino". Do you want an external IC or you want to do it with arduino?

yes external IC , im sorry for my english

What's wrong with using the Arduino to just measure the frequency directly?

i'm new with this things, but i found this pjrc.com/teensy/td_libs_FreqMeasure.html a library work with arduino for my range 0,1 - 1 KHz i think this will be fine , thank's for reply

I found this link. This is a library and will work with Arduino for my range 0,1 - 1 KHz. I think this will be fine.

In the past I used the LM2917 for this purpose:
http://www.ti.com/lit/ds/symlink/lm2907-n.pdf
That IC is a frequency to voltage converter, so it perfectly suits your need. According to some quick calculations I made it can go to some tens of kHz, so if your signal is up to 1kHz it should be fine.
Now, this is the answer to your question. But... You can easily read the frequency directly with the arduino... If your purpose was to read the frequency, I suggest you to read something about the X-Y problem

i found this https://www.pjrc.com/teensy/td_libs_FreqMeasure.html a library work with arduino for my range 0,1 - 1 KHz i think this will be fine , thank's for reply

@FrancescoValla ok, so you simply asked the wrong question. Now, please edit your question (but do not remove the original part) saying that your purpose was not to convert, but rather to read the frequency, so with that library you managed to solve your problem..

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


text:
How to transmit data from Arduino to Raspberry Pi?
I am planning to build a network with five Arduino Mega devices, each of which will collect data using multiple sensors. Each Arduino will periodically transmit the sensor data to a gateway Raspberry Pi using XBees. As it is the first time I am working with Arduino and Raspberry Pi, I need help with the following:

Which protocol to use to transmit data from Arduinos to the Raspberry Pi? Do I have to write code for both Arduino and Raspberry Pi or are there existing solutions that I can use for this purpose?
Does MQTT, Node-RED or Node.js have any role in the above?

Thank you for your advice!
A.

this looks like a repeat of your previous question ..https://arduino.stackexchange.com/questions/71291/software-for-communication-between-arduino-raspberry-pi-and-computer-server

@jsotola Yes, but I tried to be more focused this time. I hope I have been successful.

I have not bought the equipment yet. Before doing this, I would like to know the technologies involved and level of depth I would need to go into this. I think it should be straight forward for people who have experience with Arduino and Raspberry Pi to come with some good advice. Thank you for the edit.

MQTT messages are usually set over internet connections.  RaspberryPi boards have this type of interface.  Most Arduinos need to have extra hardware.  An MQTT broker can receive and send out messages.  If you want to do something with the messages between the sender and receiver NodeRED is a good choice.  You will likely want to run the MQTT broker (probably mosquitto) and NodeRED on the RaspberryPi.  Let me know if this is what you are looking for and I'll flesh out the particulars and post an answer to your question.

BTW, I don't know different your original post is, but consider making a question better before resorting to making another post.  The point of most if not all of the stackexchange web sites are to have a bunch of good searchable questions.

@st2000 Arduinos will use XBees for communication. So, no other hardware needed to send data to the RaspberryPi.

@AdnanAli, there are so many Arduino platforms that the only assumption that can be made when the OP does not specify a particular platform is to assume it is a Revision 3 Arduino Uno with no XBees or no Ethernet.   But I believe you are correct, that either can be added to the Revision 3 Arduino Uno to support sending and receiving MQTT messages.

Which protocol to use to transmit data from Arduinos to the Raspberry Pi? Do I have to write code for both Arduino and Raspberry Pi or are there existing solutions which I can use for this purpose?
Does MQTT, Node-RED or Node.js have any role in the above?

I have searched, explored, read and found that MQTT can be used to send and receive data from Arduinos to RaspberryPi as in [1] and [2]. So, no need to design and develop a new protocol.
MQTT libraries, such as PubSubClient [3] are available for Arduino. So Arduino code can use these libraries and no need to write much code either.
Simple and straight!
A.
[1] https://funprojects.blog/2018/03/04/arduino-talking-mqtt-to-node-red/
[2] https://iotdesignpro.com/projects/interface-arduino-with-node-red-to-send-sensor-data-on-webpage
[3] https://www.arduinolibraries.info/libraries/pub-sub-client


text:
aRest.io - how does it work?
With aRest.io you are able control your Arduino/Esp from all over the world - but how?
In the Client SourceCode (found here) you only find the PubSubClient, which is an MQTT client.
I'm assuming:
My Arduino can (during the aRest.h) subscribe to topics in my aRest.io dashboard (http://dashboard.arest.io/) and if I add something to the dashboard the aRest's Broker will inform my Arduino. But here is my error. How can the Broker contact my Arduino behind the firewall? Does the Arduino use hole punching? Is my attempt wrong?

The broker doesn't contact the Arduino - the Arduino contacts the broker.

So the Arduino is polling for commands ?

Not as such, no. It connects to the broker and sits there waiting for the broker to say something.

I have to test this tomorrow! Could it be really so easy... Thank you for the hint in the right direction

check this out ... visual representation of MQTT messages ... https://shiftr.io/shiftr-io/demo

The Client contacts the broker and
maintain the connection - waitung for topic to be updated.


text:
Send and receive text between Arduino Mega 2560 and C# via ENC28J60
I'm working on an Arduino project that sends and receives text to/from a C# application via ENC28J60 in a LAN network. Whenever C# sends a request to Arduino (In text), Arduino responds to it by sending also a text. What is the best way to do this? I'm newbie in network programming (Or whatever it's called). Thanls in advance :)

Use a TCP socket. Give the Arduino a static IP address, run a TCP server, and have the C# application open the connection as a TCP client.

@tttapa: you mean ENC28J60 is useless here ?

No, you need the ENC28J60 to connect the Arduino to the LAN. TCP is a network protocol that works on top of the physical connection that's established by the ENC.
This could be useful (it was written for the ESP8266, a WiFi chip for Arduino, but the principle is the same.

https://github.com/ntruchsess/arduino_uip/tree/master/examples       found this on github. I think its what youre talking about.

You can use TCP or UDP protocols.
https://www.arduino.cc/en/Tutorial/UDPSendReceiveString
https://www.arduino.cc/en/Tutorial/DhcpChatServer
You can use free UDP, TCP port listener sofwares for Windows, Linux etc.. for testing your setup.
For C# development:
https://stackoverflow.com/questions/20038943/simple-udp-example-to-send-and-receive-data-from-same-socket
and
https://stackoverflow.com/questions/10182751/server-client-send-receive-simple-text


text:
Disable auto-reset Mega 2560 on serial monitor open using 60 ohm resistor
I tried preventing my Arduino Mega 2560 from restarting every time I open the serial monitor. This link didn't work for me at all.
I tried connecting the RESET pin to 3.3v pin via a 60 ohm resistor and it worked for me. The question is: If I leave that resistor permanently connected, will this solution damage my board as time passes?

Personally I use a large capacitor between reset and ground. 22uF or greater should do it.

You should connect the resistor to 5V instead of 3.3V. There is no way you can damage the Arduino with this resistor, since the reset pin is pulled low by the USB-to-Serial chip through a (100nF) capacitor. So current can only flow for a tiny moment.

i already tried 5v with a 120ohm resistor but didn't work

A 22uF cap between reset and ground does work on my Mega 2560 - opening the serial monitor will not restart the program. However, the Mega is then not downloadable. Therefore, I grounded the cap thru a normally closed relay and connected its control to a digital output. I normally operate with the relay closed. When I want to download a new program I open the relay first. It works great :-)


text:
Problem using ICSC (by majenkotech) in RS485 bus
I want to communicate with an RS485 Bus consisting of 5 Arduino Pro Minis as slaves and one Arduino Mega 2560 as Master. I found a great library for this.
According to the documentation provided by the author of library I can use:
ICSC icsc(1, 9600, 7); //ID, BaudRate, DEpin
But I also have to define a Serial port for ICSC to work with:
ICSC icsc(1, 9600, Serial1);
I cannot mix these two sentences. I mean I cannot define both DEpin and Serial port for the ICSC in one sentence. But I need it to be defined. I don't want to use Serial for that, which I need for Serial Monitor. I want to use Serial1 for this. What can I do? I couldn't find any updated documentation about this.
UPDATE:
I found out how to define Serial port and DEpin for ICSC. The problem is I cannot get an answer!
Here is Master code:
#include <ICSC.h>
ICSC icsc(Serial1, 1, 7); //Stream, ID, DEpin

void setup() {
  Serial.begin(9600);
  Serial1.begin(9600);
  icsc.begin();
  icsc.registerCommand('R', &showTemperature);
}

void loop() {
  icsc.send(2, 'T', 0, NULL);
  icsc.process();
}

void showTemperature() {
  Serial.println("ACK");
}

And here is the Slave code:
#include <ICSC.h>
ICSC icsc(Serial, 2, 7); //Stream, ID, DEpin
String strAck = "ProMini2:ACK";

void setup() {
  Serial.begin(9600);
  icsc.begin();
  icsc.registerCommand('T', &sendTemperature);
}

void loop() {
  icsc.process();
}

void sendTemperature() {
  icsc.send(1, 'R', sizeof(strAck) + 1, (char*)&strAck);
}

Assume that there is just one slave and one master. I tried this code but got no answer. Where is the error?

The documentation for the constructors is out of date (I am re-writing as we speak, and is now here).
The constructors in the header file are like this:
ICSC(Stream *d, uint8_t station);
ICSC(Stream &d, uint8_t station);
ICSC(Stream *d, uint8_t station, int depin);
ICSC(Stream &d, uint8_t station, int depin);

That means you need to provide the serial object as the first entry:
ICSC icsc(Serial1, 'A', 5);

You need to manually start the serial object before ICSC.
void setup() {
    Serial1.begin(9600);
    icsc.begin();
}

This change was made to enable support for software serial and other Stream based devices.

Addendum for your update:

Don't spam the sending like you are. Send periodically, not constantly, or you will never be able to receive.
You cannot use String objects like that.
1 and 2 aren't good choices of station IDs. Yes, they work, but not great, since 1 is the SOH character.

But what if i begin both Serial and Serial1 right after eachother ? Which one will be assigned to ICSC?

Whichever one you assign to ICSC.

I'll give it a try tomorrow and will let you know. Thx in advance.

Can i use this constractors in current version of icsc which i'm using?

That is the constructors for the version on Github.

Question updated :)
I followed your guides, But i still have problem.

Answer updated also.

Thx, I can now send and receive data, but i still have problem sending string to master

Never use String. Use char *.

However, with ICSC there is little call to send strings. It's designed for transferring numerical data from sensors.

Now im able to send strings over ICSC. I realized a problem with ICSC: When i disconnect one of MAX485s from circuit, No other devices respond to master! For example i disconnected just DEpin of ProMiniC and then i couldnt get answer from both ProMiniB and ProMiniD

Disconnecting DE leaves it floating. You have a corrupt transceiver on the bus. Nothing to do with ICSC.

The documentation for the library notes a few different possible initialization methods:
ICSC.begin(stationId, baudRate);
ICSC.begin(stationId, baudRate, &SerialPort);
ICSC.begin(stationId, baudRate, &SerialPort, DEPin);
ICSC.begin(stationId, baudRate, DEPin);

So, if you need to define both a serial port and DE Pin, use the third option.
EDIT: Disregard this answer, as the library has changed initialization methods.

I tried that, but gives error: No overload method matches the (int, int, &, int) was found. Something like that :)

That documentation is out of date.


text:
CAN bus communication and LCD updation
I am trying to communicate arduino uno with CAN bus using MCP2515 shield.
Data sending and receiving both things are done.
Whatever data received is displayed on LCD.
CAN bus receive is done using interrupt of timer1 and LCD updating using interrupt of timer2.
I think LCD does not get enough time for updating hence garbage data appears on LCD.
So please suggest me solution so that I can get Both CAN communication and LCD updation.
I am posting my code for your reference.
#include <Wire.h>
#include <CAN.h>
#include <Adafruit_ADS1015.h>
#include <EEPROM.h>
#include <LiquidCrystal.h>

 Adafruit_ADS1115 ads;  /* Use this for the 16-bit version */

 int timer2_counter;
 int timer1_counter;
 uint16_t adc0;
 uint8_t adch,adcl;
 char receive;
 uint8_t dlc = 0;
 int addr = 0;
 long sensorValue = 0;         // the sensor value
 float rpm;
 uint16_t count = 0;

const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

void setup(void)
{
  Serial.begin(9600);
  while (!Serial);

  // initialize timer1
  noInterrupts();           // disable all interrupts

  //---------------------TIMER_1---------------------------------------//
  TCCR1A = 0;
  TCCR1B = 0;

  //timer1_counter = 64930;   // preload timer 65536-16MHz/256/100Hz   10ms 64911
  //timer1_counter = 64911;   // preload timer 65536-16MHz/256/100Hz
  timer1_counter = 64286;   // preload timer 65536-16MHz/256/50Hz
 // timer1_counter = 34286;   // preload timer 65536-16MHz/256/2Hz
 //timer1_counter = 62411;   // preload timer 65536-16MHz/256/20Hz   100msec

  TCNT1 = timer1_counter;   // preload timer
  TCCR1B |= (1 << CS12);    // 256 prescaler
  TIMSK1 |= (1 << TOIE1);   // enable timer overflow interrupt

   //Setup Timer2 to fire every 1ms
  TCCR2B = 0x00;        //Disbale Timer2 while we set it up
  TCNT2  = 130;         //Reset Timer Count to 130 out of 255
  TIFR2  = 0x00;        //Timer2 INT Flag Reg: Clear Timer Overflow Flag
  TIMSK2 = 0x01;        //Timer2 INT Reg: Timer2 Overflow Interrupt Enable
  TCCR2A = 0x00;        //Timer2 Control Reg A: Wave Gen Mode normal
  TCCR2B = 0x05;        //Timer2 Control Reg B: Timer Prescaler set to 128

  interrupts();             // enable all interrupts

  Serial.println("CAN Sender");
  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.print("DYNALEC CONTROLS");

  ads.setGain(GAIN_ONE);        // 1x gain   +/- 4.096V  1 bit = 2mV      0.125mV
  ads.begin();
  // start the CAN bus at 500 kbps
  if (!CAN.begin(500E3)) {
    Serial.println("Starting CAN failed!");
    while (1);
  }

}

ISR(TIMER2_OVF_vect)
{

  TCNT2 = timer2_counter;   // preload time
  count++;
  if(count >= 20000)
  {
     Serial.println("LCD");
    lcd_write();
    count = 0;
  }
}

ISR(TIMER1_OVF_vect)        // interrupt service routine
{
  TCNT1 = timer1_counter;   // preload time

  if(dlc == 1)
  {
    Serial.print("packet with id 0x");
    Serial.print(CAN.packetId(), HEX);
    dlc = 0;
    CAN.beginExtendedPacket(0x0C00DAEF); //(PGN-0 Priority-3 src Addr- EF Dest Addr-DA)
    CAN.write(0x00);
    CAN.write(adch);
    CAN.write(adcl);
    CAN.write(0x00);
    CAN.write(0x00);
    CAN.write(0x00);
    CAN.write(0x00);
    CAN.write(0x00);
    CAN.endPacket();
    Serial.println(" ");
  }
   else{
  CAN.beginExtendedPacket(0x0C00DAEF); //(PGN-0 Priority-3 src Addr- EF Dest Addr-DA)
  CAN.write(0xFF);
  CAN.write(adch);
  CAN.write(adcl);
  CAN.write(0xFF);
  CAN.write(0xFF);
  CAN.write(0xFF);
  CAN.write(0xFF);
  CAN.write(0xFF);
  CAN.endPacket();
  Serial.println(" ");
  }

}
//------------------------------------while_loop-------------------------------------------//
void loop(void)
{
  //lcd_write();
  read_ads();
  read_can();
  calibration();
}
// ------------------------------lcd_write---------------------------------------------------//
void lcd_write(void)
{
  noInterrupts();

  //Serial.println("LCD");
  lcd.setCursor(0, 1);
  delay(10);
  lcd.print("RPM: ");
  lcd.print(rpm);
  delay(10);
  interrupts();

}
//--------------------------ads_read--------------------------------------------------------//
void read_ads(void)
{
  adc0 = ads.readADC_SingleEnded(0);// 10v = 64255 = 8031.875 max value speed. adjust 10v = 32127 counts.
  adc0 = adc0 * 2;
  sensorValue = adc0 - offset;
  sensorValue = sensorValue * slope;
  sensorValue = sensorValue / 10000;
  Serial.println(sensorValue);
  rpm = sensorValue * 0.125;
  Serial.println("RPM:");
  Serial.println(rpm);

  /*adch = adc0 >> 8;
  adcl = adc0 & 0x00FF;
  Serial.print("AIN0: "); Serial.println(adc0);
  Serial.println(adch);
  Serial.println(adcl);*/
}
//--------------------------------------can_read-----------------------------------------------------//
void read_can(void)
{
   // try to parse packet
  int packetSize = CAN.parsePacket();

  if (packetSize) {
    // received a packet
    Serial.print("Received ");

    if (CAN.packetExtended()) {
      Serial.print("extended ");
    }

    if (CAN.packetRtr()) {
      // Remote transmission request, packet contains no data
      Serial.print("RTR ");
    }

    Serial.print("packet with id 0x");
    Serial.print(CAN.packetId(), HEX);

    if (CAN.packetRtr()) {
      Serial.print(" and requested length ");
      Serial.println(CAN.packetDlc());
    } else {
      Serial.print(" and length ");
      Serial.println(packetSize);

      // only print packet data for non-RTR packets
      while (CAN.available()) {
        Serial.print(CAN.read(),HEX);
      }
      Serial.println();
    }
    if((CAN.packetDlc() == 3) && (CAN.packetId() == 0x3AEF))
    {
      dlc = 1;
    }

    Serial.println();
  }
}

Interrupts are difficult.  You need to write your code such that you do not share resources or are protecting resources between the normal code and the interrupt code.  I almost always recommend beginners to stay away from interrupts for this reason.  Even seasoned programmers can find them selves in unexpected situations due to interrupts.

To add to that:  There are also things that are not well behaved inside interrupts.  To take one example from your code: Serial.print("packet with id 0x");  If there's not currently enough room in Serial's transmit buffer, it will wait until there is some.  However, the only way room becomes available is if another interrupt runs to take data out of it and put it into the serial peripheral.  But that can't happen while you're currently servicing another interrupt.  As a result, writing to Serial inside an ISR can lock up indefinitely if you fill the transmit buffer.


text:
LCD 16x2 shows one line cut and the 7th column also cut
My 16x2 LCD shows one line cut and the 7th column also cut:

Applying pressure:

What happens if you gently push down around the outside of the LCD display?

Push down means

Quite literally apply some pressure with your fingers to the black part, pushing it toward the PCB board while displaying your message.

Yes I apply some press on screen but not completely show all character

It's not conclusive, but it is a strong indication if it causes some of the segments to show that were otherwise not showing.

Ok i will try tell what happen

Thanks you very much

It's Work!!!! Thanku Sir

My LCD module looks so similar to yours I decided risk to taking it apart for the purposes of taking pictures for to go along with the description.  It went back to together fine.
The black part I suggested pushing down on I'm going to call a "bezel", even though I'm not sure that's technically the correct term for it.
The pink color showing between the PCB and bezel is probably a "zebra strip" or elastomeric connector.  They conduct signals from LCD controller mounted on the PCB up to the LCD glass itself.  Sometimes they don't make good contact and so some segments of the LCD don't respond or respond poorly.  They may make better contact when you apply pressure to them.  If some or all of the segments start responding when you do that, it's a fairly good indication that this is a problem, though not an Arduino problem as such, it's a problem encountered with some frequency by Arduino users.
If you may need to replace the strips, or clean them, or adjust the bezel to apply more pressure to them.  Or just get another LCD module.
Back of one of my LCD modules that looks a lot like yours:

If you look at the back side of the board you may find that you can unclip the bezel; though it could also be soldered or glued etc.  If/when you do unclip it, the zebra strips and LCD glass will probably come free, perhaps with polarization filters as well.  You'll want to pay attention to the orientation of the everything so you know what you're doing when you put it back together.
I unclipped my the bezel on mine and the zebra strips (pink; they're not always pink) stayed with it. It is no so easy to see the "zebra" pattern on these particular strips.  Often they more alternating gray/white pattern.

Here's the PCB showing the contacts that the zebra strips mate to an the LED backlight spreader. Apologies for the dust.

The strip pattern is a little easier to see in this image.  You can also see the pattern of the conductors on the LCD glass.

You can try cleaning the strips and the glass and PCB where the make contact.  I would be careful what you clean with; look for trustworthy recommendations. In any case, keep your finger grease off of everything, either by using gloves or just washing and drying your hands before working on it.


text:
CNC Y-axis stepper moving forward but not in opposite direction
I'm building an CNC mill with an Arduino UNO with a CNC Shield V3. But I have a problem with the Y motor direction. It only moves in one way while the X motor is moving both ways. When I just installed everything it worked, but after a view tries it doesn't anymore. I viewed multiple topics on this problem but nothing is working.

I tried to switch the stepper drives but that didn't make a difference.

Switched the stepper motors and then the x motor moved in one way so it isn't the stepper motor.

Tried cloning the Y controller to the 4th connection. Also didn't work.

Tried multiple GRBL HEX files, all the same.

I also tried multiple gcode senders but is just doesn't make a difference.

Is there anything else that I can try to help this problem? Or shall I order an new shield to test if this shield is broken.

So, what code is running on the Uno? How exactly is it conected to a motor? Link to the attached CNC shield and it's pinout? Pictures of the setup maybe?

Have you blown one of your drivers? Try swapping them around.

if one of the motor windings was not driven,  then the motor would fail to turn in either direction ... either the motor driver has a bad direction pin (if there is one), or the problem is caused by software

The code is running on the Uno is GRBL and the driver board is A4988, on the cnc shield 3 and i was even trying to interchange the driver and the motor no improvement

Check the DIR signal to the Y controller.


text:
Arduino PID Library
I hope you're doing well. I have some questions regarding the PID functions.
Can you please explain to me the following commands? I shall be very thankful to you.

PID myPIDX(&InputX, &OutputX, &SetpointX, Kpx, Kix, Kdx, REVERSE);
What is meant by reverse and why we used & with input, output and setpoint?

myPIDX.SetMode(AUTOMATIC);
What is meant by automatic/manual?

myPIDX.SetOutputLimits(80, 110)
What is meant by the values 80, 110 and what is range 0-255?

myPIDX.SetSampleTime(45);
What is meant by this command? is the time in milli-seconds?

myPIDX.Compute();
How is this function working? I mean what is happening at the back end of the compute function?

Best Regards!

The library documentation and/or code would be the best place to start. At the very least a link to the library you're asking about would be helpful.

https://playground.arduino.cc/Code/PIDLibrary

This is the link to this library I'm talking about

Can you guide me related to this? My project is 2 DOF Ball Balancing using a PID controller

The documentation seems to explain at least some of these fairly well. The code for each is available as well.

Yea ive done the code

I need to understand the backend work being done behind these

Then you'll need to read the code?


text:
PID Arduino UNO
I want to implement a PD controller in Arduino using the PID library. Should I put Ki=0 and the rest of the constants as desired?
/*
BALL BALANCING USING A PID CONTROL with 6" resistive Touchscreen
*/
//////////////////////////////////////////////////////
///Libraries///
#include <PID_v1.h>
#include <stdint.h>
#include <TouchScreen.h>
#include <Servo.h>

//______________________________________________________________
// Definitions TOUCH PINS
#define YP A1 //brown
#define XM A2 //black
#define YM 7  //yellow
#define XP 6  //red

//______________________________________________________________
// For better pressure precision, we need to know the resistance
// between XP and XM Use any multimeter to read it
// For the 6" its 273 ohms across the X plate
#define Rx 273 //  Resistance in Ohm of Touchscreen measured in X-Direction
TouchScreen ts = TouchScreen(XP, YP, XM, YM, Rx);

// Coordinates Touchscreen
TSPoint p;
double xmin = 146.0;  //154
double xmax = 854.0;   //851
double xLength = 160.0; //Width of Touchscreen in mm at 6.0" 158

double ymin = 63.0;    //63.0
double ymax = 953.0;    //950.0
double yLength = 96.0; //Length of Touchscreen in mm at 6.0" 94

double convertX = xLength / (xmax - xmin);   // converts raw x values to mm. found through manual calibration  0.2295   0.225988
double convertY = yLength / (ymax - ymin);   // converts raw y values to mm. found through manual calibration  0.1082   0.107865

//______________________________________________________________
//Center-Position
double x0=74.35; double y0=42.71; //center  Correct: 0.5//-7     double x0=74.35; double y0=42.71
//______________________________________________________________

int state = 0;

// servos variables
Servo servoX; //X axis
Servo servoY; //Y axis

/////TIME SAMPLE
int Ts = 45;  //Delay between taking samples/measurements

unsigned long Stable=0;
unsigned int noTouchCount = 0; //variable for noTouch
//______________________________________________________________

double Kpx = 0.08;  //Kpx = 0.08; //Proportional (P) Get the ball to set point
double Kix = 0.02;  //Kix = 0.02 0.022 //Integral (I)
double Kdx = 0.035;  //Kdx = 0.035; //Derivative (D)  Stop the ball at set point

double Kpy =0.08;  //Kpy = 0.08
double Kiy =0.02; //Kiy = 0.02 0.022;
double Kdy =0.035;  //Kdy = 0.035;

//______________________________________________________________
//INIT PID
double SetpointX, InputX, OutputX; //for X
double SetpointY, InputY, OutputY; //for Y
PID myPIDX(&InputX, &OutputX, &SetpointX, Kpx, Kix, Kdx, REVERSE);
PID myPIDY(&InputY, &OutputY, &SetpointY, Kpy, Kiy, Kdy, REVERSE);
//______________________________________________________________

void setup(){
servoX.attach(9);
servoY.attach(10);

  OutputX=92;
  OutputY=100;
  servoX.write(OutputX); // Make Plate flat in X-Direction
  servoY.write(OutputY); // Make Plate flat in Y-Direction

  //INIT OF TOUSCHSCREEN
   p = ts.getPoint();

  //INIT SETPOINT, Center of Plate
  SetpointX = 0.0;
  SetpointY = 0.0;

  //Setup PID Controller
  myPIDX.SetMode(AUTOMATIC);
  myPIDX.SetOutputLimits(77, 107); // 83 107
  myPIDY.SetMode(AUTOMATIC);
  myPIDY.SetOutputLimits(85, 115); // -- 81 105

  // TIME SAMPLE
  myPIDX.SetSampleTime(Ts);
  myPIDY.SetSampleTime(Ts);
  delay(100);

  state=0;
  setDesiredPosition();

} // end of setup

void loop()
{
  while(Stable < 15)    //REGULATION LOOP
  {
   p = ts.getPoint();   //measure pressure on plate
   if (p.x > 0 ) //ball is on plate
   {
      servoX.attach(9); servoY.attach(10); //connect servos
      setDesiredPosition();
      noTouchCount = 0;
      p = ts.getPoint(); // measure actual position
      InputX = (p.x - xmin) * convertX;  // read and convert X coordinate
      InputY = (p.y - ymin) * convertY;  // read and convert Y coordinate
      if((InputX == SetpointX && InputY == SetpointY ))

          { Stable = Stable + 1;}

       myPIDX.Compute();  // action control X compute
       myPIDY.Compute();  // action control  Y compute
  }
   else //if there is no ball on plate
  {
    noTouchCount++; //increment no touch count
    if(noTouchCount == 150)
    {
     noTouchCount++;
     OutputX=92; OutputY=100;  //make plate flat
     servoX.write(OutputX); servoY.write(OutputY);
    }
    if(noTouchCount == 300) //if there is no ball on plate longer, detach servos
    { servoX.detach(); servoY.detach(); }
  }
  servoX.write(OutputX); servoY.write(OutputY);  //control

  } // END OF REGULATION LOOP

servoX.detach(); servoY.detach(); //detach servos

///STABILITY////
 while(Stable==15)    //if is stable
 { //still measure actual postiion
    setDesiredPosition();
    p = ts.getPoint();
    InputX = (p.x - xmin) * convertX;  // read and convert X coordinate
    InputY = (p.y - ymin) * convertY; // read and convert Y coordinate
    if(InputX < SetpointX || InputX > SetpointX || InputY > SetpointY || InputY < SetpointY  ) //if ball isnt close to setpoint
    {
      servoX.attach(9); //again attach servos
      servoY.attach(10);
      Stable=0; //change STABLE state
    }

  }//end of STABLE LOOP
}//loop end

//______________________________________________________________
//#### DESIRED POSITION ####
void setDesiredPosition(){
 switch(state){

// Start-Sequence
     case 0:  SetpointX = x0;
              SetpointY = y0;
              p = ts.getPoint();
              if (p.x > 0)
              {
                state = 1;
              } // if ball is on plate
              else if (p.x <= 0)
              {
                state = 0;
                setDesiredPosition();
               } // if no ball is on plate
              break;

// Center-Position
      case 1:  SetpointX = x0;
               SetpointY = y0;
               state = 1;
               break;

    default : state = 0; break;

 }  //end of switch state
}   //end of setDesiredPosition()

//______________________________________________________________

Maybe? Without any context it's impossible to help.

I'm doing a project on ball balancing using a PID controller in arduino UNO
My plant is of type-2 and fifth order system.

you can check the code above

Yes, you can use the PID library with Ki=0; to get a PD controller.


text:
Arduino Wire library master reader, slave sender example not working
I tried i2c EPROM and that worked pretty fine with arduino master. then i wanted to establish i2c communication between 2 arduinos such that both exchange each other's sensors data. I am not able to receive bytes from slave arduino. Unable to do what i was upto i resorted to example sketches of Wire library to assess what i was doing wrong and to my surprise even example sketches were not working. Definitely there is something wrong with my approach. Problem only appears when master requests data from another arduino slave (master sends data successfully to slave arduino but vice versa is not true) . i have assessed that problem is in requestEvent function of slave as that either doesnt send anything. or returns mysterious character. I am runnign proteous simulation. Master sends data seamlessly ( although here master is just reading but i was able to send data from master to slave successfully) but when master requests data from slave it does not get desired response. Please suggest some solution. Here is the code which is just copy pasted from Wire library examples ( master reader for master arduino and slave sender for slave arduino.  slave is just to send 6 bytes ("Hello ") to master when prompted.
Master code
// Wire Master Reader
// by Nicholas Zambetti <http://www.zambetti.com>

// Demonstrates use of the Wire library
// Reads data from an I2C/TWI slave device
// Refer to the "Wire Slave Sender" example for use with this

// Created 29 March 2006

// This example code is in the public domain.

#include <Wire.h>

void setup() {
  Wire.begin();        // join i2c bus (address optional for master)
  Serial.begin(9600);  // start serial for output
}

void loop() {
  Wire.requestFrom(8, 6);    // request 6 bytes from slave device #8

  while (Wire.available()) { // slave may send less than requested
    char c = Wire.read(); // receive a byte as character
    Serial.print(c);         // print the character
  }

  delay(500);
}

Slave code
// Wire Slave Sender
// by Nicholas Zambetti <http://www.zambetti.com>

// Demonstrates use of the Wire library
// Sends data as an I2C/TWI slave device
// Refer to the "Wire Master Reader" example for use with this

// Created 29 March 2006

// This example code is in the public domain.

#include <Wire.h>

void setup() {
  Wire.begin(8);                // join i2c bus with address #8
  Wire.onRequest(requestEvent); // register event
}

void loop() {
  delay(100);
}

// function that executes whenever data is requested by master
// this function is registered as an event, see setup()
void requestEvent() {
  Wire.write("hello "); // respond with message of 6 bytes
  // as expected by master
}

but proteous simulation shows that master is getting 6 bytes from slave instead of "Hello " which was sent by slave master is getting "|     "        "

Might very well be a problem with proteus. Simulations are finicky, complex and always incomplete

What are the parameters of the virtual terminal? Because so far as I can can tell, it supports a notion of virtual baud/line discipline. Or a different question: what happens if you keep the same settings for the virtual terminal but instead write a hello world type program that uses the same (9600) baud?


text:
A library for interfacing TMS9918 with Arduino
I want to make a personal computer that includes using the ATMEGA8 acting as the CPU, and using an easy to interface DIP IC as video chip. I am considering to interface an Arduino with a TMS 9918 video chip,a chip used a lot in 1980s home computers, to an Arduino-this  seems like a good choice because it uses it own video RAM (instead of the Arduino's which cannot be expanded).
So,my question is, where is the link to a library for interfacing the Arduino Uno  and TMS9918?

I just googled for it and didn't found any Arduino library for that chip. So I guess you need to write that yourself

what do you expect the finished project to be used for?


text:
Will the arduino uno still work if I replace the onboard 16Mhz crystal with a 12Mhz crystal?
I have recently bought an arduino uno R3 (the type where the atmega328 is surface mount and not removable on a mainly blue PCB); the board has two crystals on it one for the clock for the USB serial and the other for the atmega328 clock. Suppose I have built a fully completed circuit using the arduino (this means the arduino needs not to be further connected to a PC).  Will my arduino uno based circuit still work if I  simply replace (desolder) the 16Mhz (for the atmega328)  crystal with a 12Mhz crystal (soldered in its place)? The circuit doesn't use the serial ports or the the crystal for USB serial. Actually the circuit is simply the blink LED example built into the IDE.  I am guessing it will still work but blink slower-but I don't know the answer for sure.

look at page 2 ... https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf

Per the @jsotola link, the datasheet says the chip will do 0-16MHz.  https://forum.arduino.cc/t/arduino-with-internal-oscillator-on-1mhz/24547/4 suggests that it would mess with the bootloader, and gives guidance for compiling for lower speed operation.

Assembling an answer from the comments. Ever-terse @jsotola points the OP to page two of the data sheet which @Dave X summarizes as saying that yes, the chip will operate at 0 to 16 MHz. There is a caveat though, discussions on the Arduino forum suggest that the reduction in clock speed proposed by OP might interfere with the boot loader. The same discussion provides guidance for compiling for lower speed operation.


text:
How many bits long,at most, is the seed in the randomSeed() function?
I can not find a concrete reference to how many bits long the (input) seed for the  randomSeed() function is for Arduino given here
https://www.arduino.cc/reference/en/language/functions/random-numbers/randomseed/
In the above webpage , though it is the official Arduino document for randomSeed(), it does not concretely say if the maximum bit length of the seed is 8,16 or 32 bits.
I think it is 16 bits long (in other words the seed is in the
range of integers 0 and 65535). So for example the maximum input to randomSeed would be expressed as randomSeed(65535).
But I do not know for sure if the seed input is 16 bits at most.
So my question is the seed used in randomSeed() 16 bit length at most  (thus having a maximum value of 65535).
32 bits is comparable to a 32bit windows desktop computers so I think 32 bits is too large for the input seed to randomSeed(). I am also using an Arduino Uno with Arduino IDE version 1.6.7 (if that matters regarding the input bit length of the seed).

As stated on the page you link to:

seed: number to initialize the pseudo-random sequence. Allowed data types: unsigned long.

Therefore it's 32 bits, since that is what unsigned long is.


text:
Does DFR0063 I2C LCD work with Arduino Due? I cannot even pass i2C scanner
I have 2 Due and Two DFR0063 I2C LCD.  I cannot even pass i2C scanner.
I always got No I2C devices found.  I tried both SCL/SDA and SCL1/SDA1. For SCL1/SDA1, I do add 10K pull up resister. But still not work.
I notice most of example is using Arduino Uno not Due.  So I wonder maybe they just not work together.
I actually just need any Chelp I2C device work smoothy with DUE not other board.
Anyone recommend any goof I2C device for DUE?
Thanks
Joseph

See this link about i2c problem on Due, this was several years ago so not sure whether this was fixed or not.


text:
Flash firmware with hex file over serial with Python (no avrdude, Arduino IDE)
I'm trying to make a Python function in the TCLab package to flash firmware to an Arduino Leonardo (32u4). I can compile the TCLab ino (firmware) and deploy with the Arduino IDE or with the Python avryp package. The Python avr_helpers package looks like a possible solution but is only supported with the older Python 2.7. Forum posts such as this one, how can I upload a hex file to an arduino uno?, and others suggest avrdude to upload a hex file. However, I need a Python solution that can be used on any platform (MacOS, Windows, Linux, etc) without a requirement to install packages (avrdude, Arduino IDE, etc).
I have the hex file from a successful Arduino build. Here is an unsuccessful attempt to load the hex file with serial communication:
import serial
import time
import os

# open and close COM8 to activate bootloader
ser = serial.Serial('COM8',baudrate=1200)
print(ser.isOpen()); ser.close()
time.sleep(2)

# load hex file on COM9
filesize = os.path.getsize('tclab_v2.ino.hex')
fid = open('tclab_v2.ino.hex','rb')
offset = 0; MTU = 20
ser2 = serial.Serial('COM9',115200)
while (offset < filesize):
    fid.seek(offset, 0)
    ser2.write(fid.read(MTU))
    offset = offset + MTU
ser2.close()

The script is able to activate the bootloader on another port and connect. If I transfer all at once with ser2.write(fid.read()), it semi-bricks the Arduino and I recover it by hitting the reset button just before the Arduino IDE installs the firmware. I use a Maximum Transfer Unit (MTU) of 20 but I couldn't verify if there is one for the Leonardo. I can write a Python function to identify the ports and have used COM8 and COM9 here just to simply the test. Although the TCLab firmware is preloaded for Python, sometimes users change the firmware to use MATLAB, Octave, or Java and then want to switch back to Python. I'd like to make that as easy as possible without adding more steps or more instructions to the troubleshooting FAQ. Can I update the firmware like the MATLAB Arduino Support Package that detects a new device and transfers the firmware automatically with user confirmation?

use baud rate of 9600 ... that should remove the possibility that 115200 is not supported

Thanks for the suggestion. I just tried baudrate of 9600 with ser2 = serial.Serial('COM9',9600) but it has the same result.

@jsotola, bootloader has baudrate set. 32u4 bootloader use 57600 baud.

The Leonardo uses the AVR109 protocol, not STK500.

http://ww1.microchip.com/downloads/en/AppNotes/doc1644.pdf

@Majenko, yes, I edited the comment as you wrote yours

the point is, there is some negotiation described in the protocol specification. you can't simply dump the hex to com port

This isn't the exact answer but it helps.
Uploading without avrdude is complicated and generally slow. The best solution to not using the IDE is to open and close a port then use the avrdude command that the ide usually uses.
from serial import Serial
from time import sleep
from subprocess import run

while input('Press enter to upload ') == '':
    Serial('COM5',baudrate=1200).close()
    sleep(1)
    run(["C:\\Progra~2\\Arduino\\hardware\\tools\\avr/bin/avrdude", "-CC:\\Progra~2\\Arduino\\hardware\\tools\\avr/etc/avrdude.conf", "-v", "-patmega32u4", "-cavr109", "-PCOM6", "-b57600", "-D", "-Uflash:w:C:\\Users\\USER\\Desktop\\Python\\tclab_v2/tclab_v2.ino.hex:i"])

Thanks - this is helpful because it is much faster than using the Arduino IDE. I may go look at the AVRDUDE source (although it may not be pretty): https://stackoverflow.com/questions/37713905/flash-hex-file-to-arduino-via-terminal-without-avrdude


text:
How to stop a linear actuator?
I wrote code but the motor does not stop, it keeps moving.
Can anyone send code so that I can stop the motor after my code shown below?
const int forwards = 7;
const int backwards = 6;//assign relay INx pin to arduino pin

void setup() {
  pinMode(forwards, OUTPUT);//set relay as an output
  pinMode(backwards, OUTPUT);//set relay as an output
}

void loop() {
 digitalWrite(forwards, LOW);
 digitalWrite(backwards, HIGH);//Activate the relay one direction, they must be different to move the motor
 delay(20000); // wait 2 seconds

 digitalWrite(forwards, HIGH);
 digitalWrite(backwards, HIGH);//Deactivate both relays to brake the motor
 delay(2000);// wait 2 seconds

 digitalWrite(forwards, HIGH);
 digitalWrite(backwards, LOW);//Activate the relay the other direction, they must be different to move the motor
 delay(20000);// wait 2 seconds

 digitalWrite(forwards, HIGH);
 digitalWrite(backwards, HIGH);//Deactivate both relays to brake the motor
 delay(2000);// wait 2 seconds
}

Move your code out of loop() (where it loops) and into setup() where it only runs once?

It's not working..

Then you must have done something wrong.

motor does not stop ..... what does the motor do? ...... what is it supposed to do?

you are waiting 20 seconds instead of 2

There's multiple things you can do.  Here's some examples.
1: Move code out of loop() and intosetup():
const int forwards = 7;
const int backwards = 6;//assign relay INx pin to arduino pin

void setup() {
    pinMode(forwards, OUTPUT);//set relay as an output
    pinMode(backwards, OUTPUT);//set relay as an output

    digitalWrite(forwards, LOW);
    digitalWrite(backwards, HIGH);//Activate the relay one direction, they must be different to move the motor
    delay(20000); // wait 2 seconds

    digitalWrite(forwards, HIGH);
    digitalWrite(backwards, HIGH);//Deactivate both relays to brake the motor
    delay(2000);// wait 2 seconds

    digitalWrite(forwards, HIGH);
    digitalWrite(backwards, LOW);//Activate the relay the other direction, they must be different to move the motor
    delay(20000);// wait 2 seconds

    digitalWrite(forwards, HIGH);
    digitalWrite(backwards, HIGH);//Deactivate both relays to brake the motor
    delay(2000);// wait 2 seconds
}

void loop() {
}

2: Stop loop() from looping:
const int forwards = 7;
const int backwards = 6;//assign relay INx pin to arduino pin

void setup() {
    pinMode(forwards, OUTPUT);//set relay as an output
    pinMode(backwards, OUTPUT);//set relay as an output
}

void loop() {

    digitalWrite(forwards, LOW);
    digitalWrite(backwards, HIGH);//Activate the relay one direction, they must be different to move the motor
    delay(20000); // wait 2 seconds

    digitalWrite(forwards, HIGH);
    digitalWrite(backwards, HIGH);//Deactivate both relays to brake the motor
    delay(2000);// wait 2 seconds

    digitalWrite(forwards, HIGH);
    digitalWrite(backwards, LOW);//Activate the relay the other direction, they must be different to move the motor
    delay(20000);// wait 2 seconds

    digitalWrite(forwards, HIGH);
    digitalWrite(backwards, HIGH);//Deactivate both relays to brake the motor
    delay(2000);// wait 2 seconds

    while (1); // Stop here and do nothing forever
}

3: Set a "I have done it" flag:
const int forwards = 7;
const int backwards = 6;//assign relay INx pin to arduino pin
bool complete = false;

void setup() {
    pinMode(forwards, OUTPUT);//set relay as an output
    pinMode(backwards, OUTPUT);//set relay as an output
}

void loop() {
    if (!complete) {
        digitalWrite(forwards, LOW);
        digitalWrite(backwards, HIGH);//Activate the relay one direction, they must be different to move the motor
        delay(20000); // wait 2 seconds

        digitalWrite(forwards, HIGH);
        digitalWrite(backwards, HIGH);//Deactivate both relays to brake the motor
        delay(2000);// wait 2 seconds

        digitalWrite(forwards, HIGH);
        digitalWrite(backwards, LOW);//Activate the relay the other direction, they must be different to move the motor
        delay(20000);// wait 2 seconds

        digitalWrite(forwards, HIGH);
        digitalWrite(backwards, HIGH);//Deactivate both relays to brake the motor
        delay(2000);// wait 2 seconds

        complete = true;
    }
}

Each has benefits and drawbacks. Which is right for you depends on what you are actually trying to achieve.


text:
How to find the correct navigation course by GPS navigation with Arduino?
I have an RC plane and I want to make it autonomous via GPS navigation usung an Arduino.
I have an Arduino Mega 2560 onboard connected to a GPS Ublox-Neo-M8N (GPS module) and there is the problem.
I want my RC-Plane to read its position and go to waypoints. The coordinates of  two waypoints are defined before in a matrix variable like in this example :
a [1] [3] =
{
    {38.884675, -116.671035,
     245}
};

b [1] [3] =
{
    {38.725019, -116.580951,
     1180}
};

(1st is latitude, 2nd is longitude, and 3rd is height).
So I want my Arduino to read its current position from the GPS module's data and calculate the correct azimuth (correct horizontal angle) and the correct pitch angle (vertical angle) to navigate my plane to the waypoints.
When it reaches waypoint "a" with a small error (miss distance = 4 meters), it should be able to ignore navigation to the waypoint of variable "a" and then navigate to waypoint "b".
I am looking for the exact command from any library to calculate those two angles for navigation (azimuth, direction angle, and pitch angle) to navigate the RC plane from anywhere to the waypoints.

The track (course over ground) is typically calculated by the GPS receiver and included in the data it sends. So you do not need to calculate anything there.

The "navigation" part of your question is complex, though. Particularly since your plane does not have 6 degrees of freedom (like a drone) calculating a path to a waypoint includes a curve.

very good question, however it is about navigation, not about Arduino, so it is off topic here ... downvote

The computation is not difficult. Since your drone is unlikely to travel
for thousands of kilometers, you can assume the Earth is locally flat,
and the latitude and longitude are an orthogonal coordinate system.
First, compute the vector to the next waypoint in Cartesian coordinates
(dx, dy, dz):
// Defined at global scope.
const float radians_per_degree = M_PI / 180;
const float degrees_per_radians = 180 / M_PI;
const float meters_per_degree = 1e7 / 90;

// For every reading of the GPS:
float dx = (waypoint.longitude - current.longitude) * meters_per_degree
         * cos(current.latitude * radians_per_degree);
float dy = (waypoint.latitude - current.latitude) * meters_per_degree;
float dz = waypoint.height - current.height;

Then, from this vector you can get the required angles:
float azimuth = atan2(dx, dy) * degrees_per_radians;
float pitch_angle = atan(dz/sqrt(dx*dx + dy*dy)) * degrees_per_radians;

Note that the approximation breaks down if the drone has to travel for a
distance that is a significant fraction of the distance to the closest
pole. Note also that the approximation errors are inconsequential if you
periodically update your estimate of azimuth and pitch angle: the errors
will be corrected along the way as the drone gets closer and closer to
the waypoint.
Edit: timemage posted a very interesting comment, and I would want
to further expand on the precision issue. The AVR floating point support
is indeed limited to single precision. For latitudes and longitudes in
the range shown in the question, the numerical resolution (formally, the
unit in the last place) is (3.81×10−6)° for the latitude
and (7.63×10−6)° for the longitude. This translates to about
42 cm and 66 cm respectively on the surface of the Earth. It
may be just good enough to hit the waypoint to within 4 m.
You could increase the resolution by storing the latitude and longitude
in microdegrees, as 32-bit integers. This should be easy if the GPS
always gives 6 digits after the decimal point: just ignore that
decimal point. Then, once the quantities
waypoint.longitude - current.longitude
and waypoint.latitude - current.latitude are computed, you can safely
use floating point for the rest of the computations.

I was 80% of the way through writing something like this only with TinyGPSPlus when the phone rang, after which this was posted. So, I'll just mention here that if they're being literal about wanting a library, that one will do the course and distance part (which is probably haversine based). The pitch I'd synthesized in pretty much exact same way as this. The only other difference of note I had in mine is just that the user says they're using an Mega, so AVR, so only single precision float is available which is accurate to about 6 decimal places, so they should expect errors at close range.

@timemage: Thanks for this very relevant comment. I edited my answer to address the accuracy issue.

If I understand the OP correctly, he has a wing-type RC plane, not a drone. This can't just move in a specific direction.

@PMF, They asked how to calculate correct azimuth and pitch angle from one coordinate to another. It's true that they didn't use the word "drone." I'm just guessing it's used in the answer because ¨drone" can be taken to mean (semi-)autonomous (which makes sense given the question) vs say "multi-rotor" (implying ability change direction with ease). The OP didn't seem to put any real emphasize on it being a fixed wing craft and the need to plan motion in connection with it being a "RC plane." Maybe the way-points are far enough apart for this to be of real concern.

Thanks for the answer, the main question is : Is there any Arduino's Library (mention the library) which can calculate this ?

You mentioned in the answer that the accuracy is 44 cm and 66 cm. Can you describe it more? For example this accuracy is for each kilometer? If not how much is the accuracy for 5 kilometers?

@Hamid'Smith'Salehi: There may be a library that does this, but I am not aware of any. Also, I do not understand what you mean by “accuracy for each kilometer”. Did you read the Wikipedia article Unit in the last place?

I mean, using this calcution has some error because we assumed that earth is flat, so how much is error in every kilometer distance?

And what is M_PI ?

@Hamid'Smith'Salehi: The approximation error would be quite complex to compute, and depend on the exact start and end points of the path. Not anything as simple as an “error per kilometer”. If you get GPS updates periodically, the approximation error will only make the path slightly curved, instead of being a straight line (or rather, a great circle). The error created by wind is likely to be many orders of magnitude larger. M_PI is π (pi).

M_PI = π =3.14259....  You could divide the 44 and 66cm resolution of each endpoint by the number of kilometers of distance between the two points if you want.  The inaccuracy of using the flat-earth approximation versus calculating a great circle is that the great circle course doesn't have a constant azimuth that the flat-earth approximation would.  How far are your waypoints from each other?

Thanks for your response.Maximum distance is 5 kilometers

I tested it by an example : start point is 52.70594, 13.37933 altitude = 67 meters and the waypoint is : 52.71957, 1338046 altitude is 64 and the result was : azimuth = 87.124287071904 and the pitch angle = -0.113355534.....  . The pich angle seems to be true but i know that the waypoint is in the north of the start point so the azimuth must be something like 0 (less or more). What is the problem?

i replaced latitude with longitude and also longitude with latitude in the formula, and it seemed is working properly. Can you check it please?

@Hamid'Smith'Salehi: You are right. In order for the north to be at 0°, the azimuth must be computed as atan2(dx, dy). I edited the code in my answer.