Can I make multiple void loops with Arduino Uno? I have a problem. I want to make a car with a motor, front lights and rear lights. I want to run them at the same time but in different loops.

This is my code.

const int red1 = 10;
const int red2 = 11;
const int blue1 = 12;
const int blue2 = 13;
const int front1 = 3;
const int front2 = 4;
const int back1 = 5;
const int back2 = 6;
const int enablePWMPin = 9;
const int controlPinA = 8;
const int controlPinB = 7;
int buzzer = A0;

void setup() {
  pinMode(red1, OUTPUT);
  pinMode(red2, OUTPUT);
  pinMode(blue1, OUTPUT);
  pinMode(blue2, OUTPUT);
  pinMode(front1, OUTPUT);
  pinMode(front2, OUTPUT);
  pinMode(back1, OUTPUT);
  pinMode(back2, OUTPUT);
  pinMode(enablePWMPin, OUTPUT);
  pinMode(controlPinA, OUTPUT);
  pinMode(controlPinB, OUTPUT);

  digitalWrite(enablePWMPin, LOW);
  digitalWrite(front1, LOW);
  digitalWrite(front2, LOW);
  digitalWrite(back1, LOW);
  digitalWrite(back2, LOW);
  digitalWrite(red1, LOW);
  digitalWrite(red2, LOW);
  digitalWrite(blue1, LOW);
  digitalWrite(blue2, LOW);
  noTone(buzzer);
}

void loop() {
  digitalWrite(enablePWMPin, HIGH);
  digitalWrite(controlPinA, HIGH);
  digitalWrite(controlPinB, LOW);
  delay(3000);
  digitalWrite(controlPinA, LOW);
  digitalWrite(controlPinB, HIGH);
  delay(3000);
}

void loop() {
  digitalWrite(red1, HIGH);
  digitalWrite(red2, HIGH);
  digitalWrite(blue1, LOW);
  digitalWrite(blue2, LOW);
  delay(250);
  digitalWrite(red1, LOW);
  digitalWrite(red2, LOW);
  digitalWrite(blue1, HIGH);
  digitalWrite(blue2, HIGH);
  delay(250);
}

void loop() {
  int directionA = digitalRead(controlPinA);
  int directionB = digitalRead(controlPinB);
  if (directionA == HIGH && directionB == LOW) {
    digitalWrite(front1, HIGH);
    digitalWrite(front2, HIGH);
    digitalWrite(back1, LOW);
    digitalWrite(back2, LOW);
  } else if (directionA == LOW && directionB == HIGH) {
    digitalWrite(back1, HIGH);
    digitalWrite(back2, HIGH);
    digitalWrite(front1, LOW);
    digitalWrite(front2, LOW);
  } else {
    digitalWrite(front1, LOW);
    digitalWrite(front2, LOW);
    digitalWrite(back1, LOW);
    digitalWrite(back2, LOW);
  }
}

I'm using an Arduino Uno. Can I start all the void loops at the same time?

As the others have stated, no you can't have multiple loop functions. What you need to do is modify your approach so that each thing you are trying to do can be done sequentially without blocking (ie: remove the delay function usage). Expanding on some suggestions by JRobert, Here is how I would make these functions "run at the same time":

void loop() {

    lights1();
    lights2();
    motor();

}

void lights1() {

  static unsigned long lastTime = 0;
  const long interval = 3000;
  static bool state = 0;

  unsigned long now = millis();

  if ( now - lastTime > interval && state == 0) {
    state = 1;
    lastTime = now;
    digitalWrite(enablePWMPin, HIGH);
    digitalWrite(controlPinA, HIGH);
    digitalWrite(controlPinB, LOW);
  }

  if ( now - lastTime > interval && state == 1) {
    state = 0;
    lastTime = now;
    digitalWrite(controlPinA, LOW);
    digitalWrite(controlPinB, HIGH);
  }
}

void lights2() {

  static unsigned long lastTime = 0;
  const long interval = 250;
  static bool state = 0;

  unsigned long now = millis();

  if ( now - lastTime > interval && state == 0) {
    state = 1;
    lastTime = now;
    digitalWrite(red1, HIGH);
    digitalWrite(red2, HIGH);
    digitalWrite(blue1, LOW);
    digitalWrite(blue2, LOW);
  }

  if ( now - lastTime > interval && state == 1) {
    state = 0;
    lastTime = now;
    digitalWrite(red1, LOW);
    digitalWrite(red2, LOW);
    digitalWrite(blue1, HIGH);
    digitalWrite(blue2, HIGH);
  }

}

void motor() {
  int directionA = digitalRead(controlPinA);
  int directionB = digitalRead(controlPinB);
  if (directionA == HIGH && directionB == LOW) {
    digitalWrite(front1, HIGH);
    digitalWrite(front2, HIGH);
    digitalWrite(back1, LOW);
    digitalWrite(back2, LOW);
  } else if (directionA == LOW && directionB == HIGH) {
    digitalWrite(back1, HIGH);
    digitalWrite(back2, HIGH);
    digitalWrite(front1, LOW);
    digitalWrite(front2, LOW);
  } else {
    digitalWrite(front1, LOW);
    digitalWrite(front2, LOW);
    digitalWrite(back1, LOW);
    digitalWrite(back2, LOW);
  }
}

This approach will simulate running all three functions at the same time. Each function runs one at a time. But, since the delay has been removed from the light1/2 functions, they will end quickly during the 'waiting' period instead of pausing execution. This will allow the motor(s) to run and lights to blink all at the same time.


Can a function be called automatically when an input changes? Currently, my sketch is checking an input pin every time round the main loop. If it detects a change, it calls a custom function to respond to it. Here's the code (trimmed down to the essentials):

int pinValue = LOW;

void pinChanged()
{
    //...
}

void setup()
{
    pinMode(2, INPUT);
}

void loop()
{
    // Read current input
    int newValue = digitalRead(2);

    // Has the input changed?
    if (newValue != pinValue) {
        pinValue = newValue;
        pinChanged();
    }
}

Unfortunately, this doesn't always work properly for very short changes on the input (e.g. brief pulses), especially if loop() is running a bit slowly.

Is there a way to make the Arduino detect the input change and call my function automatically?

You can do this using external interrupts. Most Arduinos only support this on a limited number of pins though. For full details, see the documentation on attachInterrupt().

Assuming you're using an Uno, you could do it like this:

void pinChanged()
{
    //...
}

void setup()
{
    pinMode(2, INPUT);
    attachInterrupt(0, pinChanged, CHANGE);
}

void loop()
{
}

This will call pinChanged() whenever a change is detected on external interrupt 0. On the Uno, that corresponds to GPIO pin 2. The external interrupt numbering is different on other boards, so it's important to check the relevant documentation.

There are limitations to this approach though. The custom pinChanged() function is being used as an Interrupt Service Routine (ISR). That means the rest of the code (everything in loop()) is temporarily stopped while the call is executing. In order to prevent disrupting any important timing, you should aim to make ISRs as fast as possible.

It's also important to note that no other interrupts will run during your ISR. That means anything relying on interrupts (such as the core delay() and millis() functions) may not work properly inside it.

Lastly, if your ISR needs to change any global variables in the sketch, they should usually be declared as volatile, e.g.:

volatile int someNumber;

That's important because it tells the compiler that the value could change unexpectedly, so it should be careful not to use any out-of-date copies/caches of it.


Send commands from cPanel website to client ESP8266 I have a project where I want to remotely turn on and off a relay using an Arduino,(ESP8266) over the internet.

I have a remote web server that hosts my existing hobby website, cPanel hosted by GoDaddy Sites.
An Arduino (ESP8266) connects to this website listening for relay on/off commands.
Open a browser and load the webpage dashboard to sent commands to Arduino.

Yes I could have the Arduino poll the website ever so often to check for a value changed in a database, but I don't want to do that, Just seems unethical to me.
I was looking at WebSockets and thought that might be what I'm looking for but I know too little about it or there's not enough relevant documentation online about it to use it in this type of project.
I am looking forward to your comments and answers, but please do not tell me to host the site on the Arduino, and also using an app or other service is not going to work either, We are working with my own webpage and thats it no thirdparty apps, Thanks.

I don't believe you will have the capability to implement a Websocket interface on the GoDaddy cPanel web site.  I think you are limited to just serving up HTML content and associated files.  Websocket requires a server-side resource to talk to which you cannot implement.
I see nothing wrong with having a simple HTML page, that doesn't even need to really contain HTML that your ESP8266 can "GET" and examine and determine to turn your relay on or off.


I keep getting an exit status 1 expected primary-expression before ')' token for my code I am trying to compile my sketch for a servo motor in order to make it move back in forth (like a pulse) I used two for loops to make this happen but when I determine the scope before the loop I get this error not matter what i change for the variable ctr before the loop commences. Here is my code so that you can see where I most likely messed up.
edit: I added the fixes so far that was suggested in the comments now I am having a new issue with line 85 i get an error that says

exit status 1
expected ';' before ':' token

here is the code in question with all the edits suggested so far

 #include <ESP8266WiFi.h>
#include <Servo.h>

const char* ssid = "RETProject";
const char* password = "mporfiri";

WiFiServer server(80);

int ledPin = 13; // GPIO13
Servo servoLeft;
Servo servoRight;
//int ctr = ();
 int ctr = 0;

void setup() {
  Serial.begin(115200);
  delay(10);

  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);

  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

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

  // Start the server
  server.begin();
  Serial.println("Server started");

  // Print the IP address
  Serial.print("Use this URL to connect: ");
  Serial.print("http://");
  Serial.print(WiFi.localIP());
  Serial.println("/");

  //servoLeft.attach(2);
  //servoRight.attach(4);

}

void loop() {
  // Check if a client has connected
  WiFiClient client = server.available();
  if (!client) {
    return;
  }

  // Wait until the client sends some data
  Serial.println("new client");
  while(!client.available()){
    delay(1);
  }

  // Read the first line of the request
  String request = client.readStringUntil('\r');
  Serial.println(request);
  client.flush();

  // Match the request

  int value = LOW;
  while (value = LOW);
  if (request.indexOf("/LED=ON") != -1)  {
    digitalWrite(LED_BUILTIN, HIGH);
    value = HIGH;
    servoLeft.attach(2);
    servoRight.attach(4);

    for (ctr = 0:pulse:1) {
      servoRight.write(ctr);
      servoLeft.write(ctr);
    }

    for (ctr = 1:-pulse:0) {
      servoRight.write(ctr)
      servoLeft.write(ctr);
    }

  if (request.indexOf("/LED=STOP") != -1)  {
    digitalWrite(LED_BUILTIN, LOW);
    value = LOW;
    servoLeft.detach();
    servoRight.detach();
    delay(1000);

  }

// Set ledPin according to the request
//digitalWrite(ledPin, value);

  // Return the response
  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: text/html");
  client.println(""); //  do not forget this one
  client.println("<!DOCTYPE HTML>");
  client.println("");

  client.print("Robot is now: ");

  if(value == HIGH) {
    client.print("Moving Forward");
  } else if(value == LOW) {
    client.print("Moving Backward");
  } else {
    client.print("Stopped");
  }
  client.println("

");
  client.println("<button>Move Forward </button>");
  client.println("<button>Move Backward </button>
");
  client.println("<button>STOP </button>
");
  client.println("");

  delay(1);
  Serial.println("Client disonnected");
  Serial.println("");

}

This int ctr = () should probably be int ctr = 0

The for loop syntax is incorrect, see: https://www.tutorialspoint.com/cplusplus/cpp_for_loop.htm

The first for loop needs a } at the end.


IDE will not open in Windows 10 I have loaded the Arduino IDE on Windows 10 32-bit on a 64-bit machine. This is my kids' laptop so they don't have admin privileges but, I installed it with admin privileges.

I have restarted the laptop, but the IDE does not start when I try to open it.  I am not signed is as administrator.

Any assistance would be greatly appreciated.

OK.  I figured out it needs to run as administrator.

Thanks for your consideration though.


USB Host Shield plus 2 identical joysticks I'm trying to get two identical joystics (Saitek cyborg 3D) running with the USB-Host-Shield on a Mega 2560 and an USB-Hub.

I already get the event-messages of both of them:

#include <usbhid.h>
#include <hiduniversal.h>
#include <usbhub.h>

// Satisfy IDE, which only needs to see the include statment in the ino.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#endif
#include <SPI.h>

#include "hidjoystickrptparser.h"

USB Usb;
USBHub Hub(&Usb);
HIDUniversal Hid1(&Usb);    // first Joystick
HIDUniversal Hid2(&Usb);    // second Joystick

JoystickEvents Joy1Events;
JoystickEvents Joy2Events;

JoystickReportParser Joy1(&Joy1Events);
JoystickReportParser Joy2(&Joy2Events);

void setup() {
        Serial.begin(115200);
#if !defined(__MIPSEL__)
        while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
#endif
        Serial.println("Start");

        if (Usb.Init() == -1)
                Serial.println("OSC did not start.");

        delay(200);

        if (!Hid1.SetReportParser(0, &Joy1))
                ErrorMessage<uint8_t > (PSTR("SetReportParser1"), 1);
        if (!Hid2.SetReportParser(0, &Joy2))
                ErrorMessage<uint8_t > (PSTR("SetReportParser2"), 1);
}

void loop() {
        Usb.Task();
        Serial.print("\tX1: ");
        PrintHex<uint8_t > (JoystickEvents::mostRecentEvent.X, 0x80);
        Serial.print("\tY1: ");
        PrintHex<uint8_t > (JoystickEvents::mostRecentEvent.Y, 0x80);
        Serial.print("\tX2: ");
        PrintHex<uint8_t > (JoystickEvents::mostRecentEvent.Z1, 0x80);
        Serial.print("\tY2: ");
        PrintHex<uint8_t > (JoystickEvents::mostRecentEvent.Z2, 0x80);
        Serial.print("\tRz: ");
        PrintHex<uint8_t > (JoystickEvents::mostRecentEvent.Rz, 0x80);
        Serial.println("");

}

My question is: How can I distinguish the events from the different joysticks.

I'm trying to get some kind of port-information from the USB-Hub. Unfortunately something like

!hid->GetAddress()

within the JoystickReportParser doesn't do the job as it always returns 0.

Any ideas?

Not quite the question that was asked but part of the problem.

This is a simple introduction to pointers.

int variable = 42;                              // Create a variable
int* pointer = &variable;                       // Create a pointer to the variable (by getting its address)
*pointer = 99;                                  // Set the address to a new value
printf ("variable has the value %d", variable); // Print 99.

&x get the address of x

*y dereferences the pointer y, which means it 'turns it back to a variable' (this is simplistic view which isn't really true, but will do for now).
So you could, if you wanted (which you wouldn't) do this *&z which would be the same as doing z.

Basically think of & and * as a pair of complimentary operators like - and + or * and /.  (They aren't operators, but to start with it might help).

The next problem is when you do this

SomeFunction(&variable);

All function parameters in C/C++ are passed by value by default.  This means the function gets a copy of them not the actual value.  So if you had:

void FunctionOne (int val)
{
    val = 99;
}
int val = 4;
FunctionOne(val);
printf("val = %d", val);   // You will see 4 printed.

If you pass by reference then you will see 99 printed, to pass by reference you can do it one of two ways.

void FunctionTwo (int& valByRef);
void FunctionThree (int* valPointer);

FunctionTwo only works with C++ (It will work with an Arduino).

FunctionThree might cause a segmentation error if NULL is passed in and the function writes to it.

If it helps in my opinion pointers was one of the hardest concepts to grasp in classic C/C++ so don't worry if you don't understand it just have a play with it and see what you can do.

Calling Methods

object.method() - Call the function method on the instance called
object which is of type X.
object->method() - Call the function method on the instance called
object which is a pointer of type X.
object::method() - call the function method
which is a static member of class object (static means it doesn't
change any data within an instance of a class)
*object->method() - Avoid this like the plague.  It either means *(object->method()) or (*object)->method() to know you would need to look at the type of object and the return type of the function.  Its easier just to bracket it to remove ambiguity.

As for *object.&method() I've never come across that one, but that doesn't mean it doesn't exist. :)


1st LED turn ON when 1st button is pressed and other LEDs remaining OFF I have 2 LEDs and 2 buttons. What I want to code is when first button pressed the 1st LED turn on (stay on for 5 seconds) and 2nd LED remain off, and same if 2nd button pressed the 2nd LED turn on and 1st LED remain off. I want the processing reset after 5 seconds.
Here is my work, what it does now is 1st LED turn on when I press 1st button, but the 2nd button and 2nd LED still can press and light up right after. I want the 2nd button deactivate when 1st button pressed for 5 seconds.
Please give me basic program because I am new to this.

int pinButton_1 = 8; //the pin where we connect the button
int pinButton_2 = 9;
int LED_1 = 1; //the pin we connect the LED
int LED_2 = 2;
void setup() {
  pinMode(pinButton_1, INPUT); //set the button pin as INPUT
  pinMode(pinButton_2, INPUT);
  pinMode(LED_1, OUTPUT); //set the LED pin as OUTPUT
  pinMode(LED_2, OUTPUT);
}

void loop() {
  int stateButton_1 = digitalRead(pinButton_1); //read the state of the button
  int stateButton_2 = digitalRead(pinButton_2); //read the state of the button
  if(stateButton_1 == 1) { //if is pressed
     digitalWrite(LED_1, HIGH); //LED_1 on
     digitalWrite(LED_2, LOW); //LED_2 off
     delay(50);
  }
     if (stateButton_2 == 1) {
      digitalWrite(LED_1, LOW);
      digitalWrite(LED_2, HIGH);
      delay(50);
     }
  }

First of all you have not implemented a stay on time of 5seconds delay(5000); but only 50ms delay(50);.

Second, you are not really switching of your LED's if no further button is pressed.

Change your loop() to the following, I guess this will help you to start your next steps into getting familiar with your code:

    void loop() {
      int stateButton_1 = digitalRead(pinButton_1); //read the state of the Button_1
      if(stateButton_1 == 1) {      //if Button_1 is pressed
         digitalWrite(LED_1, HIGH); //LED_1 on
         digitalWrite(LED_2, LOW);  //LED_2 off
         delay(5000);
      }
      digitalWrite(LED_1, LOW); //Switch off LED_1

      int stateButton_2 = digitalRead(pinButton_2); //read the state of the button 2
      if (stateButton_2 == 1) {
         digitalWrite(LED_1, LOW);
         digitalWrite(LED_2, HIGH);
         delay(5000);
      }
      digitalWrite(LED_2, LOW); //Switch off LED_2
    }

Hint: Using delay() is often not a good construct, better to do it with millis(), but this means some more changes. For the start in your case delay() will do, but check out what here in different Questions/answers is already written about delay() vs. millis()


Is it correct to use pulseIn() in ISRs? Since it is not right to use millis() in an ISR to calculate duration of the input, Is it correct to use pulseIn()?

It is quite OK to use millis() or micros() inside an ISR. In fact that is an excellent time to do it, because you are recording the time of the event shortly after it happened. Make sure the variable you are saving it to is unsigned long and volatile. Eg.

volatile unsigned long whenItHappened;
volatile bool eventHappened;

void myISR ()
  {
  whenItHappened = millis ();
  eventHappened = true;
  }

Now in your main loop you can test the eventHappened flag, so you will know if this event has happened, and whenItHappened is when.

It is not a good idea to use pulseIn() because that can wait quite a long time for a pulse. The default timeout for pulseIn is 1 second, which is far too long to wait inside an ISR.

If you want to time something (eg. how long it takes a ball to cross a sensor) use the interrupt twice, once to find the first event, and again to find the second.

Example

Example code which times how long a ball passes a sensor:

const byte LED = 12;
const byte photoTransistor = 2;

unsigned long startTime;
volatile unsigned long elapsedTime;
volatile boolean done;

void ballPasses ()
{
  // if low, ball is in front of light
  if (digitalRead (photoTransistor) == LOW)
    {
    startTime = micros ();
    }
  else
    {
    elapsedTime = micros () - startTime;
    done = true;
    }

  digitalWrite (LED, !digitalRead (LED));
}

void setup ()
{
  Serial.begin (115200);
  Serial.println ("Timer sketch started.");
  pinMode (LED, OUTPUT);
  attachInterrupt (0, ballPasses, CHANGE);
}

void loop ()
  {
  if (!done)
    return;

  Serial.print ("Time taken = ");
  Serial.print (elapsedTime);
  Serial.println (" uS");
  done = false;
  }

That code used micros() for a more accurate timing.

Reference

Interrupts


How I could make a bus connection in a prototype shield? I am a programmer but pretty new to electronics , I recently bought a prototyping shield like the picture :

In my view there is no bus connections here . I have lots components need connect to solder into a single board , and some ports like GND and VCC , SDA and SCL need connect via buses , how could I make solder such a bus connection by using this shield?
Should I just continuously solder through the holes I want to form a bus?
Thanks..!

I would mount the components to the board first then create busses with wire. Depending on the components you might be able to use the same row the component leads are in or you may need to lay the bus in the adjacent row and bridge the gap with component leads.

A quick search turned up an image that sort of gives an idea of what I'm talking about. If you look closely you can see the wire bridging the gap between each solder pad.

https://www.bing.com/images/search?q=soldering+protoboard+bus+wiring&view=detailv2&&&id=EF1514CA6486FC44E0132E7DE1CFBFDBFD015809&selectedIndex=15&ccid=vQ%2beHllm&simid=608022938507020230&thid=JN.TBpqHtXSA7o3dTvD8dPVaQ&ajaxhist=0


Arduino IDE won't use selected port I'm trying to program an ATtiny85, using an AVRISP mkII programmer (this one: https://www.amazon.de/dp/B00IYNAXUC/ref=cm_sw_r_sms_c_api_i_VXOWDb3H3N5ND) with the Arduino IDE (version 1.8.10 on Ubuntu 18.10). For the ATtiny, I've installed https://github.com/damellis/attiny using the board manager, as recommended in countless tutorials.

Now, everything seems to be recognized fine, and I've selected the programmers port in the IDE: /dev/ttyACM0.
But when I try to upload a sketch, the IDE instead trys to pass usb as the port to avrdude. This is only visble when enabling verbose output: (paths abbreviated)

/home/[...]/avrdude -C/home/[...]/avr/etc/avrdude.conf -v -pattiny85 -cstk500v2 -Pusb -Uflash:w:/tmp/arduino_build_728460/sketch.ino.hex:i

avrdude: Version 6.3-20190619
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "/home/[...]/avrdude.conf"
         User configuration file is "/home/[...]/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : usb
         Using Programmer              : stk500v2
avrdude: usbdev_open(): did not find any USB device "usb" (0x03eb:0x2104)

avrdude done.  Thank you.

usb isn't even a selectable port in the IDE!

Simply pasting the avrdude command (first line in the output above) to a terminal and changing usb to /dev/ttyACM0 makes it program the IC perfectly (but of course, that's a rather cumbersome workaround).

Also, selecting another programmer in the IDE (like AVR ISP, without the mkII) makes it use the correct port (but of course it won't work, since it's the wrong programmer).

Am I doing something wrong, or is this an actual bug in the Arduino IDE?

You mean that the STK500 v2 programmer uses an emulated serial port
rather than direct USB? Then I guess there is a bug in the Arduino IDE.
The file programmers.txt contains the following lines
describing the programmer:

avrispmkii.name=AVRISP mkII
avrispmkii.communication=usb
avrispmkii.protocol=stk500v2
avrispmkii.program.protocol=stk500v2
avrispmkii.program.tool=avrdude
avrispmkii.program.extra_params=-Pusb

You may locate this file in your Arduino installation and replace the
last line from this snippet by

avrispmkii.program.extra_params=-P{serial.port}

If that works, it would be a good idea to submit a pull request with the
fix to the Arduino team.

Alternatively, you may try selecting “Atmel STK500 development board” as
a programmer. This is supposed to autodetect the version of the STK500
protocol, and uses the correct serial port.

Edit: you may also have to replace

avrispmkii.communication=usb

by

avrispmkii.communication=serial

C.f. this bug report, which seems to cover the exact issue you are
facing.


changing device signature in avrdude I am trying to burn bootloaders to Atmega2560V and when I hit burn bootloaders it shows me this error

  avrdude: Device signature = 0x1e9803
  avrdude: Expected signature for ATmega2560 is 1E 98 01

I know this device should have 0x1e9801, But I don't know why it's showing me this error.

I tried my luck by starting threads at AVRFREAKS but no joy.

One of my friend told to try changing the device signature in the avrdude from 0x1e9801 to 0x1e9803 for a temporary try.

How can I do that.? please please please anyone help.

Thanks


HC-05 emit data without pairing Is it possible to emit data from an arduino connected to a hc-05 Bluetooth module without pairing it to another device?
i.e. imagine that I want to send a Bluetooth signal as if it was a information spot. Then whoever who gets the signal can read it.

No. The HC-05 has to be paired. It runs on Bluetooth 2.x which requires pairing.  What you want is BLE (or Bluetooth 4.x) which has various "beacon" facilities.


Can the Arduino Uno become an AVR programmer and use the ICSP header to program the target board The Arduino Uno has an ICSP header that I imagine is for programming the board using a separate ICSP programmer. That is, its ICSP header turn the board into a target.

Can one use that same ICSP to program other boards, turning the Arduino Uno effectively into a ICSP AVR programmer? How?

I'm assuming that the target boards would also be Arduinos and wanted the Uno to program them using the Arduino IDE. Is that possible?

Reading the AVR In-System Programming Application Note it looks to me that the only issue would be to make the programmer (the Arduino Uno) control the target board reset line. I've seen something like that in ArduinoISP sketch, but in that sketch, the target reset is controlled by port D10. But one could program the reset line to be an output, right? So could we change the ArduinoISP sketch to use its own reset line as output to control the target board reset line? If not, why not?

First of all, as configured, the RESET pin can not be used as an output pin. In order to use it as an I/O pin, you would have to program the RSTDISBL fuse. But once you do that, as jippie said, it becomes near-impossible to reprogram your Arduino (if you have the socketed through hole variety of the MCU, you could pull it out and put it into a high voltage programmer; in all other cases, it's effectively impossible).

So in theory, you can use the ICSP header the way you suggest. In practice, it's under almost any conceivable circumstance a terrible idea.


Start timer when pins connected I have switch is a line connected to Digital pins 1,2,3,4,5 . When pins 1 connects, I need a timer to start. as the rest connect i need it to mark the time in the console output of each one and End on the timer on connection to pin 5. ex

START:
0.00
1.43
2.12
2.94
3.89
END

Also is there a way to Save the data to a log (.txt or whatever) If not its fine but I need to record results.

(This is for a school project)
THANKS!

I will not give you code, only clues on how to write the code yourself.

The way to tackle this is to (at first) remove the Arduino from the equation. Replace it, instead, with you.

Imagine you are doing the timing yourself. How would you go about doing it?

This is how I would set about the task:

When the first button gets pressed I would look at the clock and jot down the current time.
When the second button gets pressed I would again look at the clock, and subtract the first time from the current time to find out how much time has elapsed. I would jot that down.
When the third button is pressed I would do the same again - look at the clock, subtract the start time, and jot down the difference.
And I would keep going until I had run out of buttons.

So now you need to find the right code to read what buttons are doing, get the current time, and finally send the times somewhere useful.

For all those there are many many many examples on the web.


Driving a stepper motor using ESP8266 I have a stepper motor, and a Uln2003a stepper driver, which is connected to an ESP8266.

The ESP8266 is powered via USB, and the stepper motor is powered via the driver, which is then powered by an external power source, providing it a bit more than 12 volt. When powered on the LED D1 and D2 lights red.

Pins D0, D1, D2, D3 are used for input signal for the drive, the stepper board.

Everything should be connected correctly, but for some reason I am not able to make my stepper motor move. It doesn't react on any of my commands - why?

I suspect that the logic level might have to be 5v instead of 3v. But I've seen stepper motors being driven by an ESP before. So why does this not work? Any suggestions?

Any ways to debug?

Code:

esphome:
  name: steppermotor
  platform: ESP8266
  board: d1_mini

wifi:
  ssid: "ssid"
  password: "password"

# Enable logging
logger:

# ESPHome configuration
api:
  services:
    - service: control_stepper
      variables:
        target: int
      then:
        - stepper.set_target:
            id: my_stepper
            target: !lambda 'return target;'

# Example configuration entry
stepper:
  - platform: uln2003
    id: my_stepper
    pin_a: D0
    pin_b: D1
    pin_c: D2
    pin_d: D3
    max_speed: 250 steps/s

    acceleration: inf
    deceleration: inf

I hope there must be an inbuilt pull-up resistance for each GPIO registers of ESP.

Test like this and post your observation:
 1. Don't connect anything(ULN2003 jumper wires) to your ESP and check the GPIOs you selected whether they are floating or not. If no float in reading then it's fine.
 2. Connect the load and test the GPIOs are floating or not.


Pass structure pointer as an argument to a function in c I am developing a code in which I need to pass a structure pointer value to a function as a parameter. I am calling function "proto485Compare()" in "RS485TaskSlave()". "rs485Msg" contains my data for which I need to verify for checksum, I am checking it in "RS485TaskSlave()" using "if(proto485ValidCheckSum(rs485_message_t ((uint8_t*)message)))" but it is showing error on this line.

Please help me to get the values of "rs485Msg" & check for checksum on this line

Below is my code snippet:

 typedef struct
    {
      uint8_t AB;     ///< Address byte (Start byte)
      uint8_t CB;     ///< Command (index) "ASCII-byte"
      uint8_t SI;     ///< Action (sub index) "ASCII-byte"
      uint8_t PH1;    ///< Payload "ASCII-byte" of the high nibble of the high byte of the raw payload
      uint8_t PH0;    ///< Payload "ASCII-byte" of the low nibble of the high byte of the raw payload
      uint8_t PL1;    ///< Payload "ASCII-byte" of the high nibble of the low byte of the raw payload
      uint8_t PL0;    ///< Payload "ASCII-byte" of the low nibble of the low byte of the raw payload
      uint8_t CS1;    ///< Checksum "ASCII-byte" of the high nibble of the raw checksum
      uint8_t CS0;    ///< Checksum "ASCII-byte" of the low nibble of the raw checksum
    } rs485_message_t;

    uint8_t proto485ValidCheckSum(rs485_message_t message)
    {
      uint8_t rawChecksum = (message.CB - OFFSET_ASCII) + (message.SI - OFFSET_ASCII) +
        (message.PH1 - OFFSET_ASCII) + (message.PH0 - OFFSET_ASCII) +
          (message.PL1 - OFFSET_ASCII) + (message.PL0 - OFFSET_ASCII);

      uint8_t res = (((rawChecksum & 0xF0) >> 4) + OFFSET_ASCII) == message.CS1 &&
        ((rawChecksum & 0x0F) + OFFSET_ASCII) == message.CS0;

      return res;
    }

    void RS485TaskSlave(void *p_arg) //b - RS485 communication Task
    {
        uint8_t res;
        rs485_message_t rs485Msg;
        uint8_t command, action, value;

        (void)p_arg;
        while(1)
        {
          res = driver485Read((uint8_t *)&rs485Msg, RS485_MSG_LENGTH);
          if(RS485_MSG_LENGTH == 9)
         {
            res =  proto485Compare((uint8_t *)&rs485Msg, command, action, value);
         }
        }
    }

    int16_t proto485Compare(uint8_t* message, uint8_t* comparec, uint8_t* comparea, uint8_t* comaprev)
    { int j = 0;
      rs485_message_t rs485Msg;
      char res;
      uint8_t FWmsg[9] = {0x09,0x31,0x30,0x30,0x30,0x30,0x33,0x30,0x34};
      uint8_t arduinodata[9] = {0x09,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30};

     if(proto485ValidCheckSum(rs485_message_t ((uint8_t*)message))) //
/*GETTING ERRORVON THIS LINE please help how to pass message value to verify checksum at this line*/
      {
      printf("compare command..........");

        for (j=0; j<9; j++)
        {
          arduinodata[j] = message[j];
          printf("%d ",arduinodata[j]);
        }
        printf("\n");

        if(compareArray(FWmsg,arduinodata,7)==0)
        {
          uint8_t add, fwc, fwa;
          uint16_t fwv;
          res = GetABFWversion(&add, &fwc, &fwa, &fwv);
          res = proto485OnlyWrite(add,fwc, fwa, fwv);
        }
      }
      else
      {
        printf("Arrays have different elements.\n");
      }
      return res;
    }

Remove your casting, and change your message parameter to be rs485_message_t *:

int16_t proto485Compare(rs485_message_t * message, uint8_t* comparec, uint8_t* comparea, uint8_t* comaprev) {
    int j = 0;
    rs485_message_t rs485Msg;
    char res;
    uint8_t FWmsg[9] = {0x09,0x31,0x30,0x30,0x30,0x30,0x33,0x30,0x34};
    uint8_t arduinodata[9] = {0x09,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30};

    if(proto485ValidCheckSum(message))) { ...

And when you call it, simply:

res =  proto485Compare(&rs485Msg, command, action, value);

To get at the individual bytes you can then cast a new variable:

uint8_t *messageAsBytes = (uint8_t *)message;

Then you can use:

messageAsBytes[i]

etc.

However another cleaner way is to create a union in your structure:

struct rs485_message_t {
    union {
        uint8_t bytes[9];
        struct {
            uint8_t AB;     ///< Address byte (Start byte)
            uint8_t CB;     ///< Command (index) "ASCII-byte"
            uint8_t SI;     ///< Action (sub index) "ASCII-byte"
            uint8_t PH1;    ///< Payload "ASCII-byte" of the high nibble of the high byte of the raw payload
            uint8_t PH0;    ///< Payload "ASCII-byte" of the low nibble of the high byte of the raw payload
            uint8_t PL1;    ///< Payload "ASCII-byte" of the high nibble of the low byte of the raw payload
            uint8_t PL0;    ///< Payload "ASCII-byte" of the low nibble of the low byte of the raw payload
            uint8_t CS1;    ///< Checksum "ASCII-byte" of the high nibble of the raw checksum
            uint8_t CS0;    ///< Checksum "ASCII-byte" of the low nibble of the raw checksum
        };
    };
};

So you can now access message->CS0, etc, as well as message->bytes[3].

You should also pass a pointer when you call proto485ValidCheckSum - purely to save memory.

uint8_t proto485ValidCheckSum(rs485_message_t *message)
{
  uint8_t rawChecksum = (message->CB - OFFSET_ASCII) + (message->SI - OFFSET_ASCII) +
    (message->PH1 - OFFSET_ASCII) + (message->PH0 - OFFSET_ASCII) +
      (message->PL1 - OFFSET_ASCII) + (message->PL0 - OFFSET_ASCII);

  uint8_t res = (((rawChecksum & 0xF0) >> 4) + OFFSET_ASCII) == message->CS1 &&
    ((rawChecksum & 0x0F) + OFFSET_ASCII) == message->CS0;

  return res;
}

And again call it with a pointer, which the first block of code does anyway.

In general, it's better to pass a single pointer to a struct around from function to function instead of cloning it each time.

You can also use "pass by reference" if you like, but I find it's better to stick to pointers when passing something around alot like this.


Servo Driven Through Custom Library Not working Properly I'm a little new to Arduino, but not to programming or electronics in general.  I'm working on a library that will be more fleshed out later, but I'm having issues getting the basics working properly.

The following code produces the desired behavior if a servo is attached to pin 3:

#include <Servo.h>

Servo myServo;

void setup() {
  myServo.attach(3);
}

void loop() {
  myServo.write(1);
  delay(1000);
  myServo.write(45);
  delay(1000);
  myServo.write(90);
  delay(1000);
  myServo.write(135);
  delay(1000);
  myServo.write(180);
  delay(1000);
}

However, when I try to implement similar functionality in my own library the servo locks and just sort of grinds.  Here's the header file:

#ifndef MotorControl_h
#define MotorControl_h

#include "Arduino.h"
#include "Servo.h"

class MotorControl
{
  public:
    MotorControl(int north, int south, int west, int east);
    void setNorth(int value);
    void setSouth(int value);
    void setWest(int value);
    void setEast(int value);
    int getNorth();
    int getSouth();
    int getWest();
    int getEast();
  private:
    Servo _north;
    Servo _south;
    Servo _west;
    Servo _east;
    int _northVal;
    int _southVal;
    int _westVal;
    int _eastVal;
};

#endif

And here's the .cpp file:

#include "Arduino.h"
#include "MotorControl.h"
#include "Servo.h"

MotorControl::MotorControl(int north, int south, int west, int east)
{
  _north.attach(north);
  _south.attach(south);
  _west.attach(west);
  _east.attach(east);
  _northVal = 0;
  _southVal = 0;
  _westVal = 0;
  _eastVal = 0;
}

void MotorControl::setNorth(int value)
{
  _north.write(value);
  _northVal = value;
}

void MotorControl::setSouth(int value)
{
  _south.write(value);
  _southVal = value;
}

void MotorControl::setWest(int value)
{
  _west.write(value);
  _westVal = value;
}

void MotorControl::setEast(int value)
{
  _east.write(value);
  _eastVal = value;
}

int MotorControl::getNorth()
{
   return _northVal;
}

int MotorControl::getSouth()
{
  return _southVal;
}

int MotorControl::getWest()
{
  return _westVal;
}

int MotorControl::getEast()
{
  return _eastVal;
}

And finally, the code using the above library which should produce the same behavior as the code up top, but does not:

#include <MotorControl.h>

MotorControl mc(3, 5, 6, 9);

void setup() {}

void loop() {
  mc.setNorth(1);
  delay(1000);
  mc.setNorth(45);
  delay(1000);
  mc.setNorth(90);
  delay(1000);
  mc.setNorth(135);
  delay(1000);
  mc.setNorth(180);
  delay(1000);
}

I'm not sure what else to add ... this is running on an Uno R3.

Edit:  This is interesting.  I've tried the code from this example:
How do I initialize a servo object in my own library?
which works out just fine.  I'm still not sure that I see what I'm doing incorrectly here.  I see the differences between my code and the example, but not how they are causing problems.

If it's worth mentioning, I've also stored my library in the libraries folder.  Just throwing out any random detail I can think of.

In C++, when an object is declared as a member of another object, the constructor method of the inner object must be called explicity (see constructors and member initializer lists).

In your code, properties of Servo type can be constructed within the header of the MotorControl constructor:

MotorControl::MotorControl(int north, int south, int west, int east)
    : _north(), _south(), _west(), _east()
{
  _north.attach(north);
  _south.attach(south);
  _west.attach(west);
  _east.attach(east);
  _northVal = 0;
  _southVal = 0;
  _westVal = 0;
  _eastVal = 0;
}


Correct use of interrupt vs monitoring switch Background:
I have a uni assignment which requires an autonomous robot to do a number of tasks and then finish in a set spot after being triggered to start by an outside physical interaction. I've set up a light limit switch to detect this interaction.

My approach would normaly be to look for the switch in the loop to go high and then run through my code and put a really long delay at the end.
e.g.

switchState = digitalRead(switch);
 if (switchState == HIGH){
 //do my routine which is a function defined outside of the loop
}

Would this be an appropriate use for an interupt instead of the method above. I'm still trying to understand the best practice usage.

No, an interrupt here would be pointless.

You use an interrupt to detect a change on an input whilst you are doing something else. It's a good way of getting instant (or near instant) notification of something happening.

If you're using the input to start something going when there's nothing happening then you gain nothing other than extra complexity by using an interrupt. You're not doing anything else, and you don't need an instant response, so just polling the input is the simplest option.


More than 4 MCP23S17 on 1 SPI bus I would like to use 7 MCP23S17 as output expanders on one SPI bus. Every IC has its own address from 0 to 6. The first MCP23S17 can be written with no problem. The second chip did not work properly. The CS pin of the MCP23S17 is set like at the all other 4 ICs.

Does anybody have experience with more then 4 MCP23S17 on SPI? Could anyone help?

#include <SPI.h>
#include <MCP23S17.h>

MCP A(0, 10);
MCP B(1, 8);
int d = 250;

void setup() {
  A.begin();
  B.begin();
  for (int k = 1; k <= 16; k++) {
    A.pinMode(k, OUTPUT);
    B.pinMode(k, OUTPUT);
  }
}

void loop() {
  //////////// ON THE LIGHT ONE BY ONE  FROM BEGGING
  for (int f = 1; f <= 16; f++) {
    A.digitalWrite(f, HIGH);
    delay(d );
  }
  for (int f = 1; f <= 16; f++) {
    B.digitalWrite(f, HIGH);
    delay(d );
  }
  ////////////  OFF THE LIGHT ONE BY ONE  FROM BEGINNIG
  for (int f = 1; f <= 16; f++) {
    A.digitalWrite(f, LOW);
    delay(d);
  }
  for (int f = 1; f <= 16; f++) {
    B.digitalWrite(f, LOW);
    delay(d);
  }
}

MCP A(0, 9);
 MCP B(1, 8);
 MCP C(2, 7);
 MCP D(3, 6);
 MCP E(4, 5);
 MCP F(5, 3);

CS on pin 10 is often used for Ethernet
CS on pin 4 is often used for SD


Problem using IRremote library I am using arduino pro micro 5v 16Mhz. I have built a simple IR transmitter circuit as shown.

The code i am using is
https://github.com/z3t0/Arduino-IRremote/blob/master/examples/IRsendDemo/IRsendDemo.ino

Although this worked yesterday, it doesn't seem to work now. I was able to turn on and off my TV yesterday but the led is not even blinking now. I checked led, its working.

After hours of trying to make it work I tried different library.
https://github.com/cyborg5/IRLib2/blob/master/IRLib2/examples/send/send.ino

Surprisingly this seems to work but the code is a bit complicated for receiver.

I want to use the first library. Any help is appreciated. Thank you.

The problem was with timer timer settings in library. I checked different timer configurations with different pins and its working now. I found out that timer4 uses pin 13 which is not used in Pro Micro board so I am now using timer 3.


Can you use digital pins as PWM output? I am currently working on a robotics project that requires 16 PWM outputs to control 16 servos. Is it possible to use Arduino Uno's digital pins as PWM output pins through code?

If it is not possible, what microcontrollers do you suggest to use on such a project?

Only specific Digital Pins marked with ~PWM can generate a PWM signal. In the case of arduino Uno the pins 3,5,6,9,10,11 are all hardware PWM driven, and are marked on the Uno with a ~ or something.
Others can be driven with software PWM(though I wouldn't recommend it). As the Arduino Uno uses the ATMEGA328P, the number of pins is same with other boards using same processor.

On the other hand if you want to run 16pins for PWM, its best if you use Arduino MEGA 2560 because its processor supports more than 6 Hardware pins for PWM. Also you get the advantage of a higher memory storage for your code


GCC msg "note: in definition of macro 'max'" error message I'm using the ATtiny x5 series board, compiling my project (.cpp.ino file).  Whenever I use the max(a,b) macro, I receive this message:

"C:\Documents and Settings\<user>\Local Settings\Application Data\Arduino15\packages\arduino\tools\avr-gcc\4.9.2-atmel3.5.3-arduino2/bin/avr-g++" -c -g -Os  -std=gnu++11 -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -mmcu=attiny85 -DF_CPU=8000000L -DARDUINO=10609 -DARDUINO_AVR_ATTINYX5 -DARDUINO_ARCH_AVR   "-IC:\Documents and Settings\<user>\Local Settings\Application Data\Arduino15\packages\ATTinyCore\hardware\avr\1.1.1\cores\tiny" "-IC:\Documents and Settings\<user>\Local Settings\Application Data\Arduino15\packages\ATTinyCore\hardware\avr\1.1.1\variants\tinyX5" "-IC:\Documents and Settings\<user>\My Documents\Arduino\libraries\Pins_xxxxx" "-IC:\Documents and Settings\<user>\My Documents\Arduino\libraries\TinyWireS" "C:\WINDOWS\TEMP\build18f8c74edd63168be814edc24cb0a11a.tmp\sketch\AT85PWM.ino.cpp" -o "C:\WINDOWS\TEMP\build18f8c74edd63168be814edc24cb0a11a.tmp\sketch\AT85PWM.ino.cpp.o"
C:\Documents and Settings\<user>\Local Settings\Application Data\Arduino15\packages\ATTinyCore\hardware\avr\1.1.1\cores\tiny/Arduino.h:54:24: note: in definition of macro 'max'
 #define max(a,b) ((a)>(b)?(a):(b))
                        ^

What does note: in definition of macro 'max' mean, do I need to do anything about it, and if so what?

Searching google for the message gives lots of compiler output listings with the message, but the posting is always for another different message that is causing trouble.  None of the fixes from those posts address the max note: message.

I can reproduce your message easily enough:

#define max(a,b) ((a)>(b)?(a):(b))

void setup() {
 int b = 66;
 unsigned int c = 42;
 analogWrite (3, max (b, c));
}

void loop() { }

I get these warnings:

/tmp/arduino_modified_sketch_857720/sketch_aug31a.ino: In function 'void setup()':
/tmp/arduino_modified_sketch_857720/sketch_aug31a.ino:1:25: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
 #define max(a,b) ((a)>(b)?(a):(b))
                         ^
/tmp/arduino_modified_sketch_857720/sketch_aug31a.ino:6:18: note: in expansion of macro 'max'
  analogWrite (3, max (b, c));

The point is that the warning note: in expansion of macro 'max' is just telling you where the macro is defined, so you can make sense of the real warning. The real warning is: warning: comparison between signed and unsigned integer expressions

So, reading them together, you are comparing (in the macro) a signed and unsigned number, and the compiler is warning you about that.

  The message seems like a red herring, given that there is no problem with the max(a,b) macro definition. I suspect it is being flagged only because it was tangentially involved with a statement in error.

That's right. There is no problem in that macro per se. Macros can generate weird error message because they are just text replacements. For example:

max (the quick brown fox, jumps over the lazy dog);

That will generate a slew of errors, including a "note" to where max is defined. There is nothing wrong with max until you try feeding garbage into it.

Templates

That's one of the reasons I prefer to avoid macros if possible. You can do "max" with a template. For example:

#undef max   // throw away the original macro in the Arduino header file

template<typename T> T max (T a, T b)
  {
  if (a > b)
    return a;

  return b;
  }

Now you get slightly more reasonable error messages:

/tmp/arduino_modified_sketch_711186/sketch_aug31a.ino: In function 'void setup()':
sketch_aug31a:14: error: no matching function for call to 'max(int&, unsigned int&)'
   analogWrite (3, max (b, c));
                            ^
/tmp/arduino_modified_sketch_711186/sketch_aug31a.ino:14:28: note: candidate is:
/tmp/arduino_modified_sketch_711186/sketch_aug31a.ino:3:24: note: template<class T> T max(T, T)
 template<typename T> T max (T a, T b)
                        ^
/tmp/arduino_modified_sketch_711186/sketch_aug31a.ino:3:24: note:   template argument deduction/substitution failed:
/tmp/arduino_modified_sketch_711186/sketch_aug31a.ino:14:28: note:   deduced conflicting types for parameter 'T' ('int' and 'unsigned int')
   analogWrite (3, max (b, c));
                            ^
exit status 1
no matching function for call to 'max(int&, unsigned int&)'

Of course, now you've gone from a warning to an error, because the template wants a single type.

Notice the notes? That's just the compiler trying to be helpful.

You could make the template take two types if you are prepared to guess the return type (will it be the first type, or the second type?):

#undef max

template<typename T1, typename T2> T1 max (T1 a, T2 b)
  {
  if (a > b)
    return a;

  return b;
  }

Now you don't get an error or a warning, however the result will be the first type (T1) which may or may not suit you.


Can the Arduino use this i2c LCD Panel Can the Arduino Mega2560 use the New Haven NHD-0420D3Z-NSW-BBW-V3 LCD panel by controlling it with the New LiquidCrystal library? What cable will you use to connect the LCD to Arduino, are there screw terminals on the LCD board to secure the connections? It seems like only 4 connections are needed, for GND, VCC, SDA, SCL.

Unfortunately you cannot control that display using that library; the library expects to be connected to a HD44780-compatible driver but the display uses a fully custom control scheme. You may be able to adapt the library to the scheme, but I have not looked at that specifically.

I2C itself only requires 3 connections: SDA, serial data; SCL serial clock; GND, ground reference. Since the display is not powered separately it also requires power, in this case 5V. Since the display can only communicate at 100kHz you don't need to be too terribly concerned about cable quality; Cat3 or even telephone cable is acceptable as long as you don't exceed a few feet in length. Don't forget the external pullup resistors though, on SDA and SCL.


Guideline in library creation According to this example, creation of an Arduino library is quite understandable.

But a few things I would like ask (mostly regarding to what to be defined where) when a library is not that simple:

Where to put additional libraries (such as <Wifi.h>) in .h or .cpp, since it works when defined in each one of them?
What is the purpose of defining variables in the :private section? Since they can be defined inside constructor, and as far as I know/tested, it works as well.
In a .cpp file, does it matter when instances or variables are defined outside a class (at the beginning of code ), since again, it works the same?

Where to put additional libraries (such as <Wifi.h>) in .h or .cpp, since it works when defined in each one of them?

Any library can reference any other library. So including another library in your library is the same as including in the sketch. They should be on standard locations.

Include the other libraries .h in the file where you need it. If you use something from the other library in your .h, include it there. If you need it only in .cpp include it there.

  What is the purpose of defining variables in the :private section? Since they can be defined inside constructor, and as far as I know/tested, it works as well.

With declaring a class member as private, the author of the class tells: don't use it, it is for internal use and can change in future versions.

  In a .cpp file, does it matter when instances or variables are defined outside a class (at the beginning of code ), since again, it works the same?

If the variable is not a member of the class, then if you create two instances of the class they will share the variable. A variable in constructor is restricted to the constructor's scope.


Led and button simulation of a blink My circuit:

My code:

// Pin 13 has a LED connected on most Arduino boards.
// give it a name:
int led = 13;
const int buttonPin = 2; // pushbutton connected to pin 2.

// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);
  pinMode(buttonPin, INPUT);
}

// the loop routine runs over and over again forever:
void loop()
{
  bool buttonState = digitalRead(buttonPin);
  while (buttonState == HIGH) // check while the button is pressed
  {
   digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
   delay(1000);               // wait for a second
   digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
   delay(1000);               // wait for a second
  }
}

What I wish to do is that when I press the button, the Led's start flashing and when I press them again, they stop blinking (like a fire alarm). Right now they do nothing and I dont know why. Is it something with the circuit or the code?

The volatage level on the IO pin needs to change (from low to high and vice versa), only then can the microcontroller detect a button press. Without another connection to the button, IO2 is simply floating (unconnected).

There are two methods to implement this: external pull-up or external pull-down resistors and internal pull-up resistors (both methods are described for example in this tutorial).

I prefer the internal pull-up resitor method. You need to connect the second pin of the button to GND. Then change your setup code to

pinMode(buttonPin, INPUT_PULLUP);

If the button is not pressed, the internal pull up resistor inside the microcontroller pulls IO2 to +5V and a digitalRead(buttonPin) returns HIGH. When you press the button, IO2 is pulled to GND and digitalRead(buttonPin) returns LOW.

So in your case you need to check for a LOW reading, because you want the LEDs to blink when the button is pressed.

(Btw. you can replace the while loop with an if, since the loop() function is already executed in an infinite loop.)


Serial Communication Issue with Telit LE910 LTE Modem I have a project that uses a Telit LE910 4G LTE Modem to allow me some basic monitoring via SMS and HTTP POST to Exosite.

I can connect to a Exosite server with and send a successful HTTP GET request to pull a UNIX timestamp (as a test).

Problem

The problem lies with receiving.  The information received cuts off halfway through the HTTP headers, before reaching the body of the information.

This image shows what prints out on the Serial monitor:

This image shows what the expected result should be:

And this image shows the code the executes to send the request:

The result is the same with PrintModemResponse() and with GetModemResponse().  Additionally, I have the same issue with receiving SMS messages.  The data appears to cut off partway through the expected response.  The modem serial (SW_Serial) baud rate is set to 115200.

Question

Am I doing something wrong with reading the Serial information from the modem?  Am I hitting a timeout of some sort?

First, please don't post screen images.  Just select the text and paste it into your questions.  You can copy code from the editor or messages from the Serial Monitor window.  Paste into your post, select the section again, and press ctrl-K to format it as a code block in your question (like below).

  Am I doing something wrong with reading the Serial information from the modem?

Yes, you are using delay to "wait" for the response to appear.

  Am I hitting a timeout of some sort?

In a way.  The input buffer only has room for 64 characters.  If you don't read any of them because you're blocked at a delay statement, the 65th character (and all others) will be ignored.  These answer your specific questions.

Further Suggestions:

To fix the real problem, not just the symptoms, you will have to change your sketch structure.

There are many ways to implement this in a non-blocking way (i.e., without using delay).  I prefer Finite-state Machines; there are many good tutorials for this  technique (e.g., Nick Gammon's site).

Although it's not as flexible, you could also use your own while loop for each response, with a timeout.  Here's a simple example that reads one line.

char resp[20];
char resp_Len = 0;
const uint32_t TIMEOUT_MS = 5000UL; // 5 seconds

AltSoftSerial modem_port; // pins 8 & 9 ONLY

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

void loop()
{
  uint32_t startTime = millis();
  while (millis() - startTime < TIMEOUT_MS) {
    if (modem_port.available()) {
      char c = modem_port.read();
      if (c == '\n') {
        resp[ respLen ] = '\0'; // NUL terminate
        respLen = 0; // reset for another line
        break;

      } else if (respLen < sizeof(resp)-1) { // Room for more?
        resp[ respLen++ ] = c; // accumulate one more character
      }
    }
  }

  Serial.print( F("Response = '") ); // F macro saves RAM
  Serial.print( resp );
  Serial.println( '\'' );
}

But when the response is long (hundreds of bytes), you may not have sufficient RAM to save the whole response, and then parse it.  You MUST use an FSM to parse the bytes as they are received.

For your application, you should skip all the stuff at the front and watch for the "Content-type:" pattern and the two newlines, then save the next line (as above) for parsing:

enum state_t { SKIP_TO_CONTENT_TYPE, SKIP_TO_EMPTY_LINE, SAVING_TIMESTAMP };
state_t state = SKIPPING
uint8_t index = 0;

const char ContentType[] = "Content_type:";

bool watchForTimestamp()
{
  if (modem_port.available()) {
    char c = modem_port.read();

    // Handle this one character, based on our current "state"

    switch (state) {
      case SKIP_TO_CONTENT_TYPE:
        if (c == '\n')
          index = 0;

        else if ((index < sizeof(ContentType) && (c == ContentType[ index ])) {
          // next char matches
          index++;

          if (index == sizeof(ContentType)) {
            // All matched!
            state = SKIP_TO_EMPTY_LINE;
            index = 0;
          }
        }
        break;

      case SKIP_TO_EMPTY_LINE:
        if (c == '\n') {
          index++; // this counts newlines since "Content-type:"

          if (index == 2) {
            state = SAVING_TIMESTAMP;
            index = 0;
          }
        }
        break;

      case SAVING_TIMESTAMP:
            ... Hint: something like the line-saving technique above.
        if (something) {
          return true;
        }
        break;
    }
  }

  return false;
}

Some part of loop will just call waitForTimestamp over and over:

void loop()
{
    ...

  bool gotResponse = false;
  state = SKIP_TO_CONTENT_TYPE;

  while (millis() - startTime < TIMESTAMP_TIMEOUT) {
    gotResponse = waitForTimeStamp();
    if (gotResponse) {
      // parse the timestamp from the resp array
         ...
      break;
    }
  }

  if (gotResponse) {
    Serial.print( F("Timestamp = ") );
    Serial.print( resp );
    // now you can parse the small response array
       ...

  } else {
    Serial.println( F("Didn't receive timestamp!") );
     ... other error code
  }
}

This may be a "main" FSM for loop, with a nested FSM for parsing the HTTP response.  The rest is up to you.  :)

BTW, SoftwareSerial is very inefficient.  It cannot send and receive at the same time, and it disables interrupts for long periods of time.

If you can use pins 8 & 9, you should use AltSoftSerial instead.  It is very efficient.

If you can't switch to those pins, you could use NeoSWSerial if the modem is running at 9600, 19200 or 38400.


Stuck with bad sketch How can I get my programmer board/windows computer to recognize my board again. I am using the esp32 cam and have put two boards in a state where I am unable to flash them anymore. here is the error:

serial.serialutil.SerialException: could not open port 'COM5'WindowsError(2,'The system cannot find the file specified.')Failed to execute script esptoolthe selected serial port Failed to execute script esptool

I tried reinstalling the drivers and understand that the com port is a separate chip
https://gist.github.com/wybiral/2a96c1d1605af7efa11b690586c4b13e

Here is the sketch I used. I uploaded it using the dev module board setting as well as with 80mhz and 112500 speed. I uploaded with 3v and then provided 5v to the board to run the sketch. The sketch runs but prints out gibberish.

Edit:

Here is a schematic of the board
https://github.com/SeeedDocument/forum_doc/raw/master/reg/ESP32_CAM_V1.6.pdf

This very much looks like the Serial-over-USB-Driver has chosen another port than COM5 on reconnecting the board. Assuming you are using the Arduino IDE, check whether COM5 still shows up in the Board -> Port menu -- or, in other words, go there and select the port that is listed there while the board is plugged in.

Usually, I'd expect this port to be COM3 on Windows, but that may change when you...

physically disconnect and reconnect the board too fast (i.e. the driver has not yet shut down the old COM port when a "new device on USB!" event comes in)
still have the Serial Monitor open when disconnecting and reconnecting (because the driver cannot remove the virtual COM port device while the Serial Monitor has it opened, in which case the driver creates another virtual COM port device on a different number)
disconnect and reconnect while the esptool process is still working (same reason as above).

It also might help to enable verbose output for compiling and uploading (see preferences dialog in Arduino IDE).


Arduino round to nearest 0.5 I am having a double value for example: 34.26 or 11.92 or 2.51. It should be rounded to the nearest 0.5 so 1.34 -> 1.50 and 32.78 -> 33 and 21.09 -> 21.00

How do to do this?

It is a very bad idea to use float.
That being said. multiply by 2 and do a standard round.
Then divide back by 2.

For example:

1.34     *2 = 2.68
round(2.68) = 3
3        /2 = 1.5

and

32.78    *2 = 65.56
round(65.56)= 66
66       /2 = 33


ATTiny85, how to fix overwritten clock pins? I'm using an ATTiny85 with an external 16MHz clock. I accidentally set pins 3 and 4 to output using pinMode() in a program and uploaded it, and now I'm getting an invalid device signature (the signature is 0) error when I try to upload a sketch.

How can I go about fixing this (if possible)?

I am using an Arduino UNO as ISP, with an external 16MHz clock and capacitors connected to pins 3 and 4, and have rechecked my wire setup multiple times.

Holding the chip in reset while powering it on will ensure that the pins are never reconfigured.


Loop behaves oddly in I2C receiveEvent I am messing around with an ATmega328P hooked on a Raspberry Pi, communicating over I2C. The ATmega is the slave (details at the end). While testing the basics of the concept, I faced an interesting problem.

This is the code on the ATmega:

#include <Wire.h>

#define SLAVE_ADRESS 0x1A
#define LED 6

int count = 10;
void setup()
{
    pinMode(LED, OUTPUT);
    /*for(int i=1; i<=3; i++)
    {
      digitalWrite(LED, HIGH);
      delay(100);
      digitalWrite(LED, LOW);
      delay(100);
    }*/
    Wire.begin(SLAVE_ADRESS);
    Wire.onReceive(receiveEvent);
    Wire.onRequest(requestEvent);
}

void loop()
{
  delay(10);
}

void receiveEvent(int received_bytes)
{
  while(Wire.available())
  {
    unsigned char i = Wire.read();
    if(1)
    {
      int j = 5;
      while(j>0)
      {
        digitalWrite(LED, HIGH);
        delay(300);
        digitalWrite(LED, LOW);
        delay(300);
        j-=1;
      }
    }
    delay(1);
  }
}

void requestEvent()
{
  Wire.write(count);
}

What you would expect it to do is blink the LED connected to pin 6 five times when the Pi sends a byte to the ATmega slave. (Things like if(1) are there because the code was much more specific originally.) The strange thing is that this is not the case:

The LED only blinks 1 time.

I honestly have no idea why. This "stdio-fitted" version of the problematic loop ran on the RPi as expected, prints 5*2 times:

#include <stdio.h>

int main()
{
  int j = 5;
  while(j>0)
  {
    printf("LED, HIGH\n");
    printf("LED, LOW\n");
    j-=1;
  }
  return 0;
}

Circumstances:

I compile the code in the Arduino IDE on the Pi, then upload it
using AVRDUDE to the ATmega with the Pi's GPIOs. No error messages
over the process.
The ATmega gets 3.3 V supply voltage from the Pi, and operates on
16.000 MHz. Only the LED and the Pi is connected to it.
The (Python) code I use on the Pi to write and read a byte is the following. Reading works well, and I know by tests that the ATmega actually receives the correct byte:

import pigpio
import time

pi = pigpio.pi()
atmega = pi.i2c_open(1, 0x1A)

for i in range(6):
    a = pi.i2c_read_byte(atmega)
    print a

pi.i2c_write_byte(atmega, 0x05)
time.sleep(1)

void receiveEvent(int received_bytes)
{
  while(Wire.available())
  {
    unsigned char i = Wire.read();
    if(1)
    {
      int j = 5;
      while(j>0)
      {
        digitalWrite(LED, HIGH);
        delay(300);
        digitalWrite(LED, LOW);
        delay(300);
        j-=1;
      }
    }
    delay(1);
  }
}

receiveEvent is an ISR (interrupt service routine). Don't do delay in an ISR. That will hang indefinitely. Thus the LED only blinks once. You could do delayMicroseconds for testing. In general an ISR should be short.

Interrupts
I2C


Perhaps the built-in Arduino Serial Plotter is all you need to visualize your data.  I wrote a tutorial a while back that might help you.


How to prepare data structures and classes? How can I port these structures to arduino ide, I also get error when I define pointers

// pointer to classes example
#include <iostream>
using namespace std;

class Rectangle {
  int width, height;
public:
  Rectangle(int x, int y) : width(x), height(y) {}
  int area(void) { return width * height; }
};

int main() {
  Rectangle obj (3, 4);
  Rectangle * foo, * bar, * baz;
  foo = &obj;
  bar = new Rectangle (5, 6);
  baz = new Rectangle[2] { {2,5}, {3,6} };
  cout << "obj's area: " << obj.area() << '\n';
  cout << "*foo's area: " << foo->area() << '\n';
  cout << "*bar's area: " << bar->area() << '\n';
  cout << "baz[0]'s area:" << baz[0].area() << '\n';
  cout << "baz[1]'s area:" << baz[1].area() << '\n';
  delete bar;
  delete[] baz;
  return 0;
}

In CPP shell it works

I try to put it like this

class Rectangle {
  int width, height;
public:
  Rectangle(int x, int y) : width(x), height(y) {}
  int area(void) { return width * height; }
};

  Rectangle obj (3, 4);
  Rectangle * foo, * bar, * baz;
  foo = &obj;
  bar = new Rectangle (5, 6);
  baz = new Rectangle[2] { {2,5}, {3,6} };

void setup() {
  // put your setup code here, to run once:

}

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

}

I get an error

sketch_nov27a.ino:10:3: error: 'foo' does not name a type
sketch_nov27a.ino:11:3: error: 'bar' does not name a type
sketch_nov27a.ino:12:3: error: 'baz' does not name a type
Error compiling.

The problem is that the lines saying foo = ... etc. are assignment operations. C++ lets you declare and immediately initialise variables at global scope, but after that you can only assign to them inside a function. In your original program, all your declarations/assignments were inside main(), which is why it worked there.

For your Arduino program, you could change the assignments to initialisations instead (in global scope):

Rectangle obj (3, 4);
Rectangle * foo = &obj;
Rectangle * bar = new Rectangle (5, 6);
Rectangle * baz = new Rectangle[2] { {2,5}, {3,6} };

Alternatively, you could leave the declarations in global scope and move the assignments into setup():

Rectangle obj (3, 4);
Rectangle * foo, * bar, * baz;

void setup() {
    foo = &obj;
    bar = new Rectangle (5, 6);
    baz = new Rectangle[2] { {2,5}, {3,6} };
}


Running out of pins in a 4x7-segment display clock I've been playing around with the 7-segment displays and so far I've only been able to make 1 working display hooked up to a potentiometer that changes the number on the display with a switch that turns it into a counting-up timer

My main goal is to make a Clock but that uses 4 7-segment displays and I've already used up 7 pins for 1 display so now I either need to make more pins (I'm using Arduino Uno which has 14 Digital pins + 6 if you use the Analog In pins)
or use the 7-segment decoders

if I use the 7 segment decoder that will take up 4 per display which totals up to 16 which is well in range the required amount of Pins

so can someone teach me what is easier to do:

Making more pins using the 8-bit shift registers
or
Use the 7-segment decoders to make space

and if you think one is easier can you tell me how to use them because I have no idea and I've been tinkering with the decoder for the past hour or two
(btw the 7-segment displays are all Common Anode)

The basic idea is this:

First, connect segment A of each display together, and all the segment Bs together, and all the segment Cs and so on.  Each "group" is driven by one pin on the Arduino.  For this you will need seven pins.

Your displays will have either a common anode or common cathode - perhaps you have that connected straight to +5v or straight to ground currently.  Instead, you connect the "common" pin from each display to a spare pin on your Arduino - so using another four pins.

Remember the resistors too.

Now, you can light up any segment on any display, by setting the appropriate segment pin and the appropriate common pin to the right values.

Make sense?


Serial doesn't initialise on Arduino Mega 2560 when not powered via the USB port I am working on a project with a Mega 2560 and a Sim800L module.

Everything works fine, however if i don't connect the USB port (at least once) and power only externally (either by Vin unregulated 7-12V or 5V regulated pin)
the program will seem not to initialize serial in setup().

I found this which is related to the issue but not a proper workaround:
https://forum.arduino.cc/index.php?topic=24642.0

edit: I can confirm using a resistor to short pins 0+1 together (serial) works but it is not a proper solution. This means you have to disassemble your project to access the resistor or add a switch if you want to use USB to debug later or upload new code. Another workaround which i need to test is to remove all Serial code (because i can in my specific project), but again this is not a proper solution.
Any ideas please?

edit2:
for comments

if(SIM900.available()>0){
// AT command to set SIM900 to SMS mode
SIM900.print("AT+CMGF=1\r");
delay(100);
// Set module to send SMS data to serial out upon receipt
SIM900.print("AT+CNMI=2,2,0,0,0\r");
delay(100);
textMessage = SIM900.readString();
textMessage.toUpperCase();
Serial.print(textMessage);
delay(10);
}

if(textMessage.indexOf("SET PHONE")>=0){
// Set phone number to receive notifications
phoneNumber = textMessage.substring(9,21);
Serial.println("Phone number set to: " + phoneNumber);
String message = "Notification number set to: " + phoneNumber + "\nSend 'Help' for additional commands.\nNote in case of reset number returns to hardcoded default";
sendSMS(message);
Serial.println("Confirmication of phone number change sent");
textMessage = "";
}

Ok i found the issue and the solution.

For some reason it seems that while the MCU is running Setup(); hardware or software serial don't work properly.

In my case i have code that set the SIM module to SMS mode and to send those messages to the serial port.

For some reason it doesn't send them (or probably the module is not ready to accept them).

Connecting the USB cable reset the arduino and run setup() when opening the serial monitor setting the module in the correct mode.

Adding this code in the main loop solves this issue even though i have them powered both by the same step down converter.

edit: That turns out 1 hour later after debugging more is not exactly a proper solution to the issue.
 That command to set into SMS mode only works when you are connected to the network.

I have a check for that and a reset function.

So now at Setup() i wait 10s for the module to boot up so it is ready to open a serial port, then i check if it is connected to the network before i send the commands to set into SMS mode.

Example:

// Initializing serial commmunication
Serial.begin(57600);
delay(10000);

while (ini){
    Serial3.begin(57600);
    delay(1000);
    Serial3.print("AT+CGREG?\r");
    delay(100);
    netStatus = Serial3.readString();
    if (netStatus.charAt(22) == '5' || netStatus.charAt(22) == '1') {
         digitalWrite(LED_NET, HIGH);
         ini=false;
         }
    else {
        digitalWrite(LED_NET, LOW);
        digitalWrite(resetPin, LOW);
        delay(2000);
        digitalWrite(resetPin, HIGH);
        delay(30000);
        }
}
  Serial.print("SIM800 ready...");

  // AT command to set SIM800 to SMS mode
  Serial3.print("AT+CMGF=1\r");
  delay(100);
  // Set module to send SMS data to serial out upon receipt
  Serial3.print("AT+CNMI=2,2,0,0,0\r");
  delay(100);


Using esp-wroom-32 without a development board There are lots of examples on the internet on how to build Arduino from scratch such as IN THIS LINK. I will like to do the same but with the esp32.
I have this development board:

And I am able to program it with the Arduino framework/IDE thanks to THIS VIDEO.

Now the question
How can I flash my code and run it on a standalone ESP-WROOM-32 chip like this one:

I do not want to use voltage regulator etc as I am planning to run it from a 3.3V battery.
Before asking this question this was my research:

In this video (https://www.youtube.com/watch?v=n43rHugPbTg) Hugatry does exactly what I am looking for but he does not explain what pins he is using. Moreover what happens if I connect my 5v serial to the chip? will it burn?

I went directly to espressif website and looked for the schematics (https://www.espressif.com/sites/default/files/documentation/esp32-wroom-32d_esp32-wroom-32u_datasheet_en.pdf). It is hard to understand I just want to do something simple.

This blog (http://blogs.oregonstate.edu/copaps/resources/programming-esp32-on-custom-pcb/) explains how but the pins are different than my esp-wroom-32 chip.

Looking more on the internet/youtube everyone explains how to solder it. But I haven't found a diagram that will enable me to flash it and run my code. Also will I have to burn a bootloader like with arduino?
What I am about to try is to buy a 5V to 3.3V serial converter connecting TX with RX and RX with TX. Providing 3.3V power to the 3.3V pin and connect the last cable to ground. If I try that will it work?

There are programming boards available to which you can plug one of these SOCs into them. There are different boards for different types of ESP SOCs.
You can find them at popular Chinese vendors, and probably elsewhere too.
They look like this:


How do you convert PCM to PWM? I'm a beginner and I've been developing my own library for a wave player. so far I have the SD card installed and OLED and rotary encoder all connected. I've successfully read the wave chunk and it's data(16bit and 44.1KHz). My question is that the data in wave file is PCM and I wish to play is using 16bit PWM and so how do I convert PCM to PWM?

There is no such thing as a PCM file. PCM is completely erroneously used to describe an uncompressed digital audio file. What it actually means is "A file which contains data that can be fed directly to a PCM device without any form of intermediate conversion".

What you have in a "PCM" WAV file is just raw sample data. After your header (usually 44 bytes) you just have 16-bit values representing your sample points, with the two channels interleaved one after the other.

Since PCM is a linear audio representation, the sample data it expects is a simple linear representation of the audio (unlike µLaw or A-law) and with no compression (such as MP3 or FLAC). And that is the exact same data that PWM expects since it too is a simple linear output.

However, none of that matters, because the Arduino simply isn't powerful enough to play your file. Maybe a smaller one (8kHz, mono, 8-bit) would be playable, but not yours. The numbers just don't add up.

There is a PCMAudio example available, but it only works from audio embedded within your program.

There is also a TMRpcm library available which plays from SD card, but is limited to 8-bit mono, though it can supposedly do up to 32kHz sample rate (though I wouldn't want to try doing anything else at all at that rate).

You would be better off using a system more geared towards audio - something with an I2S CODEC chip attached would be the best solution.


Esp32: upload eeprom file I'd like to flash the eeprom sector with content so that the eeprom already holds data when it boots the first time.
How do I upload such an eeprom file like I would do with avrdude on an atmega? Is there a tool that can be installed in the arduino IDE like the data uploader?

The ESP8266 has no EEPROM.

Instead the flash memory is partitioned into different areas for different purposes. One of those areas is set aside for "EEPROM Emulation" data.

To upload to that area you first need to know where that area is in the flash memory, and that is dependent on what partitioning scheme you are using at the moment.

Once you have worked that out (look in the partition scheme files in the core for more information) you can then use esptool to upload data to the right area of flash.


Problem while interfacing LCD screen with Arduino I tried to interface an LCD screen with my Arduino but I have a problem - Nothing is being displayed on my LCD screen:

Here is the code:

#include<LiquidCrystal.h>

LiquidCrystal lcd(7, 8, 9, 10, 11, 12);  // sets the interfacing pins

void setup()
{
 lcd.begin(16, 2);  // initializes the 16x2 LCD
}

void loop()
{
  lcd.setCursor(0,0);           //sets the cursor at row 0 column 0
  lcd.print("16x2 LCD MODULE"); // prints 16x2 LCD MODULE
  lcd.setCursor(2,1);           //sets the cursor at row 1 column 2
  lcd.print("HELLO WORLD");     // prints HELLO WORLD
}

In the setup() you have to state what pin the Vo (display contrast pin) on the LCD is connected to. Before the

lcd.begin(16,2)

try

analogWrite(pin Vo is connected to, contrast you want to set the screen to);

An example would be:

analogWrite(6,80);


Arduino Interrupt example not working The example program is from here: https://www.arduino.cc/en/Reference/attachInterrupt

When I paste in the code and run it, the LED is on all the time (It's supposed to blink):

const byte ledPin = 13;
const byte interruptPin = 2;
volatile byte state = LOW;

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(interruptPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(interruptPin), blink, CHANGE);
}

void loop() {
  digitalWrite(ledPin, state);
}

void blink() {
  state = !state;
}

This is my setup:

I think you misunderstood this example: it is not expected to automatically blink!

The LED is suposed to change state at every change of level on pin 2. This supposes that you wired something (e.g. a push button) to pin 2 and that this will make pin 2 change level when something happens (e.g. you press the button or you release it).

On your diagram, there is nothing wired on pin 2, so what you observe is just normal.

If you want to see attachInterrupt in practice, then connect pin 2 to a button with the other button lead connected to GND.

Then you can observe what happens when you play with that button.


Connect a TM1627 to ESP32 I want to control a 7 segment display that has a TM1637 integrated with an ESP32.

Some time ago I created a layout that used an ESP12e but I need more GPIO pins so I'm switching over to an ESP32.

This was how I had it hooked up:

CLK -> GPOI14
DIO -> GPIO12

I think I did it this way because I had to use the special CLK pin tou can see in this pinout.

Only I don't know if I need to hook them up with special pins on the ESP32. I can't find a good tutorial and I don't have the parts yet to test with.

Do you guys know which pin(s) are suitable for the TM1637?

The label CLK on esp8266 is in a context of SPI pins CLK, MISO, MOSI, SS. You had no reason to connect TM1637 CLK to this pin, since with TM1637 you can use any GPIO pins of the MCU for CLK and DIO.


Garbage stored in SD card I am an electronics graduate and an embedded design engineer, working in this field for about two years apart from the hobby time during my graduation. I am currently working on a system that has an Atmega2560 as the core controller with an arduino bootloader, we are using an 8GB memory card to save the log data from our system and send it to our server at regular intervals of time. The system worked fine however some of them are facing issues with the writing of data, some garbage value are getting stored in the SD card. I have attached the schematic and code snippet for the same, please let me know if there is any problem with the system and how can i resolve it, please let me know if any other things are required for understanding the problem correctly.

Thank you in advance.

     SD_Initialize();
  if(!SD.exists(SDTransactionDirectory))
  {
    if(SD.mkdir(SDTransactionDirectory))
    {

    }
  }
  RTC_Date_Time();
  String FileName = SDTransactionDirectory + "/" + RTCSDDate + RTCSDTime + ".txt";
  SD_File = SD.open(FileName, FILE_WRITE);
  if(SD_File)
  {
    delay(100);
    digitalWrite(LED_SD, HIGH);
    SD_File.println(GSMData);
    SD_File.close();
  }

The SD_Initialize() is a user function:-

void SD_Initialize()          //initialise SD card
{
  digitalWrite(SD_EN, HIGH);
  digitalWrite(SD_CS, LOW);

  delay(500);

  if(SD.begin(SD_CS))
  {
    digitalWrite(LED_SD, HIGH);
  }
  else
  {
    digitalWrite(LED_SD, LOW);
  }
}

The data stored in the filename is as follows:-
CLEnT|T|M008|\00Ÿûmï°]ŸëÜ£·zoòTÏæ{Œü[ŸýUô~ÛcCWY®ÞgÙë×<;wBÄgnìÇFÿÉ=XoÎ.êžÄf·®ö¯³ç~åeÝ]1_ÏÀyÿÌÍ?ô"zBõ¬ñ

As you can see the initial values till "M008" is fine but its garbage after that, and the CLEnt|T|M008 is the start of the string after that a lot of other parameter information is to be stored which turns out to be garbage.

There are many comments, but no answer yet. This answer has only a few basic rules.

The first thing to do is to see if the problem can be replicated with a small sketch and to check the voltages.

The arduino mega 2560 works best at 5.0V, or maybe a little less. It is not reliable at 4V. When powering it with a 5V power supply, the usb connecter is the best option to power the arduino board. Powering the arduino board via the 5v pin is not advised. When a strong power supply is connected to the 5v pin, the voltage regulator can be blown.

When something is not working, fall back to something that is reliable. For example a SD module with a HC4050 to shift the voltage levels. The resistors make the signal weaker.

Make a small test sketch without the use of the String object. The more experienced someone is with arduino, the more he or she tells to avoid the String object with avr microcontrollers.

There are counterfeit SD cards. One of those might turn up in your hands someday. Beside that, not every SD card is compatible with the arduino SD library.

In your situation it is suspicious that the file system is okay, the filenames are okay, the first text is okay, but when data is written it suddenly goes wrong. That is a strong indication for a memory problem.

When data to a display or SD card is wrong, then send it also to the serial monitor. You have to know what is actually written to the SD card.


Arduino how can I search for missing library header files How can I search for blank library header files (ie. .h files).

Assuming the question is about missing libraries. When running (right arrow button) the Arduino IDE the compiler will spit out an error if a header can not be found.  Not all header files are downloaded when you install the Arduino IDE because they take up space and it is very unlikely anyone would need them all.  It is recommended to manage libraries from inside the Arduino IDE.

To do this click on "Sketch->Include Libraries->Manage Libraries...".  (To be clear, click on Sketch at the top of the Arduino IDE window, move to Include Libraries in the new menu then move to Manage Libraries... in the next new menu and click on Manage Libraries... .)  This will pull up a new window.  There are many libraries.  Use the "Filter your search" box.  For example type "Nokia LCD".  This cuts the number of possibilities to about 8.  A reasonable number to go through and find the correct library.


How to chooce SDA/SCL pair on Arduino Due ? On Arduino Due, there is two pairs of pins SDA/SCL that I can use for I2C. There is SDA0 and SCL0  at, respectively, pins 20 and 21  and an another near AREF. How do I choose which one of them  I use ? I also read that 20 and 21 has built-in pull-up resistor, is that true ?

Pins 20 and 21 are the default I2C pins. A lot of libraries assume you use these, and would require some extra work to get working with SDA1/SCL1.

They also have their pullup resistors already present on the board of the Due (see schematic).

So just use pins 20 and 21, unless you have a good reason to use the other.


How to use FTDI to program Lilypad Arduino? I am trying to upload a basic Blink code from my computer to Arduino Lilypad contains Atmega 328. While my Blink codes are uploading, FTDI 1402-C CN480661 FT232RL module is not responding to the Arduino IDE at the end of the process. So I couldn't upload any codes with this uploading method, I mean using FTDI modules directly.

This is how I do the connections:

This is my Blink code:

void setup() { pinMode(13, OUTPUT);}

void loop() {
  digitalWrite(13, HIGH);     delay(1000);
  digitalWrite(13, LOW);      delay(1000);
}

I chose AVRISP mkII as a programmer. ATmega328 as a processor. Arduino Lilypad as a board on Arduino IDE v1.6.6

At this point, I got this error:

  avrdude: ser_open(): can't open device "\.\COM4": Access is denied

Windows's device manager says: USB Serial Port is attached to COM4, also Arduino IDE saw that.

I downloaded FTDI driver for Windows, but still, I can't upload any code into my Lilypad Arduino.

How can I use FTDI to program my Lilypad Arduino?

"Access is denied" this looks like you should at least restart your computer after you installed the FTDI driver if you have not already.

Run Arduino IDE as Administrator and also make sure you are logged into an Administrator account in your windows login.

If all this fails this means another application is using that com port you will need to figure out what could be using that com port another instance of Arduino IDE opened? Etc

If all else fails restart your computer with the usb unplugged, login, open arduino IDE and plug in your usb and select the com port.

Edit: You can also try changing the USB port you are currently using for another one, this will also change your com port to a new number


DHT11 + ESP plus Arduino Someone could help me?
I want to use dht11 with arduino and esp. Both will read data from dht11
the problem is that simultaneously cannot be done. So the solution will be to set one as a master and the other one as a slave.
the control will be done like so...
another wire from arduino pin->set as output ->esp pin->set as input.
if wire == 1 then dht11 will be read by arduino
if wire == 0 then esp will read dht.
with some delay ofcourse. but the problem is that i dk how to stop the communication between one board and the sensor when the other board will read it. so does it not exist any conflict

Disclaimer:

I've never used an ESP chip based board I know almost nothing about them. I am going to assume that it works, in software terms, like an Arduino, and base my answer on Arduino code. If the esp chip works differently, you'll need to adapt my suggestion.

Try something like this:

Connect a GPIO line between the microcontrollers. Also connect that line - through a 10K resistor - to +5V.

Have both microcontrollers set up it's GPIO as an input.

(We'll call the GPIO pin on both microcontrollers the "DHT_available" line. It will be HIGH when the DHT sensor is not being used by the other controller.)

When one of the microcontrollers wants to read the DHT11, have it check the GPIO line. If it's HIGH switch the GPIO line to an output and pull it low, then take a reading. When the reading is complete, switch the GPIO line back to an input.

If the GPIO line is LOW, wait and check again.

Alternately you could attach each of the microcontroller's GPIO lines to interrupt handlers on a rising edge. Then have the interrupt handler set the GPIO line to an output, pull it to LOW, and set a flag that means "begin reading".

Have your loop function check the "begin reading" flag, and if true, trigger a read from the DHT, and once it's complete, set the GPIO back to an input.

With the first option, each microcontroller would need to poll the "DHT_available" line continuously until it goes HIGH before beginning reading.

With the second option, as soon as one of your microcontrollers is done taking a reading, it would stop pulling the communications line LOW, the other one's rising edge interrupt would fire, and the other one would immediately begin reading.


Why doesn't pin 9 blink? I use simple LED blinking code on an Arduino MEGA 2560. I simulate it in Proteus. But pin number 9 doesn't power up. What is the problem?

My code:

// Set up the DATA direction
void setup()
{
  for(int i = 1; i<9; i++)
    pinMode (i, OUTPUT);
}

// The main program
void loop()
{
  for(int j=2; j<=10; j++)
  {
    digitalWrite(j, HIGH);
    delay(100);
    digitalWrite(j, LOW);
  }

  for(int j=9; j>=2; j--)
  {
    digitalWrite(j, HIGH);
    delay(100);
    digitalWrite(j, LOW);
  }
}

And the circuit is:

It looks like your main problem is the loop in setup():

for(int i = 1; i<9; i++)
    pinMode (i, OUTPUT);

This will call pinMode() with values 1 to 8 (inclusive), and then stop. That means you aren't configuring pin 9 as an output. You need to change the loop condition to i<=9.

However, if your circuit diagram is accurate then you will have another problem. When implementing the circuit for real, you absolutely must have a suitable resistor in series with each LED (maybe something around 200 Ohms, depending on the exact specifications). If not, you seriously risk destroying the LEDs and maybe damaging your Arduino.


Lag in fetching serial data from Arduino I am working on a project based on Arduino and python3.6,two HC-SR04 sense the distance of palms and process the data using Arduino and send it through serial port to python3.6 ,python3.6 with the help of pyserial ,pyautogui based on data from arduino controls a game named supertuxcart,a racing game,basically the thought behind this is  controlling game with palms instead of keyboard or mouse .But the problem am facing is Arduino takes the distance measurement data from two HC-SR04(one for each hand) ultrasonic sensors, processes according and sends processed data through serial port to python3.6 ,there while running the my python script i open the game to check if its working ,it works, but there is lag in data received from arduino thus turn the game messy.

here is arduino code am using with NewPing library

#include <NewPing.h>
int trig1=9;
int echo1=6;
int trig2=7;
int echo2=5;
int R;
int L;
NewPing right(9,6,100);
NewPing left(7,5,100);
void setup() {

  pinMode(9,OUTPUT);
  pinMode(8,OUTPUT);
  pinMode(6,INPUT);
  pinMode(5,INPUT);

}

void loop() {
  Serial.begin(9600);
  //Serial.println("hi,am arduino");
  R=right.ping_cm();
  L=left.ping_cm();
  //Serial.println(R);
  //Serial.println(L);
  delay(0000);
 if (R==0 && L==0){
    Serial.println('0');
  }
  else if(R<L&&L-R>5){
    Serial.println('1');
  }
  else if(R>L&&R-L>5){
    Serial.println('2');

delay(3000);

  }

}

Here is python3.6 code am using

import serial
import pyautogui
import time

Arduino = serial.Serial('/dev/ttyACM0', 9600)
time.sleep(0)
print(Arduino.readline())
pyautogui.keyDown('up')
while 1:
    Data = Arduino.readline()
    print(Arduino.readline())

    if Data == b'0\r\n':
        pyautogui.keyUp('up')
        pyautogui.keyUp('right')
        pyautogui.keyUp('left')
        break
    elif Data == b'1\r\n':
        pyautogui.keyUp('left')
        pyautogui.keyDown('right')
    elif Data == b'2\r\n':
        pyautogui.keyUp('right')
        pyautogui.keyDown('left')


Can you save data to EEPROM using firmata? I have a few Arduino boards connected to my computer running firmata and I want the computer to be able to differentiate between them even when I unplug them and plug them back into a different USB port in a different sequence. My solution was to save and read a Unique I.D. into each Arduino's EEPROM, but I am not sure how to accomplish this using firmata?

I want to save a few bits of data to the Arduino UNO with EEPROM, but the Arduino has to be running code compatible with firmata. Is this possible?

You have to edit the Firmata source code and add a few lines of code:

add the EEPROM library
include the library into the Firmata code
in the setup() function use the EEPROM library to read the id from the EEPROM

How do you plan to write that data into your Arduino EEPROM?
If you want to do that via serial connection than you also need to add that code.
I have done something similar in an example for my VoltageReference library, specifically in EEPROMCalibration.ino

UPDATE

After a little investigation I understand there is the possibility to exchange generic messages and handle generic commands via Firmata: commands 0x00-0x0F are reserved for customization. On the Arduino side you can use:

void storeToEEPROM(int id) {
  ...
}

void readFromEEPROM() {
  char buf[12];
  Firmata.sendString(itoa(the_id, buf, 10));
}

void setup() {
  ...
  Firmata.attach(0x00, storeToEEPROM);
  Firmata.attach(0x01, readFromEEPROM);
  ...
}

That will allow you to write and read the id using those two custom commands.


Can the EWRF 3022 module be directly connected to the pc totransmit data from the pc wirelessly? In my project I want to connect my pc to an RF transmitter. The receiver will be connected to an arduino on my robot. However most of the RF modules I looked up couldn't be directly connected to my computer- in all of them I needed to use an arduino on the transmitter end too. Then I came across this:

   EWRF 3022

Can this be directly connected to my computer? If so, how is it done?

If you use a USB to TTL UART adapter, such as an FT232 dongle, then yes you can communicate to it from a PC.

It will not directly connect to a PC though without you getting that extra hardware.


What motor to move a small telescope? i just bought a hobby telescope, it works well for being nothing much than a toy, the very problem is that the gesrs that should keep it stable are all plastic and very hard to tighten while keeping it steady.
So I thought to let the gears wide open and move it with arduino: you point the object manually then with 4 buttons move it by small steps.
I've tried to use a couple of servos i had at home, mg90s 2kg 180°; while 180° is enough for the purpose, first i don't think 2kg is enough for the X axis motor, second one is not very precise (using the default library).
I know I can achieve better results calibrating the pulse manually, but maybe is better if I use better motors.
What motors (and why) would you reccomand?
Servo or stepper?
Being for a hobby the budget is low, so very max 50$?

I wouldn't use a servo for this. You don't have very fine control over the angle with a servo. Also with a typical telescope the focus is more on rather slow and precise movements, instead of fast ones.
Instead I would use a stepper motor. Depending on your exact requirements, these can be rather cheap to rather expensive.
Here also the mechanics come into play. The motor should not be attached directly to the axis, but instead through some gears (the axis of the telescope having the larger gear). That will allow for smaller, more precise movements and also lower the needed torque for the motor. Of course this depends on your actual telescope hardware, meaning if you can put a gear right to the axis. If not, you could limit the motor driven movement a bit and install a level, which then could be pushed or pulled by a nut on a threaded rod, which gets driven by the servo motor. This would be rather easy to implement, though you may need to correct for the different rotation behavior, when you get to the outer sides of the movement (for the actuator being linear, while the resulting movement is circular), by some mathematics in your code.
Since you want to keep your costs very low, you might wanna use the 28BYJ-48 stepper motor (including the fitting driver). In terms of stepper motors they are rather bad, but they are really really cheap and - depending on the gear ratio/level length/thread pitch - it might not matter that much for you. You could always update to a better stepper motor in the future.